text:
Q: Autofs starting but seemingly doing nothing - not even logging? I am attempting to automatically mount a NTFS formatted usb raid array when inserted using autofs, but am finding that no mounting - in fact, not even an attempt to mount - is taking place.  I can't even seem to get anything to show up in the logs.  I'm quite confused.
I have a symbolic link created so that when I insert the drive it is automatically mapped to /dev/usbraid.  Now I just need it to auto mount that device to somewhere on the file system.
I am using picuntu (a stripped-down debian distro) on a Rikomagic MK802III.
I've installed autofs using apt-get, and I edited the /etc/auto.master file to read as follows:
+auto.master
/media    /etc/auto.removable

And my /etc/auto.removable file reads as follows:
/media/usbraid  -fstype=ntfs  :/dev/usbraid

I'm successfully able to start the service, but I see no feedback indicating that the auto.master file has been read or that an attempt to mount has taken place.  When I call 'service autofs status' I get the cursory 'auto fs start/running' message.
I expected at least an error or something.  In desperation, I modified the '/etc/default/autofs' file to set 'LOGGING="verbose"', but I still see nothing in any of the logs except a system log when the autofs service is started and stopped.
I'm obviously doing something wrong but can't quite figure out what.  Any ideas?

A: OK, got this one nailed down, thanks to some information from here: http://www.clearfoundation.com/component/option,com_kunena/Itemid,232/catid,13/func,view/id,14038/
Basically, the issue is that the autofs4 module isn't loaded.  If I run
modprobe autofs4

Says that the module isn't found.  It appears that the autofs module wasn't compiled into my kernel.  I suppose I can recompile the kernel, but this is probably more effort than it is worth.


text:
Q: MultiUserChat invitations in Smack I have the following code to listen for invitations to a chatroom:
    Connection.DEBUG_ENABLED = true;
    XMPPConnection connection = new XMPPConnection("jabber.org");
    connection.connect();
    connection.login("username", "password");

    MultiUserChat.addInvitationListener(connection, new InvitationListener() {
        @Override
        public void invitationReceived(Connection arg0, String arg1,
                String arg2, String arg3, String arg4, Message arg5) {
            System.out.println("Invitation Received!");
        }
    });

    System.out.println("Connected, waiting for invitation");
    while(true) {
        Thread.yield();
    }
}

I then use another account to login with pidgin create a chatroom, and invite the above user. The invitationReceived method is not called. The smack debugger receives a presence update when I login, but no other packets. However, if I am logged in to the above user with pidgin, I do receive the invitation. How can I make smack detect the invitation request?

A: I might be too late to answer this question ,but i would like to share my solution here, i had same issue ,
First off all it depends what version of smack are you using(i recommended latest version)
Second, user sending MUC invitation and user receiving invitation should be connected to same server in order to receive MUC invitation.
Third always enable smack debugger ,it will give information about incoming and outgoing stanza.
Fourth factor you should consider is to send a presence to XMPP server  after login as shown below,
       connection.setStatus(true,"ONLINE");

public void setStatus(boolean available, String status) throws XMPPException {
        Presence.Type type = available? Type.available: Type.unavailable;
        Presence presence = new Presence(type);
        presence.setStatus(status);
        connection.sendPacket(presence);
    }

sending presence informs xmpp server about user status and then presence information as well as new invitation will be received if you have enabled listener on connection object ,this works for me hope it will works for you also,please correct me if any information is wrong.

A: You might be using the wrong username from pidgin. You have to use the name followed by the email address.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Time until midnight between two date and time columns I need help with my query to calculate the time until midnight between two date and time columns
break down by day
This is the main table:

ID
Start_Time
End_time
DateDiff

32221
01-01-2022  13:10:00
01-03-2022  13:10:00
2880

My query:

SELECT
    start_time.ID,
    start_time.Date_Time AS Start_time,
    end_time.Date_Time AS End_time,
    DATEDIFF(minute, start_time.Date_Time, end_time.Date_Time) AS DateDiff
FROM
    Main

what I  need is similar to this:

ID
Date_start
End_time
DateDiff

32221
01-01-2022  13:10:00
01-01-2022  23:59:59
654

32221
01-02-2022  00:00:00
01-02-2022  23:59:59
1440

32221
01-03-2022  00:00:00
01-03-2022  13:10:00
781

how i can do that?

A: You can loop through the times, always adding the time untill midnight, untill your 'start_time + 1 day' is bigger than your end_time.
The below code can be run directly in SQL (mind the date notation, my SQL is in united states notation, so if yours is in Europe this will give you back results for 3 months instead of 3 days);
DECLARE @start_time datetime2 = '01/01/2022 13:00:00';
DECLARE @end_time datetime2 = '03/01/2022 14:00:00';
DECLARE @daily_end_time datetime2=NULL;
DECLARE @Table Table (start_time datetime2, end_time datetime2, diff nvarchar(8));
DECLARE @diff_minutes_start int = DATEDIFF(MINUTE,@start_time,DateDiff(day,0,dateadd(day,1,@start_time)));
DECLARE @diff_minutes_end int = DATEDIFF(minute,@end_time,DateDiff(day,0,dateadd(day,1,@end_time)))
SET @daily_end_time = DATEADD(mi,@diff_minutes_start,@start_time)

WHILE @daily_end_time < @end_time
BEGIN
    INSERT INTO @Table (start_time,end_time,diff)
    VALUES (
    @start_time,
    CASE WHEN DATEADD(day,1,@daily_end_time) > @end_time THEN @end_time ELSE
@daily_end_time END,
CASE WHEN DATEADD(day,1,@daily_end_time) > @end_time THEN @diff_minutes_end ELSE
@diff_minutes_start END )
  SET @daily_end_time = DATEADD(mi,@diff_minutes_start,@start_time)
SET @start_time = DATEADD(mi,1,@daily_end_time);
select @diff_minutes_start  =

DATEDIFF(MINUTE,@start_time,DateDiff(day,0,dateadd(day,1,@start_time)));
    select @diff_minutes_end  = DATEDIFF(minute,@end_time,DateDiff(day,0,dateadd(day,1,@end_time)))
    END
    SELECT * FROM @Table

And the results:

A: You may use a recursive CTE as the following:
With CTE As
(
  Select ID, Start_Time, End_time, DATEADD(Second, -1, DATEADD(Day, DATEDIFF(Day,0, Start_Time), 1)) et
  From main
  Union All
  Select C.ID, DATEADD(Second, 1, C.et), C.End_time, DATEADD(Day, 1, C.et)
  From CTE C Join main T
  On C.ID = T.ID
  Where DATEADD(Second, 1, C.et) <= C.End_time
 )
Select ID, Start_Time,
       Case When End_Time <= et Then End_Time Else et End As End_Time,
       DATEDIFF(Minute, Start_Time, DATEADD(Second, 1, Case When End_Time <= et Then End_Time Else et End)) As [DateDiff]
From CTE
Order By ID, Start_Time

See a demo with extended data sample from db<>fiddle.

A: You can also solve this with a tally table, using the expanded (to show different cases) sample data

ID
StartTime
EndTime

32221
2022-01-01 13:10:00
2022-01-03 13:10:00

32222
2022-02-02 10:10:00
2022-02-02 17:10:00

32223
2022-03-03 19:10:00
2022-03-04 08:10:00

32224
2022-04-04 19:10:00
2022-04-08 08:10:00

and the code
with cteSampleData as ( --Enter some sample data, include spans of 0, 1, and >1 days
    SELECT * --Note that we need CONVERT to make sure the dates are treated as datetime not string!
    FROM (VALUES(32221, CONVERT(datetime2(0), '01-01-2022 13:10:00'), CONVERT(datetime2(0), '01-03-2022 13:10:00') )
        , (32222, '02-02-2022 10:10:00', '02-02-2022 17:10:00')
        , (32223, '03-03-2022 19:10:00', '03-04-2022 08:10:00')
        , (32224, '04-04-2022 19:10:00', '04-08-2022 08:10:00')
    ) as Samp(ID, StartTime, EndTime)
), cteWithControl as ( --Add some fields to make testing cledarer - you could do this as part of a subsequent step instead
    SELECT *
        , CONVERT(date, StartTime) as StartDate , CONVERT(date, EndTime) as EndDate
        , DATEDIFF(day, StartTime , EndTime) as DiffDays
        --, DATEDIFF(day, CONVERT(date, StartTime) , CONVERT(date, EndTime)) as DiffDays
    FROM cteSampleData
), cteTally as ( --Get a list of integers to represent days, assume nothing lasts longer than a year
    SELECT top 365 ROW_NUMBER() over (ORDER BY name) as Tally
    FROM sys.objects --just a table we know has over 300 rows, look up tally tables for other generation methods
)--The real work begins below, partition the data into "same day" and "multi-day" spans
, cteSet as (
    SELECT ID, StartTime, EndTime, DiffDays, 1 as DayNumber
    FROM cteWithControl WHERE DiffDays = 0
    UNION ALL
    SELECT ID --For multi-day, cross with the tally table and treat first and last days special
        , CASE WHEN T.Tally = 1 THEN StartTime --For the first day the start time is the real time
            ELSE DATEADD (day, T.Tally - 1, startdate) END as StartTime --Otherwise it's the start of the day
        , CASE WHEN T.Tally = DiffDays + 1 THEN EndTime --For the last day the end is the real end
            ELSE DATEADD (second, -1, CONVERT(DATETIME2(0), DATEADD (day, T.Tally, startdate)))
            END as EndTime --otherwise 1 second less than the next day
        , DiffDays, Tally as DayNumber
    FROM cteWithControl as D CROSS JOIN cteTally as T
    WHERE DiffDays > 0 AND T.Tally <= D.DiffDays + 1
)--Now we display the results and calculate the length (in minutes) of each span
SELECT *
    , DATEDIFF(MINUTE, StartTime, EndTime) as DateDiff
FROM cteSet
ORDER BY ID, DayNumber

we get the output

ID
StartTime
EndTime
DiffDays
DayNumber
DateDiff

32221
2022-01-01 13:10:00
2022-01-01 23:59:59
2
1
649

32221
2022-01-02 00:00:00
2022-01-02 23:59:59
2
2
1439

32221
2022-01-03 00:00:00
2022-01-03 13:10:00
2
3
790

32222
2022-02-02 10:10:00
2022-02-02 17:10:00
0
1
420

32223
2022-03-03 19:10:00
2022-03-03 23:59:59
1
1
289

32223
2022-03-04 00:00:00
2022-03-04 08:10:00
1
2
490

