text:
Q: Is the usage "how many ever" correct? Eg : You may use it how many ever time.
I know the sentence can be phrased better but I just wanted to given an example.
So my question is, Is "how many ever" a correct usage?

A: As several commenters have observed above, the standard form in U.S. and British English (at least) of a wording of the type "You may use it how many ever times you like" is "You may use it however many times you like," where "however many" has the meaning "as many."
Although the poster of the question reports that expressions of the form "how many ever times" are "a common usage in Asian countries," the vast majority of matches for "how many ever" in Google Books and Elephind newspaper searches involve instances where the author is using the phrase at the beginning of a rhetorical question of the form "how many [people] ever..." This is not the form of the expression that the OP asks about.
The one instance where a Google Books match does involve use of "how many ever" in the relevant sense has a special excuse for its formulation. From Nora Roberts, Daring to Dream (1996):

"We need to talk about it," she repeated.
"I haven't asked you any questions, Margo. Whoever, how many ever, have been in your life before, there's only one now. There's only me."

The normal U.S. English wording here would be "however many have been in your life before..." but the author was unwilling to use that wording immediately after the word whoever in a parallel construction—presumably because she liked having both parallel elements end with ever and perhaps because the rhythmic pattern of "whoever, how many ever" seemed less awkward to her than the rhythmic stress of "whoever, however many."
In any case, the Roberts example stands alone in my database searches as an example in which "how many ever" is used in the sense of "however many." If English speakers in parts of Asia colloquially use "how many ever" in the same sense, their usage has not made much of an impression on the digital libraries I consulted.


text:
Q: Monoidal functor and the units II In their book Tensor Categories Etingof, Gelaki, Nikshych and Ostrik give a different definition of a (strong) monoidal functor. The difference is that they do not set the isomorphism $F(1) \cong 1$ as a part of the data, but rather impose a condition on the pair $(F\colon C\to C', (J_{X,Y}\colon F(X)\otimes F(Y)\to F(X\otimes Y))_{X,Y \in C})$ that would be a monoidal functor that some isomorphism $F(1) \cong 1$ exists. They then define a canonical isomorphism $F(1)\cong 1$ by the following diagram:

The exercise is then given to prove that, for this canonical isomorphism, the following diagrams commute:

My trouble is the second diagram. Clearly, we first should tensor diagram defining $\phi$ with $F(X)$ and $1_{F(X)}$ and appeal to functoriality, but I don't see how we can get from $1_{F(X)}\otimes (\phi \otimes 1_1)$ to $1_{F(X)}\otimes \phi$.

A: As Max already pointed out, you may start with tensoring the diagram (2.24) defining $\varphi$ with $F(X)$. So you get the commutative diagram (1):

Notice, that (1) looks like the desired diagram (2.26), tensored with $F(1)$: the diagram (2):

Now we are going to show that (2) is isomorphic to (1), which immediately implies that (2.26) is commutative. To prove that (2) is isomorphic to (1) we should prove the commutativity of the certain cube with (1) and (2) as opposite faces. To indicate faces I will use the Rubik's Cube notation. Define the B-side as (1) and F-side as (2). Set the U-side as the following diagram:

which is commutative by the triangle diagram. The L-side is simply associativity, so I will not draw it. The D-side is following:

It is commutative by the monoidal structure axiom. The R-side is automatically defined, let's prove its commutativity. Indeed,
$$
J_{X\otimes 1,1}^{-1}\circ F(a_{X,1,1}^{-1})\circ J_{X,1\otimes 1}\circ(\text{id}_{F(X)}\otimes^{\wr}F(\ell_1^{-1}))=
J_{X\otimes 1,1}^{-1}\circ F(a_{X,1,1}^{-1})\circ F(\text{id}_X\otimes\ell_1^{-1})\circ J_{X,1}=
$$
$$
J_{X\otimes 1,1}^{-1}\circ F(a_{X,1,1}^{-1}\circ(\text{id}_X\otimes\ell_1^{-1}))\circ J_{X,1}=
J_{X\otimes 1,1}^{-1}\circ F(r^{-1}_X\otimes\text{id}_1)\circ J_{X,1}=
F(r^{-1}_X)\otimes^{\wr}\text{id}_{F(1)},
$$
where the first and fourth equalities are the naturality of $J$, the second is the functoriality of $F$ and the third is the triangle diagram for the domain monoidal category.

redpajama_set_name: RedPajamaStackExchange


text:
Q: python simple socket client / server example I am trying to explore using sockets in python to stream data with a toy example:
So far,  I created the following code for the server:
from socket import *
import time

s = socket(AF_INET, SOCK_STREAM)
s.bind(('', 10000))
s.listen(5)

while True:
    client, addr = s.accept()
    print('Got a connection from %s' % str(addr))
    timestr = time.ctime(time.time()) + "\r\n"
    client.send(timestr.encode('ascii'))
    client.close()

Code for the client:
from socket import *
s = socket(AF_INET, SOCK_STREAM)
s.connect(('localhost', 10000))
tm = s.recv(1024)
s.close()
print('The time is %s' % tm.decode('ascii'))

This works.
Now I would like to transform that code so that the server send a string (no matter what) every second, and the client prints it. (i.e. testing streaming of data).
I have tried things along the lines of :
while True:
    client, addr = s.accept()
    print('Got a connection from %s' % str(addr))
    while True:
        timestr = time.ctime(time.time()) + "\r\n"
        client.send(timestr.encode('ascii'))
        time.sleep(1)
    client.close()

But with no luck.
Quite frankly I am a bit lost. I looked for such simple example of creating a basic stripped bare streaming example, but I have not found that anything matching my level of unsophistication.
Any pointers hugely appreciated.


text:
Q: Solution to cigars and squirrels puzzle on CodingBat throws syntax error I am trying to solve this CodingBat problem:

Squirrels who like to party get together and smoke cigars. Such a party is only deemed successful when the number of cigars is between 40 and 60, on a weekday. On weekends, however, there is no upper bound on number of cigars. Write a function that returns True if the party with the given values was successful.

Unfortunately, although I have used Python occasionally, I am not good enough at it to understand why my code fails with a syntax error on line 5:
def cigar_party(cigars, is_weekend):
  if is_weekend:
    if cigars >= 40:
      return True
  else if:
    cigars >= 40 and cigars =< 60:
      return True
  else:
    return False

A: In Python you need to use elif instead of else if.
More information:
http://docs.python.org/2/tutorial/controlflow.html
Also change the following line:
else if:
cigars >= 40 and cigars =< 60:

To this:
elif cigars >= 40 and cigars <= 60:
    return True

The less than or equal to sign needs to be <= and there should not be a colon between the keyword elif and the rest of the expression.

A: First of all, as tcdowney pointed out, the syntax is elif, not else if, secondly, you need to have the logical assessent in the elif statement, not as some sort of operation. Lastly, have the greaterthan/smallerthan sign before the equals sign.
elif cigars >= 40 and cigars <= 60:
    return True

That should do the trick ;)

A: def cigar_party(cigars, is_weekend):
  a = range(61)
  if is_weekend and cigars not in a:
    return True

  elif cigars in range(40,61):
    return True

  else:
    return False

A: def cigar_party(cigars, is_weekend):
   if is_weekend and cigars>=40:
     return True
   elif not is_weekend and cigars in range(40,61):
     return True
   return False

A: def cigar_party(cigars, is_weekend):
    if is_weekend:
        return cigars >= 40
    return 40 <= cigars <= 60  // Python supports this type of Boolean evaluation

or using the ternary form:
def cigar_party(cigars, is_weekend):
    return cigars >= 40 if is_weekend else 40 <= cigars <= 60

A: def cigar_party(cigars, is_weekend):
  if is_weekend:
    if cigars>=40:
      return is_weekend
  else:
    if cigars in range(40,61):
      return True
  return False

A: def cigar_party(cigars, is_weekend):
  if is_weekend == True:
    if cigars >= 40:
      return True
    else:
      return False
  if is_weekend == False:
    if cigars >= 40 and cigars <= 60:
      return True
    else:
      return False

A: #got 9/12 not bad!

is_weekday = True
is_weekend = True

def cigar_party(cigars, is_weekend):
    if is_weekend and cigars >= 0:
        return True
    elif is_weekday and cigars >= 40:
        return True
    else:
        return False

A: def cigar_party(cigars, is_weekend):
  if is_weekend and cigars >= 40:
      return True
  elif cigars >= 40 and cigars <= 60:
      return True
  else:
    return False


text:
Q: VBA dynamic cell reference in cell formula I'm trying to convert this formula "=RIGHT(G7,LEN(G7)-LEN(OFFSET(H7,0,-7)))" into VBA and wherever it references cell H7 I want it to use ActiveCell instead as this formula is used in a loop and is entered in a different row each time. Hope I explained my predicament articulately.
My attempt at converting the formula ended with:

ActiveCell.Formula = "=right(offset(" & ActiveCell &
  ",0,-1),len(offset(" & ActiveCell & ",0,-1)-len(offset(" & ActiveCell
  & ",0,-7))"

which gives me Run-time error '1004': Application-defined or object defined error.

A: This is what FormulaR1C1 was made for:
Sub foooo()

Dim ws As Worksheet
Set ws = ActiveSheet
ws.Range("H1:H100").FormulaR1C1 = "=RIGHT(RC-1,LEN(RC-1)-LEN(RC-7))"

End Sub

It will do the whole range at once.
If you really want to loop then:
Sub foooo()
Dim i As Long
Dim ws As Worksheet
Set ws = ActiveSheet
For i = 1 To 100
    ws.Cells(i, "H").FormulaR1C1 = "=RIGHT(RC-1,LEN(RC-1)-LEN(RC-7))"
Next i
End Sub

The problem with your formula is that the default characteristic of a range object is its value not its address.  so:
ActiveCell.Formula = "=right(offset(" & ActiveCell.Address(0,0) & ",0,-1),len(offset(" & ActiveCell.Address(0,0) & ",0,-1)-len(offset(" & ActiveCell.Address(0,0) & ",0,-7))"

Though I would avoid a column full of OFFSET Functions.  OFFSET is a volatile function in that it calculates every time excel calculates regardless if any of the data to which it refers has changed.  A column full of these will slow down the calculation times.


text:
Q: only able to use dbcontext once before it disposes I'm working on a site in asp.net core 3.1 and I'm trying to read the database twice in the page model. However, I'm getting a "System.OnbjectDisposedException: Cannot access a disposed object" error. This is a snippet of my Index.cshtml.cs
public class IndexModel : PageModel
{
    private readonly DocsiteContext _context;

    public IndexModel(DocsiteContext context)
    {
        _context = context;
    }

    public Document CurrDocument;

    public void OnGet()
    {
        FunctionA();
    }

    private async void FunctionA()
    {
        List<string> AllDocs = await _context.Documents.OrderBy(d => d.FileName).Select(d => d.FileName).ToListAsync();
        FunctionB();
    }

