问:
TypedArray.getText() on android.R.attr.text returns null
I am trying to implement a custom textview which uses StaticLayout. To get 'android:text' attribute of the view, I implemented like this in initializing field:

```<code>@SupressLint("ResourceType")
class ExampleTextView(context: Context, attrs: AttributeSet?, defStyleAttr: Int): View(...) {
    private var mText: String

    init {
        val styledAttributes = context.obtainStyledAttributes(attrs, intArrayOf(
            ...
            android.R.attr.text,
            ...
        ))

        mText = styledAttributes.getText(1)
        ...

        styledAttributes.recycle()
    }
    ...
}
</code>```

Then in layout xml:

```<code><com.example.package.ExampleTextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="This is an example text" />
</code>```

I obviously set 'android:text' in the custom textview. But when I try to get attribute from TypedArray, it returns null. Another try with styledAttributes.getString(1) also does return null.

Stack Trace:

```<code>E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.package, PID: 19154
    android.view.InflateException: Binary XML file line #10: Binary XML file line #10: Error inflating class com.example.package.ExampleTextView
    Caused by: android.view.InflateException: Binary XML file line #10: Error inflating class com.example.package.ExampleTextView
    Caused by: java.lang.reflect.InvocationTargetException
        at java.lang.reflect.Constructor.newInstance0(Native Method)
        at java.lang.reflect.Constructor.newInstance(Constructor.java:343)
        at android.view.LayoutInflater.createView(LayoutInflater.java:647)
        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:790)
        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:730)
        at android.view.LayoutInflater.rInflate(LayoutInflater.java:863)
        at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:824)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:515)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
        at com.example.package.adapter.elementsAdapter.onCreateViewHolder(PatchNoteElementsAdapter.kt:54)
        at androidx.recyclerview.widget.RecyclerView$Adapter.createViewHolder(RecyclerView.java:7078)
        at androidx.recyclerview.widget.RecyclerView$Recycler.tryGetViewHolderForPositionByDeadline(RecyclerView.java:6235)
        at androidx.recyclerview.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:6118)
        at androidx.recyclerview.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:6114)
        at androidx.recyclerview.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:2303)
        at androidx.recyclerview.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1627)
        at androidx.recyclerview.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1587)
        at androidx.recyclerview.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:665)
        at androidx.recyclerview.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:4134)
        at androidx.recyclerview.widget.RecyclerView.dispatchLayout(RecyclerView.java:3851)
        at androidx.recyclerview.widget.RecyclerView.onLayout(RecyclerView.java:4404)
        at android.view.View.layout(View.java:20691)
        at android.view.ViewGroup.layout(ViewGroup.java:6194)
        at com.google.android.material.appbar.HeaderScrollingViewBehavior.layoutChild(HeaderScrollingViewBehavior.java:148)
        at com.google.android.material.appbar.ViewOffsetBehavior.onLayoutChild(ViewOffsetBehavior.java:43)
        at com.google.android.material.appbar.AppBarLayout$ScrollingViewBehavior.onLayoutChild(AppBarLayout.java:1996)
        at androidx.coordinatorlayout.widget.CoordinatorLayout.onLayout(CoordinatorLayout.java:918)
        at android.view.View.layout(View.java:20691)
        at android.view.ViewGroup.layout(ViewGroup.java:6194)
        at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
        at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
        at android.view.View.layout(View.java:20691)
        at android.view.ViewGroup.layout(ViewGroup.java:6194)
        at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1812)
        at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1656)
        at android.widget.LinearLayout.onLayout(LinearLayout.java:1565)
        at android.view.View.layout(View.java:20691)
        at android.view.ViewGroup.layout(ViewGroup.java:6194)
        at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
        at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
        at android.view.View.layout(View.java:20691)
        at android.view.ViewGroup.layout(ViewGroup.java:6194)
        at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1812)
        at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1656)
        at android.widget.LinearLayout.onLayout(LinearLayout.java:1565)
        at android.view.View.layout(View.java:20691)
        at android.view.ViewGroup.layout(ViewGroup.java:6194)
        at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
        at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
E/AndroidRuntime:     at com.android.internal.policy.DecorView.onLayout(DecorView.java:765)
        at android.view.View.layout(View.java:20691)
        at android.view.ViewGroup.layout(ViewGroup.java:6194)
        at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2806)
        at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2333)
        at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1473)
        at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:7215)
        at android.view.Choreographer$CallbackRecord.run(Choreographer.java:1004)
        at android.view.Choreographer.doCallbacks(Choreographer.java:816)
        at android.view.Choreographer.doFrame(Choreographer.java:751)
        at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:990)
        at android.os.Handler.handleCallback(Handler.java:873)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:280)
        at android.app.ActivityThread.main(ActivityThread.java:6706)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
     Caused by: kotlin.KotlinNullPointerException
        at com.example.package.ExampleTextView.<init>(ExampleTextView.kt:66)
        at com.example.package.ExampleTextView.<init>(ExampleTextView.kt:22)
            ... 67 more
</code>```

Is there anything that I missed?

答:
I imported your TextView and found the same exception with the inner exception of

java.lang.NoSuchMethodException: <init> [class android.content.Context, interface android.util.AttributeSet]

I suspect it has something to do with the way attrs are set

Usually when i extend a generic view i expose all the available constructors, give this a try.

```<code>class ExampleTextView: View {
    constructor(context: Context): super(context)
    constructor(context: Context, attrs: AttributeSet?): super(context, attrs) {
        this.attrs = attrs
    }
    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int): super(context, attrs, defStyleAttr) {
        this.attrs = attrs
    }

    private var mText: String
    private var attrs: AttributeSet? = null

    init {
        val styledAttributes = context.obtainStyledAttributes(attrs, intArrayOf(android.R.attr.text))
        mText = styledAttributes.getText(1).toString()
        styledAttributes.recycle()
    }
}
</code>```

Body:
I am trying to implement a custom textview which uses StaticLayout. To get 'android:text' attribute of the view, I implemented like this in initializing field:

@SupressLint("ResourceType")
class ExampleTextView(context: Context, attrs: AttributeSet?, defStyleAttr: Int): View(...) {
    private var mText: String

    init {
        val styledAttributes = context.obtainStyledAttributes(attrs, intArrayOf(
            ...
            android.R.attr.text,
            ...
        ))

        mText = styledAttributes.getText(1)
        ...

        styledAttributes.recycle()
    }
    ...
}

Then in layout xml:

<com.example.package.ExampleTextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="This is an example text" />

I obviously set 'android:text' in the custom textview. But when I try to get attribute from TypedArray, it returns null. Another try with styledAttributes.getString(1) also does return null.

Stack Trace:

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.package, PID: 19154
    android.view.InflateException: Binary XML file line #10: Binary XML file line #10: Error inflating class com.example.package.ExampleTextView
    Caused by: android.view.InflateException: Binary XML file line #10: Error inflating class com.example.package.ExampleTextView
    Caused by: java.lang.reflect.InvocationTargetException
        at java.lang.reflect.Constructor.newInstance0(Native Method)
        at java.lang.reflect.Constructor.newInstance(Constructor.java:343)
        at android.view.LayoutInflater.createView(LayoutInflater.java:647)
        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:790)
        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:730)
        at android.view.LayoutInflater.rInflate(LayoutInflater.java:863)
        at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:824)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:515)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
        at com.example.package.adapter.elementsAdapter.onCreateViewHolder(PatchNoteElementsAdapter.kt:54)
        at androidx.recyclerview.widget.RecyclerView$Adapter.createViewHolder(RecyclerView.java:7078)
        at androidx.recyclerview.widget.RecyclerView$Recycler.tryGetViewHolderForPositionByDeadline(RecyclerView.java:6235)
        at androidx.recyclerview.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:6118)
        at androidx.recyclerview.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:6114)
        at androidx.recyclerview.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:2303)
        at androidx.recyclerview.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1627)
        at androidx.recyclerview.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1587)
        at androidx.recyclerview.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:665)
        at androidx.recyclerview.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:4134)
        at androidx.recyclerview.widget.RecyclerView.dispatchLayout(RecyclerView.java:3851)
        at androidx.recyclerview.widget.RecyclerView.onLayout(RecyclerView.java:4404)
        at android.view.View.layout(View.java:20691)
        at android.view.ViewGroup.layout(ViewGroup.java:6194)
        at com.google.android.material.appbar.HeaderScrollingViewBehavior.layoutChild(HeaderScrollingViewBehavior.java:148)
        at com.google.android.material.appbar.ViewOffsetBehavior.onLayoutChild(ViewOffsetBehavior.java:43)
        at com.google.android.material.appbar.AppBarLayout$ScrollingViewBehavior.onLayoutChild(AppBarLayout.java:1996)
        at androidx.coordinatorlayout.widget.CoordinatorLayout.onLayout(CoordinatorLayout.java:918)
        at android.view.View.layout(View.java:20691)
        at android.view.ViewGroup.layout(ViewGroup.java:6194)
        at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
        at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
        at android.view.View.layout(View.java:20691)
        at android.view.ViewGroup.layout(ViewGroup.java:6194)
        at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1812)
        at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1656)
        at android.widget.LinearLayout.onLayout(LinearLayout.java:1565)
        at android.view.View.layout(View.java:20691)
        at android.view.ViewGroup.layout(ViewGroup.java:6194)
        at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
        at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
        at android.view.View.layout(View.java:20691)
        at android.view.ViewGroup.layout(ViewGroup.java:6194)
        at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1812)
        at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1656)
        at android.widget.LinearLayout.onLayout(LinearLayout.java:1565)
        at android.view.View.layout(View.java:20691)
        at android.view.ViewGroup.layout(ViewGroup.java:6194)
        at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
        at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
E/AndroidRuntime:     at com.android.internal.policy.DecorView.onLayout(DecorView.java:765)
        at android.view.View.layout(View.java:20691)
        at android.view.ViewGroup.layout(ViewGroup.java:6194)
        at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2806)
        at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2333)
        at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1473)
        at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:7215)
        at android.view.Choreographer$CallbackRecord.run(Choreographer.java:1004)
        at android.view.Choreographer.doCallbacks(Choreographer.java:816)
        at android.view.Choreographer.doFrame(Choreographer.java:751)
        at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:990)
        at android.os.Handler.handleCallback(Handler.java:873)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:280)
        at android.app.ActivityThread.main(ActivityThread.java:6706)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
     Caused by: kotlin.KotlinNullPointerException
        at com.example.package.ExampleTextView.<init>(ExampleTextView.kt:66)
        at com.example.package.ExampleTextView.<init>(ExampleTextView.kt:22)
            ... 67 more

Is there anything that I missed?

Body:
I imported your TextView and found the same exception with the inner exception of

java.lang.NoSuchMethodException: <init> [class android.content.Context, interface android.util.AttributeSet]

I suspect it has something to do with the way attrs are set

Usually when i extend a generic view i expose all the available constructors, give this a try.

class ExampleTextView: View {
    constructor(context: Context): super(context)
    constructor(context: Context, attrs: AttributeSet?): super(context, attrs) {
        this.attrs = attrs
    }
    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int): super(context, attrs, defStyleAttr) {
        this.attrs = attrs
    }

    private var mText: String
    private var attrs: AttributeSet? = null

    init {
        val styledAttributes = context.obtainStyledAttributes(attrs, intArrayOf(android.R.attr.text))
        mText = styledAttributes.getText(1).toString()
        styledAttributes.recycle()
    }
}


来源: stackexchange

问:
How can I fix this error 'Unknown module type'?
My top model:

```<code> module top (G1, Y1, R1, G2, Y2, R2, BT1, BT2, clk, rst);
 input BT1, BT2, clk, rst;
 output G1, Y1, R1, G2, Y2, R2;
 wire En1, En2, En3, CNT_RES, FF_RES, TC_30, TC_5, GE_15, B1, B2, request;

 Controll_Unit c1(G1, Y1, R1, G2, Y2, R2, CNT_RES, FF_RES, B1, B2, BT1, BT2, clk, rst, En1, En2, En3);

 Counter t1(TC_30, TC_5, GE_15, CNT_RES, FF_RES, rst, clk);

 dff_sr q1(GE_15, clk, request);

 assign En1=TC_30||GE_15&&B1;
 assign En2=TC_30||GE_15&&B2;
 assign En3=TC_5;
 assign request = BT1||BT2;
endmodule
</code>```

My dff model:

```<code>module dff_sr(output GE_15 ,input clk, request);
reg  GE_15;

always @(posedge clk)
  begin
    if(request)
     GE_15<=1;
  end
   endmodule
</code>```

Why does my dff_sr code have this unknown error?  I want this problem quickly solved.

答:
You have mixed up ANSI and non-ANSI module port declarations.  Change:

```<code>module dff_sr(output GE_15 ,input clk, request);
    reg  GE_15;
</code>```

to:

```<code>module dff_sr(output reg GE_15 ,input clk, request);
</code>```

This uses ANSI style.  I don't get the same error as you do, but I do get this compile warning on Cadence:

```<code>reg  GE_15;
         | xmvlog: *W,ILLPDX : Multiple declarations for a port not allowed
           in module with ANSI list of port declarations (port 'GE_15') [12.3.4(IEEE-2001)].
</code>```

Refer to IEEE Std 1800-2017, section 23.2.2 Port declarations.

ContentLicense: CC BY-SA 4.0

Body:
My top model:

 module top (G1, Y1, R1, G2, Y2, R2, BT1, BT2, clk, rst);
 input BT1, BT2, clk, rst;
 output G1, Y1, R1, G2, Y2, R2;
 wire En1, En2, En3, CNT_RES, FF_RES, TC_30, TC_5, GE_15, B1, B2, request;

 Controll_Unit c1(G1, Y1, R1, G2, Y2, R2, CNT_RES, FF_RES, B1, B2, BT1, BT2, clk, rst, En1, En2, En3);

 Counter t1(TC_30, TC_5, GE_15, CNT_RES, FF_RES, rst, clk);

 dff_sr q1(GE_15, clk, request);

 assign En1=TC_30||GE_15&&B1;
 assign En2=TC_30||GE_15&&B2;
 assign En3=TC_5;
 assign request = BT1||BT2;
endmodule

My dff model:

module dff_sr(output GE_15 ,input clk, request);
reg  GE_15;

always @(posedge clk)
  begin
    if(request)
     GE_15<=1;
  end
   endmodule

Why does my dff_sr code have this unknown error?  I want this problem quickly solved.

Body:
You have mixed up ANSI and non-ANSI module port declarations.  Change:

module dff_sr(output GE_15 ,input clk, request);
    reg  GE_15;

to:

module dff_sr(output reg GE_15 ,input clk, request);

This uses ANSI style.  I don't get the same error as you do, but I do get this compile warning on Cadence:

reg  GE_15;
         | xmvlog: *W,ILLPDX : Multiple declarations for a port not allowed
           in module with ANSI list of port declarations (port 'GE_15') [12.3.4(IEEE-2001)].

Refer to IEEE Std 1800-2017, section 23.2.2 Port declarations.


Title: How to make a loop for these regressions?

Body:
I have a dataframe with 10 columns like this:

df = structure(list(X1 = c(-0.158841494166799, 1.74997712540787,
-0.603638753496694, -0.253379995687274, -1.13536828104642, -2.72698649676692,
0.0243826193956672, 3.21776393858788, -2.3633921387719, 0.0305028420399468,
-4.26940546325382, 1.55584592541131, -1.05118869595721, -2.84985861365441,
0.729293004856561, -3.80058253179317, 1.31191742952459, 2.33589025288871,
-0.315014740930705, 2.92302109498542, 2.26246357678861, 1.37039290089958,
0.0582396621450368, -0.902295561314538, 2.14889801735908, 0.391493314141552,
2.33280118206325, -0.0490864536654898, 0.068965431468872, 1.24553936025063
), X2 = c(0.428917030889186, 1.38179284926331, 2.83063848525283,
-0.926689840680047, -1.3903457418351, 0.708618895316463, -0.750232095654876,
0.894660121671367, 0.124277732759992, -1.98558522788821, 2.34165530946135,
2.85945910959032, 2.36563560772223, 0.0185741299096399, -2.48859548768527,
-1.26592501904523, -0.790849261930494, -0.828149152178906, 3.2014616981455,
-0.15442363719638, -0.516775154465199, -0.176649448869891, -1.41825025459806,
2.17806157731774, -0.44973481848562, 2.24655423722927, 2.47628395430464,
1.91613790409017, -0.393928617864301, -0.148584327095393), X3 = c(-0.430287082709084,
-0.625327045828844, -0.514958706302276, 0.751266821352889, 1.18006572060265,
-0.802136052260364, 0, 0.105706401868772, 0.442778243504233,
0.905950590121364, -1.26899829497004, 0.745801518841586, -0.978033251950966,
0.113286791573796, 1.20968420311602, -0.635010679093886, 0.858274389205649,
-1.009308286611, 0, 0.167623720006668, -0.720624475890533, -0.443172067136528,
-0.0181650919153045, -0.818017257660172, 1.18137870264753, -0.0566121497554404,
0.572314218120067, -1.01361737919216, 0.637155618813563, 0.00507063594816648
), X4 = c(1.05105923858325, -0.808507106602501, 1.01063388325313,
-0.363828197971125, -0.889357817262751, 0.0808507106602501, 0,
0.4851042639615, 0.687231040612125, -1.53616350254475, 2.02126776650625,
-1.09148459391338, -0.929783172592876, 0.323402842641, 0.768081751272376,
0.444678908631375, -1.53616350254475, 0.970208527923, 0, 0.646805685282001,
-1.01063388325313, 0.40425355330125, -0.323402842641, -0.202126776650625,
1.09148459391338, -0.970208527923, -0.606380329951876, 0, 0.606380329951876,
0.161701421320499), X5 = c(-1.68622583629267, -2.11651291900176,
-2.7418399648306, -3.25679867113288, -2.50553184977999, -1.32546612917734,
-2.12760218143771, -2.12760218143771, -2.02189577956894, -1.5791175360647,
-0.67316694594334, -1.94216524091338, -1.19636372207179, -2.17439697402276,
-2.06111018244896, -0.85142597933294, -1.48643665842683, -0.628162269221177,
-1.63747055583218, -1.63747055583218, -1.46984683582551, -2.19047131171604,
-2.63364337885257, -2.65180847076788, -3.46982572842805, -2.28844702578052,
-2.34505917553596, -1.77274495741589, -2.78636233660805, -2.14920671779449
), X6 = c(-3.52265292326337, -2.47159368468012, -3.28010079128262,
-2.26946690802949, -2.63329510600062, -3.52265292326337, -3.44180221260312,
-3.44180221260312, -2.95669794864162, -2.26946690802949, -3.80563041057424,
-1.78436264406799, -2.87584723798137, -3.80563041057424, -3.48222756793324,
-2.71414581666087, -2.26946690802949, -3.80563041057424, -2.83542188265124,
-2.83542188265124, -2.18861619736924, -3.19925008062237, -2.79499652732112,
-3.11839936996212, -3.32052614661274, -2.22904155269937, -3.19925008062237,
-3.80563041057424, -3.80563041057424, -3.19925008062237), X7 = c(1,
0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 1, 0, 0, 1, 0, 0), X8 = c(0, 0, 1, 0, 0, 0, 0, 0, 0, 0,
0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0),
    X9 = c(1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0,
    0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0), X10 = c(3.2936,
    3.283, 3.264, 3.3162, 3.31, 3.3485, 3.3017, 3.2927, 3.3186,
    3.3004, 3.3043, 3.0945, 2.7868, 2.7635, 2.749, 2.5605, 2.5571,
    2.2133, 2.0783, 2.0981, 2.0209, 2.0148, 1.973, 2.0567, 2.0214,
    2.0315, 2.0057, 2.078, 2.0152, 2.0277)), row.names = c(NA,
30L), class = "data.frame")

What I want to do is be much faster in the implementation of the following code:

p = 3

instru1 = df$X7[1:(30-p)]
instru2 = df$X8[1:(30-p)]
instru3 = df$X9[1:(30-p)]

var <- VAR(df[, c(1:4,10)], p, type = "const")