32224
2022-04-04 19:10:00
2022-04-04 23:59:59
4
1
289

32224
2022-04-05 00:00:00
2022-04-05 23:59:59
4
2
1439

32224
2022-04-06 00:00:00
2022-04-06 23:59:59
4
3
1439

32224
2022-04-07 00:00:00
2022-04-07 23:59:59
4
4
1439

32224
2022-04-08 00:00:00
2022-04-08 08:10:00
4
5
490


text:
Q: Android Logcat: NumberFormatException, how to locate? I am getting an error message within logcat that I cannot figure out. It is a NumberFormatException. How can I post the log error to stack overflow so that it can be seen?
Also how can you find the exact line where the error occurs using logcat?
Class in which the error may be:
public class Practice extends Activity implements View.OnClickListener {

    // Declaring Vars
    Button go2;
    EditText enterNumber2;
    TextView top2;
    TextView bottom2;
    int convertedNumber2; //change back to private Integer?

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // setting equal to text layout View
        setContentView(R.layout.practice);

        // calling method to intialise vars
        initialiseVars();

        // setting on click listeners for edit text and button
        go2.setOnClickListener(this);
        enterNumber2.setOnClickListener(this);

    }// on create end

    /**
     * method to initialise all of the buttons, textviews etc used to clean up
     * the onCreate.
     */
    private void initialiseVars() {
        // Setting up (initialising) all the buttons text views etc from the xml
        // (vid 25)
        go2 = (Button) findViewById(R.id.btnGoPractice);
        enterNumber2 = (EditText) findViewById(R.id.etEnterNumberPractce);
        top2 = (TextView) findViewById(R.id.tvTopPractice);
        bottom2 = (TextView) findViewById(R.id.tvBottomPractice);

    }

    /**
     * Method with on click listener that adds functionality for all of the
     * buttons, text views etc
     *
     * @param v
     */
    public void onClick(View view) {

        // switch statement which determines what is clicked
        switch ((view).getId()) {
        case R.id.btnGoPractice:

            // sets text view equal to whats typed in in editText
            final String entry = enterNumber2.getText().toString();

            // convert from string value to int
            convertedNumber2 = Integer.parseInt(entry);

            Intent intent = new Intent(this, PracticeTest.class);
            if (convertedNumber2 >= 1 && convertedNumber2 <= 12) {
                intent.putExtra("convertedNumber2", convertedNumber2);
                startActivity(intent);
            } else {
                System.out.println("Invalid number");
            }

            break;
        default:
            System.out.println("invalid entry");
            break;

        }

    }

}// c end

The full logcat report for the error:
04-28 18:14:01.533: E/AndroidRuntime(1560): java.lang.NumberFormatException: Invalid int: " 7"
04-28 18:20:26.169: E/AndroidRuntime(1788): FATAL EXCEPTION: main
04-28 18:20:26.169: E/AndroidRuntime(1788): Process: com.example.multapply, PID: 1788
04-28 18:20:26.169: E/AndroidRuntime(1788): java.lang.NumberFormatException: Invalid int: " 6"
04-28 18:20:26.169: E/AndroidRuntime(1788):     at java.lang.Integer.invalidInt(Integer.java:137)
04-28 18:20:26.169: E/AndroidRuntime(1788):     at java.lang.Integer.parse(Integer.java:374)
04-28 18:20:26.169: E/AndroidRuntime(1788):     at java.lang.Integer.parseInt(Integer.java:365)
04-28 18:20:26.169: E/AndroidRuntime(1788):     at java.lang.Integer.parseInt(Integer.java:331)
04-28 18:20:26.169: E/AndroidRuntime(1788):     at com.example.multapply.MyArrayAdapterPractice.getView(MyArrayAdapterPractice.java:59)
04-28 18:20:26.169: E/AndroidRuntime(1788):     at android.widget.AbsListView.obtainView(AbsListView.java:2263)
04-28 18:20:26.169: E/AndroidRuntime(1788):     at android.widget.ListView.measureHeightOfChildren(ListView.java:1263)
04-28 18:20:26.169: E/AndroidRuntime(1788):     at android.widget.ListView.onMeasure(ListView.java:1175)
04-28 18:20:26.169: E/AndroidRuntime(1788):     at android.view.View.measure(View.java:16497)
04-28 18:20:26.169: E/AndroidRuntime(1788):     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
04-28 18:20:26.169: E/AndroidRuntime(1788):     at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1404)
04-28 18:20:26.169: E/AndroidRuntime(1788):     at android.widget.LinearLayout.measureVertical(LinearLayout.java:695)
04-28 18:20:26.169: E/AndroidRuntime(1788):     at android.widget.LinearLayout.onMeasure(LinearLayout.java:588)
04-28 18:20:26.169: E/AndroidRuntime(1788):     at android.view.View.measure(View.java:16497)
04-28 18:20:26.169: E/AndroidRuntime(1788):     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
04-28 18:20:26.169: E/AndroidRuntime(1788):     at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
04-28 18:20:26.169: E/AndroidRuntime(1788):     at android.view.View.measure(View.java:16497)
04-28 18:20:26.169: E/AndroidRuntime(1788):     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
04-28 18:20:26.169: E/AndroidRuntime(1788):     at com.android.internal.widget.ActionBarOverlayLayout.onMeasure(ActionBarOverlayLayout.java:327)
04-28 18:20:26.169: E/AndroidRuntime(1788):     at android.view.View.measure(View.java:16497)
04-28 18:20:26.169: E/AndroidRuntime(1788):     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
04-28 18:20:26.169: E/AndroidRuntime(1788):     at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
04-28 18:20:26.169: E/AndroidRuntime(1788):     at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2291)
04-28 18:20:26.169: E/AndroidRuntime(1788):     at android.view.View.measure(View.java:16497)
04-28 18:20:26.169: E/AndroidRuntime(1788):     at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:1916)
04-28 18:20:26.169: E/AndroidRuntime(1788):     at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1113)
04-28 18:20:26.169: E/AndroidRuntime(1788):     at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1295)
04-28 18:20:26.169: E/AndroidRuntime(1788):     at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1000)
04-28 18:20:26.169: E/AndroidRuntime(1788):     at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5670)
04-28 18:20:26.169: E/AndroidRuntime(1788):     at android.view.Choreographer$CallbackRecord.run(Choreographer.java:761)
04-28 18:20:26.169: E/AndroidRuntime(1788):     at android.view.Choreographer.doCallbacks(Choreographer.java:574)
04-28 18:20:26.169: E/AndroidRuntime(1788):     at android.view.Choreographer.doFrame(Choreographer.java:544)
04-28 18:20:26.169: E/AndroidRuntime(1788):     at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:747)
04-28 18:20:26.169: E/AndroidRuntime(1788):     at android.os.Handler.handleCallback(Handler.java:733)
04-28 18:20:26.169: E/AndroidRuntime(1788):     at android.os.Handler.dispatchMessage(Handler.java:95)
04-28 18:20:26.169: E/AndroidRuntime(1788):     at android.os.Looper.loop(Looper.java:136)
04-28 18:20:26.169: E/AndroidRuntime(1788):     at android.app.ActivityThread.main(ActivityThread.java:5017)
04-28 18:20:26.169: E/AndroidRuntime(1788):     at java.lang.reflect.Method.invokeNative(Native Method)
04-28 18:20:26.169: E/AndroidRuntime(1788):     at java.lang.reflect.Method.invoke(Method.java:515)
04-28 18:20:26.169: E/AndroidRuntime(1788):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
04-28 18:20:26.169: E/AndroidRuntime(1788):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
04-28 18:20:26.169: E/AndroidRuntime(1788):     at dalvik.system.NativeStart.main(Native Method)

A: Your are getting this error cause
533: E/AndroidRuntime(1560): java.lang.NumberFormatException: Invalid int: " 7"

at this line
convertedNumber2 = Integer.parseInt(entry);

variable entry not able to parse cause it contains space
You can use below snippet inside click event .Use try catch block to avoid application force close
//      sets text view equal to whats typed in in editText
//      final String entry = enterNumber2.getText().toString();
        String entry = "5";// get your number this line is for test
        entry = entry.replaceAll("\\D+",""); // remove non-digit character

//      convert from string value to int
        int convertedNumber2 = 0;
        try {
             convertedNumber2 = Integer.parseInt(entry);
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }

//      Intent intent = new Intent(this, PracticeTest.class);
        if (convertedNumber2 >= 1 && convertedNumber2 <= 12) {
//            intent.putExtra("convertedNumber2", convertedNumber2);
//            startActivity(intent);
             System.out.println("Valid number");
        } else {
            System.out.println("Invalid number");
        }

Provide EditText inputtype i.e android:inputType="number" to avoid entering other character or just use regex to get numbers from string
Use this line to remove all nondigit character from string
entry = entry.replaceAll("\\D+","");

A: The error is apparent there as far as i can see...
java.lang.NumberFormatException: Invalid int: " 6"
There is a space before 6.
There are few fixes i will suggest:-

*

*as i see you are using the edittext as number so probably i expect you wont be taking any non-numberic values so you can directly in the xml for etEnterNumberPractce add android:inputType="number" or something which will allow only numeric values.

*you can do like this the parsing
try
  {
    final String entry = enterNumber2.getText().toString().trim(); // note trim()
    if(!entry.equals(""))
         convertedNumber2 = Integer.parseInt(entry);
    // Your rest of the code
}
  catch(Exception e)
  {
    e.printStackTrace();
  }
Hope it helps...
thx

A: according to
at com.example.multapply.MyArrayAdapterPractice.getView(MyArrayAdapterPractice.java:59)

it is in the file MyArrayAdapterPractice.java on line 59 I am looking though the stack dump and I don't see Practice in there, it might be called by the android system in another way, but the object in question is MyArrayAdapterPractice in the method getView, and it should be about line 59.  Looks like according to the stack trace that it is happening when you are building your list view object.


text:
Q: TransactionRequiredException with WeblogicJtaTransactionManager I am trying to work with distributed transactions in my application. For this purpose I have configured WeblogicJtaTransactionManager (provided by spring)to manage my distributed transaction. But its seems transactions are not starting. While running update query the get the following exception :
 Executing an update/delete query; nested exception is
 javax.persistence.TransactionRequiredException: Executing an update/delete query

My application context  :
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
    http://www.jasypt.org/schema/encryption http://www.jasypt.org/schema/encryption/jasypt-spring31-encryption-1.xsd
    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">