    private async void FunctionB()
    {
        CurrDocument = await _context.Documents.FirstOrDefaultAsync(f => f.FileName == CurrPath && !f.IsDirectory);
    }
}`

And this is a snippet of the the Startup.cs class
public void ConfigureServices(IServiceCollection services)
    {
        services.AddRazorPages();

        services.AddDbContext<DocsiteContext>(options =>
                options.UseSqlServer(Configuration.GetConnectionString("DocsiteContext")));
    }

I know the context disposes after the first use, but I'm unsure how to keep it to use the second time.
I'm pretty new to asp.net, so if this is the wrong approach I would love some suggestions!

A: A DbContext is a "scoped" service. This means that a new dbContext is created for each HTTP request. If you do something like redirect to another page, you'll get a new dbContext object.


text:
Q: For loop nested in while loop I have written a while loop in Matlab that is supposed to determine the value of the parameter "n" for "a" to exceed the value 300. I know "n" should be 17, but I'm getting a value of 4 instead. Does anyone see the problem?
The code is as follows:
a = 10;
k = 0.5;
n = 2;
while a < 300
    for m = 1:5
        a = a + (a*k) + n;
    end
    n = n + 1;
end

Edit:
I realized that I didn't reinitialize my "a" variable, thanks to Barmar's comment. Although the code might not look very efficient, this is what works for me:
a = 10;
k = 0.5;
n = 2;
while a < 300
    a = 10;
    for m = 1:5
        a = a + (a*k) + n;
    end
    if a >= 300
        break
    end
    n = n + 1;
end

A: If your formula is correct then 4 is the answer you should expect. The first for loop run turns a into the respsective values:
17, 27, 42, 65, 99

Which then turns n to 3. The next run turns a into:
151, 229, 346, 522, 786

Notice that a is now > 300 but we have to increment n one more time. Thus n = 4.


text:
Q: TSQL retrieve all records in current month/year I have a datetime field called DateFinished.  I need to be able to retrieve all records in which DateFinished is within the current month/year.

A: If you've only got a small number of rows, this will do to get all rows where DateFinished is in this month of this year.
SELECT *
FROM MyTable
WHERE Year(DateFinished) = Year(CURRENT_TIMESTAMP)
                 AND Month(DateFinished) = Month(CURRENT_TIMESTAMP)

This could get quite slow over a large number of rows though - in which case using DateAdd, DatePart and BETWEEN is probably more appropriate, and can take advantage of indexes (I don't have time to write an answer involving those right now!)

A: Just as an alternative - this should use an index on DateFinished.
SELECT *
FROM MyTable
WHERE DateFinished BETWEEN
     DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0)
     AND
     DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()) + 1, 0)

A: So the problem with @Bridge's method is use of index.
@Moose & @PCurd's method has a problems depending on how the data is stored.
@PCurd's method would work fine if all data collected on a day is rounded down to that day. E.g. event at 5pm is recorded as 2021-11-30 00:00:00. But if time is kept (which is assumed as it is a datetime field in Ops situation) then this data will be lost.
So you need to use the <> operators.
SELECT *
FROM MyTable
WHERE DateFinished >=
     DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0)
     AND DateFinished <
     DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()) + 1, 0)

For the method using datefromparts: SQL select records with current month


text:
Q: Android studio не отображает xml подсказки Android studio утратила способность отображать подсказки в xml файлах. Я пытался удалять кэш, перезагружать, удалять idea директорию.

Самое интересное, что в корневом элементе - RelativeLayout подсказки работают. Но в дочерних они не отображаются совсем.

Срочно нужна помощь. Я предпринял много мер, но пока ничего не помогло.


text:
Q: Can I run mysqli functions, without upgrading PHP version5.4 to 7 My requirement is bit odd... I have multiple doubts..

*

*Could you please tell what are all the problems I'll face if I upgrade php5.4 to PHP 7? (on PHP 5.4 a process is already running, and I don't want to interrupt it)

*Can I run mysqli functions, without upgrading PHP version5.4 to 7?

A: Yes, You can run. If your PHP version greater thank 5.3 you can run MysqLi. But I suggest you use PDO instead of MySqLi
For more information please check the URL : http://php.net/manual/en/mysqli.installation.php

A: *

*Way to long to state here. You can follow this tutorial https://auth0.com/blog/migrating-a-php5-app-to-php7-part-one/

*mysqli is available in PHP5, so it should be OK. If the app requires PHP7, there are ways to install it without affecting your current PHP5 install...

*mysqli is available in PHP5


text:
Q: how to create virtual switch in Hyper-v when host is allocated with static ip? Able to create virtual switch using Hyper-v manager, when host is not in static ip mode..
Is there any difference in creating virtual switch using power shell cmdlets and UI

A: When I use below power shell cmdlets able to add virtual switch in static ip mode.
Get-NetAdapter ,
Add-VMNetworkAdapter ,
Set-VMnetworkAdapter


text:
Q: Turning on GPS while the Application Launch I have started working on GoogleMap in Android and I want that my application to turn on the GPS automatically as the application get launched and turn off when the application goes close or user get exit from application.
How to get done above task ?

A: You can prompt user to turn on GPS like:
private void buildAlertMessageNoGps() {
        final AlertDialog.Builder builder = new AlertDialog.Builder(
                this.getActivity());
        builder.setMessage(R.string.gps_disabled)
                .setCancelable(false)
                .setTitle(R.string.gps_disabled_title)
                .setPositiveButton(R.string.enable,
                        new DialogInterface.OnClickListener() {
                            public void onClick(
                                    @SuppressWarnings("unused") final DialogInterface dialog,
                                    @SuppressWarnings("unused") final int id) {
                                startActivity(new Intent(
                                        android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
                            }
                        })
                .setNegativeButton(R.string.cancel,
                        new DialogInterface.OnClickListener() {
                            public void onClick(final DialogInterface dialog,
                                    @SuppressWarnings("unused") final int id) {
                                dialog.cancel();

                            }
                        });
        final AlertDialog alert = builder.create();
        alert.show();
    }

A: GPS can't really be turned on automatically by an Android app. It requires user's authentication to do so.
Best you can do is have a popup dialog requesting the user to allow access to the location service.

A: No it't impossible, and inappropriate. You can't just manage the users phone without his authority.
From Play Store:

"Cerberus automatically enables GPS if it is off when you try to
  localize your device (only on Android < 2.3.3) and you can protect it
  from unauthorized uninstalling - more info in the app configuration."

You can do something like this:
startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));

A: Full solution is here.
AndroidMAnifest.xml
Probably you need folowing permissions
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

MainActivity code
public class MainActivity extends AppCompatActivity {

Context context;

  protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //... some code to init Activity and etc...

        context = this;

        LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE );
        boolean statusOfGPS = manager.isProviderEnabled(LocationManager.GPS_PROVIDER);

        if(!statusOfGPS) // Before show message to turn on GPS be sure it is turned off.
        {
            buildAlertMessageNoGps();
        }
    }

private void buildAlertMessageNoGps() {
        final AlertDialog.Builder builder = new AlertDialog.Builder(
                this.getActivity());
        builder.setMessage(R.string.gps_disabled)
                .setCancelable(false)
                .setTitle(R.string.gps_disabled_title)
                .setPositiveButton(R.string.enable,
                        new DialogInterface.OnClickListener() {
                            public void onClick(
                                    @SuppressWarnings("unused") final DialogInterface dialog,
                                    @SuppressWarnings("unused") final int id) {
                                startActivity(new Intent(
                                        android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
                            }
                        })
                .setNegativeButton(R.string.cancel,
                        new DialogInterface.OnClickListener() {
                            public void onClick(final DialogInterface dialog,
                                    @SuppressWarnings("unused") final int id) {
                                dialog.cancel();

                            }
                        });
        final AlertDialog alert = builder.create();
        alert.show();
    }


text:
Q: C# delegates problem I am getting the following error from my C# Windows Application:

Error  1   No overload for 'CreateLabelInPanel' matches delegate 'WorksOrderStore.ProcessDbConnDetailsDelegate'    H:\c\WorksOrderFactory\WorksOrderFactory\WorksOrderClient.cs    43  39  WorksOrderFactory

I have 3 .cs files that essentially:

*

*Opens a windows

*Has an option for the users to connect to a db

*When that is selected, the system will go off and connect to the db, and load some data in (just test data for now)

*Then using a delegate, the system should do soemthing, which for testing will be to create a label. However I haven't coded this part yet.

But I can't build until I get this error sorted.
The 3 fiels are called:

*

*WorksOrderClient.cs (which is the MAIN)

*WorksOrderStore.cs

*LoginBox.cs

Here's the code for each file:
WorksOrderClient.cs:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using WorksOrderStore;
namespace WorksOrderFactory
{
    using WorksOrderStore;

    public partial class WorksOrderClient : Form
    {
        LoginBox lb = new LoginBox();
        private static WorksOrderDB wodb = new WorksOrderDB();

        private static int num_conns = 0;

        public WorksOrderClient()
        {
            InitializeComponent();
        }

        private void connectToADBToolStripMenuItem_Click(object sender, EventArgs e)
        {
            lb.ShowDialog();
            lb.Visible = true;
        }

        public static bool createDBConnDetObj(string username, string password, string database)
        {
            // increase the number of connections
            num_conns = num_conns + 1;
            // create the connection object
            wodb.AddDbConnDetails(username, password, database, num_conns);
            // create a new delegate object associated with the static
            // method WorksOrderClient.createLabelInPanel
            wodb.ProcessDbConnDetails(new ProcessDbConnDetailsDelegate(CreateLabelInPanel));
            return true;
        }

        static void CreateLabelInPanel(DbConnDetails dbcd)
        {
            Console.Write("hellO");
            string tmp = (string)dbcd.username;
            //Console.Write(tmp);
        }

        private void WorksOrderClient_Load(object sender, EventArgs e)
        {

        }

    }
}

WorksOrderStore.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WorksOrderFactory;

namespace WorksOrderStore
{
    using System.Collections;

    // Describes a book in the book list:
    public struct WorksOrder
    {
        public string contractor_code { get; set; } // contractor ID
        public string email_address { get; set; }   // contractors email address
        public string date_issued { get; set; }     // date the works order was issued
        public string wo_ref { get; set; }          // works order ref
        public string status { get; set; }          // status ... not used
        public job_status js { get; set; }          // status of this worksorder within this system

        public WorksOrder(string contractor_code, string email_address, string date_issued, string wo_ref) : this()
        {
            this.contractor_code = contractor_code;
            this.email_address = email_address;
            this.date_issued = date_issued;
            this.wo_ref = wo_ref;
            this.js = job_status.Pending;
        }
    }

    // Declare a delegate type for processing a WorksOrder:
    //public delegate void ProcessWorksOrderDelegate(WorksOrder worksorder);

    // Maintains a worksorder database.
    public class WorksOrderDB
    {
        // List of all worksorders in the database:
        ArrayList list = new ArrayList();

        // Add a worksorder to the database:
        public void AddWorksOrder(string contractor_code, string email_address, string date_issued, string wo_ref)
        {
            list.Add(new WorksOrder(contractor_code, email_address, date_issued, wo_ref));
        }

        // Call a passed-in delegate on each pending works order to process it:
        /*public void ProcessPendingWorksOrders(ProcessWorksOrderDelegate processWorksOrder)
        {
            foreach (WorksOrder wo in list)
            {
                if (wo.js.Equals(job_status.Pending))
                    // Calling the delegate:
                    processWorksOrder(wo);
            }
        }*/

        // Add a DbConnDetails to the database:
        public void AddDbConnDetails(string username, string password, string database, int conn_num)
        {
            list.Add(new DbConnDetails(username, password, database, conn_num));
        }

        // Call a passed-in delegate on each dbconndet to process it:
        public void ProcessDbConnDetails(ProcessDbConnDetailsDelegate processDBConnDetails)
        {
            foreach (DbConnDetails wo in list)
            {
                processDBConnDetails(wo);
            }
        }
    }

    // statuses for worksorders in this system
    public enum job_status
    {
        Pending,
        InProgress,
        Completed
    }

    public struct DbConnDetails
    {
        public string username { get; set; } // username
        public string password { get; set; } // password
        public string database { get; set; } // database
        public int conn_num { get; set; } // this objects connection number.
        public ArrayList woList { get; set; }  // list of works orders for this connection

        // this constructor just sets the db connection details
        // the woList array will get created later .. not a lot later but a bit.
        public DbConnDetails(string username, string password, string database, int conn_num) : this()
        {
            this.username = username;
            this.password = password;
            this.database = database;
            this.conn_num = conn_num;
            woList = new ArrayList();
        }
    }

    // Declare a delegate type for processing a DbConnDetails:
    public delegate void ProcessDbConnDetailsDelegate(DbConnDetails dbConnDetails);
}

LoginBox.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WorksOrderFactory
{
    public partial class LoginBox : Form
    {
        public LoginBox()
        {
            InitializeComponent();
        }

        private void LoginBox_Load(object sender, EventArgs e)
        {
            this.Visible = true;
            this.Show();
            //usernameText.Text = "Username";
            //new Font(usernameText.Font, FontStyle.Italic);
        }

        private void cancelBtn_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void loginBtn_Click(object sender, EventArgs e)
        {
            // set up a connection details object.
            bool success = WorksOrderClient.createDBConnDetObj(usernameText.Text, passwordText.Text, databaseText.Text);

        }

        private void LoginBox_Load_1(object sender, EventArgs e)
        {

        }

    }
}

Any ideas??
Cheers,
m

A: The one thing jumps out when comparing the definition of the delegate with the definition of the method you're trying to use:
static void CreateLabelInPanel(DbConnDetails dbcd)
public delegate void ProcessDbConnDetailsDelegate(DbConnDetails dbConnDetails)

CreateLabelInPanel should probably not be declared as static.

A: The compiler is just saying that the method you are providing to a delegate is not matching the signature expected by the delegate.
So, in your case.
//To get this line working...
 wodb.ProcessDbConnDetails(new ProcessDbConnDetailsDelegate(SomeMethod1));

//The method signature should be like this.
static void SomeMethod1(DbConnDetails dbcd)

//OR even this -- Instance/Static methods can be supplied to same delegate.
void SomeInstanceMethod(DbConnDetails dbcd)..

And if not, the compiler would complain.
Also, by any chance, do you have two classes with the name "DbConnDetails" ???
My best guess is you are referring to "DbConnDetails" that lies in different namespace than the one expected by the delegate.

A: thanks @amby and @massif and anyone else I may have missed.
This was a school boy error.
It turns out I had another file (which I thought I'd deleted) that also contained a class and constructor called DbConnDetails. I did a search for DbConnDetails in the solution.
I renamed that class/constructor and the filename as well, to be safe.
I then declared
static void CreateLabelInPanel(DbConnDetails dbcd)

which means that the app now compiles/builds again.
Thanks again to everyone.


text:
Q: How to perform XA transactions using SQLServer client ODBC driver in C/C++ on Linux? I've managed to perform XA transactions using SQLServer OLEDB driver on Windows. Now I've ported the C++ application to Linux. On Linux Microsoft provides the SQLServer 2019 ODBC driver and since version 17.3 of this driver, XA is reported to be supported.
Microsoft provides following example that illustrates how to implement the xa_* functions:
Using XA Transactions
The example itself works. Using the code in another context doesn't work. The call to SQLSetConnectAttr(..., SQL_ATTR_ENLIST_IN_XA, ...) for operation OP_START fails and I don't get useful information by CheckRC().

*

*How to get more informaton about failing SQL_ATTR_ENLIST_IN_XA?

*How does XA work with the SQL_ATTR_ENLIST_IN_XA approach compared to OLEDB?

*Is it possible to change the isolation level in XA mode?

Share your experiences and details with us, please.

A: Strict XID data layout
The SQLSetConnectAttr(..., SQL_ATTR_ENLIST_IN_XA, ...) function is very sensitive regarding the XID. If the XID has a branch ID then the branch ID must start at byte 64 of xid_t::data. Storing a global ID like "f9707929-a367-4e3a-9a80-3fbb3a23ab11" + branch ID "1234" directly in one sequence and identifiying the string layout by xid_t::gtrid_length and xid_t::bqual_length will work with other DB APIs and IBM MQ, but it fails with SQL_ATTR_ENLIST_IN_XA in SQLServer.
In order to get above sample XID work the UUID has to be stored at the beginning of xid_t::data (byte 0-36) and the branch id has to be stored staring at byte (64-68). The xid_t field gtrid_length has to be set to 36 and bqual_length to 4. The formatID I set to 1.
If the XID layout doesn't fit the SQL_ATTR_ENLIST_IN_XA with operation OP_START fails and SQLGetDiagRec() reports nothing about it.
Setting the isolation level
By default a XA transaction runs under isolation level "Serializable". Microsoft describes this isolation leve as follows:

The highest level where transactions are completely isolated from one another. The SQLServer keeps read and write locks acquired on selected data to be released at the end of the transaction. Range-locks are acquired when a SELECT operation uses a ranged WHERE clause, especially to avoid phantom reads.

On each call to xa_start the isolation level is set to "Serializable". Setting the isolation level using SQLSetConnectAttr(..., SQL_ATTR_TXN_ISOLATION, ...) after connect doesn't help. You have to call this after SQLSetConnectAttr(..., SQL_ATTR_ENLIST_IN_XA, OP_START, ...).
Doing so allows you to set the isolation level for instance to SQL_TXN_READ_COMMITTED. The database option READ_COMMITTED_SNAPSHOT will be also be considered. This means setting isolation level to SQL_TXN_READ_COMMITTED and having database option READ_COMMITTED_SNAPSHOT  enabled will switch the isolation level to "Snapshot".
The command "DBCC useroptions" can be used to query the isolation level of the current session.
Following query is also useful for checking the isolation level and status of active transactions:
SELECT tst.session_id, [database_name] = db_name(s.database_id)
, tat.transaction_begin_time
, transaction_duration_s = datediff(s, tat.transaction_begin_time, sysdatetime())
, transaction_type = CASE tat.transaction_type  WHEN 1 THEN 'Read/write transaction'
                                                WHEN 2 THEN 'Read-only transaction'
                                                WHEN 3 THEN 'System transaction'
                                                WHEN 4 THEN 'Distributed transaction' END
, input_buffer = ib.event_info, tat.transaction_uow
, transaction_state  = CASE tat.transaction_state
            WHEN 0 THEN 'The transaction has not been completely initialized yet.'
            WHEN 1 THEN 'The transaction has been initialized but has not started.'
            WHEN 2 THEN 'The transaction is active - has not been committed or rolled back.'
            WHEN 3 THEN 'The transaction has ended. This is used for read-only transactions.'
            WHEN 4 THEN 'The commit process has been initiated on the distributed transaction.'
            WHEN 5 THEN 'The transaction is in a prepared state and waiting resolution.'
            WHEN 6 THEN 'The transaction has been committed.'
            WHEN 7 THEN 'The transaction is being rolled back.'
            WHEN 8 THEN 'The transaction has been rolled back.' END
, trn_iso_level = CASE s.transaction_isolation_level
           WHEN 0 THEN 'Unspecified'
           WHEN 1 THEN 'ReadUncommitted'
           WHEN 2 THEN 'ReadCommitted'
           WHEN 3 THEN 'RepeatableRead'
           WHEN 4 THEN 'Serializable'
           WHEN 5 THEN 'Snapshot' END
, transaction_name = tat.name, request_status = r.status
, tst.is_user_transaction, tst.is_local
, session_open_transaction_count = tst.open_transaction_count
, s.host_name, s.program_name, s.client_interface_name, s.login_name, s.is_user_process
FROM sys.dm_tran_active_transactions tat
INNER JOIN sys.dm_tran_session_transactions tst  on tat.transaction_id = tst.transaction_id
INNER JOIN Sys.dm_exec_sessions s on s.session_id = tst.session_id
LEFT OUTER JOIN sys.dm_exec_requests r on r.session_id = s.session_id
CROSS APPLY sys.dm_exec_input_buffer(s.session_id, null) AS ib;

The Advantage of SQLServer ODBC driver SQL_ATTR_ENLIST_IN_XA
Implementing SQLServer XA with the OLEDB driver and ITransactionJoin interface directly communicates with the local distributed transaction controller (DTC) service. In case the SQLServer is running on another host then the local DTC and the DTC on the SQLServer host are involved. The DTC service must communicate over network. RPC, dynamic port ranges, firewall and security settings often makes this very difficult getting it to work.
With the new ODBC SQL_ATTR_ENLIST_IN_XA interace the DTC to DTC communication is no longer needed. The appliction has only a connection to the SQLServer database instance and on the SQLServer host the DTC service must run and the "XA option" must be set in this DTC. The application that utilizes SQL_ATTR_ENLIST_IN_XA doesn't require a local DTC.


text:
Q: Looking for a word for being in multiple places at different time So I am writing content for a health care company, (Doctor's Profiles) they did provide the content but I want it to be a bit professional. So Here's an example but I want the opposite of this. English is not my first language so can't think of a word that would be used here.

Dr. John practices as a Neonatologist at Hospital A and Hospital B and
charges $500 and $600 respectively.

Now if the doctor has the same price at both locations what will be the word that would replace "respectively"?

Dr. John practices as a Neonatologist at the hospital a and hospital b
and charges $500 -word-.

I read this article Looking for a word for being in multiple places at the same time (not bilocate) but I don't think it applies to my situation.


text:
Q: Can we overlap UI elements in watchOS? How can I design table view row like:

I can't overlap UI elements in storyboard so is there any way to design table row like that?

A: You can't overlap objects in storyboard, but you can get creative with groups. You can place your UI elements into a group (or a group within a group) and then set the background image of the group(s) to either be a static image or animate through a set of images which may give the appearance of overlapping objects. Hope this helps!


text:
Q: Multi Inheritance in JavaScript Why this type of inheritance will not work in JavaScript. Is there any way to perform this step.
Please help
function base() {}
base.prototype.findFirst = function() {
    console.log("FindMe First");
}

function base2() {}
base2.prototype.findMe = function() {
    console.log("FindMe ");
}

function inherit() {
    base.call(this);
    base2.call(this);
}

inherit.prototype = base.prototype;
inherit.prototype.constructor = inherit;
inherit.prototype = base2.prototype;
inherit.prototype.constructor = inherit;

var test = inherit();
test.findFirst();
test.findMe();

A: You are overwritting prototype with base.prototype and then with base2.prototype. So it stores base2.prtotype i.e. which is assigned second. Now if you create an instance of your inherit class
var test = new inherit(); you will see that test has base2.property i.e. it has fimeMe() method in test.property.findMe();.
To achieve your goal you should try to extend or refer
Mixin
Multiple Inheritance

A: Mixins can be used in javascript to achieve the same goal you probably want to solve via multiple inheritance at the moment.

A: I've extended the Function prototype which is not the best idea, but to give you an idea of how it works. It's not multi inheritance, but it's an inheritance tree.
Function.prototype.extend = function(child)
{
    var childPrototype = child.prototype;
    child.prototype = Object.create(this.prototype);
    for (var property in childPrototype) {
        if (childPrototype.hasOwnProperty(property)) {
            child.prototype[property] = childPrototype[property];
        }
    }
    child.prototype.constructor = child;
    return child;
};

var base = (function()
{
    var base = function()
    {

    };

    base.prototype.findFirst  = function(x, y)
    {
        console.log("FindMe First");
    };

    return base;

}());

var base2 = base.extend(function()
{
    var base2 = function()
    {

    };

    base2.prototype.findMe = function(x, y)
    {
        console.log("FindMe ");
    };

    return base2;

}());

var inherit = base2.extend(function()
{
    var inherit = function()
    {

    };

    return inherit;

}());

var test = new inherit();
test.findFirst();
test.findMe();


text:
Q: Is there any connection between filter in mathematics and signal processing? The world filter in mathematics is defined as given by: https://en.wikipedia.org/wiki/Filter_(mathematics) On the other hand filtering in signal processing is: https://en.wikipedia.org/wiki/Filter_(signal_processing)
This two definition appears quite different but the question: is there any connection between them even remotely? Specifically, can we say the filtering in signal processing is a subset of "filter" in mathematics? Motivation behind this is that both appears to be a partial ordered set. Any comment would be appreciated.


text:
Q: How can I execute a pip install from git if the branch I need starts with the # sign How can I execute a pip install from git if the branch I need starts with the # sign
I need to not separate it from the link text.
Now it is perceived as a separate sign (from the link)

A: URL-encode it, that is, replace with %23.
https://stackoverflow.com/a/39207995/7976758

A: Solution to bypass this problem: git+http://gitlab.site.com/test@<hash>


text:
Q: Reactjs(Nextjs): Cannot read properties of undefined (reading 'map') Reactjs(Nextjs) I want to ask about this error, I need your help, cause I'm seeing an course from youtube and only me is getting this error and I dont know why.
import Head from 'next/head';
import styles from '../styles/Home.module.css';
import {
    GraphQLClient,
    gql
} from 'graphql-request';
import BlogCard from '../components/BlogCard';

const graphcms = new GraphQLClient("https://api-eu-central-1.graphcms.com/v2/cl3wfrf6agpo701z13eawdfat/master");

const QUERY = gql`

