text:
Q: React Native: Unable to import React headers after updating to 0.60 After updating to React Native 0.60 the header linking does no longer work.
I'm having problems linking from the React library during build:
/Users/User/Developer/Project/node_modules/react-native-image-resizer/ios/RCTImageResizer/RCTImageResizer.m:12:9: fatal error: 'React/RCTImageLoader.h' file not found
#import <React/RCTImageLoader.h>
        ^~~~~~~~~~~~~~~~~~~~~~~~

What changed in 0.60:

*

*The file RCTImageLoader.h is now at /node_modules/react-native/React/CoreModules.

*The file React.xcodeproj that contained these headers is no longer present

A: It took me 3 hours. Finally I found the solution:
Use specific version 1.1.0 by running the command:
npm install react-native-image-resizer@1.1.0

Then run the command:
cd ios && pod install

A: There were many changes in React Native 0.60, one of the main ones is that React modules are now packaged using CocoaPods, which replaces header linking.
I recommend you generate a new project in 0.60+ and check out its project structure (mainly the Podfile). You can also use the upgrade helper to see what's changed.


text:
Q: Incorrect UDP data reception in Matlab My FPGA is continuously sending UDP packets on network using 10/100/1000 Mbps ethernet and i have written a MATLAB code to capture the data. FPGA kit is connected to a 1 gbps switch and then to PC.
The problem is that after a certain number of packets (around 1080000 Bytes) are received in Matlab, the next packets that are received are corrupted although the FPGA is sending correct data which i have verified by running Matlab with Wireshark.
1) Does it have something to do with the fact that the transmission rate from FPGA is high (5.18 Mbps in Wireshark) & the reception rate in Matlab is low?
2) Is it because of some internal memory issue. No more packets are received after around 1080000 Bytes worth of UDP data is received (problem shown in figure)? I tried changing the buffer_size & buffer_read_count but to no avail.
3) Is it because of the Matlab's internal buffer getting FULL? Will flushinput() command be of any help in this case if indeed the buffer is getting FULL?
I am pasting the Matlab code below.
clc
clearall
closeall

packet_size = 18;                %Size of 1 Packet
buffer_size = 1000*packet_size; % Buffer to store 1000 packets each of Packet_Size
buffer_read_count  = 100;         %How many times the buffer must be read

do_post_processing = 1;

u=udp('192.168.0.100','RemotePort',4660,'Localport',4661);

set(u,'DatagramTerminateMode','off');
set(u, 'InputBufferSize', 3*buffer_size);
set(u,'Timeout', 10);

fopen(u);

x=tic;

ii=1;
kk = 1;

while(1)
      if(u.BytesAvailable>= buffer_size)
            [a, count] = fread(u, buffer_size);

            data(:, kk) = a;

            data_buffer_read = reshape(a, packet_size, buffer_size/packet_size);

            data_start(:,kk) = (data_buffer_read(18,1:10)).';

            data_end(:,kk)   = (data_buffer_read(18,end-10:end)).';

            kk = kk + 1;

      end

      if(kk == buffer_read_count + 1)
          break;
      end

end

fclose(u);

%delete(u);

t=toc(x);

bw = (buffer_size*buffer_read_count*8)/t;

fprintf('Achieved data rate: %e bps\n', bw);

% post processing

data_reshape = reshape (data, packet_size, buffer_size*buffer_read_count/packet_size);

if(do_post_processing==1)
     plot(data_reshape.');
     title('UDP Data v/s Total Packets at 10 Mbps Ethernet Link');
     xlabel('Total Number of Packets');
     ylabel('Packet Data');
end

A thread i posted previously provides a link to this problem.
Slow speed of UDP reception in Matlab

Please provide any guidance about this issue.
Thank you.
Regards,

redpajama_set_name: RedPajamaStackExchange


text:
Q: Lorentz Invariance of the Dirac equation My question is more conceptual than mathematical. As a differential equation the Dirac equation is invariant under Lorentz transformations. Conceptually though Lorentz transformations describe a "Classical picture". According to the most "authoritative" interpretation of QM it is unclear or even totally forbidden to think of a path between the two inertial frames. Does this mean that the relative velocity is be interpreted as the expectation value between inertial frames? Or, is it that I just "don't get" quantum mechanics? Which is most likely anyhow!
Fosco

A: You are mixing Lorentz invariance, reference frame and relative motion. In Newtonian mechanics there are also inertial frames and relative velocities. Lorentz invariance only means that the Dirac equation looks the same in any inertial frame obtained by a Lorentz transformation. It is true though that somethings doesn't smell right. The reason being  that the Dirac equation is still "semiclassical", in the sense that it still admits an interpretation in which there is an assumed "macroscopic" observer, not bounded by QM rules.


text:
Q: Linq to Entity data model Am trying to write a very simple select statement like below using Linq against Entity data model
trying to achieve
"Select * from SAPCostcentre where costcentermanager="mike";
Created my edmx and add a new class to write my DAO like below using linq but it doesn't like it.
public void ResourceCollection(string CostCenter)
    {
        string name = "Mike";

        var context = new ScheduALLDAL.SAPCostCentre();
        var query = from c in context.CostCentreManager where      context.CostCentreManager = name select c;
        var costcenter = query.ToList();

    }

It throws exception "can not convert type string to bool here "context.CostCentreManager = name"
in my db design costcentermanger data type is varchar. Please some one throw me a light what am missing here or the right approach .

A: It should be == as you are making a Boolean evaluation. The rest of your code should be OK then :)

A: This is because you need to use a double equals sign (==).  By using a single equals sign you are trying to assign context.CostCentreManager to "name".

A: It should be:
 var query = from c in context.CostCentreManager
      where context.CostCentreManager == name select c;

use == instead of =

A: var query = from c in context.CostCentreManager
    where context.CostCentreManager == name
    select c;


text:
Q: Cannot Set Up Android Nav Drawer in Action Bar I am trying to set up the Android Nav Drawer with an action bar. I am having difficulty setting the icon for the Nav Drawer and generating all of the list items as well. Below is my code, I am currently generating a NullPointer Exception:
Crash:
                                                                                --------- beginning of crash
04-20 18:02:03.690 13170-13170/com.sourcey.materialloginexample E/AndroidRuntime: FATAL EXCEPTION: main
                                                                                Process: com.sourcey.materialloginexample, PID: 13170
                                                                                java.lang.RuntimeException: Unable to start activity ComponentInfo{com.sourcey.materialloginexample/com.troychuinard.fanpolls.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.app.ActionBar.setDisplayHomeAsUpEnabled(boolean)' on a null object reference
                                                                                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
                                                                                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
                                                                                at android.app.ActivityThread.access$800(ActivityThread.java:151)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:135)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5254)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at java.lang.reflect.Method.invoke(Method.java:372)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
                                                                                Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.app.ActionBar.setDisplayHomeAsUpEnabled(boolean)' on a null object reference
                                                                                at com.troychuinard.fanpolls.MainActivity.onCreate(MainActivity.java:71)
                                                                                at android.app.Activity.performCreate(Activity.java:5990)
                                                                                at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
                                                                                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
                                                                                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
                                                                                at android.app.ActivityThread.access$800(ActivityThread.java:151)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:135)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5254)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at java.lang.reflect.Method.invoke(Method.java:372)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)

MainActivity:
    public class MainActivity extends AppCompatActivity implements HomePollsFragment.OnFragmentInteractionListener {

    private Toolbar toolbar;

    private Firebase mPollsRef;
    private ViewPager mPager;

    private ScreenSlidePagerAdapter mPagerAdapter;
    private DateFormat mDateFormat;
    private Date mDate;
    private String mCurrentDateString;
    private ValueEventListener v;
    private String[] mPlanetTitles;
    private DrawerLayout mDrawerLayout;
    private ListView mDrawerList;
    private ActionBarDrawerToggle mDrawerToggle;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        toolbar = (Toolbar) findViewById(R.id.action_tool_bar);
        setSupportActionBar(toolbar);
        Firebase.setAndroidContext(this);

        mPollsRef = FirebaseUtil.FIREBASE.child("Polls");

        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        mDrawerToggle = new ActionBarDrawerToggle(
                this,                  /* host Activity */
                mDrawerLayout,         /* DrawerLayout object */
                toolbar,  /* nav drawer icon to replace 'Up' caret */
                R.string.drawer_open,  /* "open drawer" description */
                R.string.drawer_close  /* "close drawer" description */) {

        };
        getActionBar().setDisplayHomeAsUpEnabled(true);
        getActionBar().setHomeButtonEnabled(true);

        mDrawerList = (ListView) findViewById(R.id.left_drawer);
        ArrayList<String> drawerTitleArray = new ArrayList<>();
        drawerTitleArray.add(0, "TEST");
        drawerTitleArray.add(1, "TEST 1");
        // Set the adapter for the list view
        mDrawerList.setAdapter(new ArrayAdapter<String>(this,
                R.layout.drawer_list_item, drawerTitleArray));

        // TODO: Add Fragment Code to check if savedInstanceState == null; add at Activity Level?
        // Check that the activity is using the layout version with
        // the fragment_container FrameLayout

        //set up viewpager for current day
        mPager = (ViewPager) findViewById(R.id.home_polls_viewpager_fragment_container);
        mPagerAdapter = new ScreenSlidePagerAdapter(getSupportFragmentManager());
        mPager.setAdapter(mPagerAdapter);

        //get current date to apply to Viewpager
        mDateFormat = new SimpleDateFormat("MM-dd-yyyy");
        mDate = new Date();
        mCurrentDateString = mDateFormat.format(mDate);

        // TODO: Checkn if AuthStateListenerNecessary
        //Determine whether necessary to use an AuthStateListener here
//        mUserRef.addAuthStateListener(new Firebase.AuthStateListener() {
//            @Override
//            public void onAuthStateChanged(AuthData authData) {
//                if (authData == null) {
//                    Intent backToSignIn = new Intent(getApplication(), SignupActivity.class);
//                    startActivity(backToSignIn);
//                    finish();
//                }
//            }
//        })

    }

    @Override
    protected void onStart() {
        super.onStart();

        v = new ValueEventListener() {
            //testing methodology of adding children
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                int pollsAvailable = (int) dataSnapshot.child(mCurrentDateString).getChildrenCount();
                mPagerAdapter.setPollsAvailable(pollsAvailable);
                Log.i("TAG", "There are " + String.valueOf(pollsAvailable) + " children in today's poll count.");
            }

            @Override
            public void onCancelled(FirebaseError firebaseError) {

            }
        };

        mPollsRef.addValueEventListener(v);

    }

    @Override
    protected void onStop() {
        super.onStop();
        mPollsRef.removeEventListener(v);

    }

    @Override
    public void onFragmentInteraction(Uri uri) {

    }

    class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
        private int pollsAvailable = 0;

        //fragment adapter constructor
        public ScreenSlidePagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            return HomePollsFragment.newInstance(position);
        }

        @Override
        public int getCount() {
            return pollsAvailable;
        }

        public void setPollsAvailable(int pollsAvailable) {
            this.pollsAvailable = pollsAvailable;
            this.notifyDataSetChanged();
        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        if (mPager.getCurrentItem() == 0) {
            // If the user is currently looking at the first step, allow the system to handle the
            // Back button. This calls finish() on this activity and pops the back stack.
            super.onBackPressed();
        } else {
            // Otherwise, select the previous step.
            mPager.setCurrentItem(mPager.getCurrentItem() - 1);
        }
    }
}