<!-- <tx:jta-transaction-manager /> -->
<tx:annotation-driven  transaction-manager="transactionManager" proxy-target-class="true"/>

<context:component-scan base-package="com.myapp">
    <context:exclude-filter type="regex" expression="com.myapp.controllers"/>
</context:component-scan>

   <jee:jndi-lookup jndi-name="jdbc/myDataSource" id="dataSource"/>

<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    <property name="jtaDataSource" ref="dataSource" />
    <property name="jpaVendorAdapter">
        <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
    </property>
    <property name="jpaDialect">
        <bean class="org.springframework.orm.jpa.vendor.HibernateJpaDialect" />
    </property>
    <property name="packagesToScan" value="com.myapp.domain" />
    <property name="jpaProperties">
        <props>
            <prop key="javax.persistence.sharedCache.mode">NONE</prop>
            <prop key="hibernate.dialect">${app.db.dailect}</prop>
            <prop key="initialSize">${app.db.minpoolsize}</prop>
            <prop key="maxActive">${app.db.maxpoolsize}</prop>
            <prop key="hibernate.show_sql">true</prop>
            <prop key="hibernate.max_fetch_depth">0</prop>
            <prop key="hibernate.query.substitutions">true=1, false=0</prop>
            <prop key="hibernate.generate_statistics">false</prop>
            <prop key="javax.persistence.query.timeout">600000</prop>
            <prop key="hibernate.transaction.factory_class">org.hibernate.engine.transaction.internal.jta.JtaTransactionFactory</prop>
            <prop key="hibernate.transaction.jta.platform">org.hibernate.service.jta.platform.internal.WeblogicJtaPlatform</prop>
        </props>
    </property>
</bean>
<!-- <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
    <property name="entityManagerFactory" ref="entityManagerFactory" />
    <property name="jpaDialect">
        <bean class="org.springframework.orm.jpa.vendor.HibernateJpaDialect" />
    </property>
</bean> -->

<bean id="transactionManager" class="org.springframework.transaction.jta.WebLogicJtaTransactionManager"  >
    <property name="transactionManagerName" value="javax.transaction.TransactionManager"/>
</bean>
<jpa:repositories base-package="com.myapp.repos" factory-class="com.myapp.repos.BaseRepositoryFactoryBean"
entity-manager-factory-ref="entityManagerFactory"/>

Any help is appreciated.

A: It is the problem with your datasource. You are using ComboPooledDataSource which is not managed by weblogic.


text:
Q: How to access from child to widget in parent window? I have parent class with panel (notebook) and  combobox as follows:
class A(wx.aui.AuiMDIChildFrame):
    def __init__(self,parent):
        self.panel_1 = wx.Panel(self, -1)
        self.NB = wx.Notebook(self.panel_1, -1, style=0)
        self.NB_A= WindowFirst(self.NB)

        self.ComboA= wx.ComboBox(self.panel_1, 500, 'Phase', (50, 150), (160,-1), phasesList, wx.CB_DROPDOWN)

and in another py file:
class WindowFirst(GeneralPanel):
    def __init__(self,parent):
        how do I access ComboA from here?

This isn't my complete code... Just want is relevent for the question.
How do I acess comboA from WindowFirst? I need to be able to set values to the ComboA from WindowFirst.
I can access from A to WindowFirst, but not the other way around.
Any suggestions?

A: This cannot be done as long as you are trying to access ComboA from WindowFirst.init().  The constructor for WindowFirst is called as NB_A gets created, at which time ComboA has not yet been created.  So no matter how you try to access ComboA, it's not possible because it doesn't exist
However, if you want to access ComboA from another method of WindowFirst, that can be done.  You have NB_A as a child of NB, NB as a child of panel_1, panel_1 as a child of A and ComboA as a child of A.  You just need to make sure ComboA exists before you try to access it.  So something like this.
def anotherFunction():
    #how do I access ComboA from here?
    nb = self.GetParent()
    panel_1 = nb.GetParent()
    a = panel_1.GetParent()
    try:
        #try to access ComboA and do what you gotta do
        a.ComboA.doSomething()
    except:
        #something went wrong (like ComboA doesn't exist yet)
        print "ComboA doesn't exist yet"

or for brevity
def anotherFunction():
    #how do I access ComboA from here?
    try:
        self.GetParent().GetGrandParent().ComboA.doSomething()
    except:
        print "ComboA doesn't exist yet"

A: The recommended way to communicate between classes in wxPython is to use pubsub, which is included with wxPython. Basically you will want to create a listener in your class A and then publish messages to it from WindowFirst to tell it to update.
Here's an example:
import random
import wx
from wx.lib.pubsub import pub

########################################################################
class TabPanel(wx.Panel):
    #----------------------------------------------------------------------
    def __init__(self, parent):
        """"""
        wx.Panel.__init__(self, parent)

        colors = ["red", "blue", "gray", "yellow", "green"]
        self.color = random.choice(colors)
        self.SetBackgroundColour(self.color)
        self.Bind(wx.EVT_LEFT_DCLICK, self.update_button)

        lbox = wx.ListBox(self, choices=colors)
        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(lbox, 0, wx.ALL, 10)
        self.SetSizer(sizer)

    #----------------------------------------------------------------------
    def update_button(self, event):
        """"""
        pub.sendMessage('button_listener', message=self.color)

########################################################################
class MyPanel(wx.Panel):
    """"""

    #----------------------------------------------------------------------
    def __init__(self, parent):
        """Constructor"""
        wx.Panel.__init__(self, parent)

########################################################################
class DemoFrame(wx.Frame):
    """
    Frame that holds all other widgets
    """

    #----------------------------------------------------------------------
    def __init__(self):
        """Constructor"""
        wx.Frame.__init__(self, None, wx.ID_ANY,
                          "Notebook Tutorial",
                          size=(600,400)
                          )
        panel = MyPanel(self)
        self.tab_num = 3

        self.notebook = wx.Notebook(panel)
        tabOne = TabPanel(self.notebook)
        self.notebook.AddPage(tabOne, "Tab 1")

        tabTwo = TabPanel(self.notebook)
        self.notebook.AddPage(tabTwo, "Tab 2")

        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(self.notebook, 1, wx.ALL|wx.EXPAND, 5)

        self.btn = wx.Button(panel, label="Get Color")
        sizer.Add(self.btn)

        panel.SetSizer(sizer)
        self.Layout()

        # create a listener
        pub.subscribe(self.change_button, 'button_listener')

        self.Show()

    #----------------------------------------------------------------------
    def change_button(self, message, arg2=None):
        """"""
        self.btn.SetLabel(message)

#----------------------------------------------------------------------
if __name__ == "__main__":
    app = wx.App(False)
    frame = DemoFrame()
    app.MainLoop()

Note that the pubsub API changed slightly in wxPython 2.9 and above. If you're using an older version, then you'll need to change the code a bit. I have a tutorial illustrating the older API here.
For more information on the newer API, check out my updated article here:

*

*http://www.blog.pythonlibrary.org/2013/09/05/wxpython-2-9-and-the-newer-pubsub-api-a-simple-tutorial/


text:
Q: reading from text file to two dimensional array I try to read a text file and pass all integers to a 2 dimensional array one by one. But when i print what I tried to pass, I get weird outputs. What could be the problem?
For example if the text is:
0 1 1 1 0 1 1 0 1 1 1 1
I get this:
index=-2 index=1967626458 index=1967694074 index=207568 index=207320 index=2686776 index=1967693597 index=0 index=0 index=2686832 index=236 index=228 index=3
Here is the code:
    #include<stdio.h>

    int main()
    {

    FILE *input;
    //read file!
     if((input = fopen("abc.txt","r"))==NULL){
        printf("Error in reading file !\n");
        return 0;
    }

    int C = 4;
    int R = 3;
    int M[3][4];
    int x=0;
    int y=0;
    int c;
    //array of sorted list!
    while(!feof(input)){
        if(!feof(input)){

            fscanf( input, "%d",&c);

         M[x][y]=c;
            y++;
            if(y==C){

            x++;
            y=0;

            }
    printf("index=%d \n",M[x][y]);
         }
     }
       system("pause");
    }

A: The printout is wrong because you're changing the values of x and y between when you set the variable and when you try to print it. You need to move the printf() before the part where you increment x and y, but after you assign to the array.
As it stands right now, you assign to the array, then print the next, as yet unassigned, value. It's whatever value happens to be in that memory, such as -2 or 1967626458.

A: just increment you y variable after printing index.
#include<stdio.h>

int main()
{

    FILE *input;
    //read file!
    if((input = fopen("abcd.txt","r"))==NULL)
    {
        printf("Error in reading file !\n");
        return 0;
    }

    int C = 4;
    int R = 3;
    int M[3][4];
    int x=0;
    int y=0;
    int c;
    //array of sorted list!
    while(!feof(input))
    {
        if(!feof(input))
        {

            fscanf( input, "%d",&c);

            M[x][y]=c;
            //y++ ; not increment here
            if(y==C)
            {
                x++;
                y=0;
            }
            printf("index=%d \n",M[x][y]);
            y++;//increment here
        }
    }
    system("pause");
}


text:
Q: Opening second time popup is displaying at bottom of page I am displaying one popup when user click on button.
First time when user click at that time, that popup is opening perfectly and displayed at top.
Now user submit form and click on Save button which is at bottom.
Now when user click again at that time, that popup is opening but displaying that bottom part of Save button and not going page up at top.
I have tried different solution's but none working..you can see below code.
 function showPopupNew(ob) {
            window.scrollTo(0, 0);
            $(ob).modal('show');
            $(ob).focus();
            //$(ob).css({ position: 'fixed', top: '0' });
            //$('#Template-update').show();
            //$('#Template-update').popup('open', { y: 0 })
            //$('body').scrollTop(0);
        }

Here you can see, I have tried different solutions but still not working..any idea on this.

A: I achieve this functionality
Using .scrollTop(0);


text:
Q: 'oneOf' not working as expected - json validation must fail but it is passing I am trying to write a schema to validate that an AWS IAM security group MUST NOT specify incoming IP addresses "0.0.0.0/0" can connect to port 22.
I am using oneOf operator and defining two set of properties and my intuition is that if both of the properties are satisfied, JSON schema should fail but it doesn't.
Sample JSON -
{
  "ipPermissions": [
    {
      "toPort": -1,
      "fromPort": -1,
      "ipRanges": [
        "10.0.0.0/16"
      ]
    },
    {
      "toPort": 22,
      "fromPort": 53,
      "ipRanges": [
        "0.0.0.0/0"
      ],
      "ipProtocol": "tcp"
    }
  ]
}