{
  posts{
    id,
    title,
    datePublished,
    slug,
    content{
      html
    }
    author{
      name,
      avatar{
        url
      }
    }
    coverPhoto{
      url
    }
  }
}
`;

export async function getStaticProp() {
    const {
        posts
    } = await graphcms.request(QUERY);
    return {
        props: {
            posts,
        },
        revalidate: 10,
    };
}

export default function Home({
    posts
}) {
    return ( <
        div className = {
            styles.container
        } >
        <
        Head >
        <
        title > Create Next App < /title> <
        meta name = "description"
        content = "Generated by create next app" / >
        <
        link rel = "icon"
        href = "/favicon.ico" / >
        <
        /Head>

        <
        main className = {
            styles.main
        } > {
            posts.map((post) => ( <
                BlogCard title = {
                    post.title
                }
                author = {
                    post.author
                }
                coverPhoto = {
                    post.coverPhoto
                }
                key = {
                    post.id
                }
                datePublished = {
                    post.datePublished
                }
                slug = {
                    post.slug
                } >
                <
                /BlogCard>
            ))
        } <
        /main> < /
        div >
    )
}

I am getting this error and I don't know why
Here is a screenshot of error:

A: The posts variable is probably empty, you might want to add a check before you iterate like below.

 <main className={styles.main} >
 {posts && Array.isArray(posts) && posts.map((post) => (
    <BlogCard
      title={post.title}
      author={post.author}
      coverPhoto={post.coverPhoto}
      key={post.id}
      datePublished={post.datePublished}
      slug={post.slug}
     ></BlogCard>
   ))
}
</main>


text:
Q: What is the difference between karaf running as a service via wrapper and running from console as same user? I'm running a set of applications on Karaf 3.0.1, on Windows Server 2008.  I'm running into a problem with a 3rd party library one of my services depends on.
The karaf installation is running as a dedicated Active Directory service user account.  If I log into the Windows server (using my own login), and open a command prompt as the karaf service user (using run-as), and I start up karaf, all of my processes work correctly.
But I want karaf to run as a Windows service.  I followed the instructions to use the karaf wrapper, and it has installed as a service.  I have it running as the same karaf service user I have used to run it interactively in the console, but whenever it is running from the Windows service, I get a message in the wrapper log that it "could not load or find" my 3rd party library.  I'm not sure if I'm able to disclose the 3rd party library, but I believe it uses JNI for part of it's functionality, if that matters.  There's a dll involved, and there is a copy of this dll in the deploy folder and both of the Windows\system32 / syswow64 folders for completeness.  I've given full rights to the entire karaf folder to the karaf service user as well.
This seems like some sort of permissions issue, or that the wrapper service config is missing something but I don't see anything jumping out at me.  What else would be different between karaf running as the service vs running it from the console with the same user credentials?  Any other ideas?

edit: After going through further documentation on the wrapper I ended up placing my dll in the \lib folder under my karaf installation.  After that my application appears to work.

A: Depending on the type of your dll, it might be because the provided service wrapper is a 32-bit only wrapper, this is because of licensing issues of the Tanuki Service Wrapper.
So using the dll might work when starting with bin/karaf instead of using the service.
If you want to use the Tanuki Wrapper you should be able to use it installing it by yourself. The latest and greatest version of it, just can't be shipped due to licensing issues.


text:
Q: How to perform Cumulative sum based on groupby() output in Python Below is the data in which I am facing the issue:
dict_1 = {'id' : [101, 101, 101, 101, 101, 102, 102, 102, 102, 103, 103, 103, 103, 103, 103, 104, 104, 104,
                  104, 104, 104, 104, 104, 104, 105, 105, 105, 105, 105],
          'electronics' : ['Mobile', "Laptop", "Laptop", "Laptop", "TV", 'Mobile', "Laptop", 'Mobile', "TV",
                           'Mobile', "Laptop", 'Mobile', "Laptop", "Mobile", "TV", 'Mobile', "Laptop", "TV",
                           'Mobile', "Laptop", "TV",'Mobile', "Laptop", "TV", 'Mobile', "Laptop", "TV", "Laptop", "TV",],
          'date' : ['2022-05-30', '2022-05-30', '2022-05-30', '2022-05-30', '2022-05-30', '2022-05-31', '2022-05-31',
                    '2022-05-31', '2022-05-31', '2022-06-01', '2022-06-01', '2022-06-01', '2022-06-01', '2022-06-01',
                    '2022-06-01', '2022-06-02', '2022-06-02', '2022-06-02', '2022-06-02', '2022-06-02', '2022-06-02',
                    '2022-06-02', '2022-06-02', '2022-06-02', '2022-06-03', '2022-06-03', '2022-06-03','2022-06-03', '2022-06-03']}
test = pd.DataFrame(dict_1)
test.head(7)

id
electronics
date

101
Mobile
2022-05-30

101
Laptop
2022-05-30

101
Laptop
2022-05-30

101
Laptop
2022-05-30

101
TV
2022-05-30

102
Mobile
2022-05-31

102
Laptop
2022-05-31

I need to find Cumulative sum of ID(Count) based on Month i.e. if the month end then it should start with 0.
I have used below code to find cumulative sum of the above data
grp_by = test.groupby(['electronics', 'date'])['id'].count().groupby(level=0).cumsum().reset_index()
grp_by.head()

electronics
date
id

Laptop
2022-05-30
3

Laptop
2022-05-31
4

Laptop
2022-06-01
6

Laptop
2022-06-02
9

Laptop
2022-06-03
11

Till date = 2022-05-31 data is working correctly however for 2022-06-01 value should be 2(because new month and there are 2 Laptop) and for 2022-06-02 value should be 5 and so on.

A: Let us try two groupby's
s = test.groupby(['electronics', 'date'], as_index=False).size()
s['size'] = s.groupby(['electronics', s['date'].str[:7]]).cumsum()

print(s)

   electronics        date  size
0       Laptop  2022-05-30     3
1       Laptop  2022-05-31     4
2       Laptop  2022-06-01     2
3       Laptop  2022-06-02     5
4       Laptop  2022-06-03     7
5       Mobile  2022-05-30     1
6       Mobile  2022-05-31     3
7       Mobile  2022-06-01     3
8       Mobile  2022-06-02     6
9       Mobile  2022-06-03     7
10          TV  2022-05-30     1
11          TV  2022-05-31     2
12          TV  2022-06-01     1
13          TV  2022-06-02     4
14          TV  2022-06-03     6

A: you can create a month column and then include in the groupby. you can always drop the month column afterwards
test['yearmonth'] = test['date'].astype('datetime64').dt.strftime('%Y%m')
test.groupby(['electronics', 'yearmonth', 'date'])['id'].count().groupby(level=1).cumsum().reset_index()

    electronics     month   date    id
0   Laptop  202205  2022-05-30  3
1   Laptop  202205  2022-05-31  4
2   Laptop  202206  2022-06-01  2
3   Laptop  202206  2022-06-02  5
4   Laptop  202206  2022-06-03  7

thanks you @creanion, you have a valid point, i updated it


text:
Q: Connecting UCM with Apache server on another machine I am trying to connect to my content server(UCM) using apache server installed in another machine.
In more short notation ,i want to use apache server of another machine to login to my system's content server (UCM)
Any kind of help would be of great use

A: I got my answer and I thought it would be nice to tell this to others too,
so I found the following link
https://docs.oracle.com/cd/E12839_01/core.1111/e12037/contentsvr.htm#BGBDDCFF
Here in section 9.4 , you can go through what is to be done.
For avoiding confusion, in this section WCHOST is local machine and WEBHOST is remote one.
Thanks


text:
Q: Hypothesis testing and confidence interval The log return $X$ on a certain stock investment is an $N(\mu,\sigma^2)$ random variable.
A financial analyst has claimed that the volatility $\sigma$ of the log return on this stock is less than $3$ units. A random sample of $11$ returns on this stock gave an estimated variance of the log-returns as $s^2 = 16$.

*

*Assess the analyst's claim by using a significance test at level $\alpha = 0.05$ to test
$H_0: \sigma^2 \leq 9 \text{ against } H_1: \sigma^2 > 9.$

*Find a two-sided $95\%$ confidence interval for $\sigma^2$.

A: Since log returns is normally distributed the sample variance $S^2$ has a distribution that is proportional to a chi-square with $n-1$ degrees of freedom.  So precisely stated
$(n-1)S^2/σ^2$ has a chi square distribution with $n-1$ degrees of freedom.  So for the above test use
$(n-1)S^2/9$ as the test statistic and use the chi square distribution with $n-1$ degrees of freedom to get the test results.
In your case n-1 =10.

A: Since
$$
\frac{(n-1)S^2}{\sigma^2} = \frac{10 S^2}{\sigma^2} \sim \chi^2_{11-1} = \chi^2_{10},
$$
you have
$$
\Pr\left( A < \frac{(n-1)S^2}{\sigma^2} < B\right) = 0.95
$$
where $A$ and $B$ are so chosen that
$$
\Pr(\chi^2_{10}<A) = 0.025 = \Pr(\chi^2_{10}>B).
$$
(You can get $A$ and $B$ from tables or software.)
Via simple algebra it follows that
$$
\Pr\left( \frac 1 B < \frac{\sigma^2}{10S^2} < \frac 1 A   \right) = 0.95,
$$
whence
$$
\Pr\left( \frac {10S^2}{B} < \sigma^2 < \frac{10S^2}{A}   \right) =0.95.
$$
So there's your confidence interval.
If $9$ is less than the lower end of this confidence interval, you'd reject the null hypothesis at the 2.5% level.  So instead of half of 5% that we used above, use half of 10%, and that will tell you whether to reject the null hypothesis at the 5% level.


text:
Q: Spring inside war cannot find classpath resource in an inner jar file I have a project organized like this:
core
  -- /src/main/resources/company/config/spring-config.xml
webapp
  -- /WEB-INF/applicationContext.xml

The webapp depends on core.jar, which is included correctly in WEB-INF/lib when I deploy.
In web.xml I have:
<param-value>
    /WEB-INF/applicationContext.xml
</param-value>

And in applicationContext.xml I have:
<import resource="classpath:/company/config/spring-config.xml" />

But when I run, I get this error:
2012-10-04 20:03:39,156 [localhost-startStop-1] springframework.web.context.ContextLoader ERROR: Context initialization failed
org.springframework.beans.factory.parsing.BeanDefinitionParsingException: Configuration problem: Failed to import bean definitions from URL location [classpath:/company/config/spring-config.xml]
Offending resource: ServletContext resource [/WEB-INF/applicationContext.xml]; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from class path resource [company/config/spring-config.xml]; nested exception is java.io.FileNotFoundException: class path resource [company/config/spring-config.xml] cannot be opened because it does not exist
    at org.springframework.beans.factory.parsing.FailFastProblemReporter.error(FailFastProblemReporter.java:68)
....
Caused by: java.io.FileNotFoundException: class path resource [company/config/spring-config.xml] cannot be opened because it does not exist
    at org.springframework.core.io.ClassPathResource.getInputStream(ClassPathResource.java:142)
    at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:336)
... 36 more

When spring-config.xml is in webapp, everything works fine.
I noticed the leading / is removed from some of the errors on the stack trace, and I wonder if this has anything to do with it.
Also, I am (unfortunately) using Spring 2.5, if that matters.

A: For future reference, I figured out the problem after much debugging. It turns out Eclipse was building my "core" library as a jar, but with a web application package layout, so instead of my resource being located here:
/company/config/spring-config.xml

it was located here:
/WEB-INF/company/config/spring-config.xml

which caused the problem. I had checked the jar a few times before, but had never noticed the sneaky "/WEB-INF" hiding in plain sight.
Removing the project and re-importing it into Eclipse (via the Maven pom.xml file) was not enough to fix the problem.
I had to manually delete the Eclipse-specific .project, .classpath, and .settings files. When I did that and re-imported the project everything was fixed.
The moral of the lesson is: ALWAYS check your resource paths when the exception says "File Not Found".


text:
Q: Toad for Mysql gives error on Compare I've posted this message on Toad World looking for help but no one has answered.  So I'm trying here.
I repeatedly get the same error while using any of the Compare options when connecting to a remote host.  In this specific case it is a HostGator server.  I did create a support ticket with them, they refereed me to my unanswered Toad World forum post.
The error is:  Keyword not supported: 'btkkw;pooling'.
I am using Toad for MySQL 7.5.0.966.  This has been happening for a the past month or more.  I noticed it while running 7.3.x, updating hasn't helped.  Deleted the remote profile but that didn't help either.
Otherwise I can connect to the remote server with no problems, view the db, make changes and export without problems.
Can somebody please help me with this problem?  Maybe make some suggestions?


text:
Q: How can I retrieve a value in jquery with a button click? I have the following code:
jQuery
$(document).ready(function(){
    $('input[name="new_tax_button_post_tag"]').click(function(){
        value = $('input[name="post_tag"]').val();
        $("#fieldID3").val(value);
    });
});

and I want it change:
HTML
 <input type="text" id="fieldID3" name="changeme"value="n/a">

The problem is that the click itself is what creates the value, so I have to click the button twice to get the desired results. The first click creates the value. The second click sets the value in the field.
How do I make it so that it does it in one click?
It's like which came first the chicken or the egg.....

A: I write jquery on the basis of ID of button and textbox,
and also remove value from following input field,
<input type="text" id="fieldID3" name="changeme">

$(document).ready(function(){
    $("#new_tax_button_post_tag").click(function(){
        value = $("#post_tag").val();
        $("#fieldID3").val(value);
    });
});

I hope this useful for you.


text:
Q: Functions of a random variable Assume that $Y$ ~ $Exp(Ω)$. Find the cdf and pdf of $Z$ = |$Y$ - $δ$|.
In order to solve this question so far, for $Y$, I am thinking about using the pdf equation for the exponential distribution i.e. $f(Y)$ = $Ωexp(-Ωx)$ for $x$ > $0$ and $0$ for $x$ < 0. But that is only $Y$, whereas furthermore $Z$ it is shifted by $δ$ to the left and is the absolute value function. Please help me on how to work out the cdf and pdf for this.

A: In my opinion, it is easier to start by the cdf. Let $z\in\mathbb{R}$.
$P(Z\leq z)=P(|Y-\delta |\leq z)=P(\delta - z\leq Y\leq \delta+z)=F_Y(\delta+z)-F_Y(\delta -z)$
where $F_Y(y)=(1-\exp(-\Omega y))\mathbf{1}_{y\geq 0}$ is the cdf of $Y$.


text:
Q: Unable to parse the rows in ResultSet returned by connection.execute(), Python and SQLAlchemy I have a task to compare data of two tables in two different oracle databases. We have access of views in both of db. Using SQLAlchemy ,am able to fetch rows from views but unable to parse it.
In one db the type of ID column is : Raw
In db where column type is "Raw", below is the row am getting from resultset .
(b'\x0b\x975z\x9d\xdaF\x0e\x96>[Ig\xe0/', 1, datetime.datetime(2011, 6, 7, 12, 11, 1), None, datetime.datetime(2011, 6, 7, 12, 11, 1), b'\xf2X\x8b\x86\x03\x00K|\x99(\xbc\x81n\xc6\xd3', None, 'I', 'Inactive')
ID Column data: b'\x0b\x975z\x9d\xdaF\x0e\x96>[_Ig\xe0/'
Actual data in ID column in database: F2588B8603004B7C9928BC816EC65FD3
This data is not complete hexadecimal format as it has some speical symbols like >|[_ etc. I want to know that how can I parse the data in ID column and get it as a string.

A: bytes.hex() solved the problem


text:
Q: Python Click: Exception Handling under setuptools I have a python click application that works great, but I want to be notified whenever a user types in an unknown command. For example, if mycli foo is valid, but they type in mycli bar, I want to override the default exception handling behavior and fire off an error to an error tracker, such as rollbar.
I found this page which describes how to override the exception handling, but it assumes I have a Command. The problem I've run into is that I've also integrated with setuptools by following this guide, and it points to my Command in the [console_scripts] section. For example, yourscript=yourscript:cli points to the cli command.
I'm not sure how to call cli.main() from within [console_scripts] or if that's even the right way of thinking about it.

A: With a custom click.Command class, you can capture the invoking command line and then report any error in the command line in an exception handler using a custom class like:
Custom Class
def CatchAllExceptions(cls, handler):

    class Cls(cls):

        _original_args = None

        def make_context(self, info_name, args, parent=None, **extra):

            # grab the original command line arguments
            self._original_args = ' '.join(args)

            try:
                return super(Cls, self).make_context(
                    info_name, args, parent=parent, **extra)
            except Exception as exc:
                # call the handler
                handler(self, info_name, exc)

                # let the user see the original error
                raise

        def invoke(self, ctx):
            try:
                return super(Cls, self).invoke(ctx)
            except Exception as exc:
                # call the handler
                handler(self, ctx.info_name, exc)

                # let the user see the original error
                raise

    return Cls

def handle_exception(cmd, info_name, exc):
    # send error info to rollbar, etc, here
    click.echo(':: Command line: {} {}'.format(info_name, cmd._original_args))
    click.echo(':: Raised error: {}'.format(exc))

Using the custom class
Then to use the custom command/group, pass it as the cls argument to the click.command or click.group decorator like one of:
@click.command(cls=CatchAllExceptions(click.Command, handler=report_exception))

@click.group(cls=CatchAllExceptions(click.Group, handler=report_exception))

@click.group(cls=CatchAllExceptions(click.MultiCommand, handler=report_exception))

Note the need to specify which click.Command subclass is required as well as
the handler to send the exception information to.
How does this work?
This works because click is a well designed OO framework. The @click.group() and @click.command() decorators usually instantiates a click.Group or click.Command objects, but allows this behavior to be over ridden with the cls parameter. So it is a relatively easy matter to inherit from click.Command (etc) in our own class and over ride desired methods.
In this case we over ride click.Command.make_context() to grab the original command line, and click.Command.invoke() to catch the exception and then call our exception handler.
Test Code:
import click

@click.group(cls=CatchAllExceptions(click.Group, handler=report_exception))
def cli():
    """A wonderful test program"""
    pass

@cli.command()
def foo():
    """A fooey command"""
    click.echo('Foo!')

if __name__ == "__main__":
    commands = (
        'foo',
        'foo --unknown',
        'foo still unknown',
        '',
        '--help',
        'foo --help',
    )

    import sys, time

    time.sleep(1)
    print('Click Version: {}'.format(click.__version__))
    print('Python Version: {}'.format(sys.version))
    for cmd in commands:
        try:
            time.sleep(0.1)
            print('-----------')
            print('> ' + cmd)
            time.sleep(0.1)
            cli(cmd.split())

        except BaseException as exc:
            if str(exc) != '0' and \
                    not isinstance(exc, (click.ClickException, SystemExit)):
                raise

Results:
Click Version: 6.7
Python Version: 3.6.3 (v3.6.3:2c5fed8, Oct  3 2017, 18:11:49) [MSC v.1900 64 bit (AMD64)]
-----------
> foo
Foo!
-----------
> foo --unknown
Error: no such option: --unknown
:: Command line: test.py foo --unknown
:: Raised error: no such option: --unknown
-----------
> foo still unknown
:: Command line: test.py foo still unknown
:: Raised error: Got unexpected extra arguments (still unknown)
Usage: test.py foo [OPTIONS]

Error: Got unexpected extra arguments (still unknown)
-----------
>
Usage: test.py [OPTIONS] COMMAND [ARGS]...

  A wonderful test program

Options:
  --help  Show this message and exit.

Commands:
  foo  A fooey command
-----------
> --help
Usage: test.py [OPTIONS] COMMAND [ARGS]...

  A wonderful test program

Options:
  --help  Show this message and exit.

Commands:
  foo  A fooey command
-----------
> foo --help
Usage: test.py foo [OPTIONS]

  A fooey command

Options:
  --help  Show this message and exit.


text:
Q: How to monitor different events in 3rd party applications I am developing a C# application. I am looking for a way to monitor different events in 3rd party applications.
Example 1: Calculator is running, and I want to know when the user has clicked on "=" button.
Example 2: Skype is running and I want to monitor when the user hits the "Call" button.
Example 3: Word is running and I want to monitor when the user opens the "Font" drop down list.
I am not looking for simple Mouse or Keyboard events.

A: Take a look at EventSpy, Both of those seams to do what you need.
http://www.codeproject.com/Articles/11918/EventSpy
http://eventspy.codeplex.com/

A: You basically need to tap into the "Windows Messaging" loop.  In order to properly filter the GAZILLION messages that come flying through you'll also need to be able to periodically scan through all of the active windows to see which ones (if any) are relevant to you.
Be aware that this whole subsystem of windows is a GIANT security hole.  (I have not worked with it much since NT4 / W95/W98 days so they might have tried attempts to "secure" it since then so it might be even harder to get to than it used to be.
You're going to need a good ide / 3rd party tools to help you get started on your way to have some idea of what you're looking for.
In a "previous" life we used this basic technique to get ~4,000 workstations to install their own software, updates, patches, etc through monitoring for existence of certain windows, controls, etc and "injecting" messages into the Windows Messaging loop to control Application Setup Programs, configuration changes that were not stored in the registry, etc, etc...


text:
Q: ImportError when trying to run a python unittest with pydev I am getting the following error when trying to run a module as a python unittest with PyDev.
Finding files...
['C:\\Projectos\\spa\\sensor\\src\\test\\test_sensor.py'] ... done
Importing test modules ... Traceback (most recent call last):
  File "C:\eclipse\plugins\org.python.pydev.debug_1.6.3.2010100513\pysrc\runfiles.py", line 342, in __get_module_from_str
    mod = __import__(modname)
ImportError: No module named :\Projectos\spa\sensor\src\test\test_sensor
ERROR: Module: :\Projectos\spa\sensor\src\test\test_sensor could not be imported.
done.

I noticed the path in the ERROR: Module: line starts with ":\" but I don't know what's causing it.
Any ideas?
Thank you.

A: Turns out pydev does not play well with cygwin's python.
Installed python 2.7 for windows and it works.


text:
Q: Exponencial mantissa I try to compute a function of type $e^x$. Since its natural fast-growing behaviour, the most natural behaviour is to decompose the resulting number into its mantissa and exponent components. However, due limited computational precision, one may not compute the prior exponential due numerical issues.
Henceforth, the statement follows: find a, b for given x in $x = ln \, a + b \, ln \, 10$, $a \in \mathbb{R}$, $b \in \mathbb{N}$.
I thank in advance.


text:
Q: If JSON contains $myid then (Perl) I'm trying to loop through JSON:
my $cards = $json_obj->decode( $jsoncards->content );
foreach my $card ( @$cards )
            {
                    print Dumper $card->{idMembers};
                    if ( $card->{idMembers} =~ $myid )
                    {
                            print $card->{name} . "\n";
                    }
            }

The output from print Dumper $card->{idMembers}; is:
$VAR1 = [
      '50e442a195105cde670743e4',
      '50fd66804825017002070285',
      '50f71f02a30d2a8c0d07d10d'
    ];

How do I compare to those ids?

A: The bind operator =~ treats its LHS as a string and the RHS as a pattern. The stringification of an arrayref looks like ARRAY(0x12ABF14), so this isn't useful.
We have two possibilities to match the $myid against each member of the array:

*

*The grep EXPR, LIST builtin. Selects all elements where the expression returns a true value. If the count of the returned items is ≥ 1, then a matching element was found.
if ( grep $myid eq $_, @{ $card->{idMembers} }) { do stuff }
# or: grep /\Q$myid/, ... if you don't want string equality

*Use the smartmatch operator ~~ in the member-of meaning:
if ( $myid ~~ $card->{idMembers} ) { do stuff }

This is subjects to multiple caveats: (1) It is only usable since v10.1. Therefore, code using smartmatch should at least use 5.010001. (2) Smartmatch was re-labeled as experimental in the latest release of perl, and may change without much notice. (3) If the idMembers entry is not an array, smartmatch may hide the error.
Smartmatch depends on the type of both operands. If you want to select all entries that contain $myid as a substring, you should probably pass it as a regex object: qr/\Q$myid/ ~~ .... Otherwise, it will likely test for equality


text:
Q: ImgBurn and adware, where is a safe place to download it? ImgBurn has adware in it!
I just used it and now all my google results are redirecting to those ad like pages.
Where is a safe place to get it from?
I used betanews: http://fileforum.betanews.com/detail/ImgBurn/1128426215/1 (dont install from here!)

A: I just used the betanews mirror and installed it for fun, there is no adware in it as far as I and my anti-malware programs can see. My google searches are not redirected in any browser - though of course that doesn't mean everything is fine, with computer software one can never really truly know ^^
Perhaps you clicked the fake download link of an advertisement on the site, instead of the imgburn download link?

A: No it doesn't. I just binary compared the BetaNews one you linked to, to http://download.imgburn.com/SetupImgBurn_2.5.0.0.exe and they're identical.
I suspect your adware has come from somewhere else, or you clicked the wrong link.
By the way the official site is http://www.imgburn.com/

A: Try their website. They have tons of mirrors.
List of mirrors
I've never used imgburn before, but I use powerISO. I know it doesn't come with adware


text:
Q: Connect to server within open source application What is the best, most secure way to connect to a server such as a mysql server, from within a program that's source code will be released? I'm trying to keep from just giving out an ip address. Sorry if this is a bad or simple question, I am really new to network centered programming.

A: You can have a file that holds that info and then the program just reads from there, or you can have that info in a source code file that you include in the main program. Just don't share them with the rest of the source code and you're set ;)
e.g.
readDataFromFile("confidential.dat")
or
#include "confidential.h"
(...)

A: You would do this the same way you would make pi into a rational number. You can't make an IP address in a distributed program a secret. 'netstat' if nothing else will reveal it as soon as the program makes a connection to your server.


text:
Q: Proving convergence of $(a_n)$ given $|a_n-a_{n-1}|<2^{-n}$ for all $n \in \mathbb{N}$ I'm trying to prove the convergence of $(a_n)$ given $|a_n-a_{n-1}|<2^{-n}$ for all $n \in \mathbb{N}$. I think this is related to Cauchy's Criterion and how one may choose $n$ such that $2^{-n}<\varepsilon$ for any $\varepsilon > 0$, but I am not sure how to proceed from here. Thank you in advance for the help!

A: \begin{align*}
|a_{m}-a_{n}|&=|a_{m}-a_{m-1}+\cdots+a_{n+1}-a_{n}|\\
&\leq|a_{m}-a_{m-1}|+\cdots+|a_{n+1}-a_{n}|\\
&<\dfrac{1}{2^{m+1}}+\cdots+\dfrac{1}{2^{n+1}}\\
&<\dfrac{1}{2^{n+1}}+\cdots\\
&=\dfrac{1}{2^{n}}
\end{align*}
for $m>n$, can you finish from here?


text:
Q: Static child rows (additional info) in DataTables in Twig-Template I'm using Symfony2 with Doctrine, Twig and DataTables. In a DataTable an overview of my entites are shown, with basic information. On click on a row I want to show additional information of the entity, as you can see here.
Here is the code (where applications is a Collection of my doctrine entities):

                    {% for application in applications %}

                                {{ application.name }}

                                {{ application.company.name | default("") }}

                                {{ application.events.count }}

                                {{ application.dateCreate | date('d.m.Y')  }}

                                {% if application.dateSent %}
                                    {{ application.dateSent | date('d.m.Y')  }}
                                {% else %}
                                    {{ application.readableStatus(constant('APPLICATION_STATUS_OPEN', application)) }}
                                {% endif %}

                    {% endfor %}

The documentation says an ajax call would be used for getting the data. But since I already have the information of my entity, I don't want to used AJAX but rather create the child rows from the beginning. What would be the best practise for this? As you can see I tried to savethe json encoded entity in the data-tag, so I can read it in the javascript function (see format function in DataTables documentation.

A: You dont have to use the approach from the docs, it is just a suggestion.  You can simply inject the content of data-child-information into the details row :
$('#example tbody').on('click', 'td.details-control', function () {
    var tr = $(this).closest('tr');
    var row = table.row( tr );

    if ( row.child.isShown() ) {
       // This row is already open - close it
       row.child.hide();
       tr.removeClass('shown');
    }
    else {
       // Open this row
       row.child(tr.attr('data-child-information')).show();
       tr.addClass('shown');
    }
});

"work from home" demo ->  http://jsfiddle.net/mgmL0f8c/


text:
Q: How do i install pygame in python3.8? Collecting pygame
Using cached pygame-1.9.6.tar.gz (3.2 MB)
ERROR: Command errored out with exit status 1:
command: /usr/bin/python3 -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-lva53fx4/pygame/setup.py'"'"'; file='"'"'/tmp/pip-install-lva53fx4/pygame/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(file);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' egg_info --egg-base /tmp/pip-install-lva53fx4/pygame/pip-egg-info
cwd: /tmp/pip-install-lva53fx4/pygame/
Complete output (29 lines):
WARNING, No "Setup" File Exists, Running "buildconfig/config.py"
Using UNIX configuration...

/bin/sh: 1: sdl-config: not found
/bin/sh: 1: sdl-config: not found
/bin/sh: 1: sdl-config: not found
Package freetype2 was not found in the pkg-config search path.
Perhaps you should add the directory containing `freetype2.pc'
to the PKG_CONFIG_PATH environment variable
No package 'freetype2' found
Package freetype2 was not found in the pkg-config search path.
Perhaps you should add the directory containing `freetype2.pc'
to the PKG_CONFIG_PATH environment variable
No package 'freetype2' found
Package freetype2 was not found in the pkg-config search path.
Perhaps you should add the directory containing `freetype2.pc'
to the PKG_CONFIG_PATH environment variable
No package 'freetype2' found
/bin/sh: 1: freetype-config: not found
/bin/sh: 1: freetype-config: not found
/bin/sh: 1: freetype-config: not found

