问:
ASP.NET MVC 3.0 Razor, load View from anywhere out of the box?
Is it true that it is possible to load View from anywhere without
implementation of custom VirtualPathProvider in MVC 3.0?

If it is true how to do it?

Basically it is not a problem to implement custom VirtualPathProvider which would load the
View from anywhere but my implementation working only in MVC 2.0 and not working wih MVC 3.0, fore some reason method GetFile newer called for not existed views in MVC 3.0 and in that case I am getting "Server Error in '/' Application."

I followed the same code for my custom VirtualPathProvider from here: http://buildstarted.com/2010/09/28/mvc-3-razor-view-engine-without-a-controller/

UPDATE 1

OK i did fix my problem with my custom VirtualPathProvider after i put registration of my custom VirtualPathProvider provider first line in the Application_Start()

```<code>    protected void Application_Start()
    {
        //Should be first line before routes and areas registration.
        HostingEnvironment.RegisterVirtualPathProvider(new MyVirtualPathProvider());

        AreaRegistration.RegisterAllAreas();

        RegisterGlobalFilters(GlobalFilters.Filters);
        RegisterRoutes(RouteTable.Routes);
    }
</code>```

When registration of custom VirtualPathProvider in Global.asax.cs folowing after AreaRegistration.RegisterAllAreas(); or RegisterRoutes(RouteTable.Routes); method method override VirtualFile GetFile(string virtualPath) wont work for "virtual Views".

UPDATE 2

does it means that the classes RazorView and RazorViewEngineRender is the answer?

UPDATE 3

If i have string representation of my razor view which does not exists in the file system (e.g i store razor views in database) how may i render it using this kind of approach http://buildstarted.com/2010/09/28/mvc-3-razor-view-engine-without-a-controller/

For example string representation of my View looks like this:

```<code>"@{
    ViewBag.Title = ""About Us"";
}

<h2>About</h2>
<p>
     Put content here.
</p>"
</code>```

UPDATE 4

Now i see, to be able to use @Html.<something> custom TemplateBase should be implemented.
The sample of implementation of HtmlTemplateBase<T> could be fount here http://www.fidelitydesign.net/?p=239, but it won't work with RazorEngine v2, i am successfully getting template compiled, then after assembly loaded method public override void Execute() won't be executed i am getting an error: The method or operation is not implemented (stacktrace: http://tinypic.com/r/dcow4/7)

To make “public override T Model” happened i did change declaration of “public TModel Model” to “public virtual TModel Model” in “public abstract class TemplateBase : TemplateBase, ITemplate”. May be there is some another changes should be done? Or something in HtmlTemplateBase<T> should be done another way?

答:
No, loading a view from the database is not supported by default. You need to write your own VirtualPathProvider.

Note that Ben's blog post does not actually address directly the problem that you are trying to solve. The following blog post looks a lot closer to what you want: http://rebuildall.umbraworks.net/2009/11/17/ASP_NET_MVC_and_virtual_views. Note that it does not matter if you are trying to store razor or aspx views in the database. Virtual path providers in Asp.Net are simply about mapping a path to a stream of bytes that are the contents of the file represented by that path.

Body:
Is it true that it is possible to load View from anywhere without
implementation of custom VirtualPathProvider in MVC 3.0?

If it is true how to do it?

Basically it is not a problem to implement custom VirtualPathProvider which would load the
View from anywhere but my implementation working only in MVC 2.0 and not working wih MVC 3.0, fore some reason method GetFile newer called for not existed views in MVC 3.0 and in that case I am getting "Server Error in '/' Application."

I followed the same code for my custom VirtualPathProvider from here: http://buildstarted.com/2010/09/28/mvc-3-razor-view-engine-without-a-controller/

UPDATE 1

OK i did fix my problem with my custom VirtualPathProvider after i put registration of my custom VirtualPathProvider provider first line in the Application_Start()

    protected void Application_Start()
    {
        //Should be first line before routes and areas registration.
        HostingEnvironment.RegisterVirtualPathProvider(new MyVirtualPathProvider());

        AreaRegistration.RegisterAllAreas();

        RegisterGlobalFilters(GlobalFilters.Filters);
        RegisterRoutes(RouteTable.Routes);
    }

When registration of custom VirtualPathProvider in Global.asax.cs folowing after AreaRegistration.RegisterAllAreas(); or RegisterRoutes(RouteTable.Routes); method method override VirtualFile GetFile(string virtualPath) wont work for "virtual Views".

UPDATE 2

does it means that the classes RazorView and RazorViewEngineRender is the answer?

UPDATE 3

If i have string representation of my razor view which does not exists in the file system (e.g i store razor views in database) how may i render it using this kind of approach http://buildstarted.com/2010/09/28/mvc-3-razor-view-engine-without-a-controller/

For example string representation of my View looks like this:

"@{
    ViewBag.Title = ""About Us"";
}

About

     Put content here.

"

UPDATE 4

Now i see, to be able to use @Html.<something> custom TemplateBase should be implemented.
The sample of implementation of HtmlTemplateBase<T> could be fount here http://www.fidelitydesign.net/?p=239, but it won't work with RazorEngine v2, i am successfully getting template compiled, then after assembly loaded method public override void Execute() won't be executed i am getting an error: The method or operation is not implemented (stacktrace: http://tinypic.com/r/dcow4/7)

To make “public override T Model” happened i did change declaration of “public TModel Model” to “public virtual TModel Model” in “public abstract class TemplateBase : TemplateBase, ITemplate”. May be there is some another changes should be done? Or something in HtmlTemplateBase<T> should be done another way?


来源: stackexchange

问:
Fragment did not create a view
MyFragment.java

```<code>public class MyFragment extends Fragment {
    private onItemSelectedListener listener;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment, container,
                false);
        btn_myButton = (Button) view.findViewById(R.id.btn_new_client);
        btn_myButton .setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                updateDetail("New Layout");
            }
        });
        return view;
    }

    Button btn_myButton;

    public interface onItemSelectedListener {
        public void onItemSelected(String link);
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        if (activity instanceof onItemSelectedListener) {
            listener = (onItemSelectedListener) activity;
        } else {
            throw new ClassCastException(activity.toString()
                    + " must implemenet OnItemSelectedListener");
        }
    }
    public void updateDetail(String s) {
        listener.onItemSelected(s);
    }
}
</code>```

MainActivity.java

```<code>public class MainActivity extends Activity implements
    onItemSelectedListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
    setContentView(R.layout.main_activity);
    super.onCreate(savedInstanceState);
}

public void onItemSelected(String link) {
    FragmentManager manager = getFragmentManager();
    FragmentTransaction transaction = manager.beginTransaction();
    Fragment fragment;
    if ("New Layout".equals(link)) {
        fragment = new Fragment1();
        transaction.replace(R.id.detailFragment, fragment);
        transaction.commit();
    }
}
}
</code>```

Fragment1.java

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

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.newfragmentt, container,
                false);
        return v;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    }
}
</code>```

fragment.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/btn_new_client"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:ems="8"
        android:gravity="center|center_vertical"
        android:padding="2dp"
        android:text="@string/new_client"
        android:textColor="#FFFFFF" >
    </Button>

</LinearLayout>
</code>```

main_activity.xml

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#4B6C9E"
    android:baselineAligned="false"
    android:orientation="horizontal" >

    <fragment
        android:id="@+id/FragmentId"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        class="com.examples.MyProject.MyFragment" >
    </fragment>
    <FrameLayout
        android:id="@+id/detailFragment"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="2" >
    </FrameLayout>

</LinearLayout>
</code>```

LogCat error:

```<code> FATAL EXCEPTION: main
 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.elintsys.iCaseDiary/com.examples.MyProject.MainActivity}: android.view.InflateException: Binary XML file line #8: Error inflating class fragment
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1956)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
    at android.app.ActivityThread.access$600(ActivityThread.java:123)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:137)
    at android.app.ActivityThread.main(ActivityThread.java:4424)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:511)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
    at dalvik.system.NativeStart.main(Native Method)
 Caused by: android.view.InflateException: Binary XML file line #8: Error inflating class fragment
    at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:697)
    at android.view.LayoutInflater.rInflate(LayoutInflater.java:739)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:489)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:396)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:352)
    at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:251)
    at android.app.Activity.setContentView(Activity.java:1862)
    at com.examples.MyProject.MainActivity.onCreate(CaseEntryActivity.java:15)
    at android.app.Activity.performCreate(Activity.java:4492)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
    ... 11 more
 Caused by: java.lang.IllegalStateException: Fragment com.elintsys.iCaseDiary.CaseEntryFragment did not create a view.
    at android.app.Activity.onCreateView(Activity.java:4293)
    at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:673)
    ... 21 more
 Sending signal. PID: 16275 SIG: 9