The above JSON should fail as ipPermission[1] object is-
{
      "toPort": 22,
      "fromPort": 53,
      "ipRanges": [
        "0.0.0.0/0"
      ],
      "ipProtocol": "tcp"
}

as ipRanges has value 0.0.0.0/0 when toPort is 22
Following JSON document should pass validation-
{
      "ipPermissions": [
        {
          "toPort": 22,
          "fromPort": -1,
          "ipRanges": [
            "10.0.0.0/16"
          ]
        },
        {
          "toPort": 22,
          "fromPort": 53,
          "ipRanges": [
            "somethingElse"
          ],
          "ipProtocol": "tcp"
        }
      ]
    }

because ipPermissions index[0] object has toPort value of 22 but ipRanges[0] has value 10.0.0.0/16 which is NOT 0.0.0.0/0
the following JSON should NOT pass the validation -
{
  "ipPermissions": [
    {
      "toPort": 22,
      "fromPort": -1,
      "ipRanges": [
        "10.0.0.0/16"
      ]
    },
    {
      "toPort": 22,
      "fromPort": 53,
      "ipRanges": [
        "somethingElse",
        "0.0.0.0/0"
      ],
      "ipProtocol": "tcp"
    }
  ]
}

as ipPermissions[1].ipRanges[1] value is 0.0.0.0/0
My JSON Schema-
{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "required": [
    "ipPermissions"
  ],
  "properties": {
    "ipPermissions": {
      "type": "array",
      "items": {
        "type": "object",
        "properties": {
          "oneOf": {
            "ipRanges": {
              "type": "array",
              "items": {
                "type": "string",
                "value": "0.0.0.0/0"
              }
            },
            "toPort": {
              "type": "integer",
              "minimum": 23
            }
          }
        }
      }
    }
  }
}

A: This one gets a little complicated, so I broke it up using definitions to hopefully make it easier to follow.
#/definitions/ipPermission
The general strategy is to define your properties first and then add the complex constraints separately using anyOf, oneOf, allOf, not, and/or dependencies.  In this case the approach I took was to define a schema that matches the case you want to forbid and use not to fail validation if that schema matches.
#/definitions/port-22-and-0.0.0.0-0
This is the schema that validates if "toPort" is "22" and the "ipRanges" array contains "0.0.0.0/0".  Unfortunately, JSON Schema doesn't have a contains keyword (yet), so we have to do some boolean logic gymnastics to express that constraint.
#/definitions/array-contains-0.0.0.0-0
We can't directly constrain an array to contain "0.0.0.0/0", but we can create a schema that forbids "0.0.0.0/0" to be in the array.  Given such a schema that is valid if "0.0.0.0\0" is not in the array, then any JSON that doesn't validate must contain at least one instance of "0.0.0.0/0".
#/definitions/array-without-0.0.0.0-0
This describes the array that forbids "0.0.0.0/0" which is used to implement the contains constraint.
{
  "type": "object",
  "required": ["ipPermissions"],
  "properties": {
    "ipPermissions": {
      "type": "array",
      "items": { "$ref": "#/definitions/ipPermission" }
    }
  },
  "definitions": {
    "ipPermission": {
      "type": "object",
      "properties": {
        "toPort": { ... },
        "fromPort": { ... },
        "ipRanges": { ... },
        "ipProtocol": { ... }
      }
      "not": { "$ref": "#/definitions/port-22-and-0.0.0.0-0"}
    },
    "port-22-and-0.0.0.0-0": {
      "type": "object",
      "properties": {
        "toPort": { "enum": [22] },
        "ipRanges": { "$ref": "#/definitions/array-contains-0.0.0.0-0" }
      },
      "required": ["toPort", "ipRanges"]
    },
    "array-contains-0.0.0.0-0": {
      "not": { "$ref": "#/definitions/array-without-0.0.0.0-0" }
    },
    "array-without-0.0.0.0-0": {
      "type": "array",
      "items": {
        "not": { "enum": ["0.0.0.0/0"] }
      }
    }
  }
}

A: You need to add a "required" node to your schema. However, in this case it also needs to specify one of N allowed nodes:
{
    "$schema":"http://json-schema.org/draft-04/schema#",
    "required":[
        "ipPermissions"
    ],
    "properties":{
        "ipPermissions":{
            "type":"array",
            "items":{
                "type":"object",
                "properties":{
                    "oneOf":{
                        "ipRanges":{
                            "type":"array",
                            "items":{
                                "type":"string",
                                "value":"0.0.0.0/0"
                            }
                        },
                        "toPort":{
                            "type":"integer",
                            "minimum":23
                        }
                    }
                },
                "oneOf":[
                    {
                        "required":[
                            "ipRanges"
                        ]
                    },
                    {
                        "required":[
                            "toPort"
                        ]
                    }
                ]
            }
        }
    }
}

This will validate instances with either an ipRanges node or a toPort node, but not both together, eg:
{
    "ipPermissions":[
        {
            "toPort":-1,
            "fromPort":-1
        },
        {
            "fromPort":53,
            "ipRanges":[
                "0.0.0.0/0"
            ],
            "ipProtocol":"tcp"
        }
    ]
}


text:
Q: Pg-promise: does changing the search_path inside a db.task() also change it for queries running outside? Let's say I have the following code:
db.task(t => {
    return t.none('set search_path to myschema').then(() => {
        return t.any('select * from mytable').then(results => {
            return t.none('set search_path to originalschema').then(() => {
                return results
      })
    })
  })
})

Could a query outside of db.task(), that happened to run in between of the two search_path changes inside db.task(), actually access the data in 'myschema' instead of 'originalschema'?

A:
Could a query outside of db.task(), that happened to run in between of the two search_path changes inside db.task(), actually access the data in 'myschema' instead of 'originalschema'?

No.
SET search_path is a session-based operation, i.e. it applies only to the current connection, which the task allocates exclusively for the entire duration of its execution.
Once the task has finished, it releases the connection back to the pool. At that point, any query that gets that same connection will be working with the alternative schema, unless it is another task that sets the schema again. This gets tricky, if you are setting schema in just one task, and generally not recommended.
Here's how it should be instead:

*

*If you want to access a special-case schema inside just one task, best is to specify the schema name explicitly in the query.

*If you want to set custom schema(s) dynamically, for the entire app, best is to use option schema, of the Initialization Options. This will propagate the schema automatically through all new connections.

*If you want to set schema statically, there are queries for setting schema permanently.

Addition:
And if you have a very special case, whereby you have a task that needs to run reusable queries inside an alternative schema, then you would set the schema in the beginning of the task, and then restore it to the default schema at the end, so any other query that picks up that connection later won't try to use the wrong schema.
Extra:
Example below creates your own task method (I called it taskEx), consistent across the entire protocol, which accepts new option schema, to set the optional schema inside the task:
const initOptions = {
    extend(obj) {
        obj.taskEx = function () {
            const args = pgp.utils.taskArgs(arguments); // parse arguments
            const {schema} = args.options;
            delete args.options.schema; // to avoid error thrown
            if (schema) {
                return obj.task.call(this, args.options, t => {
                    return t.none('SET search_path to $1:name', [schema])
                        .then(args.cb.bind(t, t));
                });
            }
            return obj.task.apply(this, args);
        }
    }
});

const pgp = require('pg-promise')(initOptions);

So you can use anywhere in your code:
const schema = 'public';
// or as an array: ['public', 'my_schema'];

db.taskEx({schema}, t => {
    // schema set inside task already;
});

Note that taskEx implementation assumes that the schema is fully dynamic. If it is static, then there is no point re-issuing SET search_path on every task execution, and you would want to do it only for fresh connections, based on the following check:
const isFreshConnection = t.ctx.useCount === 0;

However, in that case you would be better off using initialization option schema instead, as explained earlier.


text:
Q: If electricity creates a magnetic field, could a (strong) magnetic field stop electricity? Surely this would make the two magnetic fields interact and if movement was made impossible, the stronger magnetic field would block the weaker electromagnetic filed. Am I right (presuming that the magnetic field is stronger than the electromagnetic field created by the electricity)?

A: There are a few things that need to be cleared:

*

*now we know that there is a field called EM field, which unifies both electric and magnetic fields.

*the expression electric field and magnetic field is observer dependent, one observer might see the same field as magnetic, another observer as electric
So basically you are asking whether if there are two EM fields, will they conflict or interact with the field itself.
Now let's say you have two charges (electrons), they will create an EM field around themselves. These fields will affect both the other charges, that is when the EM field of one charge will interact with the other charge.
This is what we call the near field, and let's assume you are asking about that.
Basically you are asking whether two near fields affect each other. This would mean that the near fields, if they would have an edge, would affect each other without affecting the charge itself (from far away).
You are mistaking the interaction by assuming that the near fields will interact themselves, repelling in this case. It is not true. What creates the repulsive force between two electrons, is when the near field of one charge interacts with the other charge. And vica versa.
We use virtual particles in the mathematical description of the near fields, to describe the interaction, because truly, we do not know what or how interacts.
You are asking whether when the edges of the near fields touch, will they repel, they will not. The near fields of the two charges themselves will not interact in this way. The interaction is always between the charge and another field.
The magnetic and electric fields are observer dependent, but let's assume you are asking from one observer's frame. Now if there is a magnetic field from this observer's view and another electric field, then you are asking whether the magnetic field (created by one charge) will affect the other charge (that creates the electric field). Yes it could affect it. But how could it stop it?


text:
Q: What does "like being drowned in Skittles" mean? From here: http://www.loper-os.org/?p=568

Using Squeak is "like being drowned in Skittles." I understand that it is a monumentally great thing if one is able to see past that, but I suspect that most prospective users cannot do so.

I searched for an explanation, but I can't seem to find one. Does it mean that you're getting "too much" good stuff? So much that it's actually a disadvantage?

A: It's just a reference to the overdone colour scheme on Squeak:

Skittles come in all rainbow colours.

A: Being drowned in Skittles refers specifically to the television commercials for the Skittles candy. In the commercials, millions of Skittles invariably end up falling out of the sky like a heavy rain. Being drowned in Skittles, then, is a metaphor. It means being knocked down and overcome by a deluge of colorful things.


text:
Q: Python: Return entire row when two data frames share a common value in two different columns I would like to print the entire row when two different dataframes share a common value in two different columns. I can identify them but instead of returning the entire row, I could only figure out how to return the boolean as shown below:
df1 = pd.DataFrame(np.array([[1, 2, 1],
                             [4, 55, 6],
                             [1, 8, 88]]),
                   columns=['col1', 'col2', 'col3'])