Hunting dependencies...
WARNING: "sdl-config" failed!
WARNING: "pkg-config freetype2" failed!
WARNING: "freetype-config" failed!
Unable to run "sdl-config". Please make sure a development version of SDL is installed.
----------------------------------------

ERROR: Command errored out with exit status 1:

A: for this moment there is no official version. There is a dev version:
pip install pygame==2.0.0.dev6

but I recommend you go back to 3.7 and wait.

A: Use this
sudo apt-get install python3-pygame


text:
Q: LOGIN into facebook or google from another domain I there anyway to log users to facebook and google gmail, from another domain site?
Or are there specific API to do that?
I'm not talking about fb login or connect or google login API, i'm talking about "triggering" login forms in some whay or launch requests to sites to login in users.
I would like to make users able to log to facebook from another site, setting up cookies, so when he will return to facebook he will be logged, and viceversa.
And if is there, is it legal or not?
Thanks

A: Thats not possible, since Facebook are the ones that issue the cookies, I think it might be possible to generate a cookie that will log you into Facebook, but it would be illegal. Swift


text:
Q: nonlinear Poisson equation - finite elements I am kind of new in finite elements and I am solving simple "Poisson nonlinear" problem.
$- \nabla ((1 + u^2) \nabla u) = f$
$u = 0 \ \text{on} \  \Omega $
I am using Newton solver, where I have defined step as following
$J = s * ( -g )$,
where  $ J = \int (2 \delta u \nabla u_h) \nabla v + (( 1 + u_h^2) \nabla \delta u ) \nabla v  dx $
and
g = $\int (1 + u^2 ) \nabla u \nabla v - f v \ dx$.
I would like to check my solution and monitor energy, however I am bit stuck here. I know that in linear case it would be QP function, but how is my strain energy function defined here?