XML:
 <android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <LinearLayout
        android:id="@+id/content_frame"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <android.support.v7.widget.Toolbar
            android:id="@+id/action_tool_bar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@color/actionRed">

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

        <android.support.v4.view.ViewPager
            android:id="@+id/home_polls_viewpager_fragment_container"
            android:layout_width="match_parent"
            android:layout_height="match_parent">
        </android.support.v4.view.ViewPager>

    </LinearLayout>

    <!-- The navigation drawer -->
    <ListView
        android:id="@+id/left_drawer"
        android:layout_width="240dp"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:background="#111"
        android:choiceMode="singleChoice"
        android:divider="@android:color/transparent"
        android:dividerHeight="0dp" />
</android.support.v4.widget.DrawerLayout>

A: I do it like this:
 android.support.v7.app.ActionBar actionBar = getSupportActionBar();
        if(actionBar != null){
            actionBar.setDisplayHomeAsUpEnabled(true);
            actionBar.setHomeButtonEnabled(true);
        }

This should solve the java.lang.NullPointerException.
"and generating all of the list items as well"
I cant see whats the problem here. Could you explain it a little bit?
The icon - Three horizontal lines in closed mode, a back arrow in opened mode with a nice smoot animation:
  drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawerToggle = new ActionBarDrawerToggle(
                this,                  /* host Activity */
                drawerLayout,         /* DrawerLayout object */
                toolbar,  /* nav drawer icon to replace 'Up' caret */
                R.string.nav,  /* "open drawer" description */
                R.string.nav  /* "close drawer" description */
        ) {

            /** Called when a drawer has settled in a completely closed state. */
            public void onDrawerClosed(View view) {
                super.onDrawerClosed(view);
                if(extra == null){
                    toolbar.setTitle(title);
                }else{
                    toolbar.setTitle(title + " - " + extra);
                }
                isOpen = false;
            }

            /** Called when a drawer has settled in a completely open state. */
            public void onDrawerOpened(View drawerView) {
                super.onDrawerOpened(drawerView);
                actionBar.setTitle(R.string.nav);
                isNavReady = true;
                isOpen = true;
            }
        };
        drawerLayout.addDrawerListener(drawerToggle);

@Override
    public boolean onOptionsItemSelected(MenuItem item){
        return drawerToggle.onOptionsItemSelected(item) || super.onOptionsItemSelected(item);
    }

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        // Sync the toggle state after onRestoreInstanceState has occurred.
        drawerToggle.syncState();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        drawerToggle.onConfigurationChanged(newConfig);
    }


text:
Q: Get starts and ends of following values I have an array of following (aka ordrered) values, and an array of picked values:
$orderedValues = array("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");

$pickedValues = array("Jan", "Mar", "Apr", "Jul", "Aug", "Sep", "Dec");

What I want is to have a resulting array giving me each start and end of the following picked values.

*

*The $pickedValues is already sorted the same way $orderedValues is.

*If a value is "alone", the value is the start and the next value is the end ; if the alone value is the last, then it is the end too.

In given example, the result should be as follow:
$result = array(
    array( // Alone value, end is the next from the order
        "start" => "Jan",
        "end" => "Feb"
    ),
    array(
        "start" => "Mar",
        "end" => "Apr"
    ),
    array(
        "start" => "Jul",
        "end" => "Sep",
    ),
    array( // Alone and last
        "start" => "Dec",
        "end" => "Dec"
    )
);

I have no clue how to achieve this kind of grouping. Any hints?