df1

>>
col1    col2    col3
0   1   2        1
1   4   55       6
2   1   8        88

df2 = pd.DataFrame(np.array([[333, 1, 2],
                             [55, 8, 88],
                             [8, 5, 6]]),
                   columns=['col1', 'col2', 'col3'])
df2

>>
    col1    col2    col3
0   333        1    2
1   55         8    88
2   8          5    6

# Return row where df1["col2"] and df2["col1"] have the same values
# the output should print the rows of index 1 and 2

df1['col2'].isin(df2['col1'])

>>
0    False
1     True
2     True
Name: col2, dtype: bool

A: You can use boolean indexing:
mask = df1["col2"].isin(df2["col1"])
print(df1[mask])

Prints:
   col1  col2  col3
1     4    55     6
2     1     8    88


text:
Q: IOS crash in App Store build I have device logs crash report from iphone 4S.how to find the error from my crash report.
IOS version 8.3
This is not a reproducible crash.It occurs rarely and no specific senario.
Pelase help me to find out.
{
    "crash": {
        "diagnosis": "Possible zombie in call: -[SRHubProxy release]\nOriginated at or in a subcall of _mh_execute_header",
        "error": {
            "address": 2439342019,
            "mach": {
                "code": 1,
                "code_name": "KERN_INVALID_ADDRESS",
                "exception": 1,
                "exception_name": "EXC_BAD_ACCESS",
                "subcode": 0
            },
            "signal": {
                "code": 0,
                "code_name": "SEGV_NOOP",
                "name": "SIGSEGV",
                "signal": 11
            },
            "type": "mach"
        },
        "threads": [
            {
                "backtrace": {
                    "contents": [
                        {
                            "instruction_addr": 956731238,
                            "object_addr": 956653568,
                            "object_name": "libobjc.A.dylib",
                            "symbol_addr": 956731232,
                            "symbol_name": "objc_msgSend"
                        },
                        {
                            "instruction_addr": 720172673,
                            "object_addr": 720117760,
                            "object_name": "CoreFoundation",
                            "symbol_addr": 720172076,
                            "symbol_name": "CFRelease"
                        },
                        {
                            "instruction_addr": 720276233,
                            "object_addr": 720117760,
                            "object_name": "CoreFoundation",
                            "symbol_addr": 720276096,
                            "symbol_name": "<redacted>"
                        },
                        {
                            "instruction_addr": 956788055,
                            "object_addr": 956653568,
                            "object_name": "libobjc.A.dylib",
                            "symbol_addr": 956787888,
                            "symbol_name": "<redacted>"
                        },
                        {
                            "instruction_addr": 956677517,
                            "object_addr": 956653568,
                            "object_name": "libobjc.A.dylib",
                            "symbol_addr": 956677400,
                            "symbol_name": "<redacted>"
                        },
                        {
                            "instruction_addr": 956716547,
                            "object_addr": 956653568,
                            "object_name": "libobjc.A.dylib",
                            "symbol_addr": 956716512,
                            "symbol_name": "objc_destructInstance"
                        },
                        {
                            "instruction_addr": 956716583,
                            "object_addr": 956653568,
                            "object_name": "libobjc.A.dylib",
                            "symbol_addr": 956716568,
                            "symbol_name": "object_dispose"
                        },
                        {
                            "instruction_addr": 6011169,
                            "object_addr": 704512,
                            "object_name": "MYAPP",
                            "symbol_addr": 704512,
                            "symbol_name": "_mh_execute_header"
                        },
                        {
                            "instruction_addr": 956788055,
                            "object_addr": 956653568,
                            "object_name": "libobjc.A.dylib",
                            "symbol_addr": 956787888,
                            "symbol_name": "<redacted>"
                        },
                        {
                            "instruction_addr": 5421543,
                            "object_addr": 704512,
                            "object_name": "MYAPP",
                            "symbol_addr": 704512,
                            "symbol_name": "_mh_execute_header"
                        },
                        {
                            "instruction_addr": 962358403,
                            "object_addr": 962351104,
                            "object_name": "libdispatch.dylib",
                            "symbol_addr": 962358392,
                            "symbol_name": "<redacted>"
                        },
                        {
                            "instruction_addr": 962410603,
                            "object_addr": 962351104,
                            "object_name": "libdispatch.dylib",
                            "symbol_addr": 962409228,
                            "symbol_name": "<redacted>"
                        },
                        {
                            "instruction_addr": 962414755,
                            "object_addr": 962351104,
                            "object_name": "libdispatch.dylib",
                            "symbol_addr": 962414648,
                            "symbol_name": "<redacted>"
                        },
                        {
                            "instruction_addr": 963939753,
                            "object_addr": 963936256,
                            "object_name": "libsystem_pthread.dylib",
                            "symbol_addr": 963939084,
                            "symbol_name": "_pthread_wqthread"
                        }
                    ],
                    "skipped": 0
                },
                "crashed": true,
                "current_thread": false,
                "dispatch_queue": "com.apple.root.background-qos",
                "index": 18,
                "notable_addresses": {
                    "r0": {
                        "address": 377088480,
                        "last_deallocated_obj": "SRHubProxy",
                        "type": "string",
                        "value": "unsigned __int128"
                    },
                    "r1": {
                        "address": 904568254,
                        "type": "string",
                        "value": "release"
                    },
                    "r11": {
                        "address": 377034864,
                        "class": "__NSDictionaryM",
                        "ivars": {
                            "_mutations": 2,
                            "_size": 0
                        },
                        "last_deallocated_obj": "NSSortDescriptor",
                        "type": "objc_object"
                    },
                    "r2": {
                        "address": 966640552,
                        "class": "__NSCFType",
                        "ivars": {},
                        "type": "objc_object"
                    },
                    "r5": {
                        "address": 377088484,
                        "type": "string",
                        "value": "gned __int128"
                    },
                    "r6": {
                        "address": 377088480,
                        "last_deallocated_obj": "SRHubProxy",
                        "type": "string",
                        "value": "unsigned __int128"
                    },
                    "r8": {
                        "address": 966610768,
                        "class": "__NSCFType",
                        "type": "objc_class"
                    },
                    "stack@0xb08de0": {
                        "address": 374766448,
                        "last_deallocated_obj": "__NSDictionaryM",
                        "type": "unknown"
                    },
                    "stack@0xb08de8": {
                        "address": 966613168,
                        "class": "__NSCFType",
                        "ivars": {},
                        "type": "objc_object"
                    },
                    "stack@0xb08df0": {
                        "address": 966613168,
                        "class": "__NSCFType",
                        "ivars": {},
                        "type": "objc_object"
                    },
                    "stack@0xb08e0c": {
                        "address": 786090233,
                        "type": "string",
                        "value": "name"
                    },
                    "stack@0xb08e10": {
                        "address": 786074369,
                        "type": "string",
                        "value": "UTF8String"
                    },
                    "stack@0xb08e14": {
                        "address": 786110722,
                        "type": "string",
                        "value": "reason"
                    },
                    "stack@0xb08e30": {
                        "address": 377088484,
                        "type": "string",
                        "value": "gned __int128"
                    },
                    "stack@0xb08e34": {
                        "address": 374766448,
                        "last_deallocated_obj": "__NSDictionaryM",
                        "type": "unknown"
                    },
                    "stack@0xb08e40": {
                        "address": 377034864,
                        "class": "__NSDictionaryM",
                        "ivars": {
                            "_mutations": 2,
                            "_size": 0
                        },
                        "last_deallocated_obj": "NSSortDescriptor",
                        "type": "objc_object"
                    }
                },
                "registers": {
                    "basic": {
                        "cpsr": 805306416,
                        "ip": 966461428,
                        "lr": 720172673,
                        "pc": 956731238,
                        "r0": 377088480,
                        "r1": 904568254,
                        "r10": 376887340,
                        "r11": 377034864,
                        "r2": 966640552,
                        "r3": 4095,
                        "r4": 560326604,
                        "r5": 377088484,
                        "r6": 377088480,
                        "r7": 11570768,
                        "r8": 966610768,
                        "r9": 2439342007,
                        "sp": 11570696
                    },
                    "exception": {
                        "exception": 0,
                        "far": 2439342019,
                        "fsr": 5
                    }
                },
                "stack": {
                    "contents": "707B561602000000B0589D3900D87616B0589D3900D876160000000000000000508EB00013F9EC2A21B95B00F9C8DA2E018BDA2E0219DB2EFFFFFFFFFFFFFFFF0700000000D8761600000000FF2789E9E4E97916707B561620D876162CD876167018791603000000A0F27916A0F279167C8EB000098BEE2A",
                    "dump_end": 11570776,
                    "dump_start": 11570656,
                    "grow_direction": "-",
                    "overflow": false,
                    "stack_pointer": 11570696
                }
            },
            {
                "backtrace": {
                    "contents": [
                        {
                            "instruction_addr": 963426752,
                            "object_addr": 963338240,
                            "object_name": "libsystem_kernel.dylib",
                            "symbol_addr": 963426744,
                            "symbol_name": "__workq_kernreturn"
                        },
                        {
                            "instruction_addr": 963939877,
                            "object_addr": 963936256,
                            "object_name": "libsystem_pthread.dylib",
                            "symbol_addr": 963939084,
                            "symbol_name": "_pthread_wqthread"
                        }
                    ],
                    "skipped": 0
                },
                "crashed": false,
                "current_thread": false,
                "index": 19,
                "registers": {
                    "basic": {
                        "cpsr": 1073741840,
                        "ip": 368,
                        "lr": 963939877,
                        "pc": 963426752,
                        "r0": 4,
                        "r1": 0,
                        "r10": 962414649,
                        "r11": 21,
                        "r2": 0,
                        "r3": 0,
                        "r4": 91226112,
                        "r5": 2147485951,
                        "r6": 62791,
                        "r7": 91226080,
                        "r8": 65536,
                        "r9": 1005712320,
                        "sp": 91226052
                    }
                }
            }
        ]
    },
    "process": {},
    "report": {
        "id": "1DD54528-AB65-4E03-AA04-9F5A31F590EF",
        "process_name": "MYAPP",
        "timestamp": "2016-05-24T14:16:43Z",
        "type": "standard",
        "version": {
            "major": 3,
            "minor": 0
        }
    },
    "system": {
        "CFBundleExecutable": "MYAPP",
        "CFBundleExecutablePath": "/private/var/mobile/Containers/Bundle/Application/3613DF54-5D7A-4CF3-80C7-BA8645055890/MYAPP.app/MYAPP",
        "CFBundleIdentifier": "com.ca.tridentapp",
        "CFBundleName": "MYAPP",
        "CFBundleShortVersionString": "1.2.1",
        "CFBundleVersion": "1.2.1.0",
        "app_start_time": "2016-05-24T14:14:45Z",
        "app_uuid": "C7BEE99A-23FB-37FD-AE35-4F709C17F1DB",
        "application_stats": {
            "active_time_since_last_crash": 97319.4,
            "active_time_since_launch": 57261.5,
            "application_active": false,
            "application_in_foreground": true,
            "background_time_since_last_crash": 248.658,
            "background_time_since_launch": 0,
            "launches_since_last_crash": 3,
            "sessions_since_last_crash": 4,
            "sessions_since_launch": 1
        },
        "binary_cpu_subtype": 9,
        "binary_cpu_type": 12,
        "boot_time": "2016-05-23T04:36:03Z",
        "cpu_arch": "armv7f",
        "cpu_subtype": 10,
        "cpu_type": 12,
        "device_app_hash": "ff2f1547abd2cf5c9592b7eb795b0918d8ef26e9",
        "jailbroken": false,
        "kernel_version": "Darwin Kernel Version 14.0.0: Sun Mar 29 19:45:16 PDT 2015; root:xnu-2784.20.34~2/RELEASE_ARM_S5L8940X",
        "machine": "iPhone4,1",
        "memory": {
            "free": 27492352,
            "size": 529481728,
            "usable": 230555648
        },
        "model": "N94AP",
        "os_version": "12F70",
        "parent_process_id": 1,
        "parent_process_name": "launchd",
        "process_id": 5883,
        "process_name": "MYAPP",
        "system_name": "iPhone OS",
        "system_version": "8.3",
        "time_zone": "EDT"
    }
}