text:
Q: cmake FetchContent_Declare: Is there a way to have FetchContent not bring in the git repo submodules? I use FetchContent in my CMakeLists.txt to bring in a git repo I need for my build. Everything works fine. However, it also brings in a (large) submodule I don't need for the build. It seems that content fetching will update the submodules even if GIT_SUBMODULES "" argument is not present under FetchContent_Declare.
So, how do I achieve that? cmake's documentation isn't very clear for this use case.


text:
Q: How to track iteration progress using Rally's Web Services API I am writing a custom app to track iteration progress by day. Is there a builtin way in Rally to get the number of user stories that are in the "Accepted" state for a specific date, and the number of points (or do I have to get all user stories and parse their revision histories)?

A: There is IterationCumulativeFlowData object in WS API, which is populated at midnight of the Workspace Timezone when the Data Collection runs on workdays specified in the Workspace Setup screen.
Data is stored for each day of the Iteration and a corresponding state.  There is CumulativeFlowData object for Day 1 of the Iteration for everything in a Defined state, Day 1 of Release for everything in an In-Progress state, etc.
The CumulativeFlowData object also stores CardEstimateTotal which is the sum of the estimates of cards in every state.
Here is a example of an app written with rally-node that returns iteration data for specific state (Accepted) as of the last day of the iteration.
In this examle the CreationDate of the last result is '2013-08-27T06:00:00.000Z, while the EndDate of the iteration in question was 2013-08-27 11:59:59 PM America/Denver (which is 2013-08-28T05:59:59.000Z), so I had to manipulate a date in order to make this query condition return the data for the last day of the iteration:
query = query.and('CreationDate', '>', endDateMinusOneDay);