</code>```

Please help me friends.

答:
In addition to what Mel Stanley said you also need to ensure that you add the android:tag to your xml activity where the fragment is loaded:

```<code><fragment
android:id="@+id/fragment_container"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:name="com.your_app.name.fragments.NameOfFragment"
android:tag="fragment_tag"
tools:layout="@layout/layout_fragment"
/>
</code>```

This ensures that when the fragment is being loaded for the first time using the xml it is not reloaded using Mel's code. If you left this out you would have 2 loads of the fragment on first run - this is a problem if you have asynchronous requests that change the layout upon completion.

ContentLicense: CC BY-SA 3.0

Title: Fragment did not create a view

Body:
MyFragment.java

public class MyFragment extends Fragment {
    private onItemSelectedListener listener;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment, container,
                false);
        btn_myButton = (Button) view.findViewById(R.id.btn_new_client);
        btn_myButton .setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                updateDetail("New Layout");
            }
        });
        return view;
    }

    Button btn_myButton;

    public interface onItemSelectedListener {
        public void onItemSelected(String link);
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        if (activity instanceof onItemSelectedListener) {
            listener = (onItemSelectedListener) activity;
        } else {
            throw new ClassCastException(activity.toString()
                    + " must implemenet OnItemSelectedListener");
        }
    }
    public void updateDetail(String s) {
        listener.onItemSelected(s);
    }
}

MainActivity.java

public class MainActivity extends Activity implements
    onItemSelectedListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
    setContentView(R.layout.main_activity);
    super.onCreate(savedInstanceState);
}

public void onItemSelected(String link) {
    FragmentManager manager = getFragmentManager();
    FragmentTransaction transaction = manager.beginTransaction();
    Fragment fragment;
    if ("New Layout".equals(link)) {
        fragment = new Fragment1();
        transaction.replace(R.id.detailFragment, fragment);
        transaction.commit();
    }
}
}

Fragment1.java

public class Fragment1 extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.newfragmentt, container,
                false);
        return v;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    }
}

fragment.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/btn_new_client"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:ems="8"
        android:gravity="center|center_vertical"
        android:padding="2dp"
        android:text="@string/new_client"
        android:textColor="#FFFFFF" >
    </Button>

</LinearLayout>

main_activity.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#4B6C9E"
    android:baselineAligned="false"
    android:orientation="horizontal" >

    <fragment
        android:id="@+id/FragmentId"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        class="com.examples.MyProject.MyFragment" >
    </fragment>
    <FrameLayout
        android:id="@+id/detailFragment"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="2" >
    </FrameLayout>

</LinearLayout>

LogCat error:

 FATAL EXCEPTION: main
 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.elintsys.iCaseDiary/com.examples.MyProject.MainActivity}: android.view.InflateException: Binary XML file line #8: Error inflating class fragment
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1956)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
    at android.app.ActivityThread.access$600(ActivityThread.java:123)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:137)
    at android.app.ActivityThread.main(ActivityThread.java:4424)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:511)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
    at dalvik.system.NativeStart.main(Native Method)
 Caused by: android.view.InflateException: Binary XML file line #8: Error inflating class fragment
    at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:697)
    at android.view.LayoutInflater.rInflate(LayoutInflater.java:739)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:489)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:396)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:352)
    at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:251)
    at android.app.Activity.setContentView(Activity.java:1862)
    at com.examples.MyProject.MainActivity.onCreate(CaseEntryActivity.java:15)
    at android.app.Activity.performCreate(Activity.java:4492)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
    ... 11 more
 Caused by: java.lang.IllegalStateException: Fragment com.elintsys.iCaseDiary.CaseEntryFragment did not create a view.
    at android.app.Activity.onCreateView(Activity.java:4293)
    at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:673)
    ... 21 more
 Sending signal. PID: 16275 SIG: 9

Please help me friends.

Body:
In addition to what Mel Stanley said you also need to ensure that you add the android:tag to your xml activity where the fragment is loaded:

<fragment
android:id="@+id/fragment_container"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:name="com.your_app.name.fragments.NameOfFragment"
android:tag="fragment_tag"
tools:layout="@layout/layout_fragment"
/>

This ensures that when the fragment is being loaded for the first time using the xml it is not reloaded using Mel's code. If you left this out you would have 2 loads of the fragment on first run - this is a problem if you have asynchronous requests that change the layout upon completion.


问:
Can't load native shared library with dependencies in a native activity app
In my Android app I have 4 libraries:

```<code>libTemplate.so
   depends on libPorkholt.so
libPorkholt.so
   depends on libpng15.so
   depends on liblua.so
   depends on libopenal.so
libpng15.so
liblua.so
libopenal.so
</code>```

If I write a small command line executable that links against libTemplate and manually call ANativeActivity_onCreate, it links and runs just fine (if I point LD_LIBRARY_PATH to /data/data/com.mycompany.Template/lib)

If I run my app I get this very useful error message:

```<code>E/AndroidRuntime(13214): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.mycompany.Template/android.app.NativeActivity}: java.lang.IllegalArgumentException: Unable to load native library: /data/data/com.mycompany.Template/lib/libTemplate.so
</code>```

It doesn't even enter ANativeActivity_onCreate, so my only guess is that's it has something to do with linking

I should probably mention that I'm using CMake with this script: http://code.google.com/p/android-cmake/ to build the libraries myself (without ndk-build). I managed to compile the native-activity sample with it, so I know it works.

Also, I made sure no library contains a version number in its soname

My manifest:

```<code><?xml version="1.0" encoding="utf-8"?>
<!-- BEGIN_INCLUDE(manifest) -->
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="com.mycompany.Template"
        android:versionCode="1"
        android:versionName="1.0">

    <!-- This is the platform API where NativeActivity was introduced. -->
    <uses-sdk android:minSdkVersion="9" />

    <!-- This .apk has no Java code itself, so set hasCode to false. -->
    <application android:label="Template Porkholt project" android:hasCode="false">

        <!-- Our activity is the built-in NativeActivity framework class.
             This will take care of integrating with our NDK code. -->
        <activity android:name="android.app.NativeActivity"
                android:label="Template Porkholt project"
                android:configChanges="orientation|keyboardHidden">
            <!-- Tell NativeActivity the name of or .so -->
            <meta-data android:name="android.app.lib_name"
                    android:value="Template" />
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
<!-- END_INCLUDE(manifest) -->
</code>```

答: This no longer affects API 24+ (see the framework fix here). However, if you need to support older versions, extend NativeActivity, refer to your extension in the manifest file instead, and add the static block mentioned in Sdra's answer as workaround.

Body:
In my Android app I have 4 libraries:

libTemplate.so
   depends on libPorkholt.so
libPorkholt.so
   depends on libpng15.so
   depends on liblua.so
   depends on libopenal.so
libpng15.so
liblua.so
libopenal.so

If I write a small command line executable that links against libTemplate and manually call ANativeActivity_onCreate, it links and runs just fine (if I point LD_LIBRARY_PATH to /data/data/com.mycompany.Template/lib)

If I run my app I get this very useful error message:

E/AndroidRuntime(13214): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.mycompany.Template/android.app.NativeActivity}: java.lang.IllegalArgumentException: Unable to load native library: /data/data/com.mycompany.Template/lib/libTemplate.so

It doesn't even enter ANativeActivity_onCreate, so my only guess is that's it has something to do with linking

I should probably mention that I'm using CMake with this script: http://code.google.com/p/android-cmake/ to build the libraries myself (without ndk-build). I managed to compile the native-activity sample with it, so I know it works.

Also, I made sure no library contains a version number in its soname

My manifest:

<?xml version="1.0" encoding="utf-8"?>

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="com.mycompany.Template"
        android:versionCode="1"
        android:versionName="1.0">

    <uses-sdk android:minSdkVersion="9" />

    <application android:label="Template Porkholt project" android:hasCode="false">

        <activity android:name="android.app.NativeActivity"
                android:label="Template Porkholt project"
                android:configChanges="orientation|keyboardHidden">

            <meta-data android:name="android.app.lib_name"
                    android:value="Template" />
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>


问:
List assignment index out of range when deleting columns in a nested list
I have a nested list with a couple of things in each list. It looks something like this:

```<code>itemsOnShelf=[[3,5,6,8],
              [2,3,7,3],
              [4,2,2,3]]
</code>```

Each column belongs to an item, for example column one/position 0 is potatoes.
In my program I have a function to add all the items for each column and save them into variables, for example potatoes=9

I also have a list where I saved these variables, it looks like this:

food=[potatoes, tomatoes, apples, peaches]

I also have a function that will delete a column if the sum of items in it is smaller than a specific number, for example 11.

```<code>minimumNumberAllowed=11
smallestNumber=[]

def throwAway(thing,pos):
   for item in smallestNumber:
    if item==thing:
        for shelf in itemsOnShelf:
            for veg in shelf:
                del shelf[pos]
                print(itemsOnShelf)
</code>```

Next I have a bit of code that goes like this:

```<code>for item in food:
       if item < minimumNumberAllowed:
              smallestNumber.append(min(food))
              print(smallestNumber)
              for item in smallestNumber:
               throwAway(potatoes,0)
               throwAway(tomatoes,1)
               throwAway(apples,2)
               throwAway(peaches,3)
</code>```

The idea is that one column (item) will be deleted if there is too few of it. My problem is that once one column is deleted, I get a "list assignment index out of range" error because now there are fewer columns and therefore column number 3 will not exist. This is a problem that prevents me from moving forward in my coding. I tried using while len(itemsOnShelf)<=3 or with other numbers but what it does is it stops before the column is deleted so I receive an unchanged list. How do I fix this index out of range error so the record deletes and the index corrects itself?

edit: I cannot manually delete the columns because the number of items in the main list can be changed so I do not always control which column needs to be deleted.

答:
With a list of dicts you could handle your data and call them by their key name. Now after removing a value, you don't know anymore what exists in any position.

Your existing data:

```<code>itemsOnShelf = [[3,5,6,8],
               [2,3,7,3],
               [4,2,2,3]]
food=['potatoes', 'tomatoes', 'apples', 'peaches']
</code>```

can be modified to a list of dicts:

```<code>m = [dict(zip(food, i)) for i in itemsOnShelf]
print(m)

[{'tomatoes': 5, 'peaches': 8, 'apples': 6, 'potatoes': 3},
 {'tomatoes': 3, 'peaches': 3, 'apples': 7, 'potatoes': 2},
 {'tomatoes': 2, 'peaches': 3, 'apples': 2, 'potatoes': 4}]
</code>```

you could get the sum for every food-key like this:

```<code>total = {k: sum(i[k] for i in m) for k in m[0]}
print(total)

{'tomatoes': 10, 'potatoes': 9, 'apples': 15, 'peaches': 14}
</code>```

and you could remove items for all dicts when sum is less than minimum allowed:

```<code>for i in m:
    for k in total:
        if total[k]<11:
            i.pop(k)
print(m)

[{'peaches': 8, 'apples': 6},
 {'peaches': 3, 'apples': 7},
 {'peaches': 3, 'apples': 2}]