Thank in advance..

A: This crash is related to "EXC_BAD_ACCESS" to detect the exact error we can take help of the Zombie Object.
We need to enable it from the Edit Scheme -> Select Run from left panel -> Select Diagnostics tab -> Select Enable Zombie Objects from Memory Management.

Also we can symbolicate the crash report to detect the exact function in which the crash detected along with the specific line.
Reference Link : Steps to symbolicate the crash report


text:
Q: Factorization of polynomials and the Fundamental Theorem of Algebra I'm just learning about Complex Analysis and somehow the factorization of polynomials and the Fundamental Theorem of Algebra confuse me.
For example let $f(z) = z^9$. Then $f(z) = 0$ has according to the Fundamental Theorem of Algebra $9$ solutions (counted with multiplicity).
But why is it wrong to say that in this case there is exactly one solution? Namely, $z=0$. I know that $z^9 = (z-z_1)\dots (z-z_9)$ but shouldn't all $z_i$'s equal 0?.


text:
Q: Overloading the stream extraction operator - Invalid operands to binary expression trying to overload the extraction operator in this class
class Mystring {

private:

    char* cstring;
    size_t size;

public:

    friend std::istream &operator>>(std::istream &is, Mystring &str);

the function:
#include <iostream>
#include "mystring.h"

std::istream &operator>>(std::istream &is, Mystring &obj) {
    char *buff = new char[1000];
    is >> buff;                  /* Invalid operands to binary expression ('std::istream' (aka 'basic_istream<char>') and 'char *') */
    obj = Mystring{buff};
    delete [] buff;
    return is;
}

the error I get is: Invalid operands to binary expression ('std::istream' (aka 'basic_istream<char>') and 'char *')
when I tried to do something like this:
is >> *buff;
It reads only the first char
Mystring name;
std::cout << "name: " << std::endl;
std::cin >> name;
std::cout << "Your name is " << name;

name: harry
Your name is h

A: You get the error because the overload reading into a CharT*:
template< class CharT, class Traits>
basic_istream<CharT, Traits>&
  operator>>( basic_istream<CharT, Traits>& st, CharT* s );

was removed in C++20. In C++20, the closest you can get is to read into an array of known extent, using the new overload:
template< class CharT, class Traits, std::size_t N >
basic_istream<CharT, Traits>&
  operator>>( basic_istream<CharT, Traits>& st, CharT (&s)[N] );

which in this case could be used by declaring buff as an array instead of a pointer:
std::istream &operator>>(std::istream &is, Mystring& obj) {
    if(char buff[1000]; is >> buff)
        obj = Mystring{buff};
    return is;
}

I however suggest that you use a std::string instead of this pair:
char* cstring;
size_t size;

A: Well, istream formatted input does not support reading strings into char* buffers, should it read a single character? a word? a line? everything up to EOF? After all, it doesn't know how large the buffer is.
You should use either

*

*read(buffer,count) to read exactly count characters, waiting until they are available or until EOF.

*auto num_read = readsome(buffer,count) to read up to count characters, without blocking so it might return num_read<count.


text:
Q: Running python script from php and write to a file My php code is in htdocs/series/index.php.
My python code location is /home/shivam/Desktop/hello.py
I am running php using xampp in ubuntu.
here is php code
 <?php
$command = escapeshellcmd('/home/shivam/Desktop/hello.py');
$output = shell_exec($command);
echo $output;
?>

here is my python code
#!/usr/bin/env python
with open("/home/shivam/Desktop/solution.txt", "w") as myfile:
    myfile.write("write text")

I am trying to run the python script using php to write to a file 'solution.txt'. When i write something myself to solution.txt and open it in read mode using python script via php then it works but when i try to write using above code ,i am unable to do so.
One more thing, none of the code below the line "with open("/home/shivam/Desktop/solution.txt", "w") as myfile:" gets executed.
I have tried the solution given in : enter link description here

A: Absolute paths to executables and files...
run_py.php
<?php
$command = escapeshellcmd('/usr/bin/python /home/user/some_py.py');
$output = shell_exec($command);
echo $output;
?>

some_py.py
with open("/home/user/solution.txt", "w") as myfile:
    myfile.write("write text")

Output:
user@box:~/$ php run_py.php
user@box:~/$ cat solution.txt
write text


text:
Q: How to use play-slick with H2 and MySQL compatibility mode in dev, and MySQL in production? I've started using play-slick and would like to know if the following is possible. In development I want to use H2 in MySQL compatibility mode, and in production use MySQL.
However, I think this isn't working for me in development because play-slick uses the Slick driver based on the currently configured database. This is H2, so slick generates H2-style SQL, which fails in MySQL compatibility mode because the quoting for attribute and table names is different.

A: AFAICS Slick doesn't have any H2 MySql compatibility mode support in its driver, so it will be hard to get play-slick to use it.
Maybe this is a silly question but the way I see it you are using H2 instead of Mysql in dev mode either way, so why do you want it to be in MySql compatibility mode?


text:
Q: NT Challenge and Response window on virtual directory in IIS 7.0 I have set up a simple virtual directory that contains common CSS style sheets and image files on a web site hosted under IIS 7.0 and I keep getting the NT challenge and response window when I try to browse to the web site.
How do I prevent this from happening?

A: Where does the virtual directory live and what are the NTFS permissions on it?
When IIS is installed the permissions on inetpub\wwwroot are set to allow IIS to access that directory, and any directories under it will inherit the permissions. I am guessing your virtual directory points outside of the normal web directories, and thus the NTFS permissions for the directory and the files within it exclude IIS.
To fix this open explorer and navigate to the directory above the directory your virtual directory points to. Right click it and view the properties and then select the security tab. You will need to Edit the permissions and, at a minimum, give the IIS_IUSRS group Read/Read and Execute/List folder contents rights. If your app pool is running as another user you'll also need to give that account the correct permissions.


text:
Q: WUBI dual boot problem I tried to dual boot Ubuntu 16.04 in my Windows 7 PC with Wubi.
After I press the "Reboot Now" button the computer doesn't ask me to choose Ubuntu or Windows 7 and I don't know what to do.


text:
Q: Not getting multiple values while i am selecting values from drop down in jquery this.value Here is my code i am struggling with the multiple values select with jquery if i will select two values i should get two values in the function test
<html>
<select name="hello[]" id="hello" multiple="multiple" onchange="test(this.value);">
<option value="">Select Value</option>
<option value="1">PHP</option>
<option value="2">JAVA</option>
<option value="3">.NET</option>
<option value="4">ORACLE</option>
<option value="5">DBA</option>
</select>
</html>
<script>
function test(xx)
{

alert(xx);
}

please help me

A: Try the below code similar to your approach
<script>
var hello = new Array();
function test(xx)
{
  hello.push(xx);
  alert(hello);
}
</script>

A: Try removing this:
onchange="test(this.value);"

and jQuery:
var test = function(x) {
   alert(x);
}

$(document).on('change', '#hello', function() {
       var val = $(this).val();
       test(val);
});

or more compact:
$(document).on('change', '#hello', function() {
       var val = $(this).val();
       alert(val);
});

Check the DEMO


text:
Q: C++ digit separators in Visual Studio Using visual studio 2015 from command line. Options used: /std:c++14
Whenever I try to compile
int num = 10'000'000;

cl.exe says warning: digit separators not enabled, apostrophe begins a character literal
How do I enable it?


text:
Q: When is it acceptable to call GC.Collect? The general advice is that you should not call GC.Collect from your code, but what are the exceptions to this rule?
I can only think of a few very specific cases where it may make sense to force a garbage collection.
One example that springs to mind is a service, that wakes up at intervals, performs some task, and then sleeps for a long time. In this case, it may be a good idea to force a collect to prevent the soon-to-be-idle process from holding on to more memory than needed.
Are there any other cases where it is acceptable to call GC.Collect?

A: One instance where it is almost necessary to call GC.Collect() is when automating Microsoft Office through Interop. COM objects for Office don't like to automatically release and can result in the instances of the Office product taking up very large amounts of memory. I'm not sure if this is an issue or by design. There's lots of posts about this topic around the internet so I won't go into too much detail.
When programming using Interop, every single COM object should be manually released, usually though the use of Marshal.ReleseComObject(). In addition, calling Garbage Collection manually can help "clean up" a bit. Calling the following code when you're done with Interop objects seems to help quite a bit:
GC.Collect()
GC.WaitForPendingFinalizers()
GC.Collect()

In my personal experience, using a combination of ReleaseComObject and manually calling garbage collection greatly reduces the memory usage of Office products, specifically Excel.

A: As a memory fragmentation solution.
I was getting out of memory exceptions while writing a lot of data into a memory stream (reading from a network stream). The data was written in 8K chunks. After reaching 128M there was exception even though there was a lot of memory available (but it was fragmented). Calling GC.Collect() solved the issue. I was able to handle over 1G after the fix.

A: Have a look at this article by Rico Mariani. He gives two rules when to call GC.Collect (rule 1 is: "Don't"):
When to call GC.Collect()

A: I was doing some performance testing on array and list:
private static int count = 100000000;
private static List<int> GetSomeNumbers_List_int()
{
    var lstNumbers = new List<int>();
    for(var i = 1; i <= count; i++)
    {
        lstNumbers.Add(i);
    }
    return lstNumbers;
}
private static int[] GetSomeNumbers_Array()
{
    var lstNumbers = new int[count];
    for (var i = 1; i <= count; i++)
    {
        lstNumbers[i-1] = i + 1;
    }
    return lstNumbers;
}
private static int[] GetSomeNumbers_Enumerable_Range()
{
    return  Enumerable.Range(1, count).ToArray();
}

static void performance_100_Million()
{
    var sw = new Stopwatch();

    sw.Start();
    var numbers1 = GetSomeNumbers_List_int();
    sw.Stop();
    //numbers1 = null;
    //GC.Collect();
    Console.WriteLine(String.Format("\"List<int>\" took {0} milliseconds", sw.ElapsedMilliseconds));

    sw.Reset();
    sw.Start();
    var numbers2 = GetSomeNumbers_Array();
    sw.Stop();
    //numbers2 = null;
    //GC.Collect();
    Console.WriteLine(String.Format("\"int[]\" took {0} milliseconds", sw.ElapsedMilliseconds));

    sw.Reset();
    sw.Start();
//getting System.OutOfMemoryException in GetSomeNumbers_Enumerable_Range method
    var numbers3 = GetSomeNumbers_Enumerable_Range();
    sw.Stop();
    //numbers3 = null;
    //GC.Collect();

    Console.WriteLine(String.Format("\"int[]\" Enumerable.Range took {0} milliseconds", sw.ElapsedMilliseconds));
}

and I got OutOfMemoryException in GetSomeNumbers_Enumerable_Range method the only workaround is to deallocate the memory by:
numbers = null;
GC.Collect();

A: I use GC.Collect only when writing crude performance/profiler test rigs; i.e. I have two (or more) blocks of code to test - something like:
GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced);
TestA(); // may allocate lots of transient objects
GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced);
TestB(); // may allocate lots of transient objects
GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced);
...