Here is the full js file of the example:
var rally = require('rally'),
    queryUtils = rally.util.query,
    restApi = rally({
        user: 'user@co.com',
        pass: 'secret',
        apiVersion: 'v2.0',
        server: 'https://rally1.rallydev.com',
        requestOptions: {
            headers: {
                'X-RallyIntegrationName': 'My cool node.js program',
                'X-RallyIntegrationVendor': 'My company',
                'X-RallyIntegrationVersion': '1.0'
            },
        }
    });

 function findIteration() {
    return restApi.query({
        type: 'Iteration',
        start: 1,
        pageSize: 2,
        limit: 10,
        fetch: ['ObjectID', 'EndDate'],
        scope: {
            project: '/project/12352608219',
            up: false,
            down: false
    },
        query: queryUtils.where('Name', '=', 'i777')
    });
}

function queryIterationData(result) {
    var endDate = result.Results[0].EndDate,
        oid = result.Results[0].ObjectID;

    console.log('endDate',endDate);

    var date1 = new Date(endDate);
    var ms = date1.getTime() - 86400000; //86400000 is the number of milliseconds in a day
    var date2 = new Date(ms);
    var endDateMinusOneDay = date2.toISOString();
    console.log('date2 ISO', date2.toISOString());

    var query = queryUtils.where('IterationObjectID', '=',oid );
    query = query.and('CardState', '=', 'Accepted');
    query = query.and('CreationDate', '>', endDateMinusOneDay);

    return restApi.query({
        type: 'IterationCumulativeFlowData',
        fetch: ['CardCount', 'CardEstimateTotal', 'CardState', 'CardState', 'CreationDate'],
        query: query,
    });
}