summary(lm(var$varresult$[# the name of the first variable that appears]$residuals ~ instru1))

linearHypothesis(lm(var$varresult$[# the name of the first variable that appears]$residuals ~ instru1), "instru1 = 0", test = "F", vcov = vcovHAC, type = "HC1")

I did this code only for instru1 and for one column of interest (col 10 in df). I would like to do the same exercise, for instru1, instru2 and instru3 and, in addition to

VAR(df[, c(1:4,10)], p, type = "const")

for

VAR(df[, c(1:4,5)], p, type = "const")

and

VAR(df[, c(1:4,6)], p, type = "const").

In other words, I would like to avoid doing:

p = 3

instru1 = df$X7[1:(30-p)]
instru2 = df$X8[1:(30-p)]
instru3 = df$X9[1:(30-p)]

var1 <- VAR(df[, c(1:4,5)], p, type = "const")

summary(lm(var1$varresult$[# the name of the first variable that appears]$residuals ~ instru1))

linearHypothesis(lm(var1$varresult$[# the name of the first variable that appears]$residuals ~ instru1), "instru1 = 0", test = "F", vcov = vcovHAC, type = "HC1")

var2 <- VAR(df[, c(1:4,6)], p, type = "const")

summary(lm(var2$varresult$[# the name of the first variable that appears]$residuals ~ instru1))

linearHypothesis(lm(var2$varresult$[# the name of the first variable that appears]$residuals ~ instru1), "instru1 = 0", test = "F", vcov = vcovHAC, type = "HC1")

# and then the same but plugging instru2 and instru3 in place of instru1. Is it possible to have all in one loop?

Ideally I would like to have everything in one loop but, if not feasible, it is also fine to have a code for the VAR part and then I will update the 'instru' bit manually.

Can anyone help me?

Thanks a lot!

Body:
Hi Rollo/Arma 91 hopefully this answers your question (note this is untested as the package used is not specified).

# Constant:
p = 3

# Instruments:
instru_col_seq <- 7:10
instru_list <- vector("list", length(instru_col_seq))
instru_list <- setNames(lapply(instru_col_seq, function(i){
  df[(1:(30-p)), i]
  }
), paste0("instru", 1:length(instru_col_seq)))

# Var Setup:
var_col_seq <- unique(pmin(seq_along(df)+3, ncol(df)))
var_list <- vector("list", length(col_seq))
var_lm_summmary_list <- var_list
var_lh_list <- var_list

# Var computations:
var_list <- lapply(col_seq, function(j){
    var <- VAR(df[, c(1:4,j)], p, type = "const")
  }
)

# Var lm:
var_lm_summmary_list <- lapply(seq_along(var_list), function(k){
    summary(lm(var_list[k]$varresult$[names(df)[var_col_seq[k]]]$residuals ~ instru_list[1]))
  }
)

# Var lh:
var_lh_list <- lapply(seq_along(var_list), function(l){
  linearHypothesis(lm(var$varresult$[names(df)[var_col_seq[l]]]$residuals ~ instru_list[1]),
                   "instru1 = 0", test = "F", vcov = vcovHAC, type = "HC1")
  }
)

Data:

df <- structure(list(X1 = c(-0.158841494166799, 1.74997712540787,
-0.603638753496694, -0.253379995687274, -1.13536828104642, -2.72698649676692,
0.0243826193956672, 3.21776393858788, -2.3633921387719, 0.0305028420399468,
-4.26940546325382, 1.55584592541131, -1.05118869595721, -2.84985861365441,
0.729293004856561, -3.80058253179317, 1.31191742952459, 2.33589025288871,
-0.315014740930705, 2.92302109498542, 2.26246357678861, 1.37039290089958,
0.0582396621450368, -0.902295561314538, 2.14889801735908, 0.391493314141552,
2.33280118206325, -0.0490864536654898, 0.068965431468872, 1.24553936025063
), X2 = c(0.428917030889186, 1.38179284926331, 2.83063848525283,
-0.926689840680047, -1.3903457418351, 0.708618895316463, -0.750232095654876,
0.894660121671367, 0.124277732759992, -1.98558522788821, 2.34165530946135,
2.85945910959032, 2.36563560772223, 0.0185741299096399, -2.48859548768527,
-1.26592501904523, -0.790849261930494, -0.828149152178906, 3.2014616981455,
-0.15442363719638, -0.516775154465199, -0.176649448869891, -1.41825025459806,
2.17806157731774, -0.44973481848562, 2.24655423722927, 2.47628395430464,
1.91613790409017, -0.393928617864301, -0.148584327095393), X3 = c(-0.430287082709084,
-0.625327045828844, -0.514958706302276, 0.751266821352889, 1.18006572060265,
-0.802136052260364, 0, 0.105706401868772, 0.442778243504233,
0.905950590121364, -1.26899829497004, 0.745801518841586, -0.978033251950966,
0.113286791573796, 1.20968420311602, -0.635010679093886, 0.858274389205649,
-1.009308286611, 0, 0.167623720006668, -0.720624475890533, -0.443172067136528,
-0.0181650919153045, -0.818017257660172, 1.18137870264753, -0.0566121497554404,
0.572314218120067, -1.01361737919216, 0.637155618813563, 0.00507063594816648
), X4 = c(1.05105923858325, -0.808507106602501, 1.01063388325313,
-0.363828197971125, -0.889357817262751, 0.0808507106602501, 0,
0.4851042639615, 0.687231040612125, -1.53616350254475, 2.02126776650625,
-1.09148459391338, -0.929783172592876, 0.323402842641, 0.768081751272376,
0.444678908631375, -1.53616350254475, 0.970208527923, 0, 0.646805685282001,
-1.01063388325313, 0.40425355330125, -0.323402842641, -0.202126776650625,
1.09148459391338, -0.970208527923, -0.606380329951876, 0, 0.606380329951876,
0.161701421320499), X5 = c(-1.68622583629267, -2.11651291900176,
-2.7418399648306, -3.25679867113288, -2.50553184977999, -1.32546612917734,
-2.12760218143771, -2.12760218143771, -2.02189577956894, -1.5791175360647,
-0.67316694594334, -1.94216524091338, -1.19636372207179, -2.17439697402276,
-2.06111018244896, -0.85142597933294, -1.48643665842683, -0.628162269221177,
-1.63747055583218, -1.63747055583218, -1.46984683582551, -2.19047131171604,
-2.63364337885257, -2.65180847076788, -3.46982572842805, -2.28844702578052,
-2.34505917553596, -1.77274495741589, -2.78636233660805, -2.14920671779449
), X6 = c(-3.52265292326337, -2.47159368468012, -3.28010079128262,
-2.26946690802949, -2.63329510600062, -3.52265292326337, -3.44180221260312,
-3.44180221260312, -2.95669794864162, -2.26946690802949, -3.80563041057424,
-1.78436264406799, -2.87584723798137, -3.80563041057424, -3.48222756793324,
-2.71414581666087, -2.26946690802949, -3.80563041057424, -2.83542188265124,
-2.83542188265124, -2.18861619736924, -3.19925008062237, -2.79499652732112,
-3.11839936996212, -3.32052614661274, -2.22904155269937, -3.19925008062237,
-3.80563041057424, -3.80563041057424, -3.19925008062237), X7 = c(1,
0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 1, 0, 0, 1, 0, 0), X8 = c(0, 0, 1, 0, 0, 0, 0, 0, 0, 0,
0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0),
X9 = c(1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0), X10 = c(3.2936,
3.283, 3.264, 3.3162, 3.31, 3.3485, 3.3017, 3.2927, 3.3186,
3.3004, 3.3043, 3.0945, 2.7868, 2.7635, 2.749, 2.5605, 2.5571,
2.2133, 2.0783, 2.0981, 2.0209, 2.0148, 1.973, 2.0567, 2.0214,
2.0315, 2.0057, 2.078, 2.0152, 2.0277)), row.names = c(NA,
30L), class = "data.frame")


问:
Change background color of android menu
I'm trying to change the standard light grey to a light green. Seems that there is not a simple way to do this (through Android Themes, for example) but I have found a workaround as explained at this page: http://tinyurl.com/342dgn3.

The author seems disappeared, can someone help me integrating this code?  I don't understand where I need to implement the LayoutInflater factory class.

答:
When ur are inflating the menu call this setMenuBackground()  method

```<code>@Override
public boolean onCreateOptionsMenu(Menu menu)
{
    MenuInflater inflater=getMenuInflater();
    inflater.inflate(R.menu.menu,menu);
    setMenuBackground();
    return true;
}
</code>```

and write this in the setMenuBackground()  method

```<code>    protected void setMenuBackground(){
        // Log.d(TAG, "Enterting setMenuBackGround");
        getLayoutInflater().setFactory( new Factory() {
            public View onCreateView(String name, Context context, AttributeSet attrs) {
                if ( name.equalsIgnoreCase( "com.android.internal.view.menu.IconMenuItemView" ) ) {
                    try { // Ask our inflater to create the view
                        LayoutInflater f = getLayoutInflater();
                        final View view = f.createView( name, null, attrs );
                        /* The background gets refreshed each time a new item is added the options menu.
                        * So each time Android applies the default background we need to set our own
                        * background. This is done using a thread giving the background change as runnable
                        * object */
                        new Handler().post( new Runnable() {
                            public void run () {
                                // sets the background color
                                view.setBackgroundResource( R.color.androidcolor);
                                // sets the text color
                                ((TextView) view).setTextColor(Color.BLACK);
                                // sets the text size
                                ((TextView) view).setTextSize(18);
                }
                        } );
                    return view;
                }
            catch ( InflateException e ) {}
            catch ( ClassNotFoundException e ) {}
        }
        return null;
    }});
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Change background color of android menu

Body:
When ur are inflating the menu call this setMenuBackground()  method

@Override
public boolean onCreateOptionsMenu(Menu menu)
{
    MenuInflater inflater=getMenuInflater();
    inflater.inflate(R.menu.menu,menu);
    setMenuBackground();
    return true;
}

and write this in the setMenuBackground()  method

    protected void setMenuBackground(){
        // Log.d(TAG, "Enterting setMenuBackGround");
        getLayoutInflater().setFactory( new Factory() {
            public View onCreateView(String name, Context context, AttributeSet attrs) {
                if ( name.equalsIgnoreCase( "com.android.internal.view.menu.IconMenuItemView" ) ) {
                    try { // Ask our inflater to create the view
                        LayoutInflater f = getLayoutInflater();
                        final View view = f.createView( name, null, attrs );
                        /* The background gets refreshed each time a new item is added the options menu.
                        * So each time Android applies the default background we need to set our own
                        * background. This is done using a thread giving the background change as runnable
                        * object */
                        new Handler().post( new Runnable() {
                            public void run () {
                                // sets the background color
                                view.setBackgroundResource( R.color.androidcolor);
                                // sets the text color
                                ((TextView) view).setTextColor(Color.BLACK);
                                // sets the text size
                                ((TextView) view).setTextSize(18);
                }
                        } );
                    return view;
                }
            catch ( InflateException e ) {}
            catch ( ClassNotFoundException e ) {}
        }
        return null;
    }});
}


问:
Pandas drop rows in time series with less than x observation
I am working with timeseries data in Pandas (timestamp used as index). I am doing some filtering on my dataset and end up with a dataframe that mostly contains consecutive observations (one-minute data). However, there are also time intervals with only one or a few minutes of obervations. These I would like to exclude. How can I get hold of those short intervals using sth like:</p>

```<code>df = df.drop(df[<some boolean condition>].index)
</code>```

```<code>timestamp               value
2018-01-08 06:13:00     143
2018-01-08 06:14:00     324
2018-01-08 06:15:00     324
2018-01-08 06:16:00     324
2018-01-08 06:17:00     324
2018-01-08 06:20:00     324(remove)
2018-01-08 06:35:00     324
2018-01-08 06:36:00     324
2018-01-08 06:37:00     324
2018-01-08 06:38:00     324
2018-01-08 06:39:00     324
2018-01-08 06:40:00     324
</code>```

Body:
I am working with timeseries data in Pandas (timestamp used as index). I am doing some filtering on my dataset and end up with a dataframe that mostly contains consecutive observations (one-minute data). However, there are also time intervals with only one or a few minutes of obervations. These I would like to exclude. How can I get hold of those short intervals using sth like:

df = df.drop(df[<some boolean condition>].index)

timestamp               value
2018-01-08 06:13:00     143
2018-01-08 06:14:00     324
2018-01-08 06:15:00     324
2018-01-08 06:16:00     324
2018-01-08 06:17:00     324
2018-01-08 06:20:00     324(remove)
2018-01-08 06:35:00     324
2018-01-08 06:36:00     324
2018-01-08 06:37:00     324
2018-01-08 06:38:00     324
2018-01-08 06:39:00     324
2018-01-08 06:40:00     324

Body:
Use:

#convert index to Series
s = df.index.to_series()
#test if 1 Minute difference, then cumulative sum
a = s.diff().ne(pd.Timedelta(1, unit='Min')).cumsum()

#filter if counts of cumulative value greater like N, e.g. 3
N = 3
df = df[a.map(a.value_counts()).gt(N)]
print (df)
                     value
timestamp
2018-01-08 06:13:00    143
2018-01-08 06:14:00    324
2018-01-08 06:15:00    324
2018-01-08 06:16:00    324
2018-01-08 06:17:00    324
2018-01-08 06:35:00    324
2018-01-08 06:36:00    324
2018-01-08 06:37:00    324
2018-01-08 06:38:00    324
2018-01-08 06:39:00    324
2018-01-08 06:40:00    324


问:
How to send sequential requests with comlex logic in send function in Angular
I've got a complex logic in my sendForm function, which allows me to send more then 2 requests at the same time. I want to make my requests to be sent sequentially, one after another. And if previous request returns "bad request" or some other error, then next request should not be sent. Forkjoin isn't my choice because it sends request in parallel. I tried to use combineLatest operator, but it returns only the last values. Any suggestions?</p>

```<code>sendForm() {
    const team = toFormData(this.form.controls.profile.value);

    // First request
    this.teamService.sendTeam(team).subscribe(() => console.log('TEAM UPDATED'));

    // 2nd Block with requests
    this.form.controls.members.value.map((m, index) => {
      const member = toFormData(m);

      if (m.id) {
        this.teamService.updateMember(member, m.id).subscribe(() => {
        console.log('MEMBER UPDATED');
        });
      } else {
         this.teamService.createMember(member).subscribe(() => console.log('MEMBER CREATED'));
      }
    });

    // 3rd Block with requests
    this.form.controls.drinks.value.map((d, index) => {
      const drink = toFormData(d);

      if (d.id) {
        this.teamService.updateDrink(drink, d.id).subscribe(() => {
        console.log('DRINK UPDATED');
        });
      } else {
         this.teamService.createDrink(drink).subscribe(() => console.log('DRINK CREATED'));
      }
  });
}
</code>```

答:
you need to build pipes with concat:

sendForm() {
  const team = toFormData(this.form.controls.profile.value);

  // First request
  this.teamService.sendTeam(team).pipe(

    // once team has been sent does this block
    // concat makes a sequence
    concatMap(() => {
      const tasks$ = [];

      // 2nd Block with requests
      for (const m of this.form.controls.members.value) {
        const member = toFormData(m);
        if (m.id) {
          tasks$.push(this.teamService.updateMember(member, m.id));
        } else {
         tasks$.push(this.teamService.createMember(member));
        }
      }

      // 3rd Block with requests
      for (const d of this.form.controls.drinks.value) {
      const drink = toFormData(d);
      if (d.id) {
        tasks$.push(this.teamService.updateDrink(drink, d.id));
      } else {
        tasks$.push(this.teamService.createDrink(drink));
      }

      // using concat for the tasks.
      return tasks$.length ? concat(...tasks$) : EMPTY;
    }),

  ).subscribe();
}
```

Body:
I've got a complex logic in my sendForm function, which allows me to send more then 2 requests at the same time. I want to make my requests to be sent sequentially, one after another. And if previous request returns "bad request" or some other error, then next request should not be sent. Forkjoin isn't my choice because it sends request in parallel. I tried to use combineLatest operator, but it returns only the last values. Any suggestions?

sendForm() {
    const team = toFormData(this.form.controls.profile.value);

    // First request
    this.teamService.sendTeam(team).subscribe(() => console.log('TEAM UPDATED'));

    // 2nd Block with requests
    this.form.controls.members.value.map((m, index) => {
      const member = toFormData(m);

      if (m.id) {
        this.teamService.updateMember(member, m.id).subscribe(() => {
        console.log('MEMBER UPDATED');
        });
      } else {
         this.teamService.createMember(member).subscribe(() => console.log('MEMBER CREATED'));
      }
    });

    // 3rd Block with requests
    this.form.controls.drinks.value.map((d, index) => {
      const drink = toFormData(d);

      if (d.id) {
        this.teamService.updateDrink(drink, d.id).subscribe(() => {
        console.log('DRINK UPDATED');
        });
      } else {
         this.teamService.createDrink(drink).subscribe(() => console.log('DRINK CREATED'));
      }
  });
}


问:
NSPointerArray weird compaction
I have a weak NSPointerArray with some NSObject that has been released. Before calling compact what I see is:

```<code>(lldb) po [currentArray count]
1
(lldb) po [currentArray pointerAtIndex:0]
<nil>
(lldb) po [currentArray allObjects]
<__NSArrayM 0x16f04f00>(

)
</code>```

That makes sense, but what is really weird is that when I call compact on that array I see the same values! Count still returns 1 and pointerAtIndex:0 is nil.

Why the nil hasn't been removed?

EDIT

Here's the full code (yeah it's XCTesting framework):

```<code>- (void)testCompaction {
    __weak id testingPointer = nil;

    NSPointerArray *weakArray = [NSPointerArray weakObjectsPointerArray];

    @autoreleasepool {

        NSObject *someObj = [[NSObject alloc] init];

        testingPointer = someObj;

        [weakArray addPointer:(__bridge void*)testingPointer];

        NSLog(@"before compaction inside autorelease: testingPointer = %@ count = %d, allObjects = %@, pointerAtIndex:0 = %@, pointerAtIndex:0 class = %@", testingPointer, [weakArray count], [weakArray allObjects], [weakArray pointerAtIndex:0], [(id)[weakArray pointerAtIndex:0] class]);

        someObj = nil;
    }

    NSLog(@"before compaction outside autorelease: testingPointer = %@ count = %d, allObjects = %@, pointerAtIndex:0 = %@, pointerAtIndex:0 class = %@", testingPointer, [weakArray count], [weakArray allObjects], [weakArray pointerAtIndex:0], [(id)[weakArray pointerAtIndex:0] class]);

    [weakArray compact];

    NSLog(@"after compaction outside autorelease: testingPointer = %@ count = %d, allObjects = %@, pointerAtIndex:0 = %@, pointerAtIndex:0 class = %@", testingPointer, [weakArray count], [weakArray allObjects], [weakArray pointerAtIndex:0], [(id)[weakArray pointerAtIndex:0] class]);
}
</code>```

and logs:

```<code>  before compaction inside autorelease: testingPointer = <NSObject: 0x7de7ff80> count = 1, allObjects = (
    "<NSObject: 0x7de7ff80>"
), pointerAtIndex:0 = <NSObject: 0x7de7ff80>, pointerAtIndex:0 class = NSObject
2015-07-20 14:27:14.062 AppetizeSuite copy[54144:9019054] before compaction outside autorelease: testingPointer = (null) count = 1, allObjects = (
), pointerAtIndex:0 = (null), pointerAtIndex:0 class = (null)
2015-07-20 14:27:22.615 AppetizeSuite copy[54144:9019054] after compaction outside autorelease: testingPointer = (null) count = 1, allObjects = (
), pointerAtIndex:0 = (null), pointerAtIndex:0 class = (null)
</code>```

Why the compact method does not delete the first pointer? It's clearly a nil before calling compact.

答:
It's already a few year and using the sample code shows no change.

However, -compact is perfectly working when the update of the pointer is performed using the method -replacePointerAtIndex:withPointer:

In the code above, replacing

```<code>someObj = nil;
</code>```

by

```<code> [weakArray replacePointerAtIndex:0 withPointer:nil];
</code>```

provides the expected result after [weakArray compact]; and the code will crash at the last NSLog

Title: NSPointerArray weird compaction

Body:
I have a weak NSPointerArray with some NSObject that has been released. Before calling compact what I see is:

(lldb) po [currentArray count]
1
(lldb) po [currentArray pointerAtIndex:0]
<nil>
(lldb) po [currentArray allObjects]
<__NSArrayM 0x16f04f00>(

)

That makes sense, but what is really weird is that when I call compact on that array I see the same values! Count still returns 1 and pointerAtIndex:0 is nil.

Why the nil hasn't been removed?

EDIT

Here's the full code (yeah it's XCTesting framework):

- (void)testCompaction {
    __weak id testingPointer = nil;

    NSPointerArray *weakArray = [NSPointerArray weakObjectsPointerArray];

    @autoreleasepool {

        NSObject *someObj = [[NSObject alloc] init];

        testingPointer = someObj;

        [weakArray addPointer:(__bridge void*)testingPointer];

        NSLog(@"before compaction inside autorelease: testingPointer = %@ count = %d, allObjects = %@, pointerAtIndex:0 = %@, pointerAtIndex:0 class = %@", testingPointer, [weakArray count], [weakArray allObjects], [weakArray pointerAtIndex:0], [(id)[weakArray pointerAtIndex:0] class]);

        someObj = nil;
    }

    NSLog(@"before compaction outside autorelease: testingPointer = %@ count = %d, allObjects = %@, pointerAtIndex:0 = %@, pointerAtIndex:0 class = %@", testingPointer, [weakArray count], [weakArray allObjects], [weakArray pointerAtIndex:0], [(id)[weakArray pointerAtIndex:0] class]);

    [weakArray compact];

    NSLog(@"after compaction outside autorelease: testingPointer = %@ count = %d, allObjects = %@, pointerAtIndex:0 = %@, pointerAtIndex:0 class = %@", testingPointer, [weakArray count], [weakArray allObjects], [weakArray pointerAtIndex:0], [(id)[weakArray pointerAtIndex:0] class]);
}

and logs:

  before compaction inside autorelease: testingPointer = <NSObject: 0x7de7ff80> count = 1, allObjects = (
    "<NSObject: 0x7de7ff80>"
), pointerAtIndex:0 = <NSObject: 0x7de7ff80>, pointerAtIndex:0 class = NSObject
2015-07-20 14:27:14.062 AppetizeSuite copy[54144:9019054] before compaction outside autorelease: testingPointer = (null) count = 1, allObjects = (
), pointerAtIndex:0 = (null), pointerAtIndex:0 class = (null)
2015-07-20 14:27:22.615 AppetizeSuite copy[54144:9019054] after compaction outside autorelease: testingPointer = (null) count = 1, allObjects = (
), pointerAtIndex:0 = (null), pointerAtIndex:0 class = (null)

Why the compact method does not delete the first pointer? It's clearly a nil before calling compact.

Body:
It's already a few year and using the sample code shows no change.

However, -compact is perfectly working when the update of the pointer is performed using the method -replacePointerAtIndex:withPointer:

In the code above, replacing

someObj = nil;

by

 [weakArray replacePointerAtIndex:0 withPointer:nil];

provides the expected result after [weakArray compact]; and the code will crash at the last NSLog


问:
Postgresql | How to attribute index updation time in Sql Inserts
How can we attribute time taken in index updation process while executing an insert statement in postgresql?</p>

答: The only way I've found to get good answers is too benchmark with and without the index.</p>


问:
Your Ruby version is 2.2.4, but your Gemfile specified 2.3.0?
I'm trying to bundle install a ruby project in Git Bash but I'm getting the above message.

```<code>ruby -v
</code>```

ruby 2.2.4p230 (2015-12-16 revision 53155) [i836-mingw32]

```<code>gem -v
</code>```

2.3.0

New to Ruby so its really frustrating. I'm trying to do the project below
http://www.viralrails.com/?p=25

答:
Install bundler after installing ruby 2.4.0.

```<code>gem install bundler
</code>```

If you installed bundler before installing ruby 2.4.0 then you should reinstall bundler or update it.

Also if the above command didn't work.

```<code>gem update bundler
</code>```

Body:
I'm trying to bundle install a ruby project in Git Bash but I'm getting the above message.

ruby -v

ruby 2.2.4p230 (2015-12-16 revision 53155) [i836-mingw32]

gem -v

2.3.0

New to Ruby so its really frustrating. I'm trying to do the project below
http://www.viralrails.com/?p=25

Body:
Install bundler after installing ruby 2.4.0.

gem install bundler

If you installed bundler before installing ruby 2.4.0 then you should reinstall bundler or update it.

Also if the above command didn't work.

gem update bundler


问:
How to check for collisions with SFML (While using a Base class Entity)

class Entity
{
private:
    //Functions
    void initiVariables();

protected:
    //Variables
    float velocity;
    sf::Sprite  sprite;
    sf::Texture* texture;

    MovementComponent* movementComponent;
    AnimationComponent* animationComponent;
    HitboxComponent* hitboxComponent;

    //Component Functions
    void setTexture(sf::Texture& texture);
    void **strong text**MovementComponent(float maxVelocity, float acceleration, float deacceleration);
    void AnimationComponent(sf::Sprite& sprite, sf::Texture& texture);
    void HitboxComponent(sf::Sprite& sprite, sf::Color wireColor, float wireThickness);

public:
    //Constructor & Deconstructor
    Entity();
    virtual~Entity();

    //Accessor
    const sf::FloatRect& getGlobalBounds() const;

//when I check for Collsion sprite.getGlobalBounds().intersect(sprite.getGlobalBounds())
//it remains true for the entire time what am doing wrong?

    //Funtions
    void setPosition(const float x, const float y);
    virtual void move(const float x, const float y, const float& dt);
    virtual void update(const float& dt);
    virtual void render(sf::RenderTarget* target);
};
```

答:
You can do simple inheritance from the Entity class. I don't know why your program crashes when returning sf::FloatRect objects. This should also be the correct solution to this problem.

```<code>#include <SFML/Graphics.hpp>
#include <iostream>

class Entity : public sf::RectangleShape {
public:
    bool isColliding(Entity const& other) {
        return this->getGlobalBounds().intersects(other.getGlobalBounds());
    }
};

class Player : public Entity {};
class Zombie : public Entity {};

int main() {
    Player player;
    player.setPosition({ 200, 200 });
    player.setSize({ 100, 100 });

    Zombie enemy;
    enemy.setPosition({ 151, 151 });
    enemy.setSize({ 50, 50 });

    std::cout << player.isColliding(enemy);
}
</code>```

Body:
You can do simple inheritance from the Entity class. I don't know why your program crashes when returning sf::FloatRect objects. This should also be the correct solution to this problem.

#include <SFML/Graphics.hpp>
#include <iostream>

class Entity : public sf::RectangleShape {
public:
    bool isColliding(Entity const& other) {
        return this->getGlobalBounds().intersects(other.getGlobalBounds());
    }
};

class Player : public Entity {};
class Zombie : public Entity {};

int main() {
    Player player;
    player.setPosition({ 200, 200 });
    player.setSize({ 100, 100 });

    Zombie enemy;
    enemy.setPosition({ 151, 151 });
    enemy.setSize({ 50, 50 });

    std::cout << player.isColliding(enemy);
}


问:
Angular9 SSR meta tags not loading inside of promises
I'm using Angular Universal and NestJS for my SSR. When I run npm run build:ssr and deploy it I get no errors, but the meta tags inside of promises are not shown when linking the website, but links for routes where I set the meta tags at the root level of ngOnInit do load the meta tags as expected when linking the website.

Code for setting meta tags.

```<code>generateTags({ title = '', description = '', image = '' }) {

 this.title.setTitle(title);
 this.meta.addTags([
   // Open Graph
   { name: 'og:url', content: `https://firestarter.fireship.io${this.router.url}` },
   { name: 'og:title', content: title },
   { name: 'og:description', content: description },
   { name: 'og:image', content: image },
   // Twitter Card
   { name: 'twitter:card', content: 'summary' },
   { name: 'twitter:site', content: '@fireship_dev' },
 ]);
}
</code>```

Eksample of code that does not load the meta tags

```<code>this.db.firestore.collection('users').doc(this.customerId).get().then((userRef) => {
  this.seo.generateTags({
    title: userRef.data().displayName,
    description: userRef.data().about,
    image: userRef.data().photoURL,
  })
})
</code>```

Example of code that does not load the meta tags

```<code>this.seo.generateTags({
  title: userRef.data().displayName,
  description: userRef.data().about,
  image: userRef.data().photoURL,
})
</code>```

Example with full component:

```<code>import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { AngularFirestore } from '@angular/fire/firestore';
import { SeoService } from 'src/app/services/seo.service';

@Component({
  selector: 'app-profileviewer',
  templateUrl: './profileviewer.component.html',
  styleUrls: ['./profileviewer.component.css']
})
export class ProfileviewerComponent implements OnInit {

  customerId: string;

  constructor(
    private route: ActivatedRoute,
    private db: AngularFirestore,
    private seo: SeoService) { }

  ngOnInit() {
    this.customerId = this.route.snapshot.paramMap.get('id');

    this.db.firestore.collection('users').doc(this.customerId).get().then((userRef) => {
      this.seo.generateTags({
        title: userRef.data().displayName,
        description: userRef.data().about,
        image: userRef.data().photoURL,
      })
    })
  }
}
</code>```

Who can I display content from e.g firebase in my meta tags with Angular9 with NestJS?

I have made a dummy project on GitHub where I get this error. To reproduce attach firebase project in the environments file and run npm run serve:ssr (maybe npm run build:ssr if you get an error) and see in the source code in chrome that the meta tags are not rendered.

EDIT:
I have tried using resolve to fix this issue, but it still doesn't work with promises. This is the resolve script that I use:

```<code>import { Injectable } from '@angular/core';
import { AngularFirestore } from '@angular/fire/firestore';
import { Resolve, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { Http } from '@angular/http';

@Injectable({
  providedIn: 'root'
})
export class LoadSeoService implements Resolve<any> {
  constructor (private http: Http, private db: AngularFirestore) {

  }

  resolve (route: ActivatedRouteSnapshot, rstate: RouterStateSnapshot) {
    // Works
    return "test"

    // Does not work
    // return this.db.firestore.collection("articles").doc(route.params['id'].substr(route.params['id'].length - 20)).get();
  }
}
</code>```

The code I use in my component:

```<code>this.route.data.subscribe(data => {
  console.log(data.cres)

  this.seo.generateTags({
    title: data.cres,
    description: data.cres,
    image: data.cres,
  })
});
</code>```

答:
Your call to firestore is async so SSR finishes before the promise resolves. All async functions need to be resolved on router level so angular waits for them to be finished.

Try adding the firestore request to a route resolver and use the data from resolver inside the ngOnInit() function.

see more infos here: https://angular.io/api/router/Resolve

Body:
I'm using Angular Universal and NestJS for my SSR. When I run npm run build:ssr and deploy it I get no errors, but the meta tags inside of promises are not shown when linking the website, but links for routes where I set the meta tags at the root level of ngOnInit do load the meta tags as expected when linking the website.

Code for setting meta tags.

generateTags({ title = '', description = '', image = '' }) {

 this.title.setTitle(title);
 this.meta.addTags([
   // Open Graph
   { name: 'og:url', content: `https://firestarter.fireship.io${this.router.url}` },
   { name: 'og:title', content: title },
   { name: 'og:description', content: description },
   { name: 'og:image', content: image },
   // Twitter Card
   { name: 'twitter:card', content: 'summary' },
   { name: 'twitter:site', content: '@fireship_dev' },
 ]);
}

Eksample of code that does not load the meta tags

this.db.firestore.collection('users').doc(this.customerId).get().then((userRef) => {
  this.seo.generateTags({
    title: userRef.data().displayName,
    description: userRef.data().about,
    image: userRef.data().photoURL,
  })
})

Example of code that does not load the meta tags

this.seo.generateTags({
  title: userRef.data().displayName,
  description: userRef.data().about,
  image: userRef.data().photoURL,
})

Example with full component:

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { AngularFirestore } from '@angular/fire/firestore';
import { SeoService } from 'src/app/services/seo.service';

@Component({
  selector: 'app-profileviewer',
  templateUrl: './profileviewer.component.html',
  styleUrls: ['./profileviewer.component.css']
})
export class ProfileviewerComponent implements OnInit {

  customerId: string;

  constructor(
    private route: ActivatedRoute,
    private db: AngularFirestore,
    private seo: SeoService) { }

  ngOnInit() {
    this.customerId = this.route.snapshot.paramMap.get('id');

    this.db.firestore.collection('users').doc(this.customerId).get().then((userRef) => {
      this.seo.generateTags({
        title: userRef.data().displayName,
        description: userRef.data().about,
        image: userRef.data().photoURL,
      })
    })
  }
}

Who can I display content from e.g firebase in my meta tags with Angular9 with NestJS?

I have made a dummy project on GitHub where I get this error. To reproduce attach firebase project in the environments file and run npm run serve:ssr (maybe npm run build:ssr if you get an error) and see in the source code in chrome that the meta tags are not rendered.

EDIT:
I have tried using resolve to fix this issue, but it still doesn't work with promises. This is the resolve script that I use:

import { Injectable } from '@angular/core';
import { AngularFirestore } from '@angular/fire/firestore';
import { Resolve, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { Http } from '@angular/http';

@Injectable({
  providedIn: 'root'
})
export class LoadSeoService implements Resolve<any> {
  constructor (private http: Http, private db: AngularFirestore) {

  }

  resolve (route: ActivatedRouteSnapshot, rstate: RouterStateSnapshot) {
    // Works
    return "test"

    // Does not work
    // return this.db.firestore.collection("articles").doc(route.params['id'].substr(route.params['id'].length - 20)).get();
  }
}

The code I use in my component:

this.route.data.subscribe(data => {
  console.log(data.cres)

  this.seo.generateTags({
    title: data.cres,
    description: data.cres,
    image: data.cres,
  })
});


问:
Component not rendering when calling this.setState()
I have a component which calling a method in componentDidMount.
This method fetches the data and updates state through this.setState(). But then nothing happens. State is updating, but component is not rendering.

There is the code:

```<code>import React from 'react';
import TimelineChart from './TimeLineChart/index.js';
import axios from 'axios';

class MoneyChart extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            chartData: [{ x: 0, y1: 0, y2: 0 }]
        };
      }
    componentDidMount() {
        this.fillData()
    }

  fillData = () => {
    let prepChart = [{ x: 0, y1: 0, y2: 0 }]
        axios.get('http://0.0.0.0:10003/stream')
        .then(res => {
            res.data.items[0].items.forEach(el => {
                prepChart.push({
                    x: el.date_time,
                    y1: el.total,
                    y2: 0

                })
            });
            this.update_state(prepChart);
        })
}
    update_state(prepChart) {
        this.setState ({
        chartData: prepChart
        },
        () => console.log(this.state.chartData)
        );
    }

    render () {
        return(<div>
            <TimelineChart height={800} data={this.state.chartData} titleMap={{ y1: 'Этот год', y2: 'Прошлый год' }} />,
        </div>)
    }
}

export default MoneyChart;
</code>```

Here is the TimelineChart code:

```<code>import React from 'react';
import { Chart, Tooltip, Geom, Legend, Axis } from 'bizcharts';
import DataSet from '@antv/data-set';
// import Slider from 'bizcharts-plugin-slider';

import styles from './index.less';

class TimelineChart extends React.Component {
  render() {
    const {
      title,
      height = 400,
      padding = [60, 20, 40, 40],
      titleMap = {
        y1: 'y1',
        y2: 'y2',
      },
      borderWidth = 2,
      data: sourceData,
    } = this.props;

    const data = Array.isArray(sourceData) ? sourceData : [{ x: 0, y1: 0, y2: 0 }];

    data.sort((a, b) => a.x - b.x);

    let max;
    if (data[0] && data[0].y1 && data[0].y2) {
      max = Math.max(
        [...data].sort((a, b) => b.y1 - a.y1)[0].y1,
        [...data].sort((a, b) => b.y2 - a.y2)[0].y2
      );
    }

    const ds = new DataSet({
      state: {
        start: data[0].x,
        end: data[data.length - 1].x,
      },
    });

    const dv = ds.createView();
    dv.source(data)
      .transform({
        type: 'filter',
        callback: obj => {
          const date = obj.x;
          return date <= ds.state.end && date >= ds.state.start;
        },
      })
      .transform({
        type: 'map',
        callback(row) {
          const newRow = { ...row };
          newRow[titleMap.y1] = row.y1;
          newRow[titleMap.y2] = row.y2;
          return newRow;
        },
      })
      .transform({
        type: 'fold',
        fields: [titleMap.y1, titleMap.y2], // 展开字段集
        key: 'key', // key字段
        value: 'value', // value字段
      });

    const timeScale = {
      type: 'time',
      tickInterval: 60 * 60 * 1000,
      mask: 'HH:mm',
      range: [0, 1],
    };

    const cols = {
      x: timeScale,
      value: {
        max,
        min: 0,
      },
    };

    return (
      <div className={styles.timelineChart} style={{ height: height + 30 }}>
        <div>
          {title && <h4>{title}</h4>}
          <Chart height={height} padding={padding} data={dv} scale={cols} forceFit>
            <Axis name="x" />
            <Tooltip />
            <Legend name="key" position="top" />
            <Geom type="line" position="x*value" size={borderWidth} color="key" />
          </Chart>
        </div>
      </div>
    );
  }
}

export default TimelineChart;
</code>```

I expect it to re-render after every state change. How can i achieve that?

答:
Try binding update_state to this with public class fields syntax:

```<code>update_state = (prepChart) => {
  this.setState({ hartData: prepChart }, () =>
    console.log(this.state.chartData)
  );
};
</code>```

Or just bind it in the constructor:

```<code>  constructor(props) {
    super(props);
    this.state = {isToggleOn: true};

    // This binding is necessary to make `this` work in the callback
    this.update_state = this.update_state.bind(this);
  }
</code>```

Body:
I have a component which calling a method in componentDidMount.
This method fetches the data and updates state through this.setState(). But then nothing happens. State is updating, but component is not rendering.

There is the code:

import React from 'react';
import TimelineChart from './TimeLineChart/index.js';
import axios from 'axios';

class MoneyChart extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            chartData: [{ x: 0, y1: 0, y2: 0 }]
        };
      }
    componentDidMount() {
        this.fillData()
    }

  fillData = () => {
    let prepChart = [{ x: 0, y1: 0, y2: 0 }]
        axios.get('http://0.0.0.0:10003/stream')
        .then(res => {
            res.data.items[0].items.forEach(el => {
                prepChart.push({
                    x: el.date_time,
                    y1: el.total,
                    y2: 0

                })
            });
            this.update_state(prepChart);
        })
}
    update_state(prepChart) {
        this.setState ({
        chartData: prepChart
        },
        () => console.log(this.state.chartData)
        );
    }

    render () {
        return(

            <TimelineChart height={800} data={this.state.chartData} titleMap={{ y1: 'Этот год', y2: 'Прошлый год' }} />,

)
    }
}

export default MoneyChart;

Here is the TimelineChart code:

import React from 'react';
import { Chart, Tooltip, Geom, Legend, Axis } from 'bizcharts';
import DataSet from '@antv/data-set';
// import Slider from 'bizcharts-plugin-slider';

import styles from './index.less';

class TimelineChart extends React.Component {
  render() {
    const {
      title,
      height = 400,
      padding = [60, 20, 40, 40],
      titleMap = {
        y1: 'y1',
        y2: 'y2',
      },
      borderWidth = 2,
      data: sourceData,
    } = this.props;

    const data = Array.isArray(sourceData) ? sourceData : [{ x: 0, y1: 0, y2: 0 }];

    data.sort((a, b) => a.x - b.x);

    let max;
    if (data[0] && data[0].y1 && data[0].y2) {
      max = Math.max(
        [...data].sort((a, b) => b.y1 - a.y1)[0].y1,
        [...data].sort((a, b) => b.y2 - a.y2)[0].y2
      );
    }

    const ds = new DataSet({
      state: {
        start: data[0].x,
        end: data[data.length - 1].x,
      },
    });

    const dv = ds.createView();
    dv.source(data)
      .transform({
        type: 'filter',
        callback: obj => {
          const date = obj.x;
          return date <= ds.state.end && date >= ds.state.start;
        },
      })
      .transform({
        type: 'map',
        callback(row) {
          const newRow = { ...row };
          newRow[titleMap.y1] = row.y1;
          newRow[titleMap.y2] = row.y2;
          return newRow;
        },
      })
      .transform({
        type: 'fold',
        fields: [titleMap.y1, titleMap.y2], // 展开字段集
        key: 'key', // key字段
        value: 'value', // value字段
      });

    const timeScale = {
      type: 'time',
      tickInterval: 60 * 60 * 1000,
      mask: 'HH:mm',
      range: [0, 1],
    };

    const cols = {
      x: timeScale,
      value: {
        max,
        min: 0,
      },
    };

    return (

          {title &&
{title}
}
          <Chart height={height} padding={padding} data={dv} scale={cols} forceFit>
            <Axis name="x" />
            <Tooltip />
            <Legend name="key" position="top" />
            <Geom type="line" position="x*value" size={borderWidth} color="key" />
          </Chart>

    );
  }
}

export default TimelineChart;

I expect it to re-render after every state change. How can i achieve that?

Body:
Try binding update_state to this with public class fields syntax:

update_state = (prepChart) => {
  this.setState({ hartData: prepChart }, () =>
    console.log(this.state.chartData)
  );
};

Or just bind it in the constructor:

  constructor(props) {
    super(props);
    this.state = {isToggleOn: true};

    // This binding is necessary to make `this` work in the callback
    this.update_state = this.update_state.bind(this);
  }


问:
How to add 2 different C libraries with same name but having entirely different functionalities without changing the name?
How to add 2 different C libraries with same name but having entirely different functionalities without changing the name?

For example one s/w product comes with lib named libabc.so
And my lib is also having the same name libabc.lib.

So, how I can use the both the lib at the same time, without conflicting at runtime

答:
Instead of linking with -labc link with the full file library file paths like /usr/local/lib/libabc.a ./mylib/libabc.a for example.

If you do that the fact that they have the same name shouldn't matter.

What may conflict is if both libraries export symbols with identical names.

If header files also have the same name (e.g. abc.h) your #include statements may also need full paths to make sure you're including the right file.


问:
installing old versions of cv2 using pip
i've been trying to download older versions of cv2 as an easy way to get around not being able to use SIFT.
I've tried the following:

```<code>pip install opencv-contrib-python==3.4.2.17
</code>```

however I get this error:

```<code>ERROR: Could not find a version that satisfies the requirement opencv-contrib-python==3.4.2.17 (from versions: 3.4.8.29, 3.4.9.31, 3.4.9.33, 4.1.2.30, 4.2.0.32, 4.2.0.34)
ERROR: No matching distribution found for opencv-contrib-python==3.4.2.17
</code>```

All the advice I've seen on the site so far tells me to either download these older versions of opencv or to build it myself (which seems like an absolute nightmare)
Anyone have any suggestions on how to install these older versions of cv2?

答:
opencv-contrib-python 3.4.2.17 provides wheels for Pythons up to 3.7. Probably you use Python 3.8.

Use Python 3.7 (or lower). Or compile from sources for 3.8.

Body:
i've been trying to download older versions of cv2 as an easy way to get around not being able to use SIFT.
I've tried the following:

pip install opencv-contrib-python==3.4.2.17

however I get this error:

ERROR: Could not find a version that satisfies the requirement opencv-contrib-python==3.4.2.17 (from versions: 3.4.8.29, 3.4.9.31, 3.4.9.33, 4.1.2.30, 4.2.0.32, 4.2.0.34)
ERROR: No matching distribution found for opencv-contrib-python==3.4.2.17

All the advice I've seen on the site so far tells me to either download these older versions of opencv or to build it myself (which seems like an absolute nightmare)
Anyone have any suggestions on how to install these older versions of cv2?


问:
AssertContains on strings in jUnit
Is there a nicer way to write in jUnit</p>

```<code>String x = "foo bar";
Assert.assertTrue(x.contains("foo"));
</code>```

答:
Example (junit version- 4.13)

```<code>import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Test;

public class TestStr {

@Test
public void testThatStringIsContained(){
    String testStr = "hi,i am a test string";
    assertThat(testStr).contains("test");
 }

}
</code>```

ContentLicense: CC BY-SA 2.5

Title: AssertContains on strings in jUnit

Body:
Is there a nicer way to write in jUnit

String x = "foo bar";
Assert.assertTrue(x.contains("foo"));

Body:
Example (junit version- 4.13)

import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Test;

public class TestStr {

@Test
public void testThatStringIsContained(){
    String testStr = "hi,i am a test string";
    assertThat(testStr).contains("test");
 }

}


问:
Finding frequency of words in Python and frequencies in a descending order
I am trying to find the frequency of the words in a .txt file and enrich it by sorting the number of occurrences of each word.

So far, I completed %90 of the task. What is left is to sort the number of occurrences in descending order.

Here is my code:

```<code>def frequency_check(lines):
    print("Frequency of words in file")
    words = re.findall(r"\w+", lines)
    item_list = []

    for item in words:
        if item not in item_list:
            item_count = words.count(item)
            print("{} : {} times".format(item, item_count))
            item_list.append(item)

with open("original-3.txt", 'r') as file1:
    lines = file1.read().lower()
    frequency_check(lines)
</code>```

This is the .txt file on which I am finding the word frequency,

Here's the output I get:

```<code>Frequency of words in file
return : 2 times
all : 1 times
non : 1 times
overlapping : 1 times
matches : 3 times
of : 5 times
pattern : 3 times
in : 4 times
string : 2 times
as : 1 times
a : 3 times
list : 3 times
strings : 1 times
the : 6 times
is : 1 times
scanned : 1 times
left : 1 times
to : 1 times
right : 1 times
and : 1 times
are : 3 times
returned : 1 times
order : 1 times
found : 1 times
if : 2 times
one : 2 times
or : 1 times
more : 2 times
groups : 2 times
present : 1 times
this : 1 times
will : 1 times
be : 1 times
tuples : 1 times
has : 1 times
than : 1 times
group : 1 times
empty : 1 times
included : 1 times
result : 1 times
unless : 1 times
they : 1 times
touch : 1 times
beginning : 1 times
another : 1 times
match : 1 times

Process finished with exit code 0
</code>```

It would be a great challenge to sort these and output from highest number of occurrences to lowest.

PS:I thought about using dictionaries, however, dictionaries are immutable and I can't use sort method on them

Any ideas?

Thank you very much

答:
I agree with @lolu that you should use a dictionary but if you still want to use a list, here is a solution:

```<code>import re

def frequency_check(lines):
    print("Frequency of words in file")
    words = re.findall(r"\w+", lines)
    unique_words = set(words)
    item_list = []

    for item in unique_words:
        item_count = words.count(item)
        item_list.append((item, item_count))

    item_list.sort(key=lambda t: (t[1], t[0]), reverse=True)
    for item, item_count in item_list:
        print("{} : {} times".format(item, item_count))

with open("original-3.txt", 'r') as file1:
    lines = file1.read().lower()
    frequency_check(lines)
</code>```

And a much better implementation using collections.Counter:

```<code>import re
from collections import Counter

def frequency_check(lines):
    print("Frequency of words in file")
    words = re.findall(r"\w+", lines)
    word_counts = Counter(words)
    for item, item_count in word_counts.most_common():
        print("{} : {} times".format(item, item_count))

with open("original-3.txt", 'r') as file1:
    lines = file1.read().lower()
    frequency_check(lines)
</code>```

Body:
I am trying to find the frequency of the words in a .txt file and enrich it by sorting the number of occurrences of each word.

So far, I completed %90 of the task. What is left is to sort the number of occurrences in descending order.

Here is my code:

def frequency_check(lines):
    print("Frequency of words in file")
    words = re.findall(r"\w+", lines)
    item_list = []

    for item in words:
        if item not in item_list:
            item_count = words.count(item)
            print("{} : {} times".format(item, item_count))
            item_list.append(item)

with open("original-3.txt", 'r') as file1:
    lines = file1.read().lower()
    frequency_check(lines)

This is the .txt file on which I am finding the word frequency,

Here's the output I get:

Frequency of words in file
return : 2 times
all : 1 times
non : 1 times
overlapping : 1 times
matches : 3 times
of : 5 times
pattern : 3 times
in : 4 times
string : 2 times
as : 1 times
a : 3 times
list : 3 times
strings : 1 times
the : 6 times
is : 1 times
scanned : 1 times
left : 1 times
to : 1 times
right : 1 times
and : 1 times
are : 3 times
returned : 1 times
order : 1 times
found : 1 times
if : 2 times
one : 2 times
or : 1 times
more : 2 times
groups : 2 times
present : 1 times
this : 1 times
will : 1 times
be : 1 times
tuples : 1 times
has : 1 times
than : 1 times
group : 1 times
empty : 1 times
included : 1 times
result : 1 times
unless : 1 times
they : 1 times
touch : 1 times
beginning : 1 times
another : 1 times
match : 1 times

Process finished with exit code 0

It would be a great challenge to sort these and output from highest number of occurrences to lowest.

PS:I thought about using dictionaries, however, dictionaries are immutable and I can't use sort method on them

Any ideas?

Thank you very much

Body:
I agree with @lolu that you should use a dictionary but if you still want to use a list, here is a solution:

import re

def frequency_check(lines):
    print("Frequency of words in file")
    words = re.findall(r"\w+", lines)
    unique_words = set(words)
    item_list = []

    for item in unique_words:
        item_count = words.count(item)
        item_list.append((item, item_count))

    item_list.sort(key=lambda t: (t[1], t[0]), reverse=True)
    for item, item_count in item_list:
        print("{} : {} times".format(item, item_count))

with open("original-3.txt", 'r') as file1:
    lines = file1.read().lower()
    frequency_check(lines)

And a much better implementation using collections.Counter:

import re
from collections import Counter

def frequency_check(lines):
    print("Frequency of words in file")
    words = re.findall(r"\w+", lines)
    word_counts = Counter(words)
    for item, item_count in word_counts.most_common():
        print("{} : {} times".format(item, item_count))

with open("original-3.txt", 'r') as file1:
    lines = file1.read().lower()
    frequency_check(lines)


问:
Select the value of an element by name
How to access the value of this input field that is checked by its name attribute using Javascript :

```<code><input type="radio" class="radioButton" name="rate" value="1">
<input type="radio" class="radioButton" name="rate" value="2">
<input type="radio" class="radioButton" name="rate" value="3">
<input type="radio" class="radioButton" name="rate" value="4">
</code>```

I write this :

```<code>document.querySelector('input[name="rate"]:checked').value;
</code>```

but there is an error:

```<code>TypeError: document.querySelector(...) is null
</code>```

And I do not want to be checked any inputs by default

答:
You can check if any element matches your querySelector before accessing the value like this:

document.querySelector('input[name="rate"]:checked') && document.querySelector('input[name="rate"]:checked').value
```

Title: Select the value of an element by name

Body:
How to access the value of this input field that is checked by its name attribute using Javascript :

<input type="radio" class="radioButton" name="rate" value="1">
<input type="radio" class="radioButton" name="rate" value="2">
<input type="radio" class="radioButton" name="rate" value="3">
<input type="radio" class="radioButton" name="rate" value="4">

I write this :

document.querySelector('input[name="rate"]:checked').value;

but there is an error:

TypeError: document.querySelector(...) is null

And I do not want to be checked any inputs by default


问:
how to identify the triggers applyed to (associted with) a table in mysql?
I need to know the triggers associated with the a particular table in mysql.

I need to delete it so.

Please help me. Thanks in advance.

答:
List of associated triggers:

```<code>SELECT * FROM information_schema.triggers WHERE EVENT_OBJECT_SCHEMA = 'schema_name' AND EVENT_OBJECT_TABLE = 'table_name';
</code>```

Use DROP TRIGGER command to delete one.

Body:
List of associated triggers:

SELECT * FROM information_schema.triggers WHERE EVENT_OBJECT_SCHEMA = 'schema_name' AND EVENT_OBJECT_TABLE = 'table_name';

Use DROP TRIGGER command to delete one.


问:
How can I scrape "view" count of a comment with BeautifulSoup?
I'm trying to scrape customer complaint data on a website. I can get the headline and date but cannot figure out how to get the view count.

This is the code to get the headline:

```<code>headers = {'User-Agent':'Mozilla/5.0'}

complaints = []
time = []

for i in range(100):
  r = requests.get(f'https://www.sikayetvar.com/sikayetler?brand=bosch&page={i}')
  soup = bs(r.content, 'html.parser')
  complaints += soup.find_all('h5', {"class":"card-title"})
  time += soup.find_all('span', {"class":"info-icn time-tooltip"})
</code>```

The count of the complaints:

I try to get the number "479" with this code:

```<code>site = 'https://www.sikayetvar.com/sikayetler?brand=bosch'

r = requests.get(site)
soup = bs(r.content, 'html.parser')
time = soup.find_all('span', {"class":"count"})
</code>```

It returns:

```<code>print(time[0])
<span class="count">-</span>

print(time[0].text)
-
</code>```

I just get "-" instead of "479". Can anyone tell me what I'm doing wrong or a way to get that number?

Thanks in advance

答:
This is one of the ways how you can parse the names and their concerning counts from that site:

```<code>import requests
from bs4 import BeautifulSoup

link = 'https://collector.sikayetvar.com/complaints/view-count?'
url = 'https://www.sikayetvar.com/sikayetler?brand=bosch&page=1'

def get_count(data_id):
    r = requests.get(link,params={'complaints':f'{data_id}'})
    complaints = r.json()[0]['viewCount']
    return complaints

r = requests.get(url,headers={"User-Agent":"Mozilla/5.0"})
soup = BeautifulSoup(r.text,"html.parser")
for item in soup.select(".filter-cards > article.card"):
    name = item.select_one("h5.card-title > a").get_text(strip=True)
    complaints = get_count(item['data-id'])
    print(name,complaints)
</code>```

Output are like:

```<code>Ürünleri Alamıyoruz Ve Bosch Hiçbir Sorumluluk Kabul Etmiyor 50
Bosch Buzdolabından Gelen Ses 508
Bosch Online Mağaza Sipariş Gecikmesi 225
Bosch Buzdolabı Soğutmuyor Alarm Ötüyor 499
Bosch Buzdolabı Sebze Ve Meyveliği Su Doluyor 589
Bosch Bulaşık Makinesi E09 Hatası 526
</code>```

Body:
I'm trying to scrape customer complaint data on a website. I can get the headline and date but cannot figure out how to get the view count.

This is the code to get the headline:

headers = {'User-Agent':'Mozilla/5.0'}

complaints = []
time = []

for i in range(100):
  r = requests.get(f'https://www.sikayetvar.com/sikayetler?brand=bosch&page={i}')
  soup = bs(r.content, 'html.parser')
  complaints += soup.find_all('h5', {"class":"card-title"})
  time += soup.find_all('span', {"class":"info-icn time-tooltip"})

The count of the complaints:

I try to get the number "479" with this code:

site = 'https://www.sikayetvar.com/sikayetler?brand=bosch'

r = requests.get(site)
soup = bs(r.content, 'html.parser')
time = soup.find_all('span', {"class":"count"})

It returns:

print(time[0])
-

print(time[0].text)
-

I just get "-" instead of "479". Can anyone tell me what I'm doing wrong or a way to get that number?

Thanks in advance

Body:
This is one of the ways how you can parse the names and their concerning counts from that site:

import requests
from bs4 import BeautifulSoup

link = 'https://collector.sikayetvar.com/complaints/view-count?'
url = 'https://www.sikayetvar.com/sikayetler?brand=bosch&page=1'

def get_count(data_id):
    r = requests.get(link,params={'complaints':f'{data_id}'})
    complaints = r.json()[0]['viewCount']
    return complaints

r = requests.get(url,headers={"User-Agent":"Mozilla/5.0"})
soup = BeautifulSoup(r.text,"html.parser")
for item in soup.select(".filter-cards > article.card"):
    name = item.select_one("h5.card-title > a").get_text(strip=True)
    complaints = get_count(item['data-id'])
    print(name,complaints)

Output are like:

Ürünleri Alamıyoruz Ve Bosch Hiçbir Sorumluluk Kabul Etmiyor 50
Bosch Buzdolabından Gelen Ses 508
Bosch Online Mağaza Sipariş Gecikmesi 225
Bosch Buzdolabı Soğutmuyor Alarm Ötüyor 499
Bosch Buzdolabı Sebze Ve Meyveliği Su Doluyor 589
Bosch Bulaşık Makinesi E09 Hatası 526


问:
Presto fails to import PARQUET files from S3
I have a presto table that imports PARQUET files based on partitions from s3 as follows:

```<code>create table hive.data.datadump
(
    tUnixEpoch varchar,
    tDateTime varchar,
    temperature varchar,
    series varchar,
    sno varchar,
    date date
    )
 WITH (
 format = 'PARQUET',
 partitioned_by = ARRAY['series','sno','date'],
 external_location = 's3a://dev/files');
</code>```

The S3 folder structure where the parquet files are stored looks like:

```<code>s3a://dev/files/series=S5/sno=242=/date=2020-1-23
</code>```

and the partition starts from series.

The original code in pyspark that produces the parquet files has all the schema as String type and I am trying to import that as a string but when I run my create script in Presto, it successfully created the table but fails to import the data.

On Running,

```<code>select * from hive.data.datadump;
</code>```

I get the following error:

```<code>[Code: 16777224, SQL State: ]  Query failed (#20200123_191741_00077_tpmd5): The column tunixepoch is declared as type string, but the Parquet file declares the column as type DOUBLE[Code: 16777224, SQL State: ]  Query failed (#20200123_191741_00077_tpmd5): The column tunixepoch is declared as type string, but the Parquet file declares the column as type DOUBLE
</code>```

Can you guys help to resolve this issue?
Thank You in advance!

答: I ran into same issues and I found out that this was caused by one of the records in my source doesnt have a matching datatype for the column it was complaining about. I am sure this is just data. You need to trap the exact record which doesnt have the right type.</p>

Body:
I have a presto table that imports PARQUET files based on partitions from s3 as follows:

create table hive.data.datadump
(
    tUnixEpoch varchar,
    tDateTime varchar,
    temperature varchar,
    series varchar,
    sno varchar,
    date date
    )
 WITH (
 format = 'PARQUET',
 partitioned_by = ARRAY['series','sno','date'],
 external_location = 's3a://dev/files');

The S3 folder structure where the parquet files are stored looks like:

s3a://dev/files/series=S5/sno=242=/date=2020-1-23

and the partition starts from series.

The original code in pyspark that produces the parquet files has all the schema as String type and I am trying to import that as a string but when I run my create script in Presto, it successfully created the table but fails to import the data.

On Running,

select * from hive.data.datadump;

I get the following error:

[Code: 16777224, SQL State: ]  Query failed (#20200123_191741_00077_tpmd5): The column tunixepoch is declared as type string, but the Parquet file declares the column as type DOUBLE[Code: 16777224, SQL State: ]  Query failed (#20200123_191741_00077_tpmd5): The column tunixepoch is declared as type string, but the Parquet file declares the column as type DOUBLE

Can you guys help to resolve this issue?
Thank You in advance!


问:
Why is Django-1.3 not finding my fixtures for a UnitTest?
I'm trying to use my fixtures in a UnitTest.

```<code>AddFavoritesTestCase(unittest.TestCase):

fixtures = ['/Users/Bryan/work/osqa/fixtures/fixture_questions.json']

def setUp(self):
    self.factory = RequestFactory()

def testAdminCanFavorite(self):
    user = User.objects.get(pk=3)
    ...
    self.assertEqual(response.status_code, 200)

======================================================================
ERROR: testAdminCanFavorite (forum.tests.tests_building_stickyness.AddFavoritesTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/Users/Bryan/work/osqa/forum/tests/tests_building_stickyness.py", line 18, in testAdminCanFavorite
    user = User.objects.get(pk=3) # Kallie has admin
  File "/usr/local/lib/python2.7/site-packages/Django-1.3-py2.7.egg/django/db/models/manager.py", line 132, in get
    return self.get_query_set().get(*args, **kwargs)
  File "/Users/Bryan/work/osqa/forum/models/base.py", line 64, in get
    obj = super(CachedQuerySet, self).get(*args, **kwargs)
  File "/usr/local/lib/python2.7/site-packages/Django-1.3-py2.7.egg/django/db/models/query.py", line 349, in get
    % self.model._meta.object_name)
DoesNotExist: User matching query does not exist.
</code>```

It seems the fixtures are not loading.

I've been able to use the fixtures to populate the database, but for some reason the fixtures aren't being found in the tests.

The path is correct but I can't figure out what's going wrong.

```<code>$ ls /Users/Bryan/work/osqa/fixtures/fixture_questions.json
/Users/Bryan/work/osqa/fixtures/fixture_questions.json
</code>```

Running the test at a higher verbosity shows that the fixtures are not being found.
I'm running Django 1.3.

答:
Import the TestCase from django.test;

Not: import unittest

Not: import django.utils.unittest

But: import django.test

Like this:

```<code>from django.test import TestCase

class test_something(TestCase):
    fixtures = ['one.json', 'two.json']
    ...
</code>```

https://docs.djangoproject.com/en/1.3/topics/testing/#django.test.TestCase

Body:
I'm trying to use my fixtures in a UnitTest.

AddFavoritesTestCase(unittest.TestCase):

fixtures = ['/Users/Bryan/work/osqa/fixtures/fixture_questions.json']

def setUp(self):
    self.factory = RequestFactory()

def testAdminCanFavorite(self):
    user = User.objects.get(pk=3)
    ...
    self.assertEqual(response.status_code, 200)

======================================================================
ERROR: testAdminCanFavorite (forum.tests.tests_building_stickyness.AddFavoritesTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/Users/Bryan/work/osqa/forum/tests/tests_building_stickyness.py", line 18, in testAdminCanFavorite
    user = User.objects.get(pk=3) # Kallie has admin
  File "/usr/local/lib/python2.7/site-packages/Django-1.3-py2.7.egg/django/db/models/manager.py", line 132, in get
    return self.get_query_set().get(*args, **kwargs)
  File "/Users/Bryan/work/osqa/forum/models/base.py", line 64, in get
    obj = super(CachedQuerySet, self).get(*args, **kwargs)
  File "/usr/local/lib/python2.7/site-packages/Django-1.3-py2.7.egg/django/db/models/query.py", line 349, in get
    % self.model._meta.object_name)
DoesNotExist: User matching query does not exist.

It seems the fixtures are not loading.

I've been able to use the fixtures to populate the database, but for some reason the fixtures aren't being found in the tests.

The path is correct but I can't figure out what's going wrong.

$ ls /Users/Bryan/work/osqa/fixtures/fixture_questions.json
/Users/Bryan/work/osqa/fixtures/fixture_questions.json

Running the test at a higher verbosity shows that the fixtures are not being found.
I'm running Django 1.3.

Body:
Import the TestCase from django.test;

Not: import unittest

Not: import django.utils.unittest

But: import django.test

Like this:

from django.test import TestCase

class test_something(TestCase):
    fixtures = ['one.json', 'two.json']
    ...

https://docs.djangoproject.com/en/1.3/topics/testing/#django.test.TestCase


问:
Regex matching everything except what is between [ ... ]
I'm looking for two Regex which given a string like the following one:

I want [I]  cAptUre this [don't] number [want to] 9 and [be captured] this Word

(A)  return only the string inside each [] (brackets included). I've solved this with \[(.*?)\]

(B) return everything except what is inside [] (brackets excluded from the end result). So the opposite of the previous one.

Expected result:

(A) ["[I]", "[don't]", "[want to]", "[be captured]"]

(B) "I want CaptUre this number 9 and this Word"

How can I do it?

答:
I have altered source string a bit to include edge cases:

[We] I want [I]  cAptUre this [don't] number [want to] 9 and [be captured] this Word [89]

```<code>var without_brackets = Regex.Replace(s, @"\s*\[.*?\]\s*", " ").Trim();
var in_brackets = string.Join(" ", Regex.Matches(s, @"\[(.*?)\]")
                        .OfType<Match>()
                        .Select(m => m.Groups[1].Value));

WriteLine($"Without brackets: '{without_brackets}'");
WriteLine($"In brackets: '{in_brackets}'");

// Output:
// Without brackets: 'I want cAptUre this number 9 and this Word'
// In brackets:      'We I don't want to be captured 89'
</code>```

Without brackets

The pattern searches for the brackets and all spaces to both sides - and replaces them with a space. I used * quantifier for \s in order to include edge cases when there can be words in brackets at the end and at the start of the string. Also, Trim is required to remove extra spaces for edge cases.

With brackets

It's all simple - search for anything in brackets and Join them.

Body:
I have altered source string a bit to include edge cases:

[We] I want [I]  cAptUre this [don't] number [want to] 9 and [be captured] this Word [89]

var without_brackets = Regex.Replace(s, @"\s*\[.*?\]\s*", " ").Trim();
var in_brackets = string.Join(" ", Regex.Matches(s, @"\[(.*?)\]")
                        .OfType<Match>()
                        .Select(m => m.Groups[1].Value));

WriteLine($"Without brackets: '{without_brackets}'");
WriteLine($"In brackets: '{in_brackets}'");

// Output:
// Without brackets: 'I want cAptUre this number 9 and this Word'
// In brackets:      'We I don't want to be captured 89'

Without brackets

The pattern searches for the brackets and all spaces to both sides - and replaces them with a space. I used * quantifier for \s in order to include edge cases when there can be words in brackets at the end and at the start of the string. Also, Trim is required to remove extra spaces for edge cases.

With brackets

It's all simple - search for anything in brackets and Join them.


问:
How do I pass data from another page?
I have two forms. one is Main Entry Form and other is District. In District form I Add district and i want that the District add i in District Table Show in Main Entry Form District Combo Box.</p>

```<code>private void Mian_Entry_Form_Load(object sender, EventArgs e)
    {

        // TODO: THIS CODE LOAD DISTRICT TO COMBOBOX IN MAINENTRY FORM

        string q = string.Format("Select districtid, districtname from district");
        DataTable dt = new DataTable();
        SqlDataAdapter sd = new SqlDataAdapter(q, connection);
        sd.Fill(dt);
        foreach (DataRow dr in dt.Rows)
        {
            comboBoxEditdistrict.Items.Add(dr[1].ToString());
            //comboBoxEditdistrict.
        }
</code>```

答: After sd.Fill(dt); you can set a session Session["districtList"] = dt; you can use this session wherever you want; DataTable dt = Session["districtList"] as DataTable;

Title: How do I pass data from another page?

Body:
I have two forms. one is Main Entry Form and other is District. In District form I Add district and i want that the District add i in District Table Show in Main Entry Form District Combo Box.

private void Mian_Entry_Form_Load(object sender, EventArgs e)
    {

        // TODO: THIS CODE LOAD DISTRICT TO COMBOBOX IN MAINENTRY FORM

        string q = string.Format("Select districtid, districtname from district");
        DataTable dt = new DataTable();
        SqlDataAdapter sd = new SqlDataAdapter(q, connection);
        sd.Fill(dt);
        foreach (DataRow dr in dt.Rows)
        {
            comboBoxEditdistrict.Items.Add(dr[1].ToString());
            //comboBoxEditdistrict.
        }


问:
how to color closed polylines in tkinter canvas?
I would like to color the area enclosed by any closed non-intersecting polyline. Heres an
example of what I want:

import tkinter as tk

class GUI:
    def __init__(self, master, x, y):
        self.master = master
        self.canvas = tk.Canvas(master, width=x, height=y)
        self.canvas.pack()
        polyline = self.canvas.create_line(10, 10, 10, 20, 200, 300, 250, 150, 10, 10)

x, y = 500, 500
root = tk.Tk()
gui = GUI(root, x, y)
root.mainloop()
```

I would like to color the area defined by the polyline canvas object.

答:
You can create a polygon instead of a polyline. In this case, you can set both fill and outline colors. Here is a usage example:</p>

```<code>import tkinter as tk

class GUI:
    def __init__(self, master, x, y):
        self.master = master
        self.canvas = tk.Canvas(master, width=x, height=y)
        self.canvas.pack()
        polyline = self.canvas.create_polygon(10, 10, 10, 20, 200, 300, 250, 150, 10, 10, outline="green", fill="blue")

x, y = 500, 500
root = tk.Tk()
gui = GUI(root, x, y)
root.mainloop()
</code>```

Body:
I would like to color the area enclosed by any closed non-intersecting polyline. Heres an
example of what I want:

import tkinter as tk

class GUI:
    def __init__(self, master, x, y):
        self.master = master
        self.canvas = tk.Canvas(master, width=x, height=y)
        self.canvas.pack()
        polyline = self.canvas.create_line(10, 10, 10, 20, 200, 300, 250, 150, 10, 10)

x, y = 500, 500
root = tk.Tk()
gui = GUI(root, x, y)
root.mainloop()

I would like to color the area defined by the polyline canvas object.

Body:
You can create a polygon instead of a polyline. In this case, you can set both fill and outline colors. Here is a usage example:

import tkinter as tk

class GUI:
    def __init__(self, master, x, y):
        self.master = master
        self.canvas = tk.Canvas(master, width=x, height=y)
        self.canvas.pack()
        polyline = self.canvas.create_polygon(10, 10, 10, 20, 200, 300, 250, 150, 10, 10, outline="green", fill="blue")

x, y = 500, 500
root = tk.Tk()
gui = GUI(root, x, y)
root.mainloop()


问:
trying to use imread() and imshow() raises OpenCV Error: Assertion failed (size.width>0 && size.height>0)
I am trying to run this simple OpenCV program, but i got this error:

OpenCV Error: Assertion failed (size.width>0 && size.height>0) in imshow, file .../opencv/modules/highgui/src/window.cpp, line 276

Code:

```<code>#include <iostream>
#include <opencv2/opencv.hpp>

using namespace std;

int main()
{
    cout << "Hello World!" << endl;

    cv::Mat inputImage = cv::imread("/home/beniz1.jpg");
    cv::imshow("Display Image", inputImage);

    return 0;
}
</code>```

What's the cause of this error?

答:
Simply add your image to your project directory folder.

How:

1-Right click on your project name at Search Solution Explorer which is on left by default.

2-Click on Open folder in file explorer

3-Paste your image to that folder

then

```<code>#include <opencv2/opencv.hpp>
#include <iostream>

using namespace std;
using namespace cv;
int main()
{
    //change "beniz1" to "beniz1.jpg"

    Mat inputImage = imread("beniz1.jpg");
    imshow("Display Image", inputImage);
    waitKey(5000);

    return 0;
}
</code>```

Body:
I am trying to run this simple OpenCV program, but i got this error:

OpenCV Error: Assertion failed (size.width>0 && size.height>0) in imshow, file .../opencv/modules/highgui/src/window.cpp, line 276

Code:

#include <iostream>
#include <opencv2/opencv.hpp>

using namespace std;

int main()
{
    cout << "Hello World!" << endl;

    cv::Mat inputImage = cv::imread("/home/beniz1.jpg");
    cv::imshow("Display Image", inputImage);

    return 0;
}

What's the cause of this error?

Body:
Simply add your image to your project directory folder.

How:

1-Right click on your project name at Search Solution Explorer which is on left by default.

2-Click on Open folder in file explorer

3-Paste your image to that folder

then

#include <opencv2/opencv.hpp>
#include <iostream>

using namespace std;
using namespace cv;
int main()
{
    //change "beniz1" to "beniz1.jpg"

    Mat inputImage = imread("beniz1.jpg");
    imshow("Display Image", inputImage);
    waitKey(5000);

    return 0;
}