So that TestA() and TestB() run with as similar state as possible - i.e. TestB() doesn't get hammered just because TestA left it very close to the tipping point.
A classic example would be a simple console exe (a Main method sort-enough to be posted here for example), that shows the difference between looped string concatenation and StringBuilder.
If I need something precise, then this would be two completely independent tests - but often this is enough if we just want to minimize (or normalize) the GC during the tests to get a rough feel for the behaviour.
During production code? I have yet to use it ;-p

A: You should try to avoid using GC.Collect() since its very expensive. Here is an example:
        public void ClearFrame(ulong timeStamp)
    {
        if (RecordSet.Count <= 0) return;
        if (Limit == false)
        {
            var seconds = (timeStamp - RecordSet[0].TimeStamp)/1000;
            if (seconds <= _preFramesTime) return;
            Limit = true;
            do
            {
                RecordSet.Remove(RecordSet[0]);
            } while (((timeStamp - RecordSet[0].TimeStamp) / 1000) > _preFramesTime);
        }
        else
        {
            RecordSet.Remove(RecordSet[0]);

        }
        GC.Collect(); // AVOID
    }

TEST RESULT: CPU USAGE 12%
When you change to this:
        public void ClearFrame(ulong timeStamp)
    {
        if (RecordSet.Count <= 0) return;
        if (Limit == false)
        {
            var seconds = (timeStamp - RecordSet[0].TimeStamp)/1000;
            if (seconds <= _preFramesTime) return;
            Limit = true;
            do
            {
                RecordSet[0].Dispose(); //  Bitmap destroyed!
                RecordSet.Remove(RecordSet[0]);
            } while (((timeStamp - RecordSet[0].TimeStamp) / 1000) > _preFramesTime);
        }
        else
        {
            RecordSet[0].Dispose(); //  Bitmap destroyed!
            RecordSet.Remove(RecordSet[0]);

        }
        //GC.Collect();
    }

TEST RESULT: CPU USAGE 2-3%

A: In your example, I think that calling GC.Collect isn't the issue, but rather there is a design issue.
If you are going to wake up at intervals, (set times) then your program should be crafted for a single execution (perform the task once) and then terminate.  Then, you set the program up as a scheduled task to run at the scheduled intervals.
This way, you don't have to concern yourself with calling GC.Collect, (which you should rarely if ever, have to do).
That being said, Rico Mariani has a great blog post on this subject, which can be found here:
http://blogs.msdn.com/ricom/archive/2004/11/29/271829.aspx

A: One useful place to call GC.Collect() is in a unit test when you want to verify that you are not creating a memory leak (e. g. if you are doing something with WeakReferences or ConditionalWeakTable, dynamically generated code, etc).
For example, I have a few tests like:
WeakReference w = CodeThatShouldNotMemoryLeak();
Assert.IsTrue(w.IsAlive);
GC.Collect();
GC.WaitForPendingFinalizers();
Assert.IsFalse(w.IsAlive);

It could be argued that using WeakReferences is a problem in and of itself, but it seems that if you are creating a system that relies on such behavior then calling GC.Collect() is a good way to verify such code.

A: The best practise is to not force a garbage collection in most cases.  (Every system I have worked on that had forced garbage collections, had underlining problems that if solved would have removed the need to forced the garbage collection, and speeded the system up greatly.)
There are a few cases when you know more about memory usage then the garbage collector does.  This is unlikely to be true in a multi user application, or a service that is responding to more then one request at a time.
However in some batch type processing you do know more then the GC.  E.g. consider an application that.

*

*Is given a list of file names on the command line

*Processes a single file then write the result out to a results file.

*While processing the file, creates a lot of interlinked objects that can not be collected until the processing of the file have complete (e.g. a parse tree)

*Does not keep match state between the files it has processed.

You may be able to make a case (after careful) testing that you should force a full garbage collection after you have process each file.
Another cases is a service that wakes up every few minutes to process some items, and does not keep any state while it's asleep.  Then forcing a full collection just before going to sleep may be worthwhile.

The only time I would consider forcing
a collection is when I know that a lot
of object had been created recently
and very few objects are currently
referenced.

I would rather have a garbage collection API when I could give it hints about this type of thing without having to force a GC my self.
See also "Rico Mariani's Performance Tidbits"

These days I consider same of the above cases would be better to use a short lived worker process to do each batch of work and let the OS do the resource recovery.

A: There are some situations where it is better safe than sorry.
Here is one situation.
It is possible to author an unmanaged DLL in C# using IL rewrites (because there are situations where this is necessary).
Now suppose, for example, the DLL creates an array of bytes at the class level - because many of the exported functions need access to such. What happens when the DLL is unloaded? Is the garbage collector automatically called at that point? I don't know, but being an unmanaged DLL it is entirely possible the GC isn't called. And it would be a big problem if it wasn't called. When the DLL is unloaded so too would be the garbage collector - so who is going to be responsible for collecting any possible garbage and how would they do it? Better to employ C#'s garbage collector. Have a cleanup function (available to the DLL client) where the class level variables are set to null and the garbage collector called.
Better safe than sorry.

A: One case is when you are trying to unit test code that uses WeakReference.

A: The short answer is: never!

A: using(var stream = new MemoryStream())
{
   bitmap.Save(stream, ImageFormat.Png);
   techObject.Last().Image = Image.FromStream(stream);
   bitmap.Dispose();

   // Without this code, I had an OutOfMemory exception.
   GC.Collect();
   GC.WaitForPendingFinalizers();
   //
}

A: Another reason is when you have a SerialPort opened on a USB COM port, and then the USB device is unplugged. Because the SerialPort was opened, the resource holds a reference to the previously connected port in the system's registry. The system's registry will then contain stale data, so the list of available ports will be wrong. Therefore the port must be closed.
Calling SerialPort.Close() on the port calls Dispose() on the object, but it remains in memory until garbage collection actually runs, causing the registry to remain stale until the garbage collector decides to release the resource.
From https://stackoverflow.com/a/58810699/8685342:
try
{
    if (port != null)
        port.Close(); //this will throw an exception if the port was unplugged
}
catch (Exception ex) //of type 'System.IO.IOException'
{
    System.GC.Collect();
    System.GC.WaitForPendingFinalizers();
}

port = null;

A: If you are creating a lot of new System.Drawing.Bitmap objects, the Garbage Collector doesn't clear them. Eventually GDI+ will think you are running out of memory and will throw a "The parameter is not valid" exception. Calling GC.Collect() every so often (not too often!) seems to resolve this issue.

A: If you have good reason to believe that a significant set of objects - particularly those you suspect to be in generations 1 and 2 - are now eligible for garbage collection, and that now would be an appropriate time to collect in terms of the small performance hit.
A good example of this is if you've just closed a large form. You know that all the UI controls can now be garbage collected, and a very short pause as the form is closed probably won't be noticeable to the user.
UPDATE 2.7.2018
As of .NET 4.5 - there is GCLatencyMode.LowLatency and GCLatencyMode.SustainedLowLatency. When entering and leaving either of these modes, it is recommended that you force a full GC with GC.Collect(2, GCCollectionMode.Forced).
As of .NET 4.6 - there is the GC.TryStartNoGCRegion method (used to set the read-only value GCLatencyMode.NoGCRegion). This can itself, perform a full blocking garbage collection in an attempt to free enough memory, but given we are disallowing GC for a period, I would argue it is also a good idea to perform full GC before and after.
Source: Microsoft engineer Ben Watson's: Writing High-Performance .NET Code, 2nd Ed. 2018.
See:

*

*https://msdn.microsoft.com/en-us/library/system.runtime.gclatencymode(v=vs.110).aspx

*https://msdn.microsoft.com/en-us/library/dn906204(v=vs.110).aspx

A: In large 24/7 or 24/6 systems -- systems that react to messages, RPC requests or that poll a database or process continuously -- it is useful to have a way to identify memory leaks. For this, I tend to add a mechanism to the application to temporarily suspend any processing and then perform full garbage collection. This puts the system into a quiescent state where the memory remaining is either legitimately long lived memory (caches, configuration, &c.) or else is 'leaked' (objects that are not expected or desired to be rooted but actually are).
Having this mechanism makes it a lot easier to profile memory usage as the reports will not be clouded with noise from active processing.
To be sure you get all of the garbage, you need to perform two collections:
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();