function onSuccess(result) {
    console.log('Success!', result);
}

function onError(errors) {
    console.log('Failure!', errors);
}

findIteration()
    .then(queryIterationData)
    .then(onSuccess)
    .fail(onError);

It returns:


text:
Q: Google API and OAuth 2.0 I'm trying to use google calendar API with php library and i'm facing issues on the authentification of the user to the google api.
I have a question. I've seen some come where you had to set the Api key / developer key to the Google_Client object with the method setDeveloperKey(), but i've also seen some people who don't. Could someone explain to me what difference does it make ?
The thing i'd like to do is to connect a user who have a google account to my application so he can add, list, remove, etc, events from a calendar. This is what i'm doing for the moment for the authentification :
$client = new Google_Client();
$client->setApplicationName("Test GCAL");
$client->setClientId($clientid);
$client->setClientSecret($clientsecret);
$client->setRedirectUri($callback_url);
$client->setAccessType("offline");
$client->setApprovalPrompt("force");

$client->setScopes("https://www.googleapis.com/auth/calendar");
$service = new Google_Service_Calendar($client);

Am i doing it right ?
Does someone have a working commented code that i can analyse ? I can't find one that's working on the internet.. Or maybe a tutorial that explain everything about google api and oauth stuff. I'm so confused about tokens and nobody seems to use refresh tokens, and to me that's essential.. But maybe i'm wrong ?
Thanks for your answers

A: I don't think you NEED to use setDeveloperKey I suspect that its only used for public APIs to enable you to use them but I haven't really tested it or thought about it before.  I will have to look into that a bit more.
This is the code I use for connecting to Google Calendar with Oauth2.  ripped directly from the Accessing Google Calendar with PHP – Oauth2 tutorial
<?php
require_once 'Google/Client.php';
require_once 'Google/Service/Calendar.php';
require_once 'CalendarHelper.php';
session_start();
$client = new Google_Client();
$client->setApplicationName("Client_Library_Examples");
$client->setDeveloperKey("AIzaSyBBH88dIQPjcl5nIG-n1mmuQ12J7HThDBE");
$client->setClientId('2046123799103-i6cjd1hkjntu5bkdkjj5cdnpcu4iju8p.apps.googleusercontent.com');
$client->setClientSecret('6s4YOx3upyJhtwnetovfK40e');
$client->setRedirectUri('http://localhost/google-api-php-client-samples/Calendar/oauth2Pure.php');
$client->setAccessType('offline');   // Gets us our refreshtoken

$client->setScopes(array('https://www.googleapis.com/auth/calendar.readonly'));

//For loging out.
if (isset($_GET['logout'])) {
    unset($_SESSION['token']);
}

// Step 2: The user accepted your access now you need to exchange it.
if (isset($_GET['code'])) {

    $client->authenticate($_GET['code']);
    $_SESSION['token'] = $client->getAccessToken();
    $redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
    header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
}

// Step 1:  The user has not authenticated we give them a link to login
if (!isset($_SESSION['token'])) {

    $authUrl = $client->createAuthUrl();

    print "Connect Me!";
}
// Step 3: We have access we can now create our service
if (isset($_SESSION['token'])) {
    $client->setAccessToken($_SESSION['token']);
    print "LogOut
";

    $service = new Google_Service_Calendar($client);

    $calendarList  = $service->calendarList->listCalendarList();;
    print_r($calendarList);
    while(true) {
        foreach ($calendarList->getItems() as $calendarListEntry) {
            echo $calendarListEntry->getSummary()."
\n";
        }
        $pageToken = $calendarList->getNextPageToken();
        if ($pageToken) {
            $optParams = array('pageToken' => $pageToken);
            $calendarList = $service->calendarList->listCalendarList($optParams);
        } else {
            break;
        }
    }
}
?>


text:
Q: No Bundle URL Present Error Getting no bundle error while trying to run react-native app on iOS device.
I created a sample app which works on the simulator, but when i try to run on the device i get the No Bundle Error.
NO Bundle URL
i tried various options like,

*

*Editing the info.plist for NSAllowsLocalNetworking

*ran npm-install again and linking

but nothing works. I am not able to figure out where the problem arises

A: I solved this problem by adding 127.0.0.1 localhost to /etc/hosts.
Please check if you have such line there.

A: Its a simple solution

*

*Go to iOS folder

*Delete the build folder

*Re run the project from root directory of project 'react-native run-ios'

It will work like a charm

A: I had the same issue and I was able to bypass it by run npm start before run react-native run-ios.

A: You can try running the application directly from the Xcode, also follow the below steps:-

*

*For now, disable "Debug JS Remotely".

*Also, go in the project directory and run "npm start" or "react-native start" command on terminal.

A: I know its an old question but in Future if someone face this issue i have found a work around to this problem.

*

*after running "react-native run-ios" command

*Run another command "npm start"

*after running above command you will "Loading dependency graph" wait for 2 or three seconds and you will see thisLoading dependency graph, done.

*now press cmd+R OR you may tap on reload on screen if problem not solved do step 4 2.. to 3 times


text:
Q: dynamically assigning an event I am dynamically creating a GroupBox and trying to assign the MouseLeftButtonDown event to it to perform some action when the user left-clicks on it. This is what I've tried:
public MyClass()
{
    tagGroupBox.MouseLeftButtonDown += new MouseButtonEventHandler(tagGroupBox_MouseLeftButtonDown);  //generates error: "tagGroupBox_MouseLeftButtonDown does not exist in the current context"
}

private void tagGroupBox__MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
     MessageBox.Show("Left click event triggered");
}

A: There are __ (double underscores) in handler method.
void tagGroupBox_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
}

A: This works for me:
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();

        GroupBox g = new GroupBox();
        g.MouseLeftButtonUp += new MouseButtonEventHandler(g_MouseLeftButtonUp);
        MainGrid.Children.Add(g);
    }

    void g_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
    {
        System.Diagnostics.Debugger.Break();
    }
}