</code>```

Body:
I have a nested list with a couple of things in each list. It looks something like this:

itemsOnShelf=[[3,5,6,8],
              [2,3,7,3],
              [4,2,2,3]]

Each column belongs to an item, for example column one/position 0 is potatoes.
In my program I have a function to add all the items for each column and save them into variables, for example potatoes=9

I also have a list where I saved these variables, it looks like this:

food=[potatoes, tomatoes, apples, peaches]

I also have a function that will delete a column if the sum of items in it is smaller than a specific number, for example 11.

minimumNumberAllowed=11
smallestNumber=[]

def throwAway(thing,pos):
   for item in smallestNumber:
    if item==thing:
        for shelf in itemsOnShelf:
            for veg in shelf:
                del shelf[pos]
                print(itemsOnShelf)

Next I have a bit of code that goes like this:

for item in food:
       if item < minimumNumberAllowed:
              smallestNumber.append(min(food))
              print(smallestNumber)
              for item in smallestNumber:
               throwAway(potatoes,0)
               throwAway(tomatoes,1)
               throwAway(apples,2)
               throwAway(peaches,3)

The idea is that one column (item) will be deleted if there is too few of it. My problem is that once one column is deleted, I get a "list assignment index out of range" error because now there are fewer columns and therefore column number 3 will not exist. This is a problem that prevents me from moving forward in my coding. I tried using while len(itemsOnShelf)<=3 or with other numbers but what it does is it stops before the column is deleted so I receive an unchanged list. How do I fix this index out of range error so the record deletes and the index corrects itself?

edit: I cannot manually delete the columns because the number of items in the main list can be changed so I do not always control which column needs to be deleted.

Body:
With a list of dicts you could handle your data and call them by their key name. Now after removing a value, you don't know anymore what exists in any position.

Your existing data:

itemsOnShelf = [[3,5,6,8],
               [2,3,7,3],
               [4,2,2,3]]
food=['potatoes', 'tomatoes', 'apples', 'peaches']

can be modified to a list of dicts:

m = [dict(zip(food, i)) for i in itemsOnShelf]
print(m)

[{'tomatoes': 5, 'peaches': 8, 'apples': 6, 'potatoes': 3},
 {'tomatoes': 3, 'peaches': 3, 'apples': 7, 'potatoes': 2},
 {'tomatoes': 2, 'peaches': 3, 'apples': 2, 'potatoes': 4}]

you could get the sum for every food-key like this:

total = {k: sum(i[k] for i in m) for k in m[0]}
print(total)

{'tomatoes': 10, 'potatoes': 9, 'apples': 15, 'peaches': 14}

and you could remove items for all dicts when sum is less than minimum allowed:

for i in m:
    for k in total:
        if total[k]<11:
            i.pop(k)
print(m)

[{'peaches': 8, 'apples': 6},
 {'peaches': 3, 'apples': 7},
 {'peaches': 3, 'apples': 2}]


问:
SqlAlchemy ORM - restricting columns at query time (select) - column_property
I know I can lazy load columns from a table:

```<code>session.query(MyTable).options(defer(colname)
      for colname in ['col4', 'col5', ..,  'colN'])
</code>```

I only want the first 3 columns, so can shorten that to the following:

```<code>session.query(MyTable).options(defer(col.name)
      for col.name in MyTable.__table__.columns
      if col.name not in ['col1', 'col2', 'col3'])
</code>```

Because MyTable has a few extra column_propertys which aren't listed in MyTable.__table__.columns, these get included in the query even though I don't want them.

So is there a construct to express what I want directly as a restriction?
e.g. something like

```<code>session.query(MyTable).options(XXselect('col1', 'col2', 'col3'))
</code>```

答:
load_only() function can be used for this

An arbitrary set of columns can be selected as “load only” columns, which will be loaded while deferring all other columns on a given entity, using orm.load_only():

```<code>from sqlalchemy.orm import load_only

session.query(Book).options(load_only("summary", "excerpt"))
</code>```

Body:
I know I can lazy load columns from a table:

session.query(MyTable).options(defer(colname)
      for colname in ['col4', 'col5', ..,  'colN'])

I only want the first 3 columns, so can shorten that to the following:

session.query(MyTable).options(defer(col.name)
      for col.name in MyTable.__table__.columns
      if col.name not in ['col1', 'col2', 'col3'])

Because MyTable has a few extra column_propertys which aren't listed in MyTable.__table__.columns, these get included in the query even though I don't want them.

So is there a construct to express what I want directly as a restriction?
e.g. something like

session.query(MyTable).options(XXselect('col1', 'col2', 'col3'))

Body:
load_only() function can be used for this

An arbitrary set of columns can be selected as “load only” columns, which will be loaded while deferring all other columns on a given entity, using orm.load_only():

from sqlalchemy.orm import load_only

session.query(Book).options(load_only("summary", "excerpt"))


问:
How to setup Angular REST api with ClientHttp for JSON object from form inputs?
I'm struggling with the .post payload and getting a 400 error that "The request contains no valid record sets."  I want to post to a Postgres DB.  Here is my payload that is being sent to the server.  It is a string in JSON format.  It is being rejected.  I'm a noob to REST and learning JS, Angular, etc.

```<code>{"resource":[{"first_name":"John","last_name":"Johnson","main_skill_title":"Application developer - frontend","main_skills":"Angular,JavaScript",,"country":"United States","email":"j@j.com"}]}
</code>```

The URL is setup as the DreamFactory middleware recommends in their API Docs, in this case with the error message in the console:

```<code>http://localhost:8080/api/v2/pfpsql/_table/members 400 (Bad Request)
</code>```

DreamFactory middleware provides examples for Angular 2 but they were mostly written during the RC stage of Angular development and outdated.  Also, the code doesn't follow the Style Guide.

I've succeeded with .get.  This code works fine and populates Angular Material2 DataTable with data I manually entered into the db.

GET in the component:

```<code>constructor(private http: HttpClient) {}

  ngAfterViewInit() {
    this.membersAdminService = new MembersAdminService(this.http);

    // This is for the Material2 DataTable.
    Observable.merge(this.paginator.page)
      .startWith(null)  // Delete this and no data is downloaded.
      .switchMap(() => {
        return this.membersAdminService.getMembers(
          this.paginator.pageIndex);
      })
      .map(data => {
        return data.resource;  // Change from json to array data.
      })
      .subscribe(data => {
        this.dataLength = data.length;
        this.dataSource.data = data;
      });
  }
</code>```

GET in the service:

```<code> constructor(
    private http: HttpClient,
  ) { }

  public getMembers(page: number): Observable<DfApi> {
    return this.http.get<DfApi>(this.baseUrl, {headers: this.headers});
  }