As the first collection will cause any objects with finalizers to be finalized (but not actually garbage collect these objects). The second GC will garbage collect these finalized objects.

A: You can call GC.Collect() when you know something about the nature of the app the garbage collector doesn't.
As the author, it's often tempting to think this is likely or normal. However, the truth is the GC amounts to a pretty well-written and tested expert system, and it's rare you'll know something about the low level code paths it doesn't.
The best example I can think of where you might have some extra information is an app that cycles between idle periods and very busy periods. You want the best performance possible for the busy periods and therefore want to use the idle time to do some clean up.
However, most of the time the GC is smart enough to do this anyway.

A: i am still pretty unsure about this.
I am working since 7 years on an Application Server. Our bigger installations take use of 24 GB Ram. Its hightly Multithreaded, and ALL calls for GC.Collect() ran into really terrible performance issues.
Many third party Components used GC.Collect() when they thought it was clever to do this right now.
So a simple bunch of Excel-Reports blocked the App Server for all threads several times a minute.
We had to refactor all the 3rd Party Components in order to remove the GC.Collect() calls, and all worked fine after doing this.
But i am running Servers on Win32 as well, and here i started to take heavy use of GC.Collect() after getting a OutOfMemoryException.
But i am also pretty unsure about this, because i often noticed, when i get a OOM on 32 Bit, and i retry to run the same Operation again, without calling GC.Collect(), it just worked fine.
One thing i wonder is the OOM Exception itself...
If i would have written the .Net Framework, and i can't alloc a memory block, i would use GC.Collect(), defrag memory (??),  try again, and if i still cant find a free memory block, then i would throw the OOM-Exception.
Or at least make this behavior as configurable option, due the drawbacks of the performance issue with GC.Collect.
Now i have lots of code like this in my app to "solve" the problem:
public static TResult ExecuteOOMAware<T1, T2, TResult>(Func<T1,T2 ,TResult> func, T1 a1, T2 a2)
{

    int oomCounter = 0;
    int maxOOMRetries = 10;
    do
    {
        try
        {
            return func(a1, a2);
        }
        catch (OutOfMemoryException)
        {
            oomCounter++;
            if (maxOOMRetries > 10)
            {
                throw;
            }
            else
            {
                Log.Info("OutOfMemory-Exception caught, Trying to fix. Counter: " + oomCounter.ToString());
                System.Threading.Thread.Sleep(TimeSpan.FromSeconds(oomCounter * 10));
                GC.Collect();
            }
        }
    } while (oomCounter < maxOOMRetries);

    // never gets hitted.
    return default(TResult);
}

(Note that the  Thread.Sleep() behavior is a really App apecific behavior, because we are running a ORM Caching Service, and the service takes some time to release all the cached objects, if RAM exceeds some predefined values. so it waits a few seconds the first time, and has increased waiting time each occurence of OOM.)

A: one good reason for calling GC is on small ARM computers with little memory, like the Raspberry PI (running with mono).
If unallocated memory fragments use too much of the system RAM, then the Linux OS can get unstable.
I have an application where I have to call GC every second (!) to get rid of memory overflow problems.
Another good solution is to dispose objects when they are no longer needed. Unfortunately this is not so easy in many cases.

A: This isn't that relevant to the question, but for XSLT transforms in .NET (XSLCompiledTranform) then you might have no choice. Another candidate is the MSHTML control.

A: If you are using a version of .net less than 4.5, manual collection may be inevitable (especially if you are dealing with many 'large objects').
this link describes why:
https://blogs.msdn.microsoft.com/dotnet/2011/10/03/large-object-heap-improvements-in-net-4-5/

A: Since there are Small object heap(SOH) and Large object heap(LOH)
We can call GC.Collect() to clear de-reference object in SOP, and move lived object to next generation.
In .net4.5, we can also compact LOH by using largeobjectheapcompactionmode


text:
Q: $.post data html returns null Got some strange problem, when i use $.post to a php file. The file itself without any post echos 'someresult' and when i go $.post the html() of post data is null... Help out plz
$('#podborform').submit(function(){
    var phone = $('#tour_selection_phone').val();
    if(phone != null && phone != '' && phone.length >= 7){
        var values = $(this).serialize();
        var qwer = String('captcha');
        var url = $(this).attr( 'action' );
        $.post( url, values,
            function( data ) {
                var content1 = $( data ).html();
                //content = String(content);
                //alert(qwer+'  -  '+content);
                if(content1 == qwer){
                    alert('Вы не правильно ввели код с картинки, попробуйте еще раз!');
                }
                if(content1 == 'false'){
                    alert('Извините произошла ошибка!');
                }
                if(content1 == 'true'){
                    alert('Ваша заявка успешно отправлена!');
                }
            }
        );
    }else{
        alert('Вы не ввели все обязательные поля!');
    }
    return false;
});

it is connected to php that contains this:
<?php
class mailer{
    //var $fields = array();
    function __construct(){
        if($this->captcha()){
            $this->sendmail();
        }else{
            exit('false');
        }
    }
    function sendmail(){
        foreach($_POST as $key=>$post){
            $text .= $key.': '.$post.PHP_EOL;
        }
        if(mail("123@gmail.com", "the subject", $text,
            "From: sales@123.ru\r\n"
           ."Reply-To: {$_POST['email']}\r\n"
           ."X-Mailer: PHP/" . phpversion())){
                exit('true');
            }else{
                exit('false_mail');
        }
    }
    function captcha(){
        require_once('recaptchalib.php');
        $privatekey = "123123";
        $resp = recaptcha_check_answer ($privatekey,
                                      $_SERVER["REMOTE_ADDR"],
                                      $_POST["recaptcha_challenge_field"],
                                      $_POST["recaptcha_response_field"]);

        if (!$resp->is_valid) {
          // What happens when the CAPTCHA was entered incorrectly
          echo 'captcha'; exit;
        } else {
            unset($_POST["recaptcha_challenge_field"],
                                      $_POST["recaptcha_response_field"]);
          return true;
        }
    }
}
    $mail = new mailer;
?>

A: you forgot the () on the construct of the object mailer:
$mail = new mailer;

should be
$mail = new mailer();

A: .html gets the containing HTML.
Example
$('

').html() // returns ''
$('test').html() // returns null

You can use data directly. It will contain the response as a string
if(data == qwer){
}
if(data == 'true'){
}


text:
Q: bitcoins, how can someone receive much less than have spent? Here is blockchain link:
    https://blockchain.info/address/14f4WdcxkRhP2N5JbCWe3q7QcNtDiX82ba?filter=1
Here you can clearly see that that total received bitcoin was about, but he spent more than 200 i guess...
Can someone explain how is that even possible?

A: Whoever who made these transactions had other sources of funds than just the account you queried. Thus he was able to form transactions that delivered more funds than that one account received.
If you total amount delivered by all of the transactions that drew from that account, they do total more than 200 Bitcoins. But those transactions drew from many accounts, not just this one.
For example, if you look closely at transaction ce99101a40bcf2bceab57ac43ff881260a6961c546b9d52e0737ed6acd39a43a you can see that while the transaction delivered over 25 Bitcoins, it had numerous input accounts. Only 0.1528 Bitcoins came from 14f4WdcxkRhP2N5JbCWe3q7QcNtDiX82ba.
Note that this is perfectly ordinary. Some wallets behave this way automatically, constantly generating additional accounts to hold funds and managing those sources as a unit, forming transactions that draw from several of them and returning unspent funds to yet another new account.


text:
Q: How to search through results of instant search Outlook I have the following code that does an instant search in Outlook, but I am unsure of how now to loop through these results to do further checks.
Any pointers would be gratefully received!
Sub SearchByAddress()

    Dim myOlApp As New Outlook.Application
    Dim ns As Outlook.NameSpace
    Dim strFilter As String
    Dim oMail  As Outlook.MailItem

    Set ns = myOlApp.GetNamespace("MAPI")

          strFilter = "joebloggs@hotmail.com"

    Set myOlApp.ActiveExplorer.CurrentFolder = ns.GetDefaultFolder(olFolderInbox)
         txtSearch = "from:(" & Chr(34) & strFilter & Chr(34) & ") AND " & Chr(34) & "Check" & Chr(34)
         myOlApp.ActiveExplorer.Search txtSearch, olSearchScopeAllFolders

    Set myOlApp = Nothing

End Sub

A: Use Application.AdvancedSearch instead - it returns an instance of the Search object.


text:
Q: Strophe to Openfire: Error during WebSocket handshake: Unexpected response code: 302 I am writing a simple chat client (using strophe) which connects to my Openfire server. Strophe works successfully with BOSH, but for some reason cannot connect using websockets.
I have installed the latest version (websockets-0.0.0.6) of "WebSockets Plugin" plugin for OpenFire, using the default path "ws". My client url is ws://my-server:7070/ws.
I get the following error in my browser console:

WebSocket connection to 'ws://localhost:7070/ws' failed: Error during
  WebSocket handshake: Unexpected response code: 302

I look at other related post (stackoverflow.com/questions/22983302/strophe-failed-to-connect-openfire-by-websocket) but have not been successful.
Has anyone come across this problem before?
Any help would really be appreciated.
Thanks in advance.

A: I'm assuming you were using the latest version of Strophe. The openfire-websocket is developed against with older version Strophe 1.0 . They are not capable now.
You can take a look at https://community.igniterealtime.org/thread/53783


text:
Q: How to get the full path of script where is path getting from method which located in another folder from class? Let's say so
package1/
    main.py == here i'm calling from Utils class that must give me the path of this file where i call it
package2/
    utils.py = which must contain method that return path where they call it
from main.py wanna get path of that main.py from packages Utils

A: Create Utils class like this:
class Utils:
    """docstring for Utils"""

    def getRootPath():
        pass

    def get_current_path(self):
        return os.path.realpath(self.filePath)

    def __init__(self, filePath):
        super(Utils, self).__init__()
        self.filePath = filePath

When you initialize your class somewhere just put the name of script where you init you Utils class like this:
utils = Utils(os.path.basename(__file__))
print(utils.get_current_path())

If you wanna get the dirname where you call it so make another method or replace it with
return os.path.dirname(os.path.realpath(self.filePath))

While you wait someone faster you will do it yourself, especially when morons ask so what do you want to do