XAML
<Window x:Class="WpfApplication1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525">
    <Grid x:Name="MainGrid">

    </Grid>
</Window>


text:
Q: How to rewriting url to split the last path by "dot" and redirect to a query string by splitted items? I have a whois form that works with get query string and make results.
I want to redirect url from:

mysite.com/domain/google.com

to

mysite.com/domain?sld=google&tld=com

Thanks

A: In .htacees
For example try this --
Redirect /domain/google.com /domain?sld=google&tld=com

OR
Try this using through jquery for using any url
var baseurl = "mysite.com/domain/";
var a = window.location.pathname.split("/").pop();
var name = a.split(".")[0];
var name1 = a.split(".")[1];
alert(name);
alert(name1);
alert(baseurl+'?sld='+name+'&tld='+name1);
window.open(baseurl+'?sld='+name+'&tld='+name1);

Hope it will work for you


text:
Q: Error when setting default value to entire new column in Pandas dataframe Code works however getting this error when trying to set default value =1 to entire new column in Pandas dataframe. What does this warning error mean and how can I rework it so I don't get this warning error.
df['new']=1

A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead

A: this should solve the problem:
soldactive = df[(df.DispositionStatus == 'Sold') & (df.AssetStatus == 'Active')].copy()

your code:
removesold = df(df.ExitDate.isin(errorval)) & (df.DispositionStatus == 'Sold') & (af.AssetStatus == 'Resolved')]
df = df.drop(removesold.index)
soldactive = df[(df.DispositionStatus == 'Sold') & (df.AssetStatus == 'Active')]
soldactive['FlagError'] = 1

you've created soldactive DF as a copy  of the subset (sliced) df.
After that you'are trying to create a new column on that copy. It gives you a warning: A value is trying to be set on a copy of a slice from a DataFrame because dataframes are value-mutable (see excerpt from docs below)
Docs:

All pandas data structures are value-mutable (the values they contain
  can be altered) but not always size-mutable. The length of a Series
  cannot be changed, but, for example, columns can be inserted into a
  DataFrame. However, the vast majority of methods produce new objects
  and leave the input data untouched. In general, though, we like to
  favor immutability where sensible.

Here is a test case:
In [375]: df
Out[375]:
   a  b  c
0  9  6  4
1  5  2  8
2  8  1  6
3  3  4  1
4  8  0  2

In [376]: a = df[1:3]

In [377]: a['new'] = 1
C:\envs\py35\Scripts\ipython:1: SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead

See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy

In [378]: del a

In [379]: a = df[1:3].copy()

In [380]: a['new'] = 1

In [381]: a
Out[381]:
   a  b  c  new
1  5  2  8    1
2  8  1  6    1

In [382]: df
Out[382]:
   a  b  c
0  9  6  4
1  5  2  8
2  8  1  6
3  3  4  1
4  8  0  2

A: Solution
df.loc[:, 'new'] = 1

pandas uses [] to provide a copy.  Use loc and iloc to access the DataFrame directly.
What's more is that if the 'new' column didn't already exist, it would have worked.  It only threw that error because the column already existed and you were trying to edit it on a view or copy... I think


text:
Q: How to find 10 most common words in a text So I have arbitrary text in a txt file and I need to find the 10 most common words. How should I do that? I think I should read sentences from dot to a dot and put it to an array, but don't really know how to do that.

A: convert all the data to String, and split it into array
example :
char[] delimiterChars = { ' ', ',', '.', ':', '\t' };
string text = "one\ttwo three:four,five six seven";

string[] words = text.Split(delimiterChars);

var dict = new Dictionary<String, int>();
foreach(var value in array)
{
    if (dict.ContainsKey(value))
        dict[value]++;
    else
        dict[value] = 1;
}

for(int i=0;i<dict.length();i++) //or i<10
{
   Console.WriteLine(dict[i]);
}

you need to sort the array with bigger value first.

A: You could achieve it with Linq. Try something like this:
var words = "two one three one three one";
var orderedWords = words
  .Split(' ')
  .GroupBy(x => x)
  .Select(x => new {
    KeyField = x.Key,
    Count = x.Count() })
  .OrderByDescending(x => x.Count)
  .Take(10);

A: The most difficult part of the task is to split the initial text to words. Natural language (e.g. English) word is quite a complex thing:
Forget-me-not     // 1 word (a nice blue flower)
Do not Forget me! // 4 words
Cannot            // 1 word or shall we split "cannot" into "can" + "not"?
May not           // 2 words
George W. Bush    // Is "W" a word?
W.A.S.P.          // ...If it is, is it equal to "W" in the "W.A.S.P"?
Donald Trump      // Homonyms: name
Spades is a trump // ...and a special follow in a game of cards
It's an IT; it is // "It" and "IT" are different (IT is an acronym), "It" and "it" are same

Another issue is the case: you may want to count It and it as one and the same word, but IT as a different acronym. As a first try, I suggest something like this:
var top10words = File
  .ReadLines(@"C:\MyFile.txt")
  .SelectMany(line => Regex
    .Matches(value, @"[A-Za-z-']+")
    .OfType<Match>()
    .Select(match => CultureInfo.InvariantCulture.TextInfo.ToTitleCase(match.Value)))
  .GroupBy(word => word)
  .Select(chunk => new {
     word = chunk.Key,
     count = chunk.Count()})
  .OrderByDescending(item => item.count)
  .ThenBy(item => item.word)
  .Take(10);

In my solution I've assumed:

*

*Words can contain A..Z, a..z, - (dash) and ' (apostroph) letters only

*TitleCase has been used to separate all upper case acronyms from regular words (It and it will be treat as the same word, while IT as different one)

*In case of tie (two or many words have the same frequence) this tie is breaking by alphabet order

A: Here is a combined method I wrote from the answers provided by Aldi Renaldi Gunawan and JanneP. I guess the delimiter chars will depend on your use case though. In your case you can provide 10 for the numWords parameter.
public static Dictionary<string, int> WordCount(string text, int numWords = int.MaxValue)
{
    var delimiterChars = new char[] { ' ', ',', ':', '\t', '\"', '\r', '{', '}', '[', ']', '=', '/' };
    return text
        .Split(delimiterChars)
        .Where(x => x.Length > 0)
        .Select(x => x.ToLower())
        .GroupBy(x => x)
        .Select(x => new { Word = x.Key, Count = x.Count() })
        .OrderByDescending(x => x.Count)
        .Take(numWords)
        .ToDictionary(x => x.Word, x => x.Count);
}


text:
Q: Pick up pen when turtle is not at coordinate My program draws images that already have coordinates attach to them. I want my turtle to be able to pick up the pen when not at the coordinate. Right now the turtle continues to write before getting to the coordinate.
code:
with open('output.txt', 'r') as f:
    data = ast.literal_eval(f.read())

tony = turtle.Turtle()

for z in data:
    position = tony.pos()
    tony.goto(z)

output
1:
As you can see the turtle continues to draw even before getting to the coordinate.
Here's something I think may work but I'm not sure how to implement it.
for z in data:
     position = tony.pos()
     while position in z == False:
         tony.penup()

for z in data:
     position = tony.pos()
     while position in z == True:
        tony.pendown()
        print("True")

A: I created a function that detected whether the position of the turtle was in the list of coordinates. This function was then called every millisecond using the ontimer function. I also had to slow down my turtle in order for the program to check the position within a millisecond
code:
tony = turtle.Turtle()
tony.color("white", "cyan")
tony.speed(5.5)

def on_canvas():
    position = tony.pos()
    if position in data:
        tony.pendown()
        print("This is a coordinate")
    else:
        tony.penup()
        print("This is not a coordinate")

for z in data:
    playground.ontimer(on_canvas, 1)
    tony.goto(z)

turtle.done()

A: Maybe try picking up the pen before you move and putting it down after:
with open('output.txt', 'r') as f:
    data = ast.literal_eval(f.read())

tony = turtle.Turtle()

for z in data:
    tony.penup()
    tony.goto(z)
    tony.pendown()


text:
Q: Crash in SDWebImageManager imageDownloader:didFinishWithImage: We recently released our app to the appstore, and almost immediately got a few crashes in SDWebImageManager imageDownloader:didFinishWithImage:
The top of the stacks look like:
0 libobjc.A.dylib 0x33c28c98 objc_msgSend + 16
1 CoreFoundation 0x308f0571 -[NSObject(NSObject) performSelector:withObject:withObject:] + 25
2 Ourcode 0x0001d98f -SDWebImageManager imageDownloader:didFinishWithImage:
3 CoreFoundation 0x308f0571 -[NSObject(NSObject) performSelector:withObject:withObject:] + 25
4 Ourcode 0x0001cb03 -SDWebImageDownloader connectionDidFinishLoading:

We have the latest SD code that does a retain on the delegate inside this function.
As long as our delegate is created properly, I don't see how we get into this situation. It appears to me that the delgate the performSelector on has been freed. But SDWebImageManager reatains the delegate.
The relevant code for imageDownloader:didFinishWithImage: is:
- (void)imageDownloader:(SDWebImageDownloader *)downloader didFinishWithImage:(UIImage *)image
{
    [downloader retain];
    SDWebImageOptions options = [[downloader.userInfo objectForKey:@"options"] intValue];

     // Notify all the downloadDelegates with this downloader
    for (NSInteger idx = (NSInteger)[downloaders count] - 1; idx >= 0; idx--)
    {
        NSUInteger uidx = (NSUInteger)idx;
        SDWebImageDownloader *aDownloader = [downloaders objectAtIndex:uidx];
        if (aDownloader == downloader)
        {
            id<SDWebImageManagerDelegate> delegate = [[[downloadDelegates objectAtIndex:uidx] retain] autorelease];

            if (image)
            {
                if ([delegate respondsToSelector:@selector(webImageManager:didFinishWithImage:)])
                {
                    [delegate performSelector:@selector(webImageManager:didFinishWithImage:) withObject:self withObject:image];
               }
           }


text:
Q: Creating TrueCrypt volumes on Windows Currently it is not possible to create TrueCrypt volumes using the command line on Windows. According to the official website, this is "planned to be implemented in the future" (see: http://www.truecrypt.org/future).
For an autmated script I want to create multiple TrueCrypt volumes on a daily base. Is there any work around or any other solution to create TrueCrypt volumes on Windows? Linux is not an option, it has to be Windows.

A: For future reference. I was looking into this and apparently is not possible yet...
http://www.truecrypt.org/future

A: I think you should automate the GUI with any of the GUI-scripting tools available until truecrypt will update their command line options. I was searching a little in the web and found this:
http://www.autoitscript.com/forum/topic/151825-truecrypt-volume-creation-automation/
I haven't checked it out, but maybe it can help you somehow...
Good luck!

A: As a possible workaround, you can once manually create truecrypt container. Than copy it and work with the copy. You can automate mounting, copying data to mounted volume, dismounting and so on.

A: Use a /q parameter. See here. Example: "C:\Program Files\TrueCrypt\TrueCrypt.exe" /q /lT /v "C:\mydata.tc".