A: Based on @El_Vanja's pseudo-code, here is what I came up to:
$orderedValues = array("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
$pickedValues = array("Jan", "Mar", "Apr", "Jul", "Aug", "Sep", "Dec");

$result = array();
$index = null;
foreach ( $pickedValues as $k => $v ) {
    if ( $index === null ) {
        $index = array_search($v, $orderedValues);
    }

    $orderIndex = array_search($v, $orderedValues);
    if ( $orderIndex + 1 == count($orderedValues) ) {
        // last value
        $result[] = array(
            "start" => $orderedValues[$index],
            "end" => $orderedValues[$orderIndex],
        );
    } else {
        $nextOrderValue = $orderedValues[$orderIndex + 1];
        $nextValue = $pickedValues[$k + 1];
        if ( $nextOrderValue != $nextValue ) {
            $result[] = array(
                "start" => $orderedValues[$index],
                "end" => $orderedValues[$orderIndex],
            );
            $index = null;
        }
    }
}
echo '<pre>' . print_r($result, true) . '</pre>';

It looks like it's working, according to this live sample. Thanks!


text:
Q: pass list from listbox to mvc controller with jquery I would like to know how I can pass a list with values in MVC method via jquery. I have a jquery UI dialog in which records are pasted in each row. Once the user will click the submit button, I want to have a jquery which will post the values from the popup multiline textbox to the method.
Is that possible?
Thanks in advance, Laziale

A: Yes it can be done simply get the values from the list and pass the to the controller.
your java script will look something like this:
$('#submit').click(function() {
        //parsing and collecting the values from the list
        var values = { 'values': 'your string array here'};

         $.ajax({
        type: "GET",
        cache: false,
        url: "/controller/YourAction",
        dataType: "json",
        traditional: true,
        data: values
    });
    });

and you will have such an action in the controller:
[HttpGet]
    public JsonResult YourAction(string[] values)
    {
        //your action here
        return Json("success", JsonRequestBehavior.AllowGet);
    }


text:
Q: Event when cursor changes position wxWidgets Text Box? In wxWidgets, how can I detect when the cursor position changed in a wxTextCtrl? I looked at the manual and couldn't find any event relating to it, but maybe there is another way I've missed.

A: Since a wxTextCtrl inherits from wxWindow, you can bind the following mouse events with that control:
http://docs.wxwidgets.org/2.8/wx_wxmouseevent.html#wxmouseevent
I think the one you're interested in is EVT_MOTION(func). However, I have never used this event so I can't say for sure if it is only raised on mouse motion inside the window it is binded to (which would be the more interesting approach) or global mouse movement.

A: I'm fairly certain he means the insertion point cursor, in which case, there isn't a wxWidgets event for changes in it's position. Additionally, while wxTextCtrl::SetInsertionPoint() and wxTextCtrl::SetInsertionPointEnd() are virtual methods that can be overwritten, this only catches situations where it's changed programmatically and not through various actions depending on the native platform involvement (which are likely why this event doesn't exist in wxWidgets currently).
The best solution I can think of to portably catch all insertion point changes right now is to continuously poll the insertion point position with a timer. You could derive your own wxTextCtrl with this functionality built in that generates your own custom event if you need this feature in more than one location.
My personal recommendation would be to look for an alternative solution to your problem that doesn't require knowing the insertion point position at all times. Are you sure that you actually need to know the insertion point position and not just when the value in the text control changes?


text:
Q: WPF I cannot access a textblock in my style I make a radiobutton style and I called it RadioButtonStyle but in my code behind, when I write the name of my radiobutton Q1A  and trying Q1A.RadioContentTxt it does not come up.

see.
here is my Style : `

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                    xmlns:local="clr-namespace:SpeedReadingControl">
    <Style x:Key="FocusVisual">
        <Setter Property="Control.Template">
            <Setter.Value>
                <ControlTemplate>
                    <Rectangle Margin="2" SnapsToDevicePixels="true" Stroke="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}" StrokeThickness="1" StrokeDashArray="1 2"/>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
    <SolidColorBrush x:Key="RadioButton.Static.Background" Color="#FFFFFFFF"/>
    <SolidColorBrush x:Key="RadioButton.Static.Border" Color="#FFE4F0FF"/>
    <Style x:Key="OptionMarkFocusVisual">
        <Setter Property="Control.Template">
            <Setter.Value>
                <ControlTemplate>
                    <Rectangle Margin="14,0,0,0" SnapsToDevicePixels="true" Stroke="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}" StrokeThickness="1" StrokeDashArray="1 2"/>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
    <SolidColorBrush x:Key="RadioButton.MouseOver.Background" Color="#FFF3F9FF"/>
    <SolidColorBrush x:Key="RadioButton.MouseOver.Border" Color="#FF5593FF"/>
    <SolidColorBrush x:Key="RadioButton.MouseOver.Glyph" Color="#FF212121"/>
    <SolidColorBrush x:Key="RadioButton.Disabled.Background" Color="#FFE6E6E6"/>
    <SolidColorBrush x:Key="RadioButton.Disabled.Border" Color="#FFBCBCBC"/>
    <SolidColorBrush x:Key="RadioButton.Disabled.Glyph" Color="#FF707070"/>
    <SolidColorBrush x:Key="RadioButton.Pressed.Background" Color="#FFD9ECFF"/>
    <SolidColorBrush x:Key="RadioButton.Pressed.Border" Color="#FF3C77DD"/>
    <SolidColorBrush x:Key="RadioButton.Pressed.Glyph" Color="#FF212121"/>
    <SolidColorBrush x:Key="RadioButton.Static.Glyph" Color="#FF212121"/>
    <Style x:Key="RadioButtonStyle" TargetType="{x:Type RadioButton}">
        <Setter Property="FocusVisualStyle" Value="{StaticResource FocusVisual}"/>
        <Setter Property="Background" Value="{StaticResource RadioButton.Static.Background}"/>
        <Setter Property="BorderBrush" Value="{StaticResource RadioButton.Static.Border}"/>
        <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}"/>
        <Setter Property="BorderThickness" Value="1"/>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type RadioButton}">
                    <ControlTemplate.Resources>
                        <Storyboard x:Key="OncheckSB">
                            <ColorAnimationUsingKeyFrames Storyboard.TargetProperty="(TextElement.Background).(SolidColorBrush.Color)" Storyboard.TargetName="RadioContentTxt">
                                <EasingColorKeyFrame KeyTime="0" Value="#FFE4F0FF"/>
                            </ColorAnimationUsingKeyFrames>
                            <ColorAnimationUsingKeyFrames Storyboard.TargetProperty="(Panel.Background).(SolidColorBrush.Color)" Storyboard.TargetName="radioButtonBorder">
                                <EasingColorKeyFrame KeyTime="0:0:0.1" Value="#FF0075FF"/>
                            </ColorAnimationUsingKeyFrames>
                            <Int32AnimationUsingKeyFrames Storyboard.TargetProperty="(Grid.RowSpan)" Storyboard.TargetName="radioButtonBorder">
                                <EasingInt32KeyFrame KeyTime="0:0:0.1" Value="2"/>
                            </Int32AnimationUsingKeyFrames>
                        </Storyboard>
                    </ControlTemplate.Resources>
                    <Grid x:Name="templateRoot" Background="Transparent" Height="14"  SnapsToDevicePixels="True">
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="Auto"/>
                            <ColumnDefinition Width="*"/>
                        </Grid.ColumnDefinitions>
                        <Border x:Name="radioButtonBorder"  BorderBrush="AliceBlue" BorderThickness="{TemplateBinding BorderThickness}" Background="White" CornerRadius="100" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" Margin="1,1,2,1" VerticalAlignment="{TemplateBinding VerticalContentAlignment}">
                            <Grid x:Name="markGrid" Margin="4" >
                                <Canvas HorizontalAlignment="Left" >
                                    <Path  x:Name="CheckMarkIcon" Canvas.Left="-2" StrokeThickness="2"  Stretch="Fill" Stroke="White" StrokeLineJoin="Round" StrokeStartLineCap="Round" StrokeEndLineCap="Round" Data="M427 391.5L429.5 394L435 389"/>
                                </Canvas>
                                <Ellipse x:Name="optionMark" Fill="White" MinWidth="6" MinHeight="6" Opacity="0"/>
                            </Grid>
                        </Border>
                        <TextBlock x:Name="RadioContentTxt" Grid.Column="1"  Foreground="#33454B57" Margin="3,1,667.25,4562" TextWrapping="Wrap" Text=""  Background="Transparent"/>
                    </Grid>
                    <ControlTemplate.Triggers>
                        <Trigger Property="IsChecked" Value="True">
                            <Trigger.ExitActions>
                                <StopStoryboard BeginStoryboardName="OncheckSB_BeginStoryboard"/>
                            </Trigger.ExitActions>
                            <Trigger.EnterActions>
                                <BeginStoryboard x:Name="OncheckSB_BeginStoryboard" Storyboard="{StaticResource OncheckSB}"/>
                            </Trigger.EnterActions>
                        </Trigger>
                        <Trigger Property="HasContent" Value="true">
                            <Setter Property="FocusVisualStyle" Value="{StaticResource OptionMarkFocusVisual}"/>
                            <Setter Property="Padding" Value="4,-1,0,0"/>
                        </Trigger>
                        <Trigger Property="IsMouseOver" Value="true">
                            <Setter Property="Background" TargetName="radioButtonBorder" Value="{StaticResource RadioButton.MouseOver.Background}"/>
                            <Setter Property="BorderBrush" TargetName="radioButtonBorder" Value="{StaticResource RadioButton.MouseOver.Border}"/>
                            <Setter Property="Fill" TargetName="optionMark" Value="{StaticResource RadioButton.MouseOver.Glyph}"/>
                        </Trigger>
                        <Trigger Property="IsEnabled" Value="false">
                            <Setter Property="Background" TargetName="radioButtonBorder" Value="{StaticResource RadioButton.Disabled.Background}"/>
                            <Setter Property="BorderBrush" TargetName="radioButtonBorder" Value="{StaticResource RadioButton.Disabled.Border}"/>
                            <Setter Property="Fill" TargetName="optionMark" Value="{StaticResource RadioButton.Disabled.Glyph}"/>
                        </Trigger>
                        <Trigger Property="IsPressed" Value="true">
                            <Setter Property="Background" TargetName="radioButtonBorder" Value="{StaticResource RadioButton.Pressed.Background}"/>
                            <Setter Property="BorderBrush" TargetName="radioButtonBorder" Value="{StaticResource RadioButton.Pressed.Border}"/>
                            <Setter Property="Fill" TargetName="optionMark" Value="{StaticResource RadioButton.Pressed.Glyph}"/>
                        </Trigger>
                        <Trigger Property="IsChecked" Value="true">
                            <Setter Property="Opacity" TargetName="optionMark" Value="1"/>
                        </Trigger>
                        <Trigger Property="IsChecked" Value="{x:Null}">
                            <Setter Property="Opacity" TargetName="optionMark" Value="0.56"/>
                        </Trigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

</ResourceDictionary>

I make it using Blend.
How do I set my RadioContentTxt.Text from the code behind?
I try doing    Q1A.Content
but it does not work.

A: Bind the TextBlock in the template to the Content property of the control:
<TextBlock x:Name="RadioContentTxt" Grid.Column="1"  Foreground="#33454B57" TextWrapping="Wrap"
           Text="{TemplateBinding Content}"  Background="Transparent"/>

...and set the Content property:
Q1A.Content = "...";

You cannot directly access an element in the template using a property of the control.


text:
Q: Inserting references to variables into HashSet then using variables afterwards I am trying insert pairs of a variable into a HashSet, after checking if the pair is present already. I then need to do downstream work with the pair, within the same context. Here is a playground reproducing my problem:
https://play.rust-lang.org/?gist=5eecfa9c1e54b468d79955aab916dd84&version=stable&mode=debug&edition=2015
use std::collections::HashSet;

fn main() {
    let mut h = HashSet::new();
    let a = 1;
    let b = 2;
    if h.contains(&(&a, &b)) {
        println!("fail");
    }
    h.insert(&(&a, &b));
}

error[E0597]: borrowed value does not live long enough
  --> src/main.rs:10:15
   |
10 |     h.insert(&(&a, &b));
   |               ^^^^^^^^ - temporary value dropped here while still borrowed
   |               |
   |               temporary value does not live long enough
11 | }
   | - temporary value needs to live until here
   |
   = note: consider using a `let` binding to increase its lifetime

error[E0597]: `a` does not live long enough
  --> src/main.rs:10:17
   |
10 |     h.insert(&(&a, &b));
   |                 ^ borrowed value does not live long enough
11 | }
   | - `a` dropped here while still borrowed
   |
   = note: values in a scope are dropped in the opposite order they are created

error[E0597]: `b` does not live long enough
  --> src/main.rs:10:21
   |
10 |     h.insert(&(&a, &b));
   |                     ^ borrowed value does not live long enough
11 | }
   | - `b` dropped here while still borrowed
   |
   = note: values in a scope are dropped in the opposite order they are created

How can I check if a and b are in the set, then insert them afterwards if they are not, and then do other things with them? How are they being borrowed if I am loading in a reference to them within the same scope?

A: Leaving "why"s aside for a moment, the example as presented has three issues:

*

*The tuple &(...) ceases to exist once the function call ends. So inserting a reference to something that will not exist once HashSet::insert returns is an error, and one that the compiler thankfully catches.

*You declared the HashSet before the variables you want to reference, which the compiler sees as an error (likely due to the fact that, at some point in the HashSet's scope, the variables a and b do not exist). This is something I've been burnt by on numerous occasions and is a limitation you should keep in mind until the compiler improves.

*As pointed out in the comments above, HashSets take T when inserting and &T when accessing. Your code uses T for both.
The following code fixes these issues:
use std::collections::HashSet;

fn main() {
    let a = 1;
    let b = 2;
    let mut h = HashSet::new();
    if h.contains(&(&a, &b)) {
        println!("fail");
    }
    h.insert((&a, &b));
}

playground
Compare the lines that declare the HashSet and insert the tuple.


text:
Q: Questions involving the inductive sequence, $x_1 = 7$, $x_{n+1} = \sqrt{3x_n + 4}$ for $n \geq 1$ I'm a university student and I've got a test coming up and revising. I've answered my question as best I could but if anyone has any tips to set me on the right course that would be fantastic! My logic will likley be a little messy so I apologise in advance.
The sequence in question is...
$$x_1 = 7, x_{n+1} = \sqrt{3x_n + 4}, n \geq 1$$
The question asks me to show that $4 < x_n < 10$. I'll try solve inductivly. We establish the base case to be $x_1 = 7$ we assume $4<x_n<10$ therefore for case $x_n \rightarrow 10$...
$$ x_{n+1} = \sqrt{30+4}= \sqrt{34}, 4<\sqrt{34} < 10$$
And for the case $x_n \rightarrow 4$...
$$ x_{n+1} = \sqrt{16}= 4, 4<\sqrt{16} < 10$$
I am confused here, the range would seem make sense if $4 \leq x_n <10$. Moving on, the question now tells me to prove $x_n$ is decreasing.
$$x_{n+1} - x_n = \sqrt{3x_n + 4} - x_n $$
Here I take the highest number in the range (10) and the lowest (4) and observe $x_n=4$ yields 0 and $x_n = 10$ yeilds a negative result therefore it must be decreasing. We can then deduce by the monotone convergence theorem that $\{ x_n \}$ converges, so $x_n \rightarrow x$ and $x_{n+1} \rightarrow x $. The uniqueness of limits implies...
$x = \sqrt{3x+4}$
Which has root, $x=4$, and is thus the limit.

A: Hint. Note that if $x_n>4$ then
$$x_{n+1} - x_n = \sqrt{3x_n + 4} - x_n=\frac{3x_n + 4 - x^2_n}{\sqrt{3x_n + 4} + x_n}=-\frac{(x_n-4)(x_n+1)}{\sqrt{3x_n + 4} + x_n}<0$$
and therefore $(x_n)_n$ is strictly decreasing.

A: Induction step:
If $4<x_k < 10$, then we have $12+4 < 3x_k+4 < 30+4<36$, hence  by taking square root we have
$$4<x_{k+1}<6$$
which implies that $$4 < x_{k+1}< 10.$$
Remark: You should not be using $\to$ in your proof, we are just taking a single step.
To prove decreasing:
$$x_{n+1}-x_n = \sqrt{3x_n+4}-x_n=\frac{3x_n+4-x_n^2}{\sqrt{3x_n+4}+x_n}=\frac{(-x_n-1)(x_n-4)}{\sqrt{3x_n+4}+x_n}\le 0$$
Remark: We have to do more besides checking the end points.

A: Decreasing:
$f(x)=(3x+4)^{1/2}; $
$f'(x)=(1/2)(3x+4)^{-1/2} >0$, increasing .
$ x_2=5; x_1=7;$
$x_2<x_1;$
$x_3 =f(x_2) < f(x_1)= x_2;$
$x_4 =f(x_3) < f(x_2)=x_3;$
Define inductively:
$x_{n+1}< x_n$;
$x_{n+2}=f(x_{n+1})<f(x_n) =x_{n+1}.$


text:
Q: Better Way to Test Presence of a Value in a Bundle? I have an activity to play a game.  The user may be resuming from a saved state or initiating a new game.  If resuming, the identifier for the game to resume is passed to the activity in the bundle.  If it is a new game, that part of the bundle isn't passed, and is therefore null.  I currently implement this as follows...
Bundle bundle = this.getIntent().getExtras();

        int GameNumberToResume;
        boolean StartNewGame = false;
        try
        {
            GameNumberToResume = bundle.getInt("GameToResume");
        }
        catch (Exception e)
        {
            System.out.println("Exception Catch, so we start a new game.");
            StartNewGame = true;
            System.out.println((e.toString()));
        }

...and it works.  StartNewGame drives the decision tree on if we are starting a new one or resuming a saved one, and if we are resuming, GameNumberToResume has the game ID to resume.  However, Android Studio throws the soft warning...

Variable 'GameNumberToResume' is assigned but never accessed.

...because in the parts of the decision tree when I need the value of the game to resume, I pull it straight from the bundle via bundle.getInt("GameToResume").
So here's my question:  What should I do different?  I can make the warning go away by referencing the variable GameNumberToResume downstream instead of pulling it from the bundle, but it doesn't seem to me like that would change anything.  The intent of the warning is to point out that I'm wasting memory, and if I do this, I still have two things in scope that both contain the same value.

*

*Is there a way to detect the absence or presence of "GameToResume" in
the bundle without doing a variable assignment in a try/catch loop?

*If I move the declaration inside the try part of the loop, then
fire off a System.gc(); after the catch portion of the loop,
would it free up what was used by the variable GameNumberToResume ?

I know in this specific case it probably doesn't matter, but it is simple enough to follow and illustrates a general hole in my understanding of how to efficiently code Android.

A: Checkout
bundle.containsKey ("GameToResume");

it will return whether this key is there or not in bundle.

A: Do not use the try-catch here. And you can initialise the game number like int GameNumberToResume=Integer.MAX_VALUE. Then remove the try-catch. Just use if(xx==Integer.MAX_VALUE).
In my opinion, try-catch can only use for the unknown error or unpredictable situation. Here, you know everything.

A: You can utilize getInt second parameter to put default value, like this.
Bundle bundle = this.getIntent().getExtras();

// Don't forget NullPointerException
if(bundle != null){
    final int IMPOSSIBLE_VALUE = -1; // default value
    boolean startNewGame = false;

    int gameNumberToResume = bundle.getInt("GameToResume", IMPOSSIBLE_VALUE);
    if(gameNumberToResume != IMPOSSIBLE_VALUE){
        startNewGame = true;
        // continue ..
    }
}


text:
Q: Is it a martingale? I need to show that the following is a martingale:
I know that $(X_i)_{i=0,1,...}$ is a sequence of i.i.d. r.v.'s with $E(X_i) = 0$ and $Var(X_i) = 4$.
I need to show that $(S^2_n-4n)_{n=1,2,..}$ is a martingale (I remember that $S_n =$ sum of $X_i$).
So here I know that I need to show that $E(S^2_n-4n|F_{n-1})=S^2_{n-1}-4(n-1)$, where $F_n$ is the filtration.
Using independence, I get $E(S^2_n)-E(4n)$. I have the feeling that this $S^2_n$ should be a hint to use the info about the mean and the variance (because of the squared), but I don't see how I could do that.

A: Note that $Var(S_n)=E(S_n^2)$ since $S_n$ has expectation zero.
Also, be aware that $S_n$ is not independent of $F_{n-1}$ since the first n-1 terms in the sum are measurable.
So what you want is actually:
$$E[S_n^2-4n|F_{n-1}]=E[(S_{n-1}+X_n)^2|F_{n-1}]-4n=E[S_{n-1}^2+2*S_{n-1}X_n+X_n^2|F_{n-1}]-4n$$
Now you can use that $S_{n-1}$ is $F_{n-1}$ measurable and $X_n$ is independent OF $F_{n-1}$. Can you finish the calculation from here?


text:
Q: How can I get in a variable the message i have sent discord.js I need to send a message in the channel, and react to it, so I need to get that message to make a message.react
bot.sendMessage({
   to: channelID,
   message: '@everyone\n' + message.slice(16) + '\n\nCe message vise à demander quels jours vous pourriez être disponibles dans la semaine (de préférence le soir, vers 20h et alentours, pour un temps mentionné dans ce message). Réagissez donc sous ce message avec vos disponnibilités.\nJAAJ)'
});

message.react('')
   .then(() => message.react(''))
   .then(() => message.react(''))
   .then(() => message.react(''))
   .then(() => message.react(''))
   .then(() => message.react(''))
   .then(() => message.react(''))

Thanks for any answers ! :D

A: channel.send returns a promise of a message, so you would use something like this:
bot.channels.fetch(channelId).then(channel =>
  channel.send('message content here').then(message => {
    message.react('')
      .then(() => message.react(''))
       // rest of reactions
  })
)

A: You can do it like this if you use discord v12. But better use ID for get a channel.
let channel = message.guild.channels.cache.find(ch => ch.name = 'test')
if (!channel) return console.log('can`t find a channel')

channel.send('SOME TEXT').then(msg => {
    msg.react('').then(() => msg.react('emojo').then(() => msg.react('emoji')))
})


text:
Q: Owl Carousel autoplay and pagination problems Carousel in question: https://codepen.io/ben456789/pen/jxVrXJ
I'm building this fairly custom autoplaying & looping Owl Carousel and I've run into some issues, which I've not found a solution for here.
When the carousel loops back around to 'tab 1' the active class is placed on the correct div but the inline styling to position the slide does not update so the slide is shown off screen. Is there something wrong with my options set on the initialisation? I believe I have the same problem when I click on the tabs to go to a specific slide. Any help would be greatly appreciated!
Note: I've stripped out alot of HTML, SCSS and Script which I thought would just cause unnecessary bloat for the purpose of this question. So if there's anything there that your like 'Why's that there??!?!' Just assume is part of something else, i.e video, slide transition animation etc...
And also just for ease if you want to increase the time before the carousel progresses. Line 67 of the js increase that from 10 to whatever you like!
I've tried updating versions of jQuery and Owl Carousel, but this led to no, fix.
jquery version: 1.9.1
Owl Version: 2.3.4

A: I found alot of issues have come up with the animationOut & In options with wol carousel in my case, so I changed it out with an alternate and it has fixed my issue! Thank you to the 5 other people who at least saw this question but unfortunately couldn't provide any assistance, your good intentions are clear.


text:
Q: Excel, using Visual Basic Whilst Running a Macro I am trying to use VBA code whilst running a macro in Microsoft Excel.
I am running a macro by "RecordMacro" in excel.
During the macro, I need to use some VBA code. To do this I click Visual Basic and then use some VBA code.
During the macro, the VBA code works as specified, but then when I click stop recording and try and run the macro it misses out completely the VBA part.
The VBA code is already stored in my workbook before I start the macro so I don't see this as a copying and pasting problem.
To try for yourself write a list of numbers in a column, Record and macro and try and execute the below code.
Sub SplitColumn()
    'Updateby20141106
    Dim rng As Range
    Dim InputRng As Range
    Dim OutRng As Range
    Dim xRow As Integer
    Dim xCol As Integer
    Dim xArr As Variant
    xTitleId     = "KutoolsforExcel"
    Set InputRng = Application.Selection
    Set InputRng = Application.InputBox("Range :", xTitleId, InputRng.Address, Type: = 8)
    xRow         = Application.InputBox("Rows :", xTitleId)
    Set OutRng   = Application.InputBox("Out put to (single cell):", xTitleId, Type: = 8)
    Set InputRng = InputRng.Columns(1)
    xCol         = InputRng.Cells.Count / xRow
    ReDim xArr(1 To xRow, 1 To xCol + 1)
    For i = 0 To InputRng.Cells.Count - 1
        xValue = InputRng.Cells(i + 1)
        iRow = i Mod xRow
        iCol = VBA.Int(i / xRow)
        xArr(iRow + 1, iCol + 1) = xValue
    Next
    OutRng.Resize(UBound(xArr, 1), UBound(xArr, 2)).Value = xArr
End Sub

A: I inserted a module and pasted the above code into it.
I then input two cells, A1 = "1,1" and A2 = "1,2".
Next I recorded a macro that did a flash fill of that series to A30. In the macro, I also set the typeface to bold and then stopped recording.
I opened the module the macro was recorded in and added the line SplitColumn. Running the recorded macro resulted in executing the first couple steps, then running the SplitColumn subroutine, then finishing the macro. Bottom line being that you can call a sub or function from another sub.
Sub flashfill()
'
' flashfill Macro
'

'
    Selection.AutoFill Destination:=Range("A1:A30"), Type:=xlFillDefault
    Range("A1:A30").Select
    SplitColumn
    Selection.Font.Bold = True
End Sub

Hope that helps!


text:
Q: convert 1 row as column and concatenate the results to the corresponding column I have 2 tables
table 1 - apps
-----------
id  | name
-----------
1   | abc
-----------
2   | sdf
-----------
3   | dfg
-----------

table 2 - contacts
------------------------
id  | cnt_type  | cnt_id
------------------------
1   | manager   |    20
------------------------
1   | supervisor |  32
------------------------
1   | teamlead   | 45
------------------------
1   | teamlead  | 54
------------------------
2   | manager    |   20
------------------------
2   | supervisor |  32
------------------------

I need a view as below where cnt_type rows are represented as columns and the corresponding values are concatenated and group by the cnt_type per id...
---------------------------------------
id  | manager | supervisor  | teamlead
--------------------------------------
1   | 20      |    32       | 45, 54
--------------------------------------
2   | 20      |    32       |
--------------------------------------

Any help is greatly appreciated.

A: PROPOSED QUERY
SELECT
    A.id,
    IFNULL(GROUP_CONCAT(DISTINCT B.cnt_id),'') 'manager',
    IFNULL(GROUP_CONCAT(DISTINCT C.cnt_id),'') 'supervisor',
    IFNULL(GROUP_CONCAT(DISTINCT D.cnt_id),'') 'teamlead'
FROM apps A
LEFT JOIN contacts B ON A.id = B.id AND B.cnt_type='manager'
LEFT JOIN contacts C ON A.id = C.id AND C.cnt_type='supervisor'
LEFT JOIN contacts D ON A.id = D.id AND D.cnt_type='teamlead'
WHERE ISNULL(B.cnt_id)+ISNULL(C.cnt_id)+ISNULL(D.cnt_id) < 3
GROUP BY A.id;

SAMPLE DATA
DROP DATABASE IF EXISTS kumar;
CREATE DATABASE kumar;
USE kumar
CREATE TABLE apps
(
    id INT NOT NULL AUTO_INCREMENT,
    name VARCHAR(20) NOT NULL,
    PRIMARY KEY (id)
);
CREATE TABLE contacts
(
    id INT NOT NULL,
    cnt_type VARCHAR(20) NOT NULL,
    cnt_id INT NOT NULL
);
INSERT INTO apps (name) VALUES ('abc'),('sdf'),('dfg');
INSERT INTO contacts (id,cnt_type,cnt_id) VALUES
(1,'manager',20), (1,'supervisor',32), (1,'teamlead',45),
(1,'teamlead',54), (2,'manager',20), (2,'supervisor',32);

SAMPLE DATA LOADED
mysql> DROP DATABASE IF EXISTS kumar;
Query OK, 2 rows affected (0.05 sec)

mysql> CREATE DATABASE kumar;
Query OK, 1 row affected (0.00 sec)

mysql> USE kumar
Database changed
mysql> CREATE TABLE apps
    -> (
    ->     id INT NOT NULL AUTO_INCREMENT,
    ->     name VARCHAR(20) NOT NULL,
    ->     PRIMARY KEY (id)
    -> );
Query OK, 0 rows affected (0.02 sec)

mysql> CREATE TABLE contacts
    -> (
    ->     id INT NOT NULL,
    ->     cnt_type VARCHAR(20) NOT NULL,
    ->     cnt_id INT NOT NULL
    -> );
Query OK, 0 rows affected (0.03 sec)

mysql> INSERT INTO apps (name) VALUES ('abc'),('sdf'),('dfg');
Query OK, 3 rows affected (0.00 sec)
Records: 3  Duplicates: 0  Warnings: 0

mysql> INSERT INTO contacts (id,cnt_type,cnt_id) VALUES
    -> (1,'manager',20), (1,'supervisor',32), (1,'teamlead',45),
    -> (1,'teamlead',54), (2,'manager',20), (2,'supervisor',32);
Query OK, 6 rows affected (0.00 sec)
Records: 6  Duplicates: 0  Warnings: 0

mysql>

SAMPLE DATA IN TABLES
mysql> select * from apps;
+----+------+
| id | name |
+----+------+
|  1 | abc  |
|  2 | sdf  |
|  3 | dfg  |
+----+------+
3 rows in set (0.00 sec)

mysql> select * from contacts;
+----+------------+--------+
| id | cnt_type   | cnt_id |
+----+------------+--------+
|  1 | manager    |     20 |
|  1 | supervisor |     32 |
|  1 | teamlead   |     45 |
|  1 | teamlead   |     54 |
|  2 | manager    |     20 |
|  2 | supervisor |     32 |
+----+------------+--------+
6 rows in set (0.00 sec)

mysql>

PROPOSED QUERY EXECUTED
mysql> SELECT
    ->     A.id,
    ->     IFNULL(GROUP_CONCAT(DISTINCT B.cnt_id),'') 'manager',
    ->     IFNULL(GROUP_CONCAT(DISTINCT C.cnt_id),'') 'supervisor',
    ->     IFNULL(GROUP_CONCAT(DISTINCT D.cnt_id),'') 'teamlead'
    -> FROM apps A
    -> LEFT JOIN contacts B ON A.id = B.id AND B.cnt_type='manager'
    -> LEFT JOIN contacts C ON A.id = C.id AND C.cnt_type='supervisor'
    -> LEFT JOIN contacts D ON A.id = D.id AND D.cnt_type='teamlead'
    -> WHERE ISNULL(B.cnt_id)+ISNULL(C.cnt_id)+ISNULL(D.cnt_id) < 3
    -> GROUP BY A.id;
+----+---------+------------+----------+
| id | manager | supervisor | teamlead |
+----+---------+------------+----------+
|  1 | 20      | 32         | 45,54    |
|  2 | 20      | 32         |          |
+----+---------+------------+----------+
2 rows in set (0.00 sec)

mysql>

GIVE IT A TRY !!!


text:
Q: How can I create buttons and labels in a canvas widget and make the whole set of widgets in the canvas scrollable? How can I create buttons and labels in a canvas widget and make the whole set of widgets in the canvas scrollable?
I came across a _create() option in my IDE but I'm not sure how to use it. I tried entering Button for itemType but it didn't work.
I tried create_window() but I'm not sure how to use it either.
My question is not how to use a loop and add the buttons, but how can I create widgets and place them in a canvas, but scrollable? Also is there a _create()? If yes, is there any way to create widgets using it?

A:
How to create buttons and labels in a canvas widget and make the whole set of widgets in the canvas scrollable?

You have two choices:

*

*use the canvas method create_window to add the buttons and labels to the canvas at specific coordinates

*use the canvas method create_window to add a frame to the canvas, and then put your buttons and labels inside of the frame using pack or grid or place.

You then have to make sure you configure the scrollregion of the canvas to be large enough to include the widgets.

I came across a _create() option in my IDE but I'm not sure how to use it.

The following example shows how to use create_window to add a button to a canvas. The procedure is the same for any type of widget.
canvas = tk.Canvas(root)
canvas.pack(fill="both", expand=True)

the_button = tk.Button(canvas, text="Click me", ...)
canvas.create_window(10, 10, window=the_button, anchor="nw")
canvas.configure(scrollregion=canvas.bbox("all"))


text:
Q: Unable to detect error while using PhotonView.isMine method using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Photon.Pun;
using Photon.Realtime;
using System.IO;
using UnityEngine.UI;

public class PhotonPlayerSetup : MonoBehaviourPunCallbacks, IInRoomCallbacks
{
    private PhotonView PV;

    void Awake()
    {
        PV = GetComponent<PhotonView>();
    }

    void Start()
    {
        if(PV.isMine)
        {

        }
    }
}

While using above mentioned code this error appears:

"PhotonView does not contain a definition for isMine and no
accessible extension method isMine accepting a first argument of
type 'PhotonView' could be found (are you missing a using directive or
an assembly reference?)"

A: Thank you for choosing Photon!
PhotonView.isMine from PUN Classic was renamed to PhotonView.IsMine in PUN 2.
Make sure to check out the Migration Notes.


text:
Q: How to prevent a SharePoint site collection from being deleted? I am currently using Sharepoint 2010 admin web service and want to be sure that a specific site collection cannot be deleted. Does anyone know of a way to make this happen such that if I have a call like
adminService.DeleteSite(SiteCollection_TO_NEVER_DELETE);
Would never be removed?
Thanks for any suggestions

A: If I understand you correctly, it can be done by using a SharePoint Feature.
You can create and deploy a SharePoint Feature which has a web event receiver. In this event receiver you can override the SiteDeleting method and cancel the request to delete a site collection by changing the value of the property Cancel of the parameter to true. This would return an error for anyone trying to delete the site collection. You can also add an error message.
For example:
    /// <summary>
    /// A site collection is being deleted
    /// </summary>
    public override void SiteDeleting(SPWebEventProperties properties)
    {
        base.SiteDeleting(properties);
        if(/*some condition*/)
        {
            properties.Cancel = true;
            properties.ErrorMessage = "This site collection should never be deleted.";
        }
     }

You can check for a specific name or a specific URL.
Of course, it would still be possible to deactivate the feature and still delete the site. But at least it would prevent it from being deleted accidentally.


text:
Q: Cannot find "conan.conf" file in .conan2 folder I am using conan 2.0 and in the .conan2.0 folder there is no conan.conf file. Is it removed from Conan2.0?

A: Conan 2.0 no longer uses conan.conf, but only the new global.conf, which is already available too in 1.X. Also the legacy conan.conf used environment variables, while the new conf system uses self.conf.get() in recipes to get values, and conan config list can display the existing built-in configuration items (all of this available in 1.X)


text:
Q: How to Remove element from the list I want to remove all rohitsharma names from the list remove function is remove only the first one what should I do?
names=['rohitsharma','msd','Brettlee','Dravid','rohitsharma','akhil','python','rohitsharma','dhoni','rohitsharma','rohitsharma']
print(names)
names.remove('rohitsharma')
print(names)

A: Build from scratch to remove all occurrences:
names[:] = [x for x in names if x != "rohitsharma"]

This is linear (done in a single iteration) while repeated removal is bound by both the length of the list and the number of occurrences.
You could also get functional about this one and use filter with the ready-made dunder method:
names[:] = filter("rohitsharma".__ne__, names)

A: You can use the filter method to check if each element satisfies the condition or not.
names = list(filter(lambda x: x !='rohitsharma', names))
print(names)

Output
['msd', 'Brettlee', 'Dravid', 'akhil', 'python', 'dhoni']


text:
Q: Substituting an expression with sympy I have the following expression :
p/l

which I extract from a matrix. I later define p and l with following code
from sympy.abc import c,G,M,J,l,u,v,w
us = (2*G*M/c**2)
a = (J/(M*c))
p = (u**2 + a**2*cos(v))
l = (u**2 - us*u + a**2)

I want to substitute the expression p/l and describe it instead with all of the expressions above. I tried doing the following. If g is a sympy.Matrix object and the first element is defined as p/l, then
g[0,0].subs([(p,u**2 + a**2*cos(v)),(l,u**2 - us*u + a**2)])

should do the trick, yet instead I still get p/l, the expression remains unchanged. If I simply type p/l in an ipython session, I get the output
(J**2*cos(v)/(M**2*c**2) + u**2)/(-2*G*M*u/c**2 + J**2/(M**2*c**2) + u**2)

Which is what I desire. (Well almost, I would prefer applying simplify on it first as such : (J**2*cos(v) + M**2*c**2*u**2)/(-2*G*M**3*u + J**2 + M**2*c**2*u**2) ).

A: You are substituting expressions with identical expressions, the result of the substitution is thus identical to the original expression.
Make sure not to confuse SymPy symbols and Python variables:
# Python variable: `p` stores an addition object:
p = (u**2 + a**2*cos(v))

# SymPy symbol, it's just a symbol, no expressions:
p = Symbol('p')

# express symbol-expression relation in some way, like:
{p: (u**2 + a**2*cos(v))}


text:
Q: How to access old state value in new Terraform run I am using Terraform to execute a script to apply some configuration that are not handled via a provider.
This is done using a null_resource.
The executed script will generate a configuration with a name based on current values. Terraform does not keep track of anything created within a null_resource.
The created configuration should also be updatable. But in order to do that I need to know the values used in the prior execution.
Then the old configuration can be targeted by its name, deleted and the new configuration can be added.
So two consecutive runs would look like this:

*

*First execution has the variable setting var.name="ValA". It creates a configuration resource via REST API call called "config-ValA"

*Next execution has the variable setting var.name="ValB". It first deletes the configuration "config-ValA" and then creates "config-ValB". But at this point I no longer have access to the var.name state from the "ValA" execution.

I imagine something like this:
resource "null_resource" "start_script" {

  # Not actual code! I would like to access the old value with var.name.old
  # but I don't know how.
  provisioner "local-exec" {
    command     = "../scripts/dosth.sh ${resource.name.value} ${resource.name.value.old} ${var.name} ${var.name.old}"
    interpreter = ["/bin/bash", "-c"]
  }

}

Is there a way to access the "old" value of a resource/variable in general, or from the context of a null_resource in particular?

What I know I could already do when adding workarounds:

*

*save the old Value in a separate store. E.g. SSM Parameterstore in AWS and access it as input for the new run.

*Use a terraform state show name -raw to extract the value from the state and use it as an input in the new run.

A: Within the Terraform language itself (.tf files) we only work with the desired new state, and don't have any access to the prior state. Terraform evaluates the configuration first and then, with the help of the associated provider, compares the result of evaluating the configuration to the prior state in order to determine what needs to change.
If you want to respond to changes between the prior state and the desired new state then your logic will need to live inside a provider, rather than inside a module. A provider is the component that handles the transition from one state to another, and so only a provider can "see" both the prior state and the desired state represented by the configuration at the same time, during the planning phase.
The community provider scottwinkler/shell seems to have a resource type shell_script which can act as an adapter to forward the provider requests from Terraform Core to some externally-defined shell scripts. It seems that if you implement an update script then it can in principle access both the prior state and the new desired state, although I'm not personally familiar with the details because I've not actually used this provider. I suggest reviewing the documentation and the code to understand more about how it works, if you choose to use it.


text:
Q: Is it possible to recuperate data entered by user in a dynamic table I have created a dynamic table using html+php with input like a form (this is a matrix in reality) and
  I want to know if it is possible to recuperate data entered by user in a dynamic table? This is my code:
<?php
$rows = 3; // define number of rows
echo ' <form action="f.php" method="post">';
echo "
";
for($tr=1;$tr<=$rows;$tr++){
    echo "
";
    echo " E".$tr." 	";
        for($td=1;$td<=$rows;$td++){
               echo '<input type="number" name="etat" placeholder="nb d etat" />	';
        }
    echo "
";
}
echo "
";
echo '<input type="submit" value="Create Table">';
echo '</form>'
?>

A: Yes it is possible but you have to create form by giving row and column number because you want to create matrix:
$rows = 3; // define number of rows
echo ' <form action="f.php" method="post">';
echo "
";
for($tr=1;$tr<=$rows;$tr++){
    echo "
";
    echo " E".$tr." 	";
        for($td=1;$td<=$rows;$td++){
               echo '<input type="number" name="etat_'.$tr.'_'.$td.'" placeholder="nb d etat" />	';
        }
    echo "
";
}
echo "
";
echo '<input type="submit" name="submit" value="Create Table">';
echo '</form>';

in f.php fetch data :
if(isset($_POST['submit'])) {
    print_r($_POST);
}

It gives you output:
Array
(
    [etat_1_1] => 1 //means 1st row 1st column
    [etat_1_2] => 2 //means 1st row 2nd column
    [etat_1_3] => 3 //means 1st row 3rd column
    [etat_2_1] => 4 //means 2nd row 1st column and so on...
    [etat_2_2] => 5
    [etat_2_3] => 6
    [etat_3_1] => 7
    [etat_3_2] => 8
    [etat_3_3] => 9
    [submit] => Create Table
)


text:
Q: License error attempting to implement AppHostHttpListenerBase I'm attempting to create a second App host for self-hosting, so my unit tests are in the same process as the service, to aid debugging.  I created the new app host as follows.  When my Unit test calls the .Init() method, I receive the following error:
ServiceStack.LicenseException was unhandled by user code
  HResult=-2146233088
  Message=The free-quota limit on '10 ServiceStack Operations' has been reached. Please see https://servicestack.net to upgrade to a commercial license or visit https://github.com/ServiceStackV3/ServiceStackV3 to revert back to the free ServiceStack v3.
  Source=ServiceStack.Text
The class below is in the same assembly as my real AppHost (my main ASP.NET service project)., so there is definitely a license key in the web.config. file.
    public class ServiceTestAppHost : AppSelfHostBase
    {
        public const string BaseUrl = "http://localhost/dvsvc";

        public ServiceTestAppHost()
            : base("Test Web Services", typeof(DV.Svc.Interface.HelloService).Assembly) { }

        public override void Configure(Funq.Container container)
        {
            ServiceStack.Text.JsConfig.IncludeNullValues = true;
            ServiceStack.Text.JsConfig.DateHandler = ServiceStack.Text.DateHandler.ISO8601;
            ServiceStack.Text.JsConfig.ExcludeTypeInfo = true;   //exclude the type specification
            ServiceStack.Formats.HtmlFormat.Humanize = false;

            //most apps use credentials auth.  the TVTI player uses Basic auth
            Plugins.Add(new AuthFeature(() =>
                new DVAuthUserSession(),
                new ServiceStack.Auth.IAuthProvider[] { new DVCredentialsAuthProvider(), new DVBasicAuthProvider() })
            /*{ HtmlRedirect = null }*/
            );

            //in memory cache
            container.RegisterAs<MemoryCacheClient, ICacheClient>();

            SetConfig(new HostConfig { DebugMode = true });

        }
    }

A: Self hosted applications don't read from Web.config, they read from the app config App.config, so you would have to create an appropriate config file for the host executable.
<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <add key="servicestack:license" value="{licenseKeyText}" />
</configuration>


text:
Q: Why might a "yum upgrade" appear to work but not actually apply anything? I have a server running CentOS (with Fasthosts UK).
Running a "yum upgrade" lists - and processes - a LOT of packages that it has upgrades for. Everything is downloaded and installed.
The problem is that if I do a subsequent "yum upgrade", it list all the same upgrades again! As if it was only running as a simulation and didn't really apply any upgrades.
This effectively means that I can't upgrade any of the software packages on my server ("yum upgrade specificpackage" also has the same problem) and so I wondered if anybody has any kind of experience or advice about this?
Is this a CentOS issue or a Fasthosts issue?
PS. FWIW there is also Plesk intalled on this server.

A: Based on that log snippet, it looks like you may have some repository priority conflicts.  In my experience, the various repositories for CentOS are not well-coordinated.  RPMForge doesn't always play nicely with EPEL, for example, and you get version number races.
To get more information, you could make yum run in verbose mode with the -d (debug) and -e (error level) switches.  NUM should be between 1 and 10.
You might also try using --skip-broken, which should only hold back the package that's causing problems.

A: I haven't seen this specifically, but the first thing I would try is yum clean all to clean up package data, caches and the rpm database.  Then see if you get the same results after another update.

A: In your comments you say there is a "transaction check error". This is likely the problem. You should paste that here, although depending on what the problem was, it may have solved itself by now.
As other posters pointed out, some of the third party repos. are not very well managed. At most I would recommend: RHEL, EPEL, rpmfusion* and iuscommunity.


text:
Q: Rotation of figure around axis x=2 versus around x=0. I have two equations $y=2x  $  and $y=x^2$ which are revolved around x=2.
My integral is $2\pi \int_0^2 (2-x)(2x-x^2) $.
In another question, I have  $y=2x  $  and $y=x^2$ which are revolved around x=0. This integral is
$2\pi \int_0^2 (x)(2x-x^2) $
The first and second volume turn out to be equal. This is not intuitively clear to me. I would expect different volumes, since shells of different areas are making different rotations in the first and second problem.
Any help?

A: Integrating by oatmeal boxes like this, $V=\int2\pi rh\,dr$, if we add the same function of $x$ to both the upper and lower curves, then $h(x)=(y_2(x)-f(x))-(y_1(x)-f(x))=y_2(x)-y_1(x)$ hence also the volume, doesn't change.
Thus we choose to add $f(x)=-2x$ to both curves to get $y_2(x)-f(x)=2x-2x=0$ and $y_1(x)-f(x)=x^2-2x=(x-1)^2-1$. Now the symmetry of both upper and lower curves about $x=1$ is evident, so it should be clear that rotating about two different axes positioned symmetrically about $x=1$ should yield the same volume, $\frac{8\pi}3$.


text:
Q: How to remove background color of TextField on Flutter Widget? I can't remove the shadow and the background of the TextField, here is my code:
TextFormField(
                            decoration: InputDecoration.collapsed(),
                            validator: (input) =>
                                input == "" ? 'The task is empty' : null,
                            onSaved: (input) => task = input,
                          )

this is the result that I want

I always try BoxDecoration but no success because don't is compatible with TextFormField.

A: You should set filled to true.
TextField(decoration: InputDecoration( fillColor: Colors.red, filled: true)),

A: Wrap your TextFormField inside a Container and change its color property to match your background color (as from your picture I'll assume its white):
     Container(
        color: Colors.white, // or any color that matches your background
        child: TextFormField(
                 decoration: InputDecoration.collapsed(),
                 validator: (input) => input == "" ? 'The task is empty' : null,
                 onSaved: (input) => task = input,
               )
     ),


text:
Q: There is an identifier expected but i don't know what i need to put there What kind of identifier does the visual studio needs ? i just want to put from outside one int array with 2 different numbers between 0 and 66.
    public static void playerLocationChange(int[])
    {

    }

A: You have to give the parameter a name. Otherwise, you have no way of referring to it from the function.
public static void playerLocationChange(int[] myIntArrayParam)
                                        //Notice the name next to int[]
                                        //This is the parameter's name
{

}


text:
Q: In ASP.NET MVC, what is the difference between <%= and <%:? I'm new to ASP.NET MVC. I've seen both <%= ... %> and <%: ... %>. I'm familiar with the first from classic ASP days, but not the latter. What is the difference between the two?

A: Using <%: tells ASP.NET 4.0 to perform a Server.HtmlEncode() on the value being displayed.
Whereas using <%=, it is up to the developer to use Server.HtmlEncode().
Note HtmlEncode() helps void cross-scripting attacks.
For more info, see ScottGu's post here.

A: <%= %> - equivalent to response.write in classic ASP.
<% %> - represents a code block, if, then else, for each, etc.
<%: %> - this is a shortcut new to .NET 4, this represents <%= html.encode(item) %>
Link to video explaining the shortcut (it's a short clip):

A: <%: expression %> is an HTML encoded expression and was introduced in ASP.NET 4
It is equivalent to <%= HttpUtility.HtmlEncode(expression) %>
Go here for more detail.


text:
Q: Where to download an old Microsoft hotfix that now results in a 404 error? I need to download Microsoft's KB976811 for my Outlook 2007, that was previously available via:
http://support.microsoft.com/kb/976811
That now results in an http 404 error.
Any idea where can I get that hotfix package 976477 that they mentioned there?

A: As Ramhound mentioned above, the hotfix might be no longer available since it had been fixed in a later public hotfix.


text:
Q: attempt to solve a Bernoulli equation I tried solving the Bernoulli equation $y'-y\tan x = y^4 \cos x $ by equating the left hand side to 0 and finding the homogeneous solution, however the equation turned out to be too complex and without the ability to isolate x. Any hints on how to solve this?

A: Another trick
$$y'-y\tan x = y^4 \cos x$$
$$\cos(x)y'-y\sin x = y^4 \cos^2 x$$
$$(\cos(x)y)' = y^4 \cos^2 x$$
Substitute $z=\cos(x)y$
$$z' = \frac {z^4} {\cos^2 x}$$
It's separable
$$\frac 1{z^3}  =-3\int  \frac {dx} {\cos^2 x}$$
$$\frac 1{z^3}  =-3\tan x +K$$
$$z^3  =\frac 1 {-3\tan x +K}$$
$$\boxed{y^3(x)  =\frac 1{\cos^2(x)(K\cos(x)-3\sin x)}}$$
$$......$$

A: $y' - y\tan(x) = y^4\cos(x)$
divide throughout by $y^4$
$\frac{y'}{y^4} - \frac1{y^3}\tan(x) = \cos(x)$
let $z= \frac{1}{y^3}\implies z' = \frac{-3}{y^4}y'$
$\frac{-z'}{3} -z\tan(x) = \cos(x)$
$z' + 3\tan(x)\,z = -3\cos(x)$
it is now a Linear differential equation
Integrating factor , $I=e^{\int3\tan(x)}=e^{\ln(\sec^3(x))} = \sec^3(x)$
the solution is given by ;
$z\cdot I =\int-3\cos(x)\cdot I\,dx$
integrate and sub back for $z$
Can you proceed further?Ask if you need help.
EDIT:  on how we got $z\cdot I =\int-3\cos(x)\cdot I\,dx$;
we have $z' + 3\tan(x)\,z = -3\cos(x)$
multiply throughout by $\sec^3(x)$
we get ; $z'\cdot\sec^3(x) +3\cdot\tan(x)\cdot\sec^3(x)\cdot z = -3\cos(x)\cdot\sec^3(x)$
recognize that the LHS is a product rule derivative of  $z\cdot\sec^3(x)$
ie $d(z\cdot\sec^3(x)) =(z'\cdot\sec^3(x) +3\cdot\tan(x)\cdot\sec^3(x)\cdot)\,dx z$
therefore  the equation becomes ;
$\big(z\cdot\sec^3(x)\big)' = 3\cos(x)\cdot\sec^3(x)$
integrating on both sides gives us;
$z\cdot I =\int-3\cos(x)\cdot I\,dx$; $\quad$ where $I= \sec^3(x)$

A: Hint:
 Divide both side by $y^4$ to obtain
$$\frac{y'}{y^4}-\frac{\tan x}{y^3}=\cos x,$$
and set $u=\dfrac 1{y^3}$. The equation rewrites as
$$-\frac13 u'-u\sin x=\cos x\iff u'=-3u\tan x-3\cos x,$$
which is a classical linear differential equation.


text:
Q: TEdgeBrowser Popup menu / Context menu How can the context menu in the TEdgebrowser component be overwritten?
The property inspector does not offer an event for this.

A: The context menu can be deactivated using Javascript. This solution does not cover all use cases. It's enough for my problem..
<!DOCTYPE html>
<html lang="de">
  <head>
  <title>Test</title>
  <script type='text/javascript'>
    let ContextMenuDefault = false;
    document.addEventListener('contextmenu', function(event)
    {
      if (false == ContextMenuDefault)
       event.preventDefault();
    }, true);
  </script>
  </head>
  <body>
   Hello World
  </body>
</html>


text:
Q: Chrome not displaying webfont, falling back to Times New Roman when font-face declared in cached stylesheet I'm having an issue with FontAwesome (v4) webfont icon rendering in Chrome when Chrome's caching is enabled. Intermittently, across multiple user machines, a page will load with our FontAwesome icons displayed incorrectly as below. This issue happens only occasionally and can't be reliably reproduced or narrowed down to a single page. The only common repro steps are using Chrome and not having "disable cache" enabled in dev tools or elsewhere.

Checking dev tools computed styles for the icon elements reveals that Chrome is correctly detecting the specified font-family as "FontAwesome", but the <i> tags for the icons are being rendered in Times New Roman, rather than the FontAwesome webfont. The "FontAwesome" @font-face declaration and the above rule assigning font-family: FontAwesome to the .fa class exist in the same stylesheet, site.css, which is causing the issues.

Checking the source below, we see that site.css is properly specified in the site's <head> tag. It isn't being added to the <head> through JavaScript; it's present in the  in the initial page loaded by the browser. The href points to the correct stylesheet, which loads without issue when opened in a new tab. This isn't very surprising, since all of the styles specified in site.css are correctly being applied to the page (except for the webfont, of course). Even the .fa's font-family rule is being read correctly by Chrome, as shown in the computed styles in the screenshot above.

My suspicion is that Chrome is loading the stylesheet from cache in a weird way that's allowing all of the styles to load but is interfering with the creation of the FontAwesome webfont. Potential evidence for this below:

Above is a portion of the network tab from the dev tools session. Nothing has been filtered out, but site.css has no entry in the list of requests, even though other cached stylesheets are present and the styles from site.css are being applied to the page. There are entries for theme.css, jQuery, AdminLTE, and other stylesheets specified just after site.css in the same <head> block. It's not pictured, but the fontawesome.woff2 webfont file, specified in site.css's @font-face declaration for "FontAwesome", is also being successfully loaded.
Refreshing the page or navigating to another one sometimes fixes the issue. Refreshing with cache disabled always fixes the issue. Every page of our (quite large) web app loads this stylesheet using the same <link> tag, and while this issue pops up fairly rarely, it has happened across many of those pages. The site.css stylesheet is clearly being loaded by Chrome, as it sees the font-family: FontAwesome rule along with the rest of our site styles. But something seems to be happening during the loading of the stylesheet from cache that's causing Chrome to fall back to Times New Roman despite the webfont being both declared via @font-face and specified as the font-family for the affected elements.
We aren't using a service worker or any server-side caching. We do some cachebusting via a GET parameter as shown in the screenshots above (the ?[productName]Version=2.0.13292.0), that value is baked into the initial document loaded by ASP.NET and changes only when our backend server's version changes -- so that shouldn't be the cause of the issue here.
Has anyone experienced anything similar with Chrome webfonts?

A: I had the same problem. My compiled CSS file was missing @charset "UTF-8"; and as a result, the cached icons font was broken. Please check if this helps you.


text:
Q: How to centre the Buttons in my JFrame? I am trying to make a board game, I have Player 1 label and player 2 label set to the east and west. I am having trouble centre my 3 x 10 buttons. And is there any simpler way of making all 30 buttons at once? Below is my Code:
    JPanel panel = new JPanel();
    JButton button1 = new JButton();JButton button2 = new JButton();
    JButton button3 = new JButton();JButton button4 = new JButton();
    JButton button5 = new JButton();JButton button6 = new JButton();
    JButton button7 = new JButton();JButton button8 = new JButton();
    JButton button9 = new JButton();JButton button10 = new JButton();
    JButton button11 = new JButton();JButton button12 = new JButton();
    JButton button13 = new JButton();JButton button14 = new JButton();
    JButton button15 = new JButton();JButton button16 = new JButton();
    JButton button17 = new JButton();JButton button18 = new JButton();
    JButton button19 = new JButton();JButton button20 = new JButton();
    JButton button21 = new JButton();JButton button22 = new JButton();
    JButton button23 = new JButton();JButton button24 = new JButton();
    JButton button25 = new JButton();JButton button26 = new JButton();
    JButton button27 = new JButton();JButton button28 = new JButton();
    JButton button29 = new JButton();JButton button30 = new JButton();

    panel.add(button1);panel.add(button2);panel.add(button3);panel.add(button4);
    panel.add(button5);panel.add(button6);panel.add(button7);panel.add(button8);
    panel.add(button9);panel.add(button10);panel.add(button11);panel.add(button12);
    panel.add(button13);panel.add(button14);panel.add(button15);panel.add(button16);
    panel.add(button17);panel.add(button18);panel.add(button19);panel.add(button20);
    panel.add(button21);panel.add(button22);panel.add(button23);panel.add(button24);
    panel.add(button25);panel.add(button26);panel.add(button27);panel.add(button28);
    panel.add(button29);panel.add(button30);
    frame.add(panel);

    Panel p = new Panel();
    p.setLayout(new BorderLayout());
    p.add(new Button("Throw dice"), BorderLayout.SOUTH);
    //p.add(new Button("dice Draw"), BorderLayout.SOUTH);
    p.add(new Label("Player 1"), BorderLayout.EAST);
    p.add(new Label("Player 2"), BorderLayout.WEST);
    frame.add(p);

    panel.setLayout(new GridLayout(3,10));
    panel.setSize(new Dimension(500, 200));
    frame.setSize(new Dimension(600, 300));

  }

}

A: you can make arrays of JButtons and edit them simply by creating a table of JButtons, and use them with a GridLayout cenetred in Borderlayout.CENTER :
JButton [] buttons = new JButton[n];
for(int i=0;i<n;i++){
    buttons[i] = new JButton("label "+ i);
    buttons[i].set...
    buttons[i].set...
    gridlayout.add(buttons[i]);
}

borderlayout.add(gridlayout, BorderLayout.CENTER);
panel.setLayout(borderlayout);

hope this helps.

A: A way to do it is:
panel.setLayout(new GridLayout(3,10));
panel.setSize(new Dimension(500, 200));
//Add this line
panel.setLocation((frame.getWidth()-panel.getWidth())/2, 0); // 0 is just the Y location
frame.setSize(new Dimension(600, 300));

Look into relative layout to manage all your layouts https://stackoverflow.com/a/5346794/643500
Keep in mind that you want all pieces to layout nicely with each other, otherwise issues can be a pain to deal with.  Dahmad Boutfounast's solution is one of those nice ones to have.
And definitely use a list\array to manage all those.


text:
Q: log4net - per user logging Please help me with this query in using log4net.
I am using log4net in mhy we application. I am facing issues in configuring log4net to log errors at user level.
That is, If user X logs in, I like to create file name X and all error for user X should be written in X.log. Siilarly if Y user logs in the log file should be in name of Y.log and the most important point to note is, they could log in concurrently.
I tried the luck by creating log files whose name would be framed dynamically as soon as the user logs in. But issue here, if they are not using the application at the same time, the log files are creeated with correct name and writing as expected, but if both users have active sessions, log file is created only for user who FIRST logged in and error of second user has been recorded in log file that is created for FIRST user.
Please help me in this.

A: There has to be a better solution from this one, but you can change log4net configuration from code and even decide which config file to load - so you can do it in code, which is not as nice as editing an XML file.
so what you need to do, which is highly not recommended, is to create log4net configuration each time you call the logger static class, and do what needed based on the calling user.
again.. it doesn't feel right !
(and it will probably perform poorly).
another BETTER solution is to log everything to database (log4net supports it), with a user column, and then produce the logs from db....


text:
Q: RxJava run on subscription method every time an event occurs I have an observable that on subscribe does a long operation but when a user click on a button I want to notify my observable to do again the long operation because something change.
I don't want to make a new subscription every time the user clicks on the button. Which is the best solution to achieve this?
I would like to know if is possible to use a solution, which use the rxjava simplified way to run code on different threads.
Should I use something like this?
BehaviourProcessor<boolean> processor = BehaviourProcessor.createDefault(true);

public Flowable<List<Item>> getItems(){
     return Flowable.create(e -> e.onNext(longOp()))
                .subscribeOn(Schedulers.io())
                .switchMap(items -> processor.map(notify -> returnItems(notify)));
}

public void notifyChange(){
   processor.onNext(true);
}

Android Room library achieve this result, in fact when you subscribe this:
   @Query("SELECT * FROM user")
   Flowable<List<Item>> getUsers();

Every time you delete an item from database you immediately get the new list from the database in the subscription on next method.

A: Rather than have getItems() return the observable chain that you have shown, return a shared observable.
Flowable<List<Item>> itemGetter =
  Flowable.create(e -> e.onNext( longOp() ) )
    .subscribeOn( Schedulers.io() )
    .switchMap(items -> processor.map(notify -> returnItems(notify)))
    .replay( 1 )
    .publish();

Flowable<List<Item>> getItem() {
  return itemGetter;
}

This creates only on observer chain that you can subscribe to as many times as you want. However, if there are no subscribers and another subscriber comes along, longOp() will be called again.
If you don't want that to happen, then you should consider using a BehaviorSubject<List<Item>> to cache the value.


text:
Q: Terraform conditional iteration I would like to create a dynamic resource with for_each as well I would like to implement a resource creation condition, however by some reason which I don't understand, the resource creation condition is not working as expected.
The logic is very simple: I've a list of objects, each object is resource, therefore in each object a have a bool variable that enables creation of a resource.
resource "aws_autoscaling_group" "aws_asg"  {
   for_each = { for key, value in var.parameters : key => value if flatten([ for x in var.parameters : x.init ]) }
}

The problem in flatten([ for x in var.parameters : x.init ]), the resource takes first element, and ignores next element:
  + x = [
      + true,
      + false,
    ]

Here is var.parameters
   parameters = [
       # Runner 1
       {
            init    = true
            name    = "test-runner-1"

            scaling = {
                    desired     = 3
                    maximum     = 9
                    minimum     = 3
            }
       },

       # Runner 2
       {
            init    = false
            name    = "test-runner-2"

            scaling = {
                    desired     = 3
                    maximum     = 9
                    minimum     = 3
            }
       }
   ]
}

Any idea how to map each boolean to resource creation?

A: If you want to conditionally loop through your parameters, then it should be:
resource "aws_autoscaling_group" "aws_asg"  {
   for_each = { for key, value in var.parameters : key => value if value.init }
}


text:
Q: Column to be parsed Dynamically in PySpark Column names and No of columns in each new data came are different . I want to columns to be parsed dynamically in PySpark and creating unique schema for incoming datasets.
Input 1 : old
        Name    Position_-07/05/2020  Department
        Peter     Grade-A             LS
        Robin     Grade-B             LS
        Rosy      Grade-A             HS
        Silver    Grade-C             HS
        Jeo       Grade-B             AS

Input 2: df_new
       Name    Position_-07/06/2020  Department   percentage
        Peter     Grade-A             LS            90
        Robin     Grade-A             LS            85
        Rosy      Grade-A             HS            92
        Silver    Grade-C             HS            60
        Jeo       Grade-B             AS            75
        Wilson    Grade-A             HR            93

old_column=["name",Position_07/05/2020,Department]
col_new=[]
col_current=df_new.columns
for filed_name in df_new.columns:
       if filed_name in  old_columns:
              col_new.append(field_name)
new_col=set(col_new+col_current)
schema= [StructField(field_name, StringType(), True) for field_name in new_col]

I am stuck in after that . I want unique schema for two datasests.
 out put: Name  Position_07/05/2020 position_07/06/2020 Department percentage
          Peter   Grade-A             Grade-A             LS          90
          Robin   Grade-B             Grade-A             LS          85
          Rosy    Grade-A             Grade-A             HS          92
          Silver  Grade-C             Grade-c             HS          60
          Jeo     Grade-B             Grade-B             AS          75
          Wilson   NULL               Grade-A             HR           93

A: According to your example, that's just a basic join.
old.join(df_new, on="Name")


text:
Q: Storing results of a stored procedure in a Google Big Query table Here is a link to the question I asked earlier. The accepted answer works perfectly.
But this stored procedure processes 2 statements and after running this procedure I have to click on View Results of the second statement to see the result in Google Big Query. Is there a way to save the results in some table automatically using the 'Query Settings' in Google Big Query and specifying the name of the table I want to store the results in?

A: You cannot set a destination table for a script (or for call a procedure), instead, you can convert your SELECT statement into CREATE TABLE ... AS SELECT, for example:
SELECT 1 x;

=>

CREATE TABLE myDataset.myTable
AS SELECT 1 x;

A: You can define a string parameter for your procedure. Then use this parameter in the dynamic query to write the results to the table.
CREATE OR REPLACE PROCEDURE `my_dataset.my_procedure`(destination_table STRING)
BEGIN

CREATE TEMP TABLE tmp AS SELECT 1 x;

EXECUTE IMMEDIATE (
    FORMAT("CREATE OR REPLACE TABLE `%s` AS SELECT * FROM tmp", destination_table));

END

Now you can provide a table name and call this procedure to write the results to the table.
CALL `my_dataset.my_procedure`("my_dataset.my_table");
SELECT * FROM `my_dataset.my_table`


text:
Q: How to find different values within a group in Excel I need to write some functions in Excel that can search for different value in groups in an excel table. And I couldn't find other similar questions that can help me with my problem.
For example:
Group1  0.3
Group1  0.3
Group1  0.2
Group1  0.3
Group1  0.3
Group1  0.3
Group2  0.5
Group2  0.5
Group2  0.5
Group2  0.5
Group2  0.5
Group2  0.5

Where Group1 are not all the same, and Group2 are all 0.5. I need to write some function that can find and flag the group where the values are not all the same. My expected result is:
Group1  0.3 "Not all the same in this group"
Group1  0.3 "Not all the same in this group"
Group1  0.2 "Not all the same in this group"
Group1  0.3 "Not all the same in this group"
Group1  0.3 "Not all the same in this group"
Group1  0.3 "Not all the same in this group"
Group2  0.5 "Same"
Group2  0.5 "Same"
Group2  0.5 "Same"
Group2  0.5 "Same"
Group2  0.5 "Same"
Group2  0.5 "Same"

A: Please try:
=IF(MAX(IF(A:A=A1,B:B))=MIN(IF(A:A=A1,B:B)),"Same","Not all the same in this group")

entered as an array formula (with Ctrl+Shift+Enter) in Row1 and copied down to suit. Assumes your data starts in A1 and B1.

A: Alternatively
=IF(COUNTIF(A$2:A$100,A2)=COUNTIFS(A$2:A$100,A2,B$2:B$100,B2),"Same in this group","Not all the same in this group")

A: Without using array formula
if data starts at A1. The place following at C1 and drag below
C1 =IF(SUMIFS($B$1:$B$12,$A$1:$A$12,A2)=COUNTIFS($A$1:$A$12,A2)*B2,"same","Not all the same in this group")

A: A "Sumif" divided by a "Countif" should result in the same value as "me" if the values are all the same.   So something like this (assuming we're starting in "f11"):
=IF(SUMIF(F$11:F$22,F11,G$11:G$22)/COUNTIF(F$11:F$22,F11)=G11,"same","different")


text:
Q: how to rename a gDoc printer in Win 7 64 bit machines I have installed a printer called gDoc Creator for printing on my Windows 7 64 bit machines. If i rename the printer to anything other than "gDoc Creator" the printer is not recognized when I select it to print. It just becomes totally dead. It only works with the given name. I want to know how I can rename the printer and make it work successfully. I have tried renaming in the .inf files but I am yet to find a solution. Thanks all for your help and I appreciate the responses and please let me know if more details are required.

A: If renaming the printer causes it to stop working, the driver must have that name hard-coded and depends on it never being changed.  That's a seriously broken printer driver if it actually cares what the printer name is and doesn't allow that name to be changed.  You can confirm that by opening the driver's two DLLs with a hex editor and looking for the string "gDoc Creator."  If it is as I suspect, there's nothing you can do short of patching the DLL, and frankly that's just not worth it.  There are many PDF/Office conversion tools out there.  I recommend you find a better one.


text:
Q: If the closest packing of circles is hexagonal, what is the closest packing of spheres and what shape does it form? I'm just a high school student in Precalculus, so this isn't a very complicated question, and hopefully the answer won't be either.
The densest packing for equally sized circles is a hexagonal lattice, where each circle touches 6 other circles. If you connect these intersects, you get a hexagon, and the whole thing forms a honeycomb pattern.
What's the three dimensional equivalent of this? So:
A: What is the densest packing spheres can have?*
B: What is the polygonal equivalent of this packing (what shape)?
*EDIT: After looking at the wikipedia article Sassatelli Giulio provided, the answer to question A is that there are two packings of equal density that are the densest you can get. Face-Centered-Cubic (FCC) and Hexagonal-Close-Packed (HCP), but the wikipedia article is still rather unclear on what polygonal lattice these form.


text:
Q: setLngLat().setPopup is not a function Once the view render i get this error and popup is not added -

mapbox-gl.js:176 TypeError: (intermediate value).setLngLat(...).setPopup is not a function(…)

Does anybody face this or know something to fix this?
Code is this to set popup over marker, I've followed this link https://www.mapbox.com/mapbox-gl-js/example/set-popup/
  let tpl;
  if (vendor.get('cachedAverageRating')) {
    tpl = `

${vendor.get('cachedAverageRating')}

  `;
  } else {
    tpl = `

  `;
  }

  let markerContainer = document.createElement('div');
  markerContainer.innerHTML = tpl;

  // create the popup
  let markerPopup = new MapboxGL.Popup({offset: 25})
    .setHTML(`<div>Name : ${vendor.get('name')}, Address : ${vendor.get('address')}, Rating : ${vendor.get('cachedAverageRating')}</div>`);

  // create the marker
  new MapboxGL.Marker(markerContainer, {offset:[-25, -25]})
    .setLngLat([get(vendor, 'lon'), get(vendor, 'lat')])
    .setPopup(markerPopup) // sets a popup on this marker
    .addTo(map);

A: You're using MapboxGL instead of mapboxgl, the code is case sensitive.
There may be an error in your vendor variable too, but we can't see how you define it in your answer up there. If you can provide more information we might be able to help further. For now: this bit of code works:
mapboxgl.accessToken = '<your access token here>';

var monument = [-77.0353, 38.8895];
var map = new mapboxgl.Map({
    container: 'map',
    style: 'mapbox://styles/mapbox/light-v9',
    center: monument,
    zoom: 15
});
let tpl;

    tpl = "text";

  let markerContainer = document.createElement('div');
  markerContainer.innerHTML = tpl;

  // create the popup
  let markerPopup = new mapboxgl.Popup({offset: 25})
    .setHTML("test");

  // create the marker
  new mapboxgl.Marker(markerContainer, {offset:[-25, -25]})
    .setLngLat(monument)
    .setPopup(markerPopup) // sets a popup on this marker
    .addTo(map);

A: This should be straightforward for you to debug from the error message. Clearly, setLngLat() is returning something which is not a Marker, so setPopup() is not defined on it.
Why is it doing that? Because you're passing the wrong thing to setLngLat(). You should pass a LngLat object (defined here).
I'm not really sure what you're trying to do with your get() function, but it's obviously not returning a numbers as required.


text:
Q: How to move files in Qt? Is there a cross-platform function in Qt that is equivalent to the MoveFile function in Windows and the mv command in Linux?

A: You would use QDir::rename() but be beware of the special cases when rename() can fail:

On most file systems, rename() fails
  only if oldName does not exist, if
  newName and oldName are not on the
  same partition or if a file with the
  new name already exists. However,
  there are also other reasons why
  rename() can fail. For example, on at
  least one file system rename() fails
  if newName points to an open file.

A: Sure, QDir::rename() following the old Unix / POSIX tradition of calling this rename.
Which makes sense if you think of a file with its complete path: the underlying inodes just get assigned a different path/file label.

A: QUrlOperator::copy() is an alternative to QDir::rename() that may also work for you.


text:
Q: How to know if the loops can be parallelized for multithreading with the help of openmp? I have a nested loop. i would like to know if the outer and the inner loops can be parallelized with the help of openmp?
for (col = n-1; col >= 0; col--) {
    x[col] /= A[col][col];
    for (row = 0; row < col; row++)
        x[row] -= A[row][col] * x[col];
}

I think the outer loop can be paralelized as the inner loop depends only on the fixed value of the the column or col.

A: A sufficient condition (but not necessary!) of parallelizability is

*

*for each value of the loop variable

*only array locations with that index are changed.

In such a case iterations i1 and i2 can not write in conflicting locations, therefore the writes can be done in any order, therefore in parallel.
In your code the inner loop satisfies that condition; your outer does not. That's because the inner loop writes a whole bunch of indices, and not just [col]. So two different col values will all write to identical locations. You can sometimes fix that with an atomic directive, but that's 1. not good for performance 2. not even possible in your particular case because of the non-associativity of the operations you're doing.