</code>```

The issue is the payload for a .post.  I've used this code as a base and tried a variety of Observable operators and HttpClient suggestions from various sources but nothing has added a member to the db.  I'm clearly on the wrong track but where?  The data package from this code is listed in the beginning of this post.

POST in the service:

```<code>public addMember(memberData) {
    this.http.post(this.baseUrl, memberData, {headers: this.headers})
</code>```

POST in the component:

```<code>save(addMemberForm) {
    const enteredData = this.addMemberForm.addEditMemberForm.value;
    const memberData = JSON.stringify(enteredData);
    const jsonData = '{"resource": [' + memberData + ']}';
    this.membersAdminService.addMember(jsonData);
  }
</code>```

答:
I needed to put the data in an array format with JSON.parse.  The json string wasn't accepted.  I also had a couple of other db setup problems to fix.  I can't forget that Postgres likes snake case, first_name, and not camel case, firstName.  However, I don't think this code is as concise as it should be.  It looks like a hack.  I'm very open to other suggestions!</p>

```<code>save(addMemberForm) {
    const enteredData = this.addMemberForm.addEditMemberForm.value;
      // Result is JS object

    const memberData = JSON.stringify(enteredData);
      // Result is a string instead.

    const jsonData = '{"resource": [' + memberData + ']}';
      // Result is a string in JSON format in DreamFactory required format with {"resource": [

    const jsonArray = JSON.parse(jsonData);
      // Result is an array in JSON format.

    this.membersAdminService.addMember(jsonArray);  // I should be subscribing here, not in the service.
    addMemberForm.addEditMemberForm.reset();
    this.success();
  }
</code>```

Body:
I'm struggling with the .post payload and getting a 400 error that "The request contains no valid record sets."  I want to post to a Postgres DB.  Here is my payload that is being sent to the server.  It is a string in JSON format.  It is being rejected.  I'm a noob to REST and learning JS, Angular, etc.

{"resource":[{"first_name":"John","last_name":"Johnson","main_skill_title":"Application developer - frontend","main_skills":"Angular,JavaScript",,"country":"United States","email":"j@j.com"}]}

The URL is setup as the DreamFactory middleware recommends in their API Docs, in this case with the error message in the console:

http://localhost:8080/api/v2/pfpsql/_table/members 400 (Bad Request)

DreamFactory middleware provides examples for Angular 2 but they were mostly written during the RC stage of Angular development and outdated.  Also, the code doesn't follow the Style Guide.

I've succeeded with .get.  This code works fine and populates Angular Material2 DataTable with data I manually entered into the db.

GET in the component:

constructor(private http: HttpClient) {}

  ngAfterViewInit() {
    this.membersAdminService = new MembersAdminService(this.http);

    // This is for the Material2 DataTable.
    Observable.merge(this.paginator.page)
      .startWith(null)  // Delete this and no data is downloaded.
      .switchMap(() => {
        return this.membersAdminService.getMembers(
          this.paginator.pageIndex);
      })
      .map(data => {
        return data.resource;  // Change from json to array data.
      })
      .subscribe(data => {
        this.dataLength = data.length;
        this.dataSource.data = data;
      });
  }

GET in the service:

 constructor(
    private http: HttpClient,
  ) { }

  public getMembers(page: number): Observable<DfApi> {
    return this.http.get<DfApi>(this.baseUrl, {headers: this.headers});
  }

The issue is the payload for a .post.  I've used this code as a base and tried a variety of Observable operators and HttpClient suggestions from various sources but nothing has added a member to the db.  I'm clearly on the wrong track but where?  The data package from this code is listed in the beginning of this post.

POST in the service:

public addMember(memberData) {
    this.http.post(this.baseUrl, memberData, {headers: this.headers})

POST in the component:

save(addMemberForm) {
    const enteredData = this.addMemberForm.addEditMemberForm.value;
    const memberData = JSON.stringify(enteredData);
    const jsonData = '{"resource": [' + memberData + ']}';
    this.membersAdminService.addMember(jsonData);
  }

Body:
I needed to put the data in an array format with JSON.parse.  The json string wasn't accepted.  I also had a couple of other db setup problems to fix.  I can't forget that Postgres likes snake case, first_name, and not camel case, firstName.  However, I don't think this code is as concise as it should be.  It looks like a hack.  I'm very open to other suggestions!

save(addMemberForm) {
    const enteredData = this.addMemberForm.addEditMemberForm.value;
      // Result is JS object

    const memberData = JSON.stringify(enteredData);
      // Result is a string instead.

    const jsonData = '{"resource": [' + memberData + ']}';
      // Result is a string in JSON format in DreamFactory required format with {"resource": [

    const jsonArray = JSON.parse(jsonData);
      // Result is an array in JSON format.

    this.membersAdminService.addMember(jsonArray);  // I should be subscribing here, not in the service.
    addMemberForm.addEditMemberForm.reset();
    this.success();
  }


问:
Rails nested form attribute not showing up in form
I have two models a permit and vehicle model. The vehicle table has a foreign key of the permit_id. I am trying to input the permit_id into vehicle table where the inputted license_number on the form equals to the license_number (which is not the primary key) in the vehicle table.

vehicle.rb

```<code>class Vehicle < ApplicationRecord
self.primary_key = :vehicle_id
belongs_to  :permit, optional: true
</code>```

permit.rb

```<code>class Permit < ApplicationRecord
self.primary_key = :permit_id
has_one :vehicle
accepts_nested_attributes_for :vehicle
</code>```

permits_controller.rb

```<code>class PermitsController < ApplicationController
...
def new
  @permit = Permit.new
  @vehicle = @permit.build_vehicle
end
params.require(:permit).permit(:permit_id.,...,vehicle_attributes: [:license_number])
</code>```

permit form

```<code><%= form_with(model: permit, local: true) do |form| %>
...
<div class="field">
  <% form.fields_for :vehicle do |f| %>
    License:
    <%= f.text_field :license_number, id: :vehicle_license_number %>
  <% end %>
</div>
</code>```

My first problem is that my nested attribute license_number is not showing up at all in my field. I can see the div in the chrome elements, but the text field is not showing up. My second issue is how do I search in the vehicle table where license_number equals the license number inputted and then put the permit_id into the same row?

答:
I don't know what causes your first issue, but you should leave the id: :vehicle_license_number part out and add an actual label with f.label.

To find the vehicle you could use vehicle = Vehicle.find_by(license_number: permitted_params[:vehicle_attributes][:license_number] and then save it using @permit.update(vehicle: vehicle). That being said, I don't think you need to use filed_for and accepts_nested_attributes_for.

Body:
I have two models a permit and vehicle model. The vehicle table has a foreign key of the permit_id. I am trying to input the permit_id into vehicle table where the inputted license_number on the form equals to the license_number (which is not the primary key) in the vehicle table.

vehicle.rb

class Vehicle < ApplicationRecord
self.primary_key = :vehicle_id
belongs_to  :permit, optional: true

permit.rb

class Permit < ApplicationRecord
self.primary_key = :permit_id
has_one :vehicle
accepts_nested_attributes_for :vehicle

permits_controller.rb

class PermitsController < ApplicationController
...
def new
  @permit = Permit.new
  @vehicle = @permit.build_vehicle
end
params.require(:permit).permit(:permit_id.,...,vehicle_attributes: [:license_number])

permit form

<%= form_with(model: permit, local: true) do |form| %>
...

  <% form.fields_for :vehicle do |f| %>
    License:
    <%= f.text_field :license_number, id: :vehicle_license_number %>
  <% end %>

My first problem is that my nested attribute license_number is not showing up at all in my field. I can see the div in the chrome elements, but the text field is not showing up. My second issue is how do I search in the vehicle table where license_number equals the license number inputted and then put the permit_id into the same row?


问:
avoid hacks to properly bind to class in ES6?
I find this rather cumbersome. I probably am doing it wrong or there is some easier way I'm unaware of (did not find much w/o knowing what to search for).

I want to avoid doing the following two workarounds to ensure this is correctly pointing to the DB class inside my methods:

```<code>this.connect = this.connect.bind(this);
db.connect.bind(db)
</code>```

DB class:

```<code>'use strict';

const http = require('http');
const MongoClient = require('mongodb').MongoClient;

class DB {
  constructor(opts){
    this.opts = opts;
    this.dbUrl = process.env.MONGODB_URL;

    // anyway to avoid this hacK?
    this.connect = this.connect.bind(this);
    this.close = this.close.bind(this)
  }

  async connect(ctx, next){
    try {
      ctx.db = await MongoClient.connect(this.dbUrl); // fixes `this` being incorrect here
    } catch(err) {
      ctx.status = 500;
      ctx.body = err.message || http.STATUS_CODES[ctx.status];
    }

    await next();
  }

  async close(ctx, next){
    const result = await ctx.db.close();
    await next();
  }
}

module.exports = DB;
</code>```

Calling the DB class method db.connect():

```<code>'use strict';

const Koa = require('koa');
const DB = require('./db');
const db = new DB();
const bodyParser = require('koa-bodyparser');
const router = require('koa-router');

const api = router();
const app = new Koa();
const cors = require('kcors');

app
  .use(bodyParser())
  .use(cors())
  .use(db.connect); // the above constructor copying fixes having to do `db.connect.bind(db)` here

  // without the constructor fix in class DB:

  .use(db.connect.bind(db)) // this gets annoying having to do this everywhere
</code>```

Which is more "correct" or if there is a 3rd way which avoids both of these workarounds? Also what are the pros and cons of each if these are the only two ways to bind class methods to their class.

答:
There is a series of helpful auto binding functions. I wrote one just today to improve on them. Take a look: https://www.npmjs.com/package/auto-bind-inheritance

npm install --save auto-bind-inheritance

const autoBind = require('auto-bind-inheritance');

Just put autoBind(this); in the child class constructor and all methods and method pointers will be bound to the object, just like you would expect in C++/Java. This basically calls bind for you.

So, if you have trouble using methods as callbacks that get bound to another 'this', this package will fix it.

Body:
I find this rather cumbersome. I probably am doing it wrong or there is some easier way I'm unaware of (did not find much w/o knowing what to search for).

I want to avoid doing the following two workarounds to ensure this is correctly pointing to the DB class inside my methods:

this.connect = this.connect.bind(this);
db.connect.bind(db)

DB class:

'use strict';

const http = require('http');
const MongoClient = require('mongodb').MongoClient;

class DB {
  constructor(opts){
    this.opts = opts;
    this.dbUrl = process.env.MONGODB_URL;

    // anyway to avoid this hacK?
    this.connect = this.connect.bind(this);
    this.close = this.close.bind(this)
  }

  async connect(ctx, next){
    try {
      ctx.db = await MongoClient.connect(this.dbUrl); // fixes `this` being incorrect here
    } catch(err) {
      ctx.status = 500;
      ctx.body = err.message || http.STATUS_CODES[ctx.status];
    }

    await next();
  }

  async close(ctx, next){
    const result = await ctx.db.close();
    await next();
  }
}

module.exports = DB;

Calling the DB class method db.connect():

'use strict';

const Koa = require('koa');
const DB = require('./db');
const db = new DB();
const bodyParser = require('koa-bodyparser');
const router = require('koa-router');

const api = router();
const app = new Koa();
const cors = require('kcors');

app
  .use(bodyParser())
  .use(cors())
  .use(db.connect); // the above constructor copying fixes having to do `db.connect.bind(db)` here

  // without the constructor fix in class DB:

  .use(db.connect.bind(db)) // this gets annoying having to do this everywhere

Which is more "correct" or if there is a 3rd way which avoids both of these workarounds? Also what are the pros and cons of each if these are the only two ways to bind class methods to their class.


问:
How to normalize circle sizes in R
I have a data set as follows and am creating a bubbleplot using symbols, with the Z column used as bubble size:

```<code> X       Y      Z       TITLE
151.2  31.5    51023     xyz
160.2  51.8    4912      xyz
191.7  2.1     874201    abc

radius <- sqrt(data$z/pi)
symbols(data$x,data$y,circles=radius,inches=0.35,
cex.axis=1.5,cex.lab=1.5,xlab="xlab", ylab="ylab")
</code>```

I then would like to have a second bubbleplot with any Title of "abc" removed. However, when I do this, the bubbles then resize themselves in comparison to the original plot. How can I normalize bubble size between plots?

答:
Try something like

```<code>data$radius <- sqrt(data$Z/pi)/50
with(data[data$TITLE != "abc",],
     symbols(x = X, y = Y, circles = radius,
             inches = FALSE, asp = 1,
             xlim = c(140, 240), ylim = c(-10, 60)))
</code>```

and

```<code>with(data,
     symbols(x = X, y = Y, circles = radius,
             inches = FALSE, asp = 1,
             xlim = c(140, 240), ylim = c(-10, 60)))
</code>```

If you specify inches = 0.35, the circles are scaled to make largest circle dimension 0.35 inches. Read more at ?symbols

Title: How to normalize circle sizes in R

Body:
I have a data set as follows and am creating a bubbleplot using symbols, with the Z column used as bubble size:

 X       Y      Z       TITLE
151.2  31.5    51023     xyz
160.2  51.8    4912      xyz
191.7  2.1     874201    abc

radius <- sqrt(data$z/pi)
symbols(data$x,data$y,circles=radius,inches=0.35,
cex.axis=1.5,cex.lab=1.5,xlab="xlab", ylab="ylab")

I then would like to have a second bubbleplot with any Title of "abc" removed. However, when I do this, the bubbles then resize themselves in comparison to the original plot. How can I normalize bubble size between plots?

Body:
Try something like

data$radius <- sqrt(data$Z/pi)/50
with(data[data$TITLE != "abc",],
     symbols(x = X, y = Y, circles = radius,
             inches = FALSE, asp = 1,
             xlim = c(140, 240), ylim = c(-10, 60)))

and

with(data,
     symbols(x = X, y = Y, circles = radius,
             inches = FALSE, asp = 1,
             xlim = c(140, 240), ylim = c(-10, 60)))

If you specify inches = 0.35, the circles are scaled to make largest circle dimension 0.35 inches. Read more at ?symbols


问:
Whitespace Matching Regex - Java
The Java API for regular expressions states that \s will match whitespace. So the regex \\s\\s should match two spaces.

```<code>Pattern whitespace = Pattern.compile("\\s\\s");
matcher = whitespace.matcher(modLine);
while (matcher.find()) matcher.replaceAll(" ");
</code>```

The aim of this is to replace all instances of two consecutive whitespace with a single space. However this does not actually work.

Am I having a grave misunderstanding of regexes or the term "whitespace"?

答:
Use of whitespace in RE is a pain, but I believe they work. The OP's problem can also be solved using StringTokenizer or the split() method. However, to use RE (uncomment the println() to view how the matcher is breaking up the String), here is a sample code:

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

public class Two21WS {
    private String  str = "";
    private Pattern pattern = Pattern.compile ("\\s{2,}");  // multiple spaces

    public Two21WS (String s) {
            StringBuffer sb = new StringBuffer();
            Matcher matcher = pattern.matcher (s);
            int startNext = 0;
            while (matcher.find (startNext)) {
                    if (startNext == 0)
                            sb.append (s.substring (0, matcher.start()));
                    else
                            sb.append (s.substring (startNext, matcher.start()));
                    sb.append (" ");
                    startNext = matcher.end();
                    //System.out.println ("Start, end = " + matcher.start()+", "+matcher.end() +
                    //                      ", sb: \"" + sb.toString() + "\"");
            }
            sb.append (s.substring (startNext));
            str = sb.toString();
    }

    public String toString () {
            return str;
    }

    public static void main (String[] args) {
            String tester = " a    b      cdef     gh  ij   kl";
            System.out.println ("Initial: \"" + tester + "\"");
            System.out.println ("Two21WS: \"" + new Two21WS(tester) + "\"");
}}
</code>```

It produces the following (compile with javac and run at the command prompt):

% java Two21WS
Initial: " a    b      cdef     gh  ij   kl"
Two21WS: " a b cdef gh ij kl"

Title: Whitespace Matching Regex - Java

Body:
The Java API for regular expressions states that \s will match whitespace. So the regex \\s\\s should match two spaces.

Pattern whitespace = Pattern.compile("\\s\\s");
matcher = whitespace.matcher(modLine);
while (matcher.find()) matcher.replaceAll(" ");

The aim of this is to replace all instances of two consecutive whitespace with a single space. However this does not actually work.

Am I having a grave misunderstanding of regexes or the term "whitespace"?

Body:
Use of whitespace in RE is a pain, but I believe they work. The OP's problem can also be solved using StringTokenizer or the split() method. However, to use RE (uncomment the println() to view how the matcher is breaking up the String), here is a sample code:

import java.util.regex.*;

public class Two21WS {
    private String  str = "";
    private Pattern pattern = Pattern.compile ("\\s{2,}");  // multiple spaces

    public Two21WS (String s) {
            StringBuffer sb = new StringBuffer();
            Matcher matcher = pattern.matcher (s);
            int startNext = 0;
            while (matcher.find (startNext)) {
                    if (startNext == 0)
                            sb.append (s.substring (0, matcher.start()));
                    else
                            sb.append (s.substring (startNext, matcher.start()));
                    sb.append (" ");
                    startNext = matcher.end();
                    //System.out.println ("Start, end = " + matcher.start()+", "+matcher.end() +
                    //                      ", sb: \"" + sb.toString() + "\"");
            }
            sb.append (s.substring (startNext));
            str = sb.toString();
    }

    public String toString () {
            return str;
    }

    public static void main (String[] args) {
            String tester = " a    b      cdef     gh  ij   kl";
            System.out.println ("Initial: \"" + tester + "\"");
            System.out.println ("Two21WS: \"" + new Two21WS(tester) + "\"");
}}

It produces the following (compile with javac and run at the command prompt):

% java Two21WS
Initial: " a    b      cdef     gh  ij   kl"
Two21WS: " a b cdef gh ij kl"

ContentLicense: CC BY-SA 2.5


问:
How to call a function a certain time after a web service has been called?
How to call a function a certain time after a web service has been called?

I need to check if a request has been accepted 30s after the request has been created, something like that:

```<code>public function create_request(Request $request)
{
    $user_id = $request->id;

    $validator = Validator::make(
        $request->all(),
        array(
            'request_id' => 'required|numeric|exists:requests,id,user_id,' . $user_id,
        ));

    // Create Request
    $requests = new Requests;
    $requests->user_id = $user_id;

    if ($request->service_type)
        $requests->request_type = $request->service_type;

    $requests->status = REQUEST_NEW;
    $requests->confirmed_provider = $request->provider_id;
    $requests->request_start_time = date("Y-m-d H:i:s");
    $requests->s_address = $request->s_address ? $request->s_address : "";

    if ($request->s_latitude) {
        $requests->s_latitude = $request->s_latitude;
    }
    if ($request->s_longitude) {
        $requests->s_longitude = $request->s_longitude;
    }

    $requests->save();

    sleep(30);

    $request = Requests::where('id', '=', $request->request_id)->first();

    if ($request['provider_status'] == 0) {
        Requests::where('id', '=', $request['id'])->delete();
        $response_array = array('success' => true , 'message' => Helper::get_message(121));
    } else {
        $response_array = array('success' => false, 'error' => Helper::get_error_message(161), 'error_code' => 132);
    }

    return response()->json($response_array, 200);

}
</code>```

The problem with this approach is that the sleep function (sleep(30);) is causing the web service response (return response()->json($response_array, 200);) to be delayed too.

I was expecting something similar to setTimeout(function(){ alert("Hello"); }, 30000); in Javascript

答:
That works in JavaScript because it's asynchronous, PHP is executed fully before sending the content; just like you said - this will delay the page load time.

I think you should look into web sockets, I feel they could accomplish this task more efficiently.

I also think you're thinking a certain direction and now you're stuck that way. Take the example you're sending the client a trade and you're giving them 30s to offer. You could write the initial date of trade creation in your database, then on your AJAX call to accept the trade, verify if the current time is within the 30-second time frame using the date you saved in your database. This makes the system a lot more streamlined as you won't have any processes constantly being used by your server for each trade.

TL;DR: Look into web-sockets or a more streamlined architecture.

Body:
How to call a function a certain time after a web service has been called?

I need to check if a request has been accepted 30s after the request has been created, something like that:

public function create_request(Request $request)
{
    $user_id = $request->id;

    $validator = Validator::make(
        $request->all(),
        array(
            'request_id' => 'required|numeric|exists:requests,id,user_id,' . $user_id,
        ));

    // Create Request
    $requests = new Requests;
    $requests->user_id = $user_id;

    if ($request->service_type)
        $requests->request_type = $request->service_type;

    $requests->status = REQUEST_NEW;
    $requests->confirmed_provider = $request->provider_id;
    $requests->request_start_time = date("Y-m-d H:i:s");
    $requests->s_address = $request->s_address ? $request->s_address : "";

    if ($request->s_latitude) {
        $requests->s_latitude = $request->s_latitude;
    }
    if ($request->s_longitude) {
        $requests->s_longitude = $request->s_longitude;
    }

    $requests->save();

    sleep(30);

    $request = Requests::where('id', '=', $request->request_id)->first();

    if ($request['provider_status'] == 0) {
        Requests::where('id', '=', $request['id'])->delete();
        $response_array = array('success' => true , 'message' => Helper::get_message(121));
    } else {
        $response_array = array('success' => false, 'error' => Helper::get_error_message(161), 'error_code' => 132);
    }

    return response()->json($response_array, 200);

}

The problem with this approach is that the sleep function (sleep(30);) is causing the web service response (return response()->json($response_array, 200);) to be delayed too.

I was expecting something similar to setTimeout(function(){ alert("Hello"); }, 30000); in Javascript


问:
Pushing to Git returning Error Code 403 fatal
I want to push README.md to Github.

Using Ubuntu 14.04LTS

So, I commit in the following steps.

```<code>echo "# test" >> README.md
git init
git add README.md
git commit -m "first commit"
git remote add origin https://github.com/user/repo.git
git push -u origin master
</code>```

But, below error occurred.

```<code>error: The requested URL returned error: 403 Forbidden while accessing https://github.com/user/repo.git/info/refs

fatal: HTTP request failed
</code>```

I know solve this error this way

```<code>git remote set-url origin https://username@github.com/user/repo.git
</code>```

In this way , I must enter password.

```<code>$ git push origin master
Password:
</code>```

But I hate to enter password.

I have checked this, but I don't solved.

Pushing to Git returning Error Code 403 fatal: HTTP request failed

Please tell me how to push without password.

答:
If you're working with a clone or fork, double-check that the repository URL you're trying to push to is your fork's URL instead of the original owner's repository URL.

```<code>git remote -v
</code>```

Body:
I want to push README.md to Github.

Using Ubuntu 14.04LTS

So, I commit in the following steps.

echo "# test" >> README.md
git init
git add README.md
git commit -m "first commit"
git remote add origin https://github.com/user/repo.git
git push -u origin master

But, below error occurred.

error: The requested URL returned error: 403 Forbidden while accessing https://github.com/user/repo.git/info/refs

fatal: HTTP request failed

I know solve this error this way

git remote set-url origin https://username@github.com/user/repo.git

In this way , I must enter password.

$ git push origin master
Password:

But I hate to enter password.

I have checked this, but I don't solved.

Pushing to Git returning Error Code 403 fatal: HTTP request failed

Please tell me how to push without password.

Body:
If you're working with a clone or fork, double-check that the repository URL you're trying to push to is your fork's URL instead of the original owner's repository URL.

git remote -v


问:
discord.js bot is deleting all messages
I have the following code running in my bot, as a command that deletes cuss words. However, it seems to make the bot delete any message that's sent no matter what! HELP!</p>

```<code>bot.on('message', message => {
    if (message.content.includes == 'bannedWord1' ||'bannedWord2' || 'bannedWord3' || 'bannedWord4') {
       message.delete(1);
       message.channel.send("That word's not appropriate!");
    }
 });
</code>```

答:
The issue is message.content.includes == 'bannedWord1' ||'bannedWord2' || 'bannedWord3' || 'bannedWord4' really means (message.content.includes == 'bannedWord1') ||'bannedWord2' || 'bannedWord3' || 'bannedWord4'. Non-empty strings are truthy so this is always true.

Also, I assume message.content is a string. So you need to handle things like 'assumptions' which contains ass but isn't a bad word.

Demo solution:

var badWords = [
  'bannedWord1',
  'bannedWord2',
  'bannedWord3',
  'bannedWord4'
];

var contents = [
  'This is a test.',
  'bannedWord1 tester.',
  'bannedWord2!',
  'OkaywordthatcontainsbannedWord1.'
];

var allowed = contents.filter(content => {
  var words = content.toLowerCase().trim().match(/\w+|\s+|[^\s\w]+/g);
  return !words.find(word => {
    return badWords.includes(word);
  });
});

console.log(allowed);```
</div>
</div>
</p>

<p>Use in your case:</p>

```var badWords = [
  'bannedWord1',
  'bannedWord2',
  'bannedWord3',
  'bannedWord4'
];

bot.on('message', message => {
  var words = message.content.toLowerCase().trim().match(/\w+|\s+|[^\s\w]+/g);
  var containsBadWord = words.some(word => {
    return badWords.includes(word);
  });
  if (containsBadWord) {
    message.delete(1);
    message.channel.send("That word's not appropriate!");
  }
});
```

Regex explanation from regex101.com

1st Alternative \w+

\w+ matches any word character (equal to [a-zA-Z0-9_])

+ Quantifier — Matches between one and unlimited times, as many times as possible, giving back as needed (greedy)

2nd Alternative \S+

\S+ matches any whitespace character (equal to [\r\n\t\f\v ])

+ Quantifier — Matches between one and unlimited times, as many times as possible, giving back as needed (greedy)

3rd Alternative [^\s\w]+

Match a single character not present in the list below [^\s\w]+

+ Quantifier — Matches between one and unlimited times, as many times as possible, giving back as needed (greedy) \s matches any whitespace character (equal to [\r\n\t\f\v])

ContentLicense: CC BY-SA 4.0

Title: discord.js bot is deleting all messages

Body:
I have the following code running in my bot, as a command that deletes cuss words. However, it seems to make the bot delete any message that's sent no matter what! HELP!

bot.on('message', message => {
    if (message.content.includes == 'bannedWord1' ||'bannedWord2' || 'bannedWord3' || 'bannedWord4') {
       message.delete(1);
       message.channel.send("That word's not appropriate!");
    }
 });

Body:
The issue is message.content.includes == 'bannedWord1' ||'bannedWord2' || 'bannedWord3' || 'bannedWord4' really means (message.content.includes == 'bannedWord1') ||'bannedWord2' || 'bannedWord3' || 'bannedWord4'. Non-empty strings are truthy so this is always true.

Also, I assume message.content is a string. So you need to handle things like 'assumptions' which contains ass but isn't a bad word.

Demo solution:

var badWords = [
  'bannedWord1',
  'bannedWord2',
  'bannedWord3',
  'bannedWord4'
];

var contents = [
  'This is a test.',
  'bannedWord1 tester.',
  'bannedWord2!',
  'OkaywordthatcontainsbannedWord1.'
];

var allowed = contents.filter(content => {
  var words = content.toLowerCase().trim().match(/\w+|\s+|[^\s\w]+/g);
  return !words.find(word => {
    return badWords.includes(word);
  });
});

console.log(allowed);

Use in your case:

var badWords = [
  'bannedWord1',
  'bannedWord2',
  'bannedWord3',
  'bannedWord4'
];

bot.on('message', message => {
  var words = message.content.toLowerCase().trim().match(/\w+|\s+|[^\s\w]+/g);
  var containsBadWord = words.some(word => {
    return badWords.includes(word);
  });
  if (containsBadWord) {
    message.delete(1);
    message.channel.send("That word's not appropriate!");
  }
});

Regex explanation from regex101.com

1st Alternative \w+

\w+ matches any word character (equal to [a-zA-Z0-9_])

+ Quantifier — Matches between one and unlimited times, as many times as possible, giving back as needed (greedy)

2nd Alternative \S+

\S+ matches any whitespace character (equal to [\r\n\t\f\v ])

+ Quantifier — Matches between one and unlimited times, as many times as possible, giving back as needed (greedy)

3rd Alternative [^\s\w]+

Match a single character not present in the list below [^\s\w]+

+ Quantifier — Matches between one and unlimited times, as many times as possible, giving back as needed (greedy) \s matches any whitespace character (equal to [\r\n\t\f\v])


问:
jquery functions are not working in safari but working properly in other browsers
I am working on the following code. I want to show only option elements depending on the first selected value. As this code is working properly in chrome but not in safari.
the hide() and show() functions are not working. How i can improve this code so that it will work in safari also?
my html code is as follows:

```<code><body>
<select id="shopcategory">
    <option></option>
    <option value="american" selected="selected">american</option>
    <option value="indian">indian</option>
    <option value="chinese">chinese</option>
</select>
<select id="shop-ar">
    <option class="american">1</option>
    <option class="american">2</option>
    <option class="american">3</option>
    <option class="indian">4</option>
    <option class="indian">5</option>
    <option class="indian">6</option>
    <option class="chinese">7</option>
    <option class="chinese">8</option>
    <option class="chinese">9</option>
</select>
</code>```

my jquery code as follows:

```<code>$(document).ready(function(){
    $("#shopcategory").change(function(){
        select= $("#shopcategory option:selected").attr("value");
        $("#shop-ar").children().each(function(){
            if($(this).attr("class")== select){
        //  only selected category options must be displayed
                $(this).show();
            }
            else{
                $(this).hide();
            }
        })
    })
})
</code>```

答:
```<code>$(document).ready(function(){
$("#shopcategory").change(function(){

var select = $("#shopcategory option:selected").attr("value");
// alert(select);

$("#shop-ar").children().each(function(){
    //$(".american").hide();
    // alert($(this).attr("id"));
    if($(this).attr("class") == select){
        $(this).append();
    }
    else{
        $(this).detach();
    }
   });
 });
});
</code>```

You can use .append() and .detach() functions at the place of .show() and .hide() functions as they will work better with safari and other browsers.

Body:
I am working on the following code. I want to show only option elements depending on the first selected value. As this code is working properly in chrome but not in safari.
the hide() and show() functions are not working. How i can improve this code so that it will work in safari also?
my html code is as follows:

<select id="shopcategory">
    <option></option>
    <option value="american" selected="selected">american</option>
    <option value="indian">indian</option>
    <option value="chinese">chinese</option>
</select>
<select id="shop-ar">
    <option class="american">1</option>
    <option class="american">2</option>
    <option class="american">3</option>
    <option class="indian">4</option>
    <option class="indian">5</option>
    <option class="indian">6</option>
    <option class="chinese">7</option>
    <option class="chinese">8</option>
    <option class="chinese">9</option>
</select>

my jquery code as follows:

$(document).ready(function(){
    $("#shopcategory").change(function(){
        select= $("#shopcategory option:selected").attr("value");
        $("#shop-ar").children().each(function(){
            if($(this).attr("class")== select){
        //  only selected category options must be displayed
                $(this).show();
            }
            else{
                $(this).hide();
            }
        })
    })
})

Body:
$(document).ready(function(){
$("#shopcategory").change(function(){

var select = $("#shopcategory option:selected").attr("value");
// alert(select);

$("#shop-ar").children().each(function(){
    //$(".american").hide();
    // alert($(this).attr("id"));
    if($(this).attr("class") == select){
        $(this).append();
    }
    else{
        $(this).detach();
    }
   });
 });
});

You can use .append() and .detach() functions at the place of .show() and .hide() functions as they will work better with safari and other browsers.


问:
How to find details of Sharepoint installation programatically?
I need to find out some general background information about the Sharepoint installation on the local machine using C# - what sharepoint version/patch version it is and so on. Does anyone have any pointers on how to do this?</p>

答:
It turns out that the way to find this, for MOSS at least, is checking the registry, specifically:

```<code>SOFTWARE\Microsoft\Shared Tools\Web Server Extensions\12.0
</code>```

That includes a Sharepoint and a Version key that indicate sharepoint is installed and what version it is. Of course, the existence of the key at all is a pretty good indicator that Sharepoint is installed.

OwnerDisplayName: glenatron

Body:
It turns out that the way to find this, for MOSS at least, is checking the registry, specifically:

SOFTWARE\Microsoft\Shared Tools\Web Server Extensions\12.0

That includes a Sharepoint and a Version key that indicate sharepoint is installed and what version it is. Of course, the existence of the key at all is a pretty good indicator that Sharepoint is installed.


问:
Rendering state json in React
I am unable to get the application to render this simple state data. It seems to me that i can't get the information in the render part to understand the data json.

this.state.data should contain the object since I can console.log it when it has done it's fetch.

I assumed that the object would be able to render as it is

```<code>import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
var $ = require('jquery');

class App extends Component {

  loadData() {
    console.log("loading data");
        fetch('https://api.nytimes.com/svc/movies/v2/reviews/search.json?api-key=f90d8b6f90d04bb5bbbeb2f241155ce7&query=star wars')
            .then(response => response.json())
            .then(data => {
                this.setState({data: data });
        })
            .catch(err => console.error(this.props.url, err.toString()))
  }

  constructor(props) {
    super(props);
    this.state = { data: [] };
  }

  componentDidMount() {
    console.log('GrandChild did mount.');

      this.loadData()
  }
  render() {
    return (
      <div className="App">
        <header className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <h1 className="App-title">Welcome to React</h1>
        </header>
        <p className="App-intro">
          To get started, edit <code>src/App.js</code> and save to reload.
        </p>
        <ul>
                {this.state.data(function(name, index){
                    return <li key={ index }>{name}</li>;
                  })}
            </ul>
      </div>

    );
  }
}

export default App;
</code>```

答:
You have several errors - see fixes and comments in code:

class App extends React.Component {

  loadData() {
    console.log("loading data");
    fetch('https://api.nytimes.com/svc/movies/v2/reviews/search.json?api-key=f90d8b6f90d04bb5bbbeb2f241155ce7&query=star wars')
      .then(response => response.json())
      .then(data => {
        this.setState({ data: data });
      })
      .catch(err => console.error(this.props.url, err.toString()))
  }

  constructor(props) {
    super(props);
    this.state = { data: null }; // initialize with null
  }

  componentDidMount() {
    console.log('GrandChild did mount.');

    this.loadData()
  }

  render() {
    const { data } = this.state;
    return (

        // if data not loaded null will render nothing
        // if data is not null, we iterate data.results with map
        {data && data.results.map(function (film, index) {
          // film is an object, just one or more properties to render
          return
{film.headline}
;
        })}

    );
  }
}

ReactDOM.render(
  <App />,
  app
);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id="app"></div></code>```

Title: Rendering state json in React

Body:
I am unable to get the application to render this simple state data. It seems to me that i can't get the information in the render part to understand the data json.

this.state.data should contain the object since I can console.log it when it has done it's fetch.

I assumed that the object would be able to render as it is

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
var $ = require('jquery');

class App extends Component {

  loadData() {
    console.log("loading data");
        fetch('https://api.nytimes.com/svc/movies/v2/reviews/search.json?api-key=f90d8b6f90d04bb5bbbeb2f241155ce7&query=star wars')
            .then(response => response.json())
            .then(data => {
                this.setState({data: data });
        })
            .catch(err => console.error(this.props.url, err.toString()))
  }

  constructor(props) {
    super(props);
    this.state = { data: [] };
  }

  componentDidMount() {
    console.log('GrandChild did mount.');

      this.loadData()
  }
  render() {
    return (

Welcome to React

          To get started, edit src/App.js and save to reload.

                {this.state.data(function(name, index){
                    return
{name}
;
                  })}

    );
  }
}

export default App;

Body:
You have several errors - see fixes and comments in code:

class App extends React.Component {

  loadData() {
    console.log("loading data");
    fetch('https://api.nytimes.com/svc/movies/v2/reviews/search.json?api-key=f90d8b6f90d04bb5bbbeb2f241155ce7&query=star wars')
      .then(response => response.json())
      .then(data => {
        this.setState({ data: data });
      })
      .catch(err => console.error(this.props.url, err.toString()))
  }

  constructor(props) {
    super(props);
    this.state = { data: null }; // initialize with null
  }

  componentDidMount() {
    console.log('GrandChild did mount.');

    this.loadData()
  }

  render() {
    const { data } = this.state;
    return (
      <ul>
        // if data not loaded null will render nothing
        // if data is not null, we iterate data.results with map
        {data && data.results.map(function (film, index) {
          // film is an object, just one or more properties to render
          return <li key={index}>{film.headline}</li>;
        })}
      </ul>
    );
  }
}

ReactDOM.render(
  <App />,
  app
);

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id="app"></div>


问:
no message dialog for deleted from database

I want to delete a record from database. The code runs fine, but even when there is a record for a particular id, the message returns id not found in database. Please help me to improve my code to display a separate message when id is not found in database.i have attached my output. as u can see id=19 i there in database but when i delete id=19, that particular id record gets deleted from the database but message pops up saying id not found in database.

```<code>try {
                                    String s = TUID.getText( );
                                    Connection con = DriverManager.getConnection( "jdbc:mysql://localhost:3306/mysql", "root", "root" );
                                    Statement st = con.createStatement( );
                                    String r = "delete from mysql57.addressbook where iid = "+s;
                                    PreparedStatement preparedStatement = con.prepareStatement( r );
                                    preparedStatement.executeUpdate( );
                                    int rows = preparedStatement.executeUpdate();
                                 if(rows == 0)
                        {  JOptionPane.showMessageDialog( f, "ID NOT FOUND IN DATABASE");

                        }

                        else{
                            JOptionPane.showMessageDialog( f, "DELETED FROM DATABASE" );

                        }

                                    }

                                }
                                catch (Exception ex) {
                                    JOptionPane.showMessageDialog( f,ex );
                                }
</code>```

答:
The executeUpdate() method returns the amount of rows affected. If no rows were deleted, it returns 0 (naturally).

So...

```<code>int rows = preparedStatement.executeUpdate();
if(rows == 0)
    ...
else
    ...
</code>```

You should also use PreparedStatement correctly, and change that + s into a placeholder (it's amazing how every single tutorial seems to abuse PreparedStatement and teach bad habits).

Body:
I want to delete a record from database. The code runs fine, but even when there is a record for a particular id, the message returns id not found in database. Please help me to improve my code to display a separate message when id is not found in database.i have attached my output. as u can see id=19 i there in database but when i delete id=19, that particular id record gets deleted from the database but message pops up saying id not found in database.

try {
                                    String s = TUID.getText( );
                                    Connection con = DriverManager.getConnection( "jdbc:mysql://localhost:3306/mysql", "root", "root" );
                                    Statement st = con.createStatement( );
                                    String r = "delete from mysql57.addressbook where iid = "+s;
                                    PreparedStatement preparedStatement = con.prepareStatement( r );
                                    preparedStatement.executeUpdate( );
                                    int rows = preparedStatement.executeUpdate();
                                 if(rows == 0)
                        {  JOptionPane.showMessageDialog( f, "ID NOT FOUND IN DATABASE");

                        }

                        else{
                            JOptionPane.showMessageDialog( f, "DELETED FROM DATABASE" );

                        }

                                    }

                                }
                                catch (Exception ex) {
                                    JOptionPane.showMessageDialog( f,ex );
                                }

Body:
The executeUpdate() method returns the amount of rows affected. If no rows were deleted, it returns 0 (naturally).

So...

int rows = preparedStatement.executeUpdate();
if(rows == 0)
    ...
else
    ...

You should also use PreparedStatement correctly, and change that + s into a placeholder (it's amazing how every single tutorial seems to abuse PreparedStatement and teach bad habits).


问:
Python 2.X : Regex to find all company names ending in ".inc"
I'm trying to extract the company names from press releases. As an example, below there is a snippet (in French) of a press release containing a list of seven companies ending in .inc.

En effet, Revenu Québec avait des motifs raisonnables de croire que ces entreprises avaient utilisé de fausses factures provenant de plusieurs sociétés, dont Asphalte Vrac Transport inc., 9163-6704 Québec inc., Entreprise Denis Dupré inc., Gestion Jean M. Machado inc., Impact Technologie Environnementale inc., Les entreprises Luc Clément inc. et Transport Vrac Globe International inc.

I'm trying to extract all the names using the following code:

```<code>aa = re.findall('inc\.,? (.*?inc\.)', text)
</code>```

I do manage to capture quite a few, but for some reason I can't figure, I can't extract them all. It seems trivial but it has stomped me for a few hours....

Any help is appreciated !

答:
```<code>aa = [s.strip() for s in text.split(',') if s.lower().endswith(' inc.')]
</code>```

Body:
I'm trying to extract the company names from press releases. As an example, below there is a snippet (in French) of a press release containing a list of seven companies ending in .inc.

En effet, Revenu Québec avait des motifs raisonnables de croire que ces entreprises avaient utilisé de fausses factures provenant de plusieurs sociétés, dont Asphalte Vrac Transport inc., 9163-6704 Québec inc., Entreprise Denis Dupré inc., Gestion Jean M. Machado inc., Impact Technologie Environnementale inc., Les entreprises Luc Clément inc. et Transport Vrac Globe International inc.

I'm trying to extract all the names using the following code:

aa = re.findall('inc\.,? (.*?inc\.)', text)

I do manage to capture quite a few, but for some reason I can't figure, I can't extract them all. It seems trivial but it has stomped me for a few hours....

Any help is appreciated !


问:
R visNetwork shiny: change color of selected node
I have a very simple problem given. I want to display an interactive network with visNetwork and when I click on a node, I want the color to change (the color is predefined).

I wanted to do this via observeEvent, but somehow it doesn't work. In fact, when I add the observeEvent part in the code below, I cannot click on any node anymore.

```<code>library(shiny); library(visNetwork); library(tidyverse); library(dplyr)

server <- function(input, output, session) {

  output$network_proxy_nodes <- renderVisNetwork({
    nodes <- data.frame(id = 1:3)
    edges <- data.frame(from = c(1,2), to = c(1,3))
    visNetwork(nodes, edges) %>%
      visNodes(color = "blue") %>%
      visEvents(click="function(nodes){
                Shiny.onInputChange('current_node_id',
                nodes);
  }")
  })

  changeColorOfSelectedNode <- function(nodes, selected.node){
    nodes %>%
      mutate(color = if_else(id == selected.node,
                             "red",
                             color))
  }

  observeEvent(input$current_node_id,
               {
                 simulation_nodes <- nodes %>%
                  changeColorOfSelectedNode(input$current_node_id$nodes[[1]])

                 visNetworkProxy("network_proxy_nodes") %>%
                  visUpdateNodes(nodes = simulation_nodes)
               })

}

ui <- fluidPage(
  visNetworkOutput("network_proxy_nodes")
)

shinyApp(ui=ui, server =server)
</code>```

I am new to this kind of interactive visualization stuff with R and so maybe the error is trivial. Can you help me out?

答:
Here is a way how to do it with observe:

```<code>library(shiny)
library(visNetwork)
library(tidyverse)

nodes <- data_frame(id = 1:3, color = rep("blue", 3))
edges <- data_frame(from = c(1, 2), to = c(1, 3))

server <- function(input, output, session) {
  output$network <- renderVisNetwork({
    visNetwork(nodes, edges) %>% visOptions(nodesIdSelection = list(enabled = TRUE))
  })

  changeColorOfSelectedNode <- function(nodes, selected.node) {
    nodes %>% mutate(color = if_else(id == selected.node, "red", color))
  }

  observe({
    if (!is.null(input$network_selected) && input$network_selected > 0) {
      nodes <- changeColorOfSelectedNode(nodes, input$network_selected)
      visNetworkProxy("network") %>% visUpdateNodes(nodes)
    }
  })

}

ui <- fluidPage(visNetworkOutput("network"))

shinyApp(ui = ui, server = server)
</code>```

Body:
I have a very simple problem given. I want to display an interactive network with visNetwork and when I click on a node, I want the color to change (the color is predefined).

I wanted to do this via observeEvent, but somehow it doesn't work. In fact, when I add the observeEvent part in the code below, I cannot click on any node anymore.

library(shiny); library(visNetwork); library(tidyverse); library(dplyr)

server <- function(input, output, session) {

  output$network_proxy_nodes <- renderVisNetwork({
    nodes <- data.frame(id = 1:3)
    edges <- data.frame(from = c(1,2), to = c(1,3))
    visNetwork(nodes, edges) %>%
      visNodes(color = "blue") %>%
      visEvents(click="function(nodes){
                Shiny.onInputChange('current_node_id',
                nodes);
  }")
  })

  changeColorOfSelectedNode <- function(nodes, selected.node){
    nodes %>%
      mutate(color = if_else(id == selected.node,
                             "red",
                             color))
  }

  observeEvent(input$current_node_id,
               {
                 simulation_nodes <- nodes %>%
                  changeColorOfSelectedNode(input$current_node_id$nodes[[1]])

                 visNetworkProxy("network_proxy_nodes") %>%
                  visUpdateNodes(nodes = simulation_nodes)
               })

}

ui <- fluidPage(
  visNetworkOutput("network_proxy_nodes")
)

shinyApp(ui=ui, server =server)

I am new to this kind of interactive visualization stuff with R and so maybe the error is trivial. Can you help me out?

Body:
Here is a way how to do it with observe:

library(shiny)
library(visNetwork)
library(tidyverse)

nodes <- data_frame(id = 1:3, color = rep("blue", 3))
edges <- data_frame(from = c(1, 2), to = c(1, 3))

server <- function(input, output, session) {
  output$network <- renderVisNetwork({
    visNetwork(nodes, edges) %>% visOptions(nodesIdSelection = list(enabled = TRUE))
  })

  changeColorOfSelectedNode <- function(nodes, selected.node) {
    nodes %>% mutate(color = if_else(id == selected.node, "red", color))
  }

  observe({
    if (!is.null(input$network_selected) && input$network_selected > 0) {
      nodes <- changeColorOfSelectedNode(nodes, input$network_selected)
      visNetworkProxy("network") %>% visUpdateNodes(nodes)
    }
  })

}

ui <- fluidPage(visNetworkOutput("network"))

shinyApp(ui = ui, server = server)


问:
How can I make message bubble?
Like this:
http://www.premiumpixels.com/freebies/apple-iphone-chat-bubbles-psd/

I have a tcp/ip chat application, I used listbox, but its not the best solution...

答:
As you are programming with the default set of Visual Studio (C#, .NET, winforms) I expect that you also use the defaulted listbox, meaning that that one uses defaulted .

This component can be overridden (even to use customized resources like images, fonts, etc.) It is even documented on MSDN:

ListBox.DrawItem Event

If I were you, I'd look into that example provided there!

Title: How can I make message bubble?


问:
Restrict scipy.optimize.minimize to integer values
I'm using scipy.optimize.minimize to optimize a real-world problem for which the answers can only be integers. My current code looks like this:

```<code>from scipy.optimize import minimize

def f(x):
    return (481.79/(5+x[0]))+(412.04/(4+x[1]))+(365.54/(3+x[2]))+(375.88/(3+x[3]))+(379.75/(3+x[4]))+(632.92/(5+x[5]))+(127.89/(1+x[6]))+(835.71/(6+x[7]))+(200.21/(1+x[8]))

def con(x):
    return sum(x)-7

cons = {'type':'eq', 'fun': con}

print scipy.optimize.minimize(f, [1,1,1,1,1,1,1,0,0], constraints=cons, bounds=([0,7],[0,7],[0,7],[0,7],[0,7],[0,7],[0,7],[0,7],[0,7]))
</code>```

This yields:

```<code>x: array([  2.91950510e-16,   2.44504019e-01,   9.97850733e-01,
     1.05398840e+00,   1.07481251e+00,   2.60570253e-01,
     1.36470363e+00,   4.48527831e-02,   1.95871767e+00]
</code>```

But I want it optimized with integer values (rounding all x to the nearest whole number doesn't always give the minimum).

Is there a way to use scipy.optimize.minimize with only integer values?

(I guess I could create an array with all possible permutations of x and evaluate f(x) for each combination, but that doesn't seem like a very elegant or quick solution.)

答:
One thing that might help your problem  you could have a constraint as:

```<code>max([x-int(x)])=0
</code>```

This is not going to completely solve your problem, the algorithm will still try and cheat and you will get values with some level of error ~±5e-10 that it will still try and optimize towards just by the error in scipy's algorithm but it's better than nothing.

```<code>cons = ({'type':'eq', 'fun': con},
        {'type':'eq','fun': lambda x : max([x[i]-int(x[i]) for i in range(len(x))])})
</code>```

 having tested this process on some optimizations I know the solution to, this process is more sensitive to the initial values than the unconstrained search, it gets fairly accurate answers however the solution may actually not find the true value, you are basically requiring the large jump of the optimization process (what it uses to make sure it's not optimizing to a local minimum) to search the sample space as the smaller increments are usually not strong enough to move to the next number over.

Body:
I'm using scipy.optimize.minimize to optimize a real-world problem for which the answers can only be integers. My current code looks like this:

from scipy.optimize import minimize

def f(x):
    return (481.79/(5+x[0]))+(412.04/(4+x[1]))+(365.54/(3+x[2]))+(375.88/(3+x[3]))+(379.75/(3+x[4]))+(632.92/(5+x[5]))+(127.89/(1+x[6]))+(835.71/(6+x[7]))+(200.21/(1+x[8]))

def con(x):
    return sum(x)-7

cons = {'type':'eq', 'fun': con}

print scipy.optimize.minimize(f, [1,1,1,1,1,1,1,0,0], constraints=cons, bounds=([0,7],[0,7],[0,7],[0,7],[0,7],[0,7],[0,7],[0,7],[0,7]))

This yields:

x: array([  2.91950510e-16,   2.44504019e-01,   9.97850733e-01,
     1.05398840e+00,   1.07481251e+00,   2.60570253e-01,
     1.36470363e+00,   4.48527831e-02,   1.95871767e+00]

But I want it optimized with integer values (rounding all x to the nearest whole number doesn't always give the minimum).

Is there a way to use scipy.optimize.minimize with only integer values?

(I guess I could create an array with all possible permutations of x and evaluate f(x) for each combination, but that doesn't seem like a very elegant or quick solution.)

Body:
One thing that might help your problem  you could have a constraint as:

max([x-int(x)])=0

This is not going to completely solve your problem, the algorithm will still try and cheat and you will get values with some level of error ~±5e-10 that it will still try and optimize towards just by the error in scipy's algorithm but it's better than nothing.

cons = ({'type':'eq', 'fun': con},
        {'type':'eq','fun': lambda x : max([x[i]-int(x[i]) for i in range(len(x))])})

 having tested this process on some optimizations I know the solution to, this process is more sensitive to the initial values than the unconstrained search, it gets fairly accurate answers however the solution may actually not find the true value, you are basically requiring the large jump of the optimization process (what it uses to make sure it's not optimizing to a local minimum) to search the sample space as the smaller increments are usually not strong enough to move to the next number over.


问:
invalid URI - How to prevent, URI::InvalidURIError errors?
I got the following back from delayed_job:

```<code>[Worker(XXXXXX pid:3720)] Class#XXXXXXX failed with URI::InvalidURIError: bad URI(is not URI?): https://s3.amazonaws.com/cline-local-dev/2/attachments/542/original/mac-os-x[1].jpeg?AWSAccessKeyId=xxxxxxxx&Expires=1295403309&Signature=xxxxxxx%3D - 3 failed attempts
</code>```

The way this URI comes from in my app is.

In my user_mailer I do:

```<code>  @comment.attachments.each do |a|
    attachments[a.attachment_file_name] = open(a.authenticated_url()) {|f| f.read }
  end
</code>```

Then in my attachments model:

```<code>  def authenticated_url(style = nil, expires_in = 90.minutes)
    AWS::S3::S3Object.url_for(attachment.path(style || attachment.default_style), attachment.bucket_name, :expires_in => expires_in, :use_ssl => attachment.s3_protocol == 'https')
  end
</code>```

That being said, is there some type of URI.encode or parsing I can do to prevent a valid URI (as I checked the URL works in my browser) for erroring and killing delayed_job in rails 3?

Thank you!

答:
Ruby has (at least) two modules for dealing with URIs.

URI is part of the standard library.

Addressable::URI, is a separate gem, and more comprehensive, and claims to conform to the spec.

Parse a URL with either one, modify any parameters using the gem's methods, then convert it using to_s before passing it on, and you should be good to go.

I tried ' open( URI.parse(URI.encode( a.authenticated_url() )) ' but that errord with OpenURI::HTTPError: 403 Forbidden

If you navigated to that page via a browser and it succeeded, then later failed going to it directly via code, it's likely there is a cookie or session state that is missing. You might need to use something like Mechanize, which will maintain that state while allowing you to navigate through a site.

EDIT:

```<code>require 'addressable/uri'

url = 'http://www.example.com'

uri = Addressable::URI.parse(url)
uri.query_values = {
  :foo => :bar,
  :q   => '"one two"'
}

uri.to_s # => "http://www.example.com?foo=bar&q=%22one%20two%22"
</code>```

Body:
I got the following back from delayed_job:

[Worker(XXXXXX pid:3720)] Class#XXXXXXX failed with URI::InvalidURIError: bad URI(is not URI?): https://s3.amazonaws.com/cline-local-dev/2/attachments/542/original/mac-os-x[1].jpeg?AWSAccessKeyId=xxxxxxxx&Expires=1295403309&Signature=xxxxxxx%3D - 3 failed attempts

The way this URI comes from in my app is.

In my user_mailer I do:

  @comment.attachments.each do |a|
    attachments[a.attachment_file_name] = open(a.authenticated_url()) {|f| f.read }
  end

Then in my attachments model:

  def authenticated_url(style = nil, expires_in = 90.minutes)
    AWS::S3::S3Object.url_for(attachment.path(style || attachment.default_style), attachment.bucket_name, :expires_in => expires_in, :use_ssl => attachment.s3_protocol == 'https')
  end

That being said, is there some type of URI.encode or parsing I can do to prevent a valid URI (as I checked the URL works in my browser) for erroring and killing delayed_job in rails 3?

Thank you!

Body:
Ruby has (at least) two modules for dealing with URIs.

URI is part of the standard library.

Addressable::URI, is a separate gem, and more comprehensive, and claims to conform to the spec.

Parse a URL with either one, modify any parameters using the gem's methods, then convert it using to_s before passing it on, and you should be good to go.

I tried ' open( URI.parse(URI.encode( a.authenticated_url() )) ' but that errord with OpenURI::HTTPError: 403 Forbidden

If you navigated to that page via a browser and it succeeded, then later failed going to it directly via code, it's likely there is a cookie or session state that is missing. You might need to use something like Mechanize, which will maintain that state while allowing you to navigate through a site.

EDIT:

require 'addressable/uri'

url = 'http://www.example.com'

uri = Addressable::URI.parse(url)
uri.query_values = {
  :foo => :bar,
  :q   => '"one two"'
}

uri.to_s # => "http://www.example.com?foo=bar&q=%22one%20two%22"