Q: Let's have better idea on how to get rid of the point of parent user in chat Note that I'm talking about our main chat server i.e chat.SE
The parent user in chat profile serves two important purposes today:

*

*Base for being able to talk in chat
We know that when a user get 20 reputation on any SE site (excluding the case of SO and MSE), s/he can talk in any active chat-room on main chat server. Which I discussed as Chat related privileges are not site specific.
Here the parent user provides a base to talk in any active chat room on the main server.

*Name and Avatar
As user can talk in any room, name and avatar of a parent user is used to identify him/her.
Now upon the discussion Show the avatar of related site of a chat-room instead of parent site of a user, I've found that there will be no point to the parent user (above mentioned 2nd point) if we implement drawing name and avatar from related site.
As balpha ♦ already declared in the post What is the point of the "Parent User" in Chat? that parent user is, for the most part, a relic.

To be honest, much of the "parent user" idea is still a leftover of the original plan to let each StackExchange site have its own chat site.

And

I don't know if we're ever going to totally get rid of the idea of a user's "main site", since most people have such a site that they consider to be the most important (if not only) site they're active on, but over time, this idea should disappear into the background more and more.

So, I think we should have some idea to get rid of parent users by identifying the user by related site of chat-room instead of parent user.

But we've to compensate for above mentioned two points if we want to get rid of the parent user mechanism. I've some suggestions[1]:

*

*When a privileged user enters a chat-room, use Name and Avatar from/of his/her profile of related site to that chat-room.

*If a user doesn't have an account on related site to the chat-room then apply one of the following:

*

*Use the parent site mechanism and user Name and Avatar from parent site.

*Use Name and Avatar of Network-Profile. (remove parent site mechanism)

*Force/prompt user to join the community. (so that s/he get Name and Avatar of related site to corresponding chat-room)

In my opinion, the 2nd option is the best. (As now you can also control what account to synchronize your network-profile with.)
Well, is there any thing we've missed? yes, the diamond! Moderators will not be identified as a moderator on the chat-rooms related to other sites. But I think it may be OK for a moderator to be identified as a moderator only on chat rooms related to site on which s/he is a moderator as s/he is a site moderator not MSE moderator. So, We'll need to provide a diamond that works through out main chat server to moderators.
[1] I was free from estimating/guessing possible programming/coding complication!

A: Some of these proposals, I like. Some, less so.
Primarily Parent sites are mostly invisible. What does this even fix? What additional utility does this give our users over the current system? Some of the proposals seem interesting but in other contexts, and If they did, there's a few ideas for implementation

We know that when a user get 20 reputation on any SE site (excluding the case of SO and MSE), s/he can talk in any active chat-room on main chat server. Which I discussed as Chat related privileges are not site specific. Here the point of parent user provide a base to talk in any active chat room on main server.

We could rejig this to letting people create a chat user at 20 reputation on any site. Then we could do all manner of positive and negative reinforcement to that account (Suspensions, account deletions) . That said, we'd have an edge case of sub 20 rep users who can chat, depending on how they lost the reputation.
If we did lose the parent site suspensions, I'd like an easier way to set longer suspensions than calculating it by the hour. In essence I'd love for this to work just like main site suspensions, and getting all the tools like annotations I'm used to having.
This also pretty much handles the reparenting name switch loophole.

Well, is there any thing we've missed? yes, the diamond! Moderator will not be identified as a moderator on the chat-rooms related to other sites. But I think it may be ok for a moderator to be identified as a moderator only on chat rooms related to site on which s/he is a moderator as s/he is a site moderator not MSE moderator. Not agreed? ok. Then we've to provide a special function for it.

I'm on half a dozen rooms right now. On a good chunk of them I am trusted to jump in and use my modly powers if things go wrong. On my home site, I have a bunch of U&L and AU mods who're pretty helpful in handling issues when I can't.
That said considering a few misconceptions I've come across, it might be worth explicitly going "Hey, all yalls are chat mods too." In many cases its also handy to have a neutral third party go "Hey guys, chill".
Removing "universal" chat mod powers is going to adversely affect chat moderation, both directly, and in terms of soft power
Having said all that, I'm not sure other than a minor annoyance one or two users abuse, and the occational need to talk to a mod on another site or a CM about problem users, I'm not sure what this fixes.

A: I realize it's confusing if somebody is Joe on one site and AwesomeGeek on another and the "wrong" one shows up in your chat room, but anybody who chooses to use different names on different sites is going to cause some confusion somewhere.  Having the name/avatar change based on a room's location can be confusing too, and leaves the problem of unparented rooms.  (Not all chat rooms are associated with sites.)
Having a chat profile on chat.SE tied to the network profile has some appeal.  You can't assume that somebody in your chat room has an account on the local site and we certainly shouldn't force creation of one, so the options are either the chat-parent system that we have now or the network profile.  This also works for unparented rooms.
We should not reduce the ability of moderators to moderate on the shared chat server.  As a moderator, I'm not prepared to be one of only 3 or 4 people able to police rooms created on my site.  Chat is the third or fourth place, not my primary concern, and I rely on the other moderators on the network to lend a hand if something is exploding in some user-created room while I'm busy or sleeping.  Fortunately, I think it's not hard for moderator status to be exposed through the network profile.
There's one other implication of chat parents that you haven't considered: suspensions.  Right now, if you're suspended on a main site and that site is your chat parent, you're also suspended in chat.  Now you could certainly argue that that's a little messed up -- getting suspended for rudeness on TwistyStraws.SE shouldn't necessarily impede the productive conversations you're having over in the Pizza.SE room.  Further, if your parent site is actually Unicorns.SE then you can still continue your ranting in the TwistyStraws.SE room, even though you're suspended on that site, and that's not right either.  So with your proposed change we'd need to do something about the connection between site suspensions and chat suspensions, ideally something better than "mods should remember to go do that manually".  Arguably we should so something about it anyway, but your proposal would force the issue.

A: Tl;dr: It's probably not worth the time to change this.
I don't think that removing the feature is worthwhile. I can pick my parent user site which is a system that seems to satisfy all functionality. To pick the network user would not provide permissions, and a database call to sum reputation for chat permissions would likely also be expensive (On Data.SE you can't even do cross-site queries.)
I am also a moderator on Lifehacks. Though chat flags are rare, being able to mod for any site (Except for the separate chat.meta.SE and chat.SO) is sometimes valuable if there's a spam fest™ going on somewhere on chat.SE. Most chat flags do not require knowledge of the associated site; something offensive or spam is always going to be offensive or spam.


Q: Significance of exact solutions to differential equations What is the importance of finding new exact solutions to partial differential equations? I kindly need someone to convince me, since my PhD will be on that.

A: If you have an analytical/exact (in contrast to some say "discretized" or similar numerical) solution, interpretation of the coefficients in this solution is much more straightforward than tackling a generic numerical solution. These coefficients of the exact solution can also be fitted to experiments to gain an understanding in that context.
An analytical solution typically is also a more tractable than a more generic numerical one (fewer parameters), and this can allow for building more complex models on top of it (which can quickly become unfeasible, if one had to build a model out of many already complicated numerical solutions). Example: exact quantum mechanical solution of the harmonic oscillator, where the exact eigenvalues (with mathematically simple form) of the modes can be employed to model what happens if you have many modes to occupy (e.g. phonons in a solid). This would be much more complicated if one would not have the understanding of the simple analytical structure of the spectrum.
Exactly solvable models had and have importance in gaining deeper understanding in a field at a very general (i.e. deep) level.


Q: Python: how do I create a list of combinations from a series of ranges of numbers For a list of numerical values of n length, e. g. [1, 3, 1, 2, ...], I would like to create a list of the lists of all possible combinations of values from range[x+1] where x is a value from the list. The output might look something like this:
for list[1, 3, 2] return all possible lists of range[x+1] values:
    # the sequence of the list is unimportant
[
[0,0,0],[1,0,0],[0,1,0],[0,2,0],[0,3,0],[0,0,1],[0,0,2],[1,1,0],
[1,2,0],[1,3,0],[1,0,1],[1,0,2],[0,1,1],[0,2,1],[0,3,1],[0,1,2],
[0,2,2],[0,3,2],[1,1,1],[1,2,1],[1,3,1],[1,1,2],[1,2,2],[1,3,2]
]

So in this example I am looking for all variations of [e1, e2, e3] from e1 in [0,1], e2 in [0,1,2,3] and e3 in [0,1,2]

A: Python's itertools module has a tool that does what you need:
import itertools
p = itertools.permutations([0, 1, 2, 3])
p_as_list = list(p)

Edit: As your needs are fairly specific you could benefit from having your own function that does something alike this one: (note I haven't got the implementation down just yet, maybe someone might refine this):
def magic_permutations (*args):
    lists = []
    larg = len(args)
    for i in range(larg):
        lists.append([])
    i = 0
    for nums in args:
        for num in nums:
            if i >= larg:
                i = 0
            lists[i].append(num)
            i += 1
    return lists

Edit: I misunderstood your question the first time, so I'll apologize for that. I'll however leave this be.

A: Use itertools.product with a dynamically-specified list of iterators:
vals = [1,3,2]
for item in itertools.product(*[range(x+1) for x in vals]):
    print item

Output:
(0, 0, 0)
(0, 0, 1)
(0, 0, 2)
(0, 1, 0)
(0, 1, 1)
(0, 1, 2)
(0, 2, 0)
(0, 2, 1)
(0, 2, 2)
(0, 3, 0)
(0, 3, 1)
(0, 3, 2)
(1, 0, 0)
(1, 0, 1)
(1, 0, 2)
(1, 1, 0)
(1, 1, 1)
(1, 1, 2)
(1, 2, 0)
(1, 2, 1)
(1, 2, 2)
(1, 3, 0)
(1, 3, 1)
(1, 3, 2)

A: To obtain the exact sequence shown in the question (albeit in a different order, but that's not a problem) use this function:
import itertools as it

def combs(lst):
    return [list(e) for e in it.product(*(range(x+1) for x in lst))]

The result is as expected:
combs([1, 3, 2])

=> [[0, 0, 0], [0, 0, 1], [0, 0, 2], [0, 1, 0], [0, 1, 1], [0, 1, 2],
    [0, 2, 0], [0, 2, 1], [0, 2, 2], [0, 3, 0], [0, 3, 1], [0, 3, 2],
    [1, 0, 0], [1, 0, 1], [1, 0, 2], [1, 1, 0], [1, 1, 1], [1, 1, 2],
    [1, 2, 0], [1, 2, 1], [1, 2, 2], [1, 3, 0], [1, 3, 1], [1, 3, 2]]

A: for ii in itertools.product(range(2),range(4),range(3):
    print ii
(0, 0, 0)
(0, 0, 1)
(0, 0, 2)
(0, 1, 0)
(0, 1, 1)
(0, 1, 2)
(0, 2, 0)
(0, 2, 1)
(0, 2, 2)
(0, 3, 0)
(0, 3, 1)
(0, 3, 2)
(1, 0, 0)
(1, 0, 1)
(1, 0, 2)
(1, 1, 0)
(1, 1, 1)
(1, 1, 2)
(1, 2, 0)
(1, 2, 1)
(1, 2, 2)
(1, 3, 0)
(1, 3, 1)
(1, 3, 2)

A: It's not in the same order, but I think this is what you wanted:
def xrangeCombinations(input):
    if len(input) > 1:
        for i in xrange(input[-1] + 1):
            for j in xrangeCombinations(input[:-1]):
                yield j + [i]
    else:
        for i in xrange(input[-1] + 1):
            yield [i]

for i in xrangeCombinations([1, 3, 2]):
    print i

Produces the output:
[0, 0, 0]
[1, 0, 0]
[0, 1, 0]
[1, 1, 0]
[0, 2, 0]
[1, 2, 0]
[0, 3, 0]
[1, 3, 0]
[0, 0, 1]
[1, 0, 1]
[0, 1, 1]
[1, 1, 1]
[0, 2, 1]
[1, 2, 1]
[0, 3, 1]
[1, 3, 1]
[0, 0, 2]
[1, 0, 2]
[0, 1, 2]
[1, 1, 2]
[0, 2, 2]
[1, 2, 2]
[0, 3, 2]
[1, 3, 2]

This solution might be slower than alternatives so if speed is an issue you should probably improve it.

A: Using numpy if you don't mind getting tuples in the end:
>>> import numpy as np
>>> e1=np.array([0,1])
>>> e2=np.array([0,1,2])
>>> e3=np.array([0,1,2,3])
>>> g=np.meshgrid(e1,e2,e3) #you need numpy ver>1.7.0, change the order of final result by changing the order of e1, e2, e3
>>> zip(*[item.flatten() for item in g])
[(0, 0, 0), (0, 0, 1), (0, 0, 2), (0, 0, 3), (1, 0, 0), (1, 0, 1), (1, 0, 2), (1, 0, 3), (0, 1, 0), (0, 1, 1), (0, 1, 2), (0, 1, 3), (1, 1, 0), (1, 1, 1), (1, 1, 2), (1, 1, 3), (0, 2, 0), (0, 2, 1), (0, 2, 2), (0, 2, 3), (1, 2, 0), (1, 2, 1), (1, 2, 2), (1, 2, 3)]


Q: Ways to dynamically render a real world 3d environment in Unity3D Using Unity3D and C# I am attempting to display a 3d version of a real world location. Inside my Unity3D app, the user will specify the GPS coordinates of a location, then my app will have to generate a 3d plane(anything doesn't have to be a plane) of that location. The plane will show a 500 metre by 500 metre 3d snapshot of that location.
How would you suggest I achieve this in Unity3D? What methodology would you use to achieve this?
NOTE: I understand that this is a very difficult endevour(to render real world locations dynamically in Unity3d) so I expect to perform many actions to achieve this. I just don't know of all the technologies out there and which would be best for my needs
For example:

Suggested methodology 1:

*

*Prompt user to specify GPS coords

*Use Google earth API and HTTP to programmatically obtain a .khm file
  describing that location(Not sure if
  google earth provides that capability

*

*does it?)

*Unzip the .khm so I have the .dae file

*Convert that file to a .3ds file using ??? third party converter(is
  there a converter that exists?)

*Import .3ds into Unity3D at runtime as a plane(is this possible)?

  Suggested methodology 2:

*

*Prompt user to specify GPS coords

*Use Google earth API and HTTP to programmatically obtain a .khm file
  describing that location(Not sure if
  google earth provides that capability

*

*does it?)

*Unzip the .khm so I have the .dae file

*Parse .dae file using my own C# parser I will write(do you think its
  possible to write a .dae parser that
  can parse the .dae into an array of
  Vector3 that describe the height map
  of that location?)

*Dynamically create a plane in Unity3D and populate it with my
  array/list of Vector3 points(is it
  possible to create a plane this way?)
  Maybe I am meant to create a mesh
  instead of a plane?

Can you think of any other ways I could render a real world 3d environment in Unity3D?

A: No service available has a detailed 3d map of an area given gps coordinates. Google has a super simple height map that they draw and then map their aerial pictures onto, but even if you could get programmatic access to that it would look terrible if you were at street level. If you're okay with a horrid level of detail (like you're going to be viewing this from high up or something) maybe it would be feasible, but not as any kind of first person street level experience.


Q: Fill Datagridview in each new identical TabPages I have TabControl with 1 TabPages and contains DataGridView.
I create TabPages2 from TabPages1 with code :
    Dim Frm As New TabFormPage
    Dim MoreTabs As TabPage = Frm.TabPage1
    Dim i As Integer
    For i = 1 To TabControl1.TabPages.Count
        MoreTabs.Text = "TabPage" & i + 1
    Next i
    TabControl1.Controls.Add(MoreTabs)
    Frm.Dispose()

TabPages2 Controls identical to TabPages1
If I fill DataGridView with BackgroundWorker in TabPages1 , it was working . But if I fill DataGridView in every New TabPages ( eg TabPages2 ) from different sources , it was not working (DataGridView in TabPages2/each New TabPages is empty/nothing) . It always fills Tabpages1 DataGridView
How to fill every DataGridView in every New TabPages with identical controls ?
Here's my code to fill DataGridview :
    Private Sub BackgroundWorker1_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
        MyConnection = New System.Data.OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + FPathTab + ";Extended Properties=Excel 12.0;")
        MyCommand = New System.Data.OleDb.OleDbDataAdapter("select * from [" & CSheetTab1 & "]'", MyConnection)

        DtSet = New System.Data.DataSet
        DtSet.Clear()
        MyCommand.Fill(DtSet)
    End Sub
    Private Sub BackgroundWorker1_RunWorkerCompleted(sender As Object, e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
        DataGridView1.DataSource = DtSet.Tables(0)
        dv = DtSet.Tables(0).DefaultView
        MaxRecords = DtSet.Tables(0).Rows.Count
        MyConnection.Close()
        DataGridView1.Columns("F20").Visible = False
        DataGridView1.Columns("F21").Visible = False
        DataGridView1.Columns("F22").Visible = False
    End Sub

Thanks for your help


Q: has anyone figured out a way to use the back-facing camera on android in any browser with getusermedia? I can’t seem to find the settings anywhere. I also tried searching the phone to set front-facing as default but had no luck. I’m using an xiaomi 1s if that helps.sorry ,my english is poor


Q: Subdomain overwiting CodeIgniter session I have 2 CodeIgniter installations, 1 on mydomain.com another on sub.mydomain.com.
I am trying to get sub.mydomain.com to be able to access the CI session created by mydomain.com. I have edited the cookie section of both config files to:
$config['cookie_prefix']    = "";
$config['cookie_domain']    = ".mydomain.com";
$config['cookie_path']      = "/";
$config['cookie_secure']    = FALSE;

Now if I go to mydomain.com setting the session and then go to sub.mydomain.com it seems to overwrite the session with a new one rather than being able to read from the existing session.
Am I missing something here?

A: This was driving me crazy for hours but the solution (as usual) was simple. I had forgotten to make sure
$config[‘encryption_key’]

was the same for both applications!
Working great now


Q: locus of complex number 2 Que:

If $\arg\left(\dfrac{z-z_1}{z-z_2}\right)=\pi$ then what is the locus of $z$?.

Doubt
In my textbook it is written that it represents the straight line joining $A(Z_1)$ and $B(Z_2)$ but excluding the segment $AB$.

Is it right or wrong?
But According to me the locus of $z$ is the straight line joining the line segment $A(Z_1)$ and  $B(Z_2)$

A: You're right.
$$\arg \frac xy = \arg x - \arg y + 2\pi n$$
so
$$\arg\frac{z-z_1}{z-z_2}=\pi$$
means the vector $z-z_1$ is parallel to, but points in opposite direction than $z-z_2$.
This implies $z$ is between $z_1$ and $z_2$, hence the answer: 'an interior of the line segment $\overline {z_1 z_2}$'.


Q: Assign post type to many users I am working on a small course engine that has a Course custom post type and a list of users. Users should apply for courses.
I was thinking about the Posts 2 Posts plugin to create the relationship, but is there any straight forward way to assign many users to a single post type (course) and see only things for that specific post type? Any premium plugin that could do that without making everything really heavy?
P.S. A user could attend several courses as well.

A: I think a plugin like Role Scoper will work for you, you can give individual users access to certain content based on their role or group.

A: On a total fluke, I saw this WPSE answer just after reading your question. It's a plugin called "User Specific Content" that seems to do exactly what you want. "Role Scoper" is a good plugin, but it's probably overkill for what you need. Best yet, the "User Specific Content" plugin was the result of a WPSE answer's code snippet!


Q: Guidance with a translation in Linq to Xml Can someone help with an explanation of what does this mean:
... .Select(Func<XElement, XElement>selector)

Please an example of what should go in as parameter will be appreciated.
Also found it a little bit difficult naming this question. Suggestion will also be appreciated.

A: It's a function taking XElement as argument and returning an XElement, so for instance:
public XElement someFunction(XElement argument)
{
    XElement someNewElement = new XElement();
    ... // do something with someNewElement, taking into account argument
    return someNewElement;
}

Func<XElement, XElement> variableForFunction = someFunction;

.... .Select(variableForFunction);

I'm not interely sure if you have to assign it to a variable first, you could probably just do this:
... .Select(variableForFunction);

give it a try (and let me know if it works :) )
oh and for more information, here's the msdn article, it also explains how to use delegates:
Func<XElement, XElement> variableForFunction = delegate(XElement argument)
    {
        ....//create a new XElement
        return newXElement;
    }

and how to use lambdas, for instance:
Func<XElement, XElement> variableForFunction = s => {
    ....;//create an XElement to return
    return newXElement;
}

or, in this instance, use the lambda directly:
.... .Select( s => {
    ....;//create an XElement to return
    return newXElement;
})

edited it following Pavel's comment


Q: If the address of a function can not be resolved during deduction, is it SFINAE or a compiler error? In C++0x SFINAE rules have been simplified such that any invalid expression or type that occurs in the "immediate context" of deduction does not result in a compiler error but rather in deduction failure (SFINAE).
My question is this:
If I take the address of an overloaded function and it can not be resolved, is that failure in the immediate-context of deduction?
(i.e is it a hard error or SFINAE if it can not be resolved)?
Here is some sample code:
struct X
{
  // template<class T> T* foo(T,T); // lets not over-complicate things for now
  void foo(char);
  void foo(int);
};

template<class U> struct S
{
  template<int> struct size_map
  { typedef int type; };

// here is where we take the address of a possibly overloaded function
  template<class T> void f(T,
      typename size_map<sizeof(&U::foo)>::type* = 0);

  void f(...);
};

int main()
{
  S<X> s;

// should this cause a compiler error because 'auto T = &X::foo' is invalid?
  s.f(3);

}

Gcc 4.5 states that this is a compiler error, and clang spits out an assertion violation.
Here are some more related questions of interest:
Does the FCD-C++0x clearly specify what should happen here?
Are the compilers wrong in rejecting this code?
Does the "immediate-context" of deduction need to be defined a little better?
Thanks!

A: template<class T> void f(T,
    typename size_map<sizeof(&U::foo)>::type* = 0);

This doesn't work, because U does not participate in deduction. While U is a dependent type, during deduction for f it's treated like a fixed type spelled with a nondependent name. You need to add it to the parameter list of f
/* fortunately, default arguments are allowed for
 * function templates by C++0x */
template<class T, class U1 = U> void f(T,
    typename size_map<sizeof(&U1::foo)>::type* = 0);

So in your case because U::foo does not depend on parameters of f itself, you receive an error while implicitly instantiating S<X> (try to comment out the call, and it should still fail). The FCD says at 14.7.1/1

The implicit instantiation of a class template specialization causes the implicit instantiation of the declarations, but not of the deﬁnitions or default arguments, of the class member functions, member classes, static data members and member templates;

That is, if you implicitly instantiate S<X> the following function template declaration will be instantiated
template<class T> void S<X>::f(T,
  typename size_map<sizeof(&X::foo)>::type* = 0);

Analysis on that template declaration will then find that it can't resolve the reference to X::foo and error out. If you add U1, the template declaration will not yet try to resolve the reference to U1::foo (since U1 is a parameter of f), and will thus remain valid and SFINAE when f is tried to be called.


Q: C# Progress Bar is not showing progress I have a progress bar on my program and I am trying to add value to it after each "DataTable" has been processed, however it only updates after everything is done.
here is the code:
int c = 0;
OdbcConnection cn = openOdbcDB();
foreach(DataSet ds in allDataSets)
{
    foreach(DataTable dt in ds.Tables)
    {
        foreach (DataRow dr in dt.Rows)
        {
           insertIntoDatabaseCurrentRecord(dr);
        }
     }
     pbMain.Value = pbMain.Value + (33 / totalFiles);
     c++;
}
cn.Close();
cn.Dispose();

Is there a way to force the bar to show progress after each table is finished like it is finished?  At the moment, I only see the progress once loops finish, I see the line  go from empty to full.  There are about 18000 records per DataTable, so I should be able to see it because it takes about a minute for it to process all the records.

A: Assuming all this is happening in the UI thread, then it's not going to update because you are keeping the thread busy with processing your loop. You need to spawn off a background thread to do the processing so that it doesn't hang your UI thread. Then you will need to have the part where you actually set the progress bar pushed back to your UI thread using Contol.Invoke.
See here: http://msdn.microsoft.com/en-us/library/zyzhdc6b.aspx for both an example of threading (although there are many ways you can do this) and Control.Invoke.

A: Use BackgroundWorker:
BackgroundWorker _worker;

// executes on another thread
void worker_DoWork(object sender, DoWorkEventArgs e)
{
    BackgroundWorker worker = (BackgroundWorker)sender;

    int c = 0;
    OdbcConnection cn = openOdbcDB();
    foreach (DataSet ds in allDataSets)
    {
        foreach (DataTable dt in ds.Tables)
        {
            foreach (DataRow dr in dt.Rows)
            {
                insertIntoDatabaseCurrentRecord(dr);
            }
        }
        // do not update UI elements here, but in ProgressChanged event
        //pbMain.Value = pbMain.Value + (33 / totalFiles);
        c++;

        worker.ReportProgress(c); // call ProgressChanged event of the worker and pass a value you can calculate the percentage from (I choose c, since it is the only calculated value here)
    }
    cn.Close();
    cn.Dispose();
}

// gets called on your main thread
void worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
    // update the progressbar here.
    // e.ProgressPercentage holds the value passed in DoWork.
}

A: Since your loops are blocking the active thread, you will have to use another Thread (clean way) or simply use Application.DoEvents() on WinForms:
int c = 0;
OdbcConnection cn = openOdbcDB();
foreach(DataSet ds in allDataSets)
{
    foreach(DataTable dt in ds.Tables)
    {
        foreach (DataRow dr in dt.Rows)
        {
           insertIntoDatabaseCurrentRecord(dr);
           Application.DoEvents(); //Quick and dirty
        }
     }
     pbMain.Value = pbMain.Value + (33 / totalFiles);
     c++;
}
cn.Close();
cn.Dispose();


Q: Snap to Ticks and move Ticks position in Custom Range slider I am very new to this and i am trying to figure out how to solve my issue.
I am trying to design an Range slider for controling the speed of an machine application.
I have been searching here for many hours now but i can not find the right result for my issue.
The code i am adding here is something i have found other pages so it might not be best solution.
I would like to do 3 different things with it to start with.

*

*First issue is that i would like the handle to snap to the ticks i have made, is it possible to do that with code so if i change my Ticks the handle will stil snap to the new ticks?

*Is it possible to have more ticks between 0 and 10% so i have like 2% steps there up to 10% and when the handle is there it will then snap to the 2% steps and when its above 10% it will snap to the other 10% step interval.

*Is it possible to move the Ticks inside the slider instead and have the labels in the middle?
I would like to have the ticks both in the bottom and in the top and then the labels in the middle. I have attached a picture of what i am aiming for.

Many thanks
Range slider idea!
Link to my Code
https://www.w3schools.com/code/tryit.asp?filename=GT1V8EFG2RUA

A:

function toggleStep(element) {
  if (element.value >= 10) { element.step = 10; }
  else { element.step = 2; }
}

/**
 * Sniffs for Older Edge or IE,
 * more info here:
 * https://stackoverflow.com/q/31721250/3528132
 */
function isOlderEdgeOrIE() {
  return (
    window.navigator.userAgent.indexOf("MSIE ") > -1 ||
    !!navigator.userAgent.match(/Trident.*rv\:11\./) ||
    window.navigator.userAgent.indexOf("Edge") > -1
  );
}

function valueTotalRatio(value, min, max) {
  return ((value - min) / (max - min)).toFixed(2);
}

function getLinearGradientCSS(ratio, leftColor, rightColor) {
  return [
    '-webkit-gradient(',
    'linear, ',
    'left top, ',
    'right top, ',
    'color-stop(' + ratio + ', ' + leftColor + '), ',
    'color-stop(' + ratio + ', ' + rightColor + ')',
    ')'
  ].join('');
}

function updateRangeEl(rangeEl) {
  var ratio = valueTotalRatio(rangeEl.value, rangeEl.min, rangeEl.max);

  rangeEl.style.backgroundImage = getLinearGradientCSS(ratio, '#00FF00', '#c5c5c5');
}

function initRangeEl() {
  var rangeEl = document.querySelector('input[type=range]');
  var textEl = document.querySelector('input[type=text]');

  /**
   * IE/Older Edge FIX
   * On IE/Older Edge the height of the <input type="range" />
   * is the whole element as oposed to Chrome/Moz
   * where the height is applied to the track.
   *
   */
  if (isOlderEdgeOrIE()) {
    rangeEl.style.height = "20px";
    // IE 11/10 fires change instead of input
    // https://stackoverflow.com/a/50887531/3528132
    rangeEl.addEventListener("change", function(e) {
      textEl.value = e.target.value;
    });
    rangeEl.addEventListener("input", function(e) {
      textEl.value = e.target.value;
    });
  } else {
    updateRangeEl(rangeEl);
    rangeEl.addEventListener("input", function(e) {
      updateRangeEl(e.target);
      textEl.value = e.target.value;
    });
  }
}

initRangeEl();
.slidecontainer {
  width: 500px;
  margin-left:15px;
}

input[type="range"] {
  -webkit-appearance: none;
  -moz-appearance: none;
  width:100%;
  height: 50px;
  padding: 0;
  border: solid 2px #000000;
  border-radius: 8px;
  outline: none;
  cursor: pointer;
}

datalist {
  display: flex;
  margin-left: 2px;
  margin-top: -50px;
}

datalist option {
  flex-basis: 10%;
  border-left: 1px solid #000;
}
datalist option:nth-child(-n+5) {
  flex-basis: 2%;
}
datalist option:last-child {
  display: none;
}

/*Chrome thumb*/

input[type="range"]::-webkit-slider-thumb {
  -webkit-appearance: none;
  -moz-appearance: none;
  -webkit-border-radius: 5px;
  /*16x16px adjusted to be same as 14x14px on moz*/
  height: 45px;
  width: 45px;
  border-radius: 5px;
  background: #e7e7e7;
  border: 2px solid #000000;
  opacity: 0.4;
  cursor: pointer;
  border-radius: 8px;

}

/*Mozilla thumb*/

input[type="range"]::-moz-range-thumb {
  -webkit-appearance: none;
  -moz-appearance: none;
  -moz-border-radius: 5px;
  height: 14px;
  width: 14px;
  border-radius: 5px;
  background: #e7e7e7;
  border: 1px solid #c5c5c5;
}

/*IE & Edge input*/

input[type=range]::-ms-track {
  width: 300px;
  height: 6px;
  /*remove bg colour from the track, we'll use ms-fill-lower and ms-fill-upper instead */
  background: transparent;
  /*leave room for the larger thumb to overflow with a transparent border */
  border-color: transparent;
  border-width: 2px 0;
  /*remove default tick marks*/
  color: transparent;
    margin-left:15px;
}

/*IE & Edge thumb*/

input[type=range]::-ms-thumb {
  height: 14px;
  width: 14px;
  border-radius: 5px;
  background: #e7e7e7;
  border: 1px solid #c5c5c5;
}

/*IE & Edge left side*/

input[type=range]::-ms-fill-lower {
  background: #000000;
  border-radius: 2px;
    margin-left:15px;
}

/*IE & Edge right side*/

input[type=range]::-ms-fill-upper {
  background: #000000;
  border-radius: 2px;
}

/*IE disable tooltip*/

input[type=range]::-ms-tooltip {
  display: none;
}

input[type="text"] {
  border: none;
}

.sliderticks {
  display: flex;
  justify-content: space-between;
  padding: 0 50px;
}

.sliderticks p {
  position: relative;
  display: flex;
  justify-content: center;
  text-align: center;
  width: 1px;
  background: #D3D3D3;
  height: 10px;
  line-height: 40px;
  margin: 0 0 20px 0;
}

Custom Range Slider

Drag the slider to display the current value.

<input type="range" value="10" min="0" max="100" oninput="toggleStep(this)" list="sliderticks"   />

 <datalist id="sliderticks">
   <option>0</option>
   <option>2</option>
   <option>4</option>
   <option>6</option>
   <option>8</option>
   <option>10</option>
   <option>20</option>
   <option>30</option>
   <option>40</option>
   <option>50</option>
   <option>60</option>
   <option>70</option>
   <option>80</option>
   <option>90</option>
   <option>100</option>
 </datalist>

A: Hope the code below solves your needs:

document.querySelectorAll('.range input[type="range"]').forEach((range) => {
  range.tickmarks = [...range.list.options].map((el) => parseFloat(el.value));
  range.list.insertAdjacentHTML('afterend', `<div class="range-value"></div>`);
  range.max = parseFloat(range.tickmarks[range.tickmarks.length - 1]);
  let q = (range.clientWidth - 40) / range.max;
  range.addEventListener('input', function(ev) {
    if (this.hasAttribute('ticks-only')) {
      this.value = range.tickmarks.map((x) => x).sort((x, y) => Math.abs(x - this.value) - Math.abs(y - this.value))[0];
    }
    this.parentElement.style.backgroundSize = `${(this.value * range.clientWidth) / range.max}px 100%, 100% 100%`;
    this.list.nextElementSibling.textContent = this.value;
    this.list.nextElementSibling.style.left = `${20 + this.value * q}px`;
  });
  range.tickmarks.forEach((el, i) => {
    range.list.options[i].label = el % 10 ? ' ' : el;
    range.list.options[i].style.left = 20 + el * q + 'px';
  });
  range.dispatchEvent(new Event('input', {bubbles: true}));
});
.range {
  position: relative;
  height: 52px; width: 500px;
  border-radius: 0.125em;
  overflow: hidden;
  font: 16px/1em sans-serif;
  background-image: linear-gradient(to right, #7bad23, #39594c), linear-gradient(to bottom, #84929d, #46576d);
  background-size: 0 100%, 100% 100%;
  background-repeat: no-repeat;
  box-shadow: 0 0 0 0.125em #7f8c97, 0.0625em 0.125em 0.3125em 0em #93a2bd, -0.125em -0.1875em 0.3125em 0em #0e1116, inset 0 0 1.25em -0.3125em #0e1116;
}

datalist {
  position: relative;
  display: block;
  height: 100%; width: 100%;
  pointer-events: none;
}

.range datalist option {
  position: absolute !important;
  display: grid;
  place-items: center;
  height: 100%;
  padding: 0;
  transform: translatex(-50%);
  font: bold 12px/1em monospace !important;
  text-shadow: 1px 0 0.16666667em #fff5;
}

.range datalist option::before,
.range datalist option::after {
  content: "";
  position: absolute;
  left: 50%;
  height: 100%; width: 0;
  box-shadow: 0 0 0 0.08333333em #0008;
}
.range datalist option::before { bottom: calc(50% + 1em); }
.range datalist option::after { top: calc(50% + 1em); }

input[type="range"] {
  appearance: none;
  position: absolute;
  top: 0; left: 0; z-index: 1;
  margin: 0;
  height: 100%; width: 100%;
  box-sizing: border-box;
  font: inherit;
  background-color: transparent;
  cursor: pointer;
}

input[type="range"]::-webkit-slider-thumb {
  appearance: none;
  display: block;
  width: 2.5em; height: 2.5em;
  border: none;
  border-radius: 0.75em;
  background-color: #99c7;
  box-shadow: 0 0 0.125em 0 #282850dd, inset 0 0 0.125em 0.125em #282850dd;
  transition: background-color 0.5s ease-out 0.5s;
}
input[type="range"]:active::-webkit-slider-thumb {
  background-color: #fff8;
  transition: background-color 0.5s ease-out;
}

.range-value {
  position: absolute;
  top: 0; left: 0; z-index: 2;
  display: grid;
  place-items: center;
  height: 100%;
  transform: translatex(-50%);
  font: bold 12px/1em monospace !important;
  text-shadow: 0 0 0.16666667em #fff;
  opacity: 0;
  pointer-events: none;
  transition: opacity 1s ease-in;
}
input[type="range"]:focus-visible~.range-value,
input[type="range"]:active~.range-value,
input[type="range"]:hover~.range-value {
  opacity: 1;
  transition: opacity 0.5s ease-out;
}

body { margin: 0; height: 100vh; background-color: #42516c; display: flex; flex-flow: column nowrap; justify-content: center; align-items: center; }

  <input type="range" list="high">
  <datalist id="high">
    <option value="0">
    <option value="2">
    <option value="4">
    <option value="6">
    <option value="8">
    <option value="10">
    <option value="20">
    <option value="30">
    <option value="40">
    <option value="50">
    <option value="60">
    <option value="70">
    <option value="100">
  </datalist>

With "ticks-only" attribute

  <input type="range" list="bass" ticks-only>
  <datalist id="bass">
    <option value="0">
    <option value="10">
    <option value="15">
    <option value="20">
    <option value="30">
    <option value="40">
    <option value="50">
    <option value="60">
    <option value="70">
    <option value="72">
    <option value="74">
    <option value="76">
    <option value="78">
    <option value="80">
    <option value="100">
    <option value="175">
    <option value="200">
  </datalist>

Note! This code only works for "webkit" (tested in Chrome). Firefox does not work correctly with the "position" property when parent and child elements are set to "absolute".


Q: Why AVL sort is not in place? I was recently told that AVL sort is not in place. Can anyone please explain it? From the below code, I am not sure where I assign extra space when sorting. In this code, when a data structure is built or an element are inserted, elements are ordered by their key.
Reference for the claim: They are using this claim to motivate "binary heap"
[1].https://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-006-introduction-to-algorithms-spring-2020/lecture-notes/MIT6_006S20_r08.pdf
Reference for code:
[2]. https://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-006-introduction-to-algorithms-spring-2020/lecture-notes/MIT6_006S20_r06.pdf
[3]. https://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-006-introduction-to-algorithms-spring-2020/lecture-notes/MIT6_006S20_r07.pdf
def height(A):
    if A: return A.height
    else: return -1

class Binary_Node:
    def __init__(self, x):
        self.item = x
        self.parent = None
        self.left = None
        self.right = None
        self.subtree_update()

    def subtree_update(self):
        self.height = 1 + max(height(self.left), height(self.right))

    def subtree_iter(self):
        if self.left: yield from self.left.subtree_iter()
        yield self
        if self.right: yield from self.right.subtree_iter()

    def subtree_first(self):
        if self.left: return self.left.subtree_first()
        else: return self

    def subtree_last(self):
        if self.right: return self.right.subtree_last()
        else: return self

    def sucessor(self):
        if self.right: return self.right.subtree_first()
        while self.parent and (self is self.parent.right): #A is parent's left child and A's parent exists
            self = self.parent
        return self.parent

    def predecessor(self):
        if self.left: return self.left.subtree_last()
        while self.parent and (self is self.parent.left):
            self = self.parent
        return self.parent

    def subtree_insert_before(self, A):
        if self.left:
            self = self.left.subtree_last()
            self.right, A.parent = A, self
        else:
            self.left, A.parent = A, self
        self.maintain()

    def subtree_insert_after(self, A):
        if self.right:
            self = self.right.subtree_first()
            self.left, A.parent = A, self
        else:
            self.right, A.parent = A, self
        self.maintain()

    def delete(self):
        if not self.left and not self.right: # when self is leaf
            if self.parent:
                A = self.parent
                if A.left is self: A.left = None
                else: A.right = None
                self.parent = None

        if self.left:
            self.item, self.left.subtree_last().item = self.left.subtree_last().item, self.item
            self.left.subtree_last().delete()

        else:
            self.item, self.right.subtree_first().item = self.right.subtree_first().item, self.item
            self.right.subtree_last().delete()

    def subtree_delete(self):
        if self.left or self.right:
            if self.left: B = self.predecessor()
            else: B = self.sucessor()
            self.item, B.item = B.item, self.item
            return B.subtree_delete()

        if self.parent:
            if self.parent.left is self: self.parent.left = None
            else: self.parent.right = None
            self.parent.maintain()
        return self

    def subtree_rotate_right(self):
        assert self.left
        B, E = self.left, self.right
        A, C = B.left, B.right
        B, self = self, B
        self.item, B.item = B.item, self.item
        B.left, B.right = A, self
        self.left, self.right = C, E
        if A: A.parent = B
        if E: E.parent = self
        B.subtree_update()
        self.subtree_update()

    def subtree_rotate_left(self):
        assert self.right
        A, D = self.left, self.right
        C, E = D.left, D.right
        self, D = D, self
        self.item, D.item = D.item, self.item
        self.left, self.right = A, C
        D.left, D.right = self, E
        if A: A.parent = self
        if E: E.parent = D
        self.subtree_update()
        D.subtree_update()

    def skew(self):
        return height(self.right) - height(self.left)

    def rebalance(self):
        if self.skew() == 2:
            if self.right.skew() < 0:
                self.right.subtree_rotate_right()
            self.subtree_rotate_left()
        elif self.skew() == -2:
            if self.left.skew() > 0:
                self.left.subtree_rotate_left()
            self.subtree_rotate_right()

    def maintain(self):
        self.rebalance()
        self.subtree_update()
        if self.parent: self.parent.maintain()

class Binary_Tree:
    def __init__(self, Node_Type = Binary_Node):
        self.root = None
        self.size = 0
        self.Node_Type = Node_Type

    def __len__(self): return self.size
    def __iter__(self):
        if self.root:
            for A in self.root.subtree_iter():
                yield A.item

    def build(self, X):
        A = [x for x in X]
        def build_subtree(A, i, j):
            c = (i + j) // 2
            root = self.Node_Type(A[c])
            if i < c:
                root.left = build_subtree(A, i, c - 1)
                root.left.parent = root
            if j > c:
                root.right = build_subtree(A, c + 1, j)
                root.right.parent = root
            return root
        self.root = build_subtree(A, 0, len(A) - 1)

class BST_Node(Binary_Node):
    def subtree_find(self, k):
        if self.item.key > k:
            if self.left: self.left.subtree_find(k)
        elif self.item.key < k:
            if self.right: self.right.subtree_find(k)
        else: return self

        return None

    def subtree_find_next(self, k):
        if self.item.key <= k:
            if self.right: return self.right.subtree_find_next(k)
            else: return None

        elif self.item.key > k:
            if self.left: return self.left.subtree_find_next(k)
            else: return self

        return self

    def subtree_find_prev(self, k):
        if self.item.key >= k:
            if self.left: return self.left.subtree_find_prev(k)
            else: return None
        elif self.item.key < k:
            if self.right: return self.right.subtree_find_prev(k)
            else: return self

        return self

    def subtree_insert(self, B):
        if B.item.key < self.item.key:
            if self.left: self.left.subtree_insert(B)
            else: self.subtree_insert_before(B)

        elif B.item.key > self.item.key:
            if self.right: self.right.subtree_insert(B)
            else: self.subtree_insert_after(B)

        else:
            self.item = B.item

class Set_Binary_Tree(Binary_Tree):
    def __init__(self): super().__init__(BST_Node)

    def iter_order(self): yield from self

    def build(self, X):
        for x in X: self.insert(x)

    def find_min(self):
        if self.root: return self.root.subtree_first()

    def find_max(self):
        if self.root: return self.root.subtree_last()

    def find(self, k):
        if self.root:
            node = self.root.subtree_find(k)
            if node:
                return node.item

    def find_next(self, k):
        if self.root:
            node = self.root.subtree_find_next(k)
            if node:
                return node.item

    def find_prev(self, k):
        if self.root:
            node = self.root.subtree_find_prev(k)
            if node:
                return node.item

    def insert(self, x):
        new = self.Node_Type(x)
        if self.root:
            self.root.subtree_insert(new)
            if new.parent is None: return False

        else:
            self.root = new

        self.size += 1
        return True

    def delete(self, k):
        assert self.root
        node = self.root.subtree_find(k)
        assert node
        ext = node.subtree_delete()
        if ext.parent is None: self.root = None
        self.size -= 1
        return ext.item

A: Wikipedia defines an in-place algorithm as follows:

In computer science, an in-place algorithm is an algorithm which transforms input using no auxiliary data structure. However, a small amount of extra storage space is allowed for auxiliary variables. The input is usually overwritten by the output as the algorithm executes. An in-place algorithm updates its input sequence only through replacement or swapping of elements.

So one of the properties of an algorithm that is called "in-place" is that it does not copy all input values into an newly allocated data structure. If an algorithm creates a binary search tree (like AVL), for which node objects are created that are populated with the input values, then it cannot be called in-place by the above definition, even if at the end of the process the values are copied back into the input array.
As a comparison, heap sort does not have to create a new data structure, as the input array can be used to reorganise its values into a heap. It merely has to swap values in that array in order to sort it. It is therefore an in-place algorithm.


Q: Добавление и удаление - код дублируется C# Не принимают работу. Помогите решить.
static void Add(ref string[] fio, ref string[] position)
    {
        string[] tempFio = new string[fio.Length + 1];
        string[] tempPosition = new string[position.Length + 1];

        Console.WriteLine("Введите ФИО: ");
        string enterFio = Console.ReadLine();
        tempFio[tempFio.Length - 1] = enterFio;

        Console.WriteLine("Введите должность: ");
        string enterPosition = Console.ReadLine();
        tempPosition[tempPosition.Length - 1] = enterPosition;

        for (int i = 0; i < fio.Length; i++)
        {
            tempFio[i] = fio[i];
            tempPosition[i] = position[i];
        }
        fio = tempFio;
        position = tempPosition;
        Console.WriteLine();
    }

    static void Remove(ref string[] fio, ref string[] position)
    {
        string[] tempRemoveFio = new string[fio.Length - 1];
        string[] tempRemovePosition = new string[position.Length - 1];
        int id = Convert.ToInt32(Console.ReadLine());
        Console.WriteLine();
        if (tempRemoveFio.Length >= id)
        {
            for (int i = 0; i < tempRemoveFio.Length; i++)
            {
                if (i < id)
                {
                    tempRemoveFio[i] = fio[i];
                    tempRemovePosition[i] = position[i];
                }
                else
                {
                    tempRemoveFio[i] = fio[i + 1];
                    tempRemovePosition[i] = position[i + 1];
                }
            }
            fio = tempRemoveFio;
            position = tempRemovePosition;
            Console.WriteLine($"Вы удалили досье под номером - {id}");
        }
        else
        {
            Console.WriteLine($"Досье под номером {id} не существует.");
        }
        Console.WriteLine();
    }


Q: How BitTorrent client is able to connect to a IP address when my browser cant? My institute's router blocks all my http request on browser. The image below shows what I get when i type in google.com (while connected to my institute's router)

But I observed a weird thing. my bittorent client (utorrent app) is able to connect to peers and download torrents when I am connected to that same router. I was able to download over 4gb of torrents.
v
This is the peerlist I got from my recent torrent download(successfully finished using that institute's router)
43.231.56.248:20473
196.235.182.163:24814
58-97-16-42.static.asianet.co.th:9185

from this list... I chose 196.235.182.163:24814 for experimenting.

*

*When connected to my mobile wifi I typed http://196.235.182.163:24814/ in the browser addressbar.
In return: this page shown below came in response

*when connected to my institute's wifi I typed http://196.235.182.163:24814/ in the browser addressbar.
In return: this error page showed up and in another tab that router's logging software's Login page showed up
ERROR PAGE

My question
when connected to institute's wifi, How utorrent is able to connect with that peer at 196.235.182.163:24814 and at the same time my browser shows "Connection timed out" error page when trying to get response from http://196.235.182.163:24814??
How uTorrent is able to connect and not my browser?
IMPORTANT thing to note
In the browser's address bar when I type in google.com:80 (port:80) while connected to institute's router I get a "cant reach page" in browser
AND
when I type in 196.235.182.163:24814 (port:24814 which falls in the range of 6881 to 65535) while connected to institute's router I get a "connection timed out" in browser
I know a few things about Bittorrent:
standard BitTorrent protocol uses ports 6881 through 6889, however in reality BitTorrent clients may use any port available(maximum possible TCP port number is 65535)
(maybe these ports are not banned by that router's firewall and can allow communication/torrenting)


Q: Unhandled exception is not being caught by the handlers We have registered for the unhandled exceptions in the following way. The application is a remoting server. If an unhandled exception is thrown from the remoting server it is not handled by the unhandled exception handlers. What could be the problem?
[STAThread]

[Obfuscation(Exclude = true)]
static void Main(string[] args)
{

    Application.ThreadException += new ThreadExceptionEventHandler(OnThreadException);
    AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(OnUnhandledException);
    .
    .
    .

    Application.EnableVisualStyles();
    Application.Run(form);

}

A: Hope this method helps you 'Application.SetUnhandledExceptionMode'. It instructs the application how to respond to unhandled exceptions.
static void Main(string[] args)
{

    Application.ThreadException += new ThreadExceptionEventHandler(OnThreadException);
    AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(OnUnhandledException);

    Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);

    Application.EnableVisualStyles();
    Application.Run(form);

}

A: If it's a remoting server and the exception is happening as part of client interaction, then the exception will be sent to the client without causing the server to crash.


Q: OPENSSL error: could not find native static library `C`, perhaps an -L flag is missing? I get the following error when I try to run the below code for a DTLS client server program using rust through visual studio code and its terminal. I have already installed openssl libraries using vcpkg and set the environment variables. I have also installed the c/c++ extensions for vscode.
Error: error: could not find native static library C, perhaps an -L flag is missing?

How do I resolve this error? My DTLS code is given below along with build.rs and cargo.toml
MAIN.rs
use openssl::ssl::SslMethod;
use std::{
io::{Read, Write},
net::UdpSocket,
thread,
time::Duration,
};

use udp_dtls::{Certificate, DtlsAcceptor, DtlsConnector, Identity, SrtpProfile};
use udp_dtls::{DtlsAcceptorBuilder, UdpChannel};

fn main() {
let buffer = include_bytes!("../test/identity.p12");
let identity = Identity::from_pkcs12(buffer, "mypass").unwrap();

let root_ca = include_bytes!("../test/root-ca.der");
let root_ca = Certificate::from_der(root_ca).unwrap();

let acceptor = DtlsAcceptor::builder(identity).build().unwrap();
let connector = DtlsConnector::builder()
    .add_srtp_profile(SrtpProfile::Aes128CmSha180)
    .add_srtp_profile(SrtpProfile::AeadAes256Gcm)
    .add_root_certificate(root_ca)
    .build()
    .unwrap();

let server = UdpSocket::bind("127.0.0.1:0").unwrap();
let client = UdpSocket::bind("127.0.0.1:0").unwrap();

let server_addr = server.local_addr().unwrap();
let client_addr = client.local_addr().unwrap();

let server_channel = UdpChannel {
    socket: server,
    remote_addr: client_addr,
};

let client_channel = UdpChannel {
    socket: client,
    remote_addr: server_addr,
};

let guard = thread::spawn(move || {
    let mut dtls_server = acceptor.accept(server_channel).unwrap();

    let mut count = 0;

    while true {
        let mut received = [0; 5];

        dtls_server.read_exact(&mut received);

        println!(
            "{:?} {:?}",
            count,
            String::from_utf8_lossy(received.as_ref())
        );

        count = count + 1;
        thread::sleep(Duration::from_millis(2));
    }
});

let mut dtls_client = connector.connect("foobar.com", client_channel).unwrap();

while true {
    let mut buf = [0; 5];

    let buf = b"hello";
    dtls_client.write_all(buf);

    thread::sleep(Duration::from_millis(30));
}
}

CARGO.toml
[package]
name = "udp-dtls"
version = "0.1.0"
authors = ["Timon Post <https://github.com/TimonPost>"]
edition = "2018"
description = "DTLS abstraction ontop of UDP"
repository = "https://github.com/TimonPost/udp-dtls"
documentation = "https://docs.rs/udp-dtls/"
license = "MIT"
keywords = ["DTLS", "UDP", "connection", "openssl", "ssl"]
exclude = ["target", "Cargo.lock"]
readme = "README.md"

[dependencies]
openssl = "0.10.19"
openssl-probe = "0.1.2"
log = "0.4.6"
bytes = "0.4.11"

[features]
vendored = ["openssl/vendored"]

BUILD.rs
use std::fs::File;
use std::io::Write;
use std::process::Command;
use std::env;
fn main() -> std::io::Result<()> {

if let Ok(v) = env::var("DEP_OPENSSL_VERSION_NUMBER") {
    let version = u64::from_str_radix(&v, 16).unwrap();

    if version >= 0x1_01_01_00_0 {
        println!("cargo:rustc-cfg=openssl111");
    }
}

let certs_dir = "src/certs";
let keys_dir = "src/keys";
let scratch_dir = "openssl-temp";
let server_ext = &format!("{}/server_ext", scratch_dir);
let client_ext = &format!("{}/client_ext", scratch_dir);

for dir in &[certs_dir, keys_dir, scratch_dir] {
    // create if dir does not exist
    match std::fs::create_dir(dir) {
        _ => {}
    }
}

let mut file = File::create(server_ext).unwrap();
file.write(b"basicConstraints=CA:false\nkeyUsage=critical,keyEncipherment")?;

let mut file = File::create(client_ext).unwrap();
file.write(b"basicConstraints=CA:false\nkeyUsage=critical,digitalSignature")?;

// Generate self-signed CA
Command::new("openssl")
    .args(&[
        "req",
        "-x509",
        "-newkey",
        "rsa:2048",
        "-subj",
        "/CN=ca",
        "-nodes",
        "-keyout",
        &format!("{}/ca-key.pem", keys_dir),
        "-out",
        &format!("{}/ca-cert.pem", certs_dir),
        "-addext",
        "keyUsage=critical,keyCertSign",
    ])
    .output()?;

// Generate server key and CSR
Command::new("openssl")
    .args(&[
        "req",
        "-newkey",
        "rsa:2048",
        "-subj",
        "/CN=server",
        "-nodes",
        "-keyout",
        &format!("{}/server-key.pem", keys_dir),
        "-out",
        &format!("{}/server-csr.pem", scratch_dir),
    ])
    .output()?;

// Sign server CSR
Command::new("openssl")
    .args(&[
        "x509",
        "-req",
        "-CAcreateserial",
        "-CA",
        &format!("{}/ca-cert.pem", certs_dir),
        "-CAkey",
        &format!("{}/ca-key.pem", keys_dir),
        "-in",
        &format!("{}/server-csr.pem", scratch_dir),
        "-out",
        &format!("{}/server-cert.pem", certs_dir),
        "-extfile",
        server_ext,
    ])
    .output()?;

// Generate client key and CSR
Command::new("openssl")
    .args(&[
        "req",
        "-newkey",
        "rsa:2048",
        "-subj",
        "/CN=client",
        "-nodes",
        "-keyout",
        &format!("{}/client-key.pem", keys_dir),
        "-out",
        &format!("{}/client-csr.pem", scratch_dir),
    ])
    .output()?;

// Sign client CSR
Command::new("openssl")
    .args(&[
        "x509",
        "-req",
        "-CAcreateserial",
        "-CA",
        &format!("{}/ca-cert.pem", certs_dir),
        "-CAkey",
        &format!("{}/ca-key.pem", keys_dir),
        "-in",
        &format!("{}/client-csr.pem", scratch_dir),
        "-out",
        &format!("{}/client-cert.pem", certs_dir),
        "-extfile",
        client_ext,
    ])
    .output()?;

std::fs::remove_dir_all(scratch_dir)?;

Ok(())
}

For further reference please check this link for full code: https://github.com/TimonPost/udp-dtls


Q: SMPS step-down transformer unexpected waveforms In the process of attempting to modify the output voltage of an existing SMPS (see sketched circuit), I've come across unexpected waveforms of the step-down transformer (see two snapshots of primary coil, two time bases).
I was expecting a square wave (instead of a "fading-ringing" occurring 3 times in sequence) oscillating at a frequency specified by the PWM controller (DP2281 with Fixed Switching Frequency of 65kHz).
I was hoping someone could explain what's going on.
Thanks
P.S. This post is to help me progress with a previous post seeking help to modify the output voltage of a SMPS.

SMPS Circuit diagram

Primary waveform in 20 microseconds time base

Primary waveform in 5 milliseconds time base

A:
I was expecting a square wave (instead of a "fading-ringing" occurring
3 times in sequence)

According to the data sheet of the DP2281, it's a flyback converter controller and, what you see is pretty much what all flyback converters produce regarding the waveforms.
The ringing is the leakage inductance of the transformer primary trying to get rid of the unused (and unusable) energy by dumping it into both the snubber and the power MOSFET's parasitic capacitance. Pretty typical I'd say.
So, that's the "fading-ringing" you see. Regarding only seeing three pulses then a bigger gap to another bunch of pulses (not captured on your o-scope), that's because the loading on the secondary circuit is quite light and the controller is going into burst mode having achieved its primary objective of producing the correct DC voltage on the secondary DC output.

I was hoping someone could explain what's going on.

Hopefully that's sorted now.


Q: Wordpress if logged out, Laravel if logged in Well, the title explains it well... I do use Laravel for a control panel and Wordpress as the frontend facing the "outside world".
I need to use the same URL for both, I've accomplished it partially processing Wordpress as a Laravel view, but I have troubles with the Laravel namespaces/autoload and the Wordpress functionality.
It's easy to do what I need with .htaccess considering default routes... But the main trouble is with the index. The idea is to have the / route with Wordpress by default and with Laravel when logged in. Any ideas?

A: Well, sadly nobody answered. But I did it. Simply I did use a cookie to know where am I.
On laravel's www/index.php
if($_COOKIE['laravel']||$_SERVER['REQUEST_URI']=='/login'){
    require __DIR__ . '/../private/bootstrap/autoload.php';
    $app = require_once __DIR__ . '/../private/bootstrap/start.php';
    $app->run();
}else{
    define('WP_USE_THEMES', true);
    require( dirname( __FILE__ ) . '/wordpress/wp-blog-header.php' );
}

On controllers/UserController.php function login()
if(Input::has('remember'))
   setcookie ('laravel','yes!');
else
   setcookie ('laravel','right!',time()+60*60*24*30);

On controllers/UserController.php function logout()
setcookie('laravel', null, -1);

Hope it helps somebody :)


Q: maven download plugin to add downloaded resource to jar I am using download-maven-plugin to download some of resources to be used in my project. The download is successful and I can use the downloaded file.
However, what I want is to include the downloaded file in the JAR.
Note : The resource file will be included in the JAR when it was pre-downloaded before running the build, but if it is not present (e.g. deleted or I want to update it perhaps) the resource file is not included in the JAR.
Basically what I want is to include the recently downloaded file (from mvn clean install) in the output JAR.
        <plugin>
            <groupId>com.googlecode.maven-download-plugin</groupId>
            <artifactId>download-maven-plugin</artifactId>
            <version>1.4.0</version>
            <executions>
                <execution>
                    <phase>prepare-package</phase>
                    <goals>
                        <goal>wget</goal>
                    </goals>
                    <configuration>
                        <url>https://downloadurl</url>
                        <outputFileName>error.json</outputFileName>
                        <outputDirectory>${project.resources.dir}/commons</outputDirectory>
                    </configuration>
                </execution>
            </executions>
        </plugin>

Same thing happens when I use maven-ant-run plugin.
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-antrun-plugin</artifactId>
            <executions>
                <execution>
                    <id>download-files</id>
                    <phase>prepare-package</phase>
                    <goals>
                        <goal>run</goal>
                    </goals>
                    <configuration>
                        <tasks>
                            <get src="https://downloadurl"
                                 dest="${project.resources.dir}/commons/data.json"
                                 verbose="true"
                                 usetimestamp="true"/>
                        </tasks>
                    </configuration>
                </execution>
            </executions>
        </plugin>

A: Just download it to ${basedir}/target/classes before packaging phase. You don't need it to be in sources in order to include it to JAR.

A: Solved!
I changed the phase to process-resources..
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-antrun-plugin</artifactId>
            <executions>
                <execution>
                    <id>download-files</id>
                    <phase>process-sources</phase>
                    <goals>
                        <goal>run</goal>
                    </goals>
                    <configuration>
                        <tasks>
                            <get src="https://downloadUrl"
                                 dest="${project.resources.dir}/commons/error.json"
                                 verbose="true"
                                 usetimestamp="true"/>
                        </tasks>
                    </configuration>
                </execution>
            </executions>
        </plugin>


Q: Can not import copy_reg I am hosting my Web2py app on PythonAnyware and have an issue importing copy_reg which web2py apparently needs. In previous versions this was no issue.
The trace back is as follows:
Traceback (most recent call last):

File "/home/richdijk/web2py/gluon/restricted.py", line 220, in restricted
  exec ccode in environment
File "/home/richdijk/web2py/applications/im/models/db.py", line 78, in <module>
  auth.define_tables(username=False, signature=False)
File "/home/richdijk/web2py/gluon/tools.py", line 1784, in define_tables
   format='%(first_name)s %(last_name)s (%(id)s)'))
File "/home/richdijk/web2py/gluon/dal.py", line 8223, in define_table
   table = self.lazy_define_table(tablename,*fields,**args)
File "/home/richdijk/web2py/gluon/dal.py", line 8260, in lazy_define_table
   polymodel=polymodel)
File "/home/richdijk/web2py/gluon/dal.py", line 1122, in create_table
   sql_fields_old = pickle.load(tfile)
File "/home/richdijk/web2py/gluon/custom_import.py", line 92, in custom_importer
  return base_importer(pname, globals, locals, fromlist, level)
ImportError: No module named copy_reg

Does anybody know the resolution for this?
Thank you

A: For future reference:
Most often you should clear the cache and sessions. Use the appadmin interface to have a gui for this. This solved the issue for me more than once.
Sessions are pickled files which might lead to these problems. For example if you synchronize between different platforms, python versions and maybe sometimes even between upgrades on web2py (though i'm not certain on the latter).


Q: Run an activity in background I'm using an activity to get MMS attachment once a MMS is received. I have completed the MMS listener for this and it will call the activity, which will use getContentResolver() to grab the attachment. I want the activity to run in the background, without showing the empty UI to the user. Is there anyway to do it?

A: You will want to use a service to make this happen. It is basically an activity without a view.  Check out the link below for more info.
http://developer.android.com/guide/topics/fundamentals/services.html


Q: git reset --mixed delete newly added file? I'm working with git on Github with a C++ project.
I have done the following in this order:

*

*Codding existing and new .cpp and .h files. Also added a big .stl file.

*Add the new files to git

*Create commit "A" with this changes

*Tried to push commit "A" to Github. It didn't let me push the commit because a file of 121MB had been added, which is more than the Github limit.

*Used the git reset --mixed command so that I could undo the commit "A" containing the large file, add that file to .gitignore, and recreate a commit without that file.

Now the changes contained in files that were already tracked have remained and I can re-commit them, but the newly added files in commit "A" are all gone.
Isn't the git reset --mixed command just undoing the commits without changing the files?
Is there any way to recover these files that I had just added to git and that have been deleted?

A: Apparently, the action that hides behind your IDE's "reset commit" isn't git reset --mixed, and it resulted in files being deleted from your disk.

As said in the comments : you can use the reflog to find past commits.

*

*run git reflog to spot the sha for commit A (the faulty commit with the 121MB file)

*use whatever action you see fit to get files back from that commit :

*

*git reset A

*git checkout A -- file1 file2

*git restore -s A -W -- . or git restore -s A -W -- file1 file2

*...


Q: how can i add an attribute onClick oto my links generated automatically? I would like to add an attribute onClick to my links generated automatically with jquery.
I select the parent div and then search if it has a link child, then add the attribute onClick.
It works on localhost but not on server
there is my code :
$('div.holder_notify_drop_data,li.holder_notify_drop_data').each(function () {
    if ($(this).children('a').hasClass('holder_notify_drop_link')) {
        $(this).on('click', function (e) {
            var url = $(this).children('a').attr('href');
            $(this).children('a').attr('onClick', "openFrame('" + url + "','yes')");
            e.preventDefault();
        });
    };)
};

How can i do this ?

A: Make sure you include jQuery:

IMPORTANT: Also put your code inside a document-ready function and I would suggest you to use jQuery click() function instead of the way you have done, but that's okay:
$(document).ready(function () {

$('div.holder_notify_drop_data,li.holder_notify_drop_data').each(function(){
if ($(this).children('a').hasClass('holder_notify_drop_link')){
$(this).on('click',function(e) {
var url = $(this).children('a').attr('href');
$(this).children('a').attr('onClick',"openFrame('"+url+"','yes')");
  e.preventDefault();
});
};
)};

});

A: Here's a working example http://jsfiddle.net/g248G/.
HTML:

    Stackoverflow.com

        Google.com

Javascript:
function openFrame(URL, option) {
    window.open(URL);
}

$(document).ready(function() {

    $('div.holder_notify_drop_data,li.holder_notify_drop_data').each(function() {
        $(this).children('a').each(function() {
            var $link = $(this);
            if ($link.hasClass('holder_notify_drop_link')) {
                var URL = $link.attr('href');
                $link.on('click', function(event) {
                    event.preventDefault();
                    openFrame(URL, 'yes');
                });
            }
        });
    });

});

A: Why not use jQuery.on() for that?
This will bind click function to all current and future elements of a in holder_notify_drop_data container.
$('.holder_notify_drop_data').on('click', 'a', function (ev) {
    ev.preventDefault();

    openFrame($(this).prop('href'), 'yes');
});


Q: Existence of global attractor in duffing equation How to prove the existence and identify global attractor in Duffing equation
$$\ddot{x}+\epsilon \dot{x}+x^3-ax=0$$
where $\epsilon >0$ and $a>0$?
I found a definition:
A bounded closed set $A_1 \subset X$ is called a global attractor for a dynamical system $(X, S_t)$, if

*

*$A_1$ is an invariant set

*the set $A_1$ uniformly attracts all trajectories starting in bounded sets, i.e. for any bounded set $B$ from $X$
$$\lim_{t\to \infty} \sup \lbrace \operatorname{dist}(S_t y, A_1): y\in B \rbrace=0$$
where $\operatorname{dist}(z,A)=\inf\lbrace\operatorname{d}(z,y): y\in A\rbrace$ where $\operatorname{d}(z,y)$ is the distance between the elements $z$ and $y$ in $X$.

I finished only ODE course and I don't know a lot about dynamical systems.

A: The equation describes a mechanical system with friction/energy dissipation. Or in formulas
$$
\frac{d}{dt}\left[\frac12\dot x^2+\frac14(x^2-a)^2\right]=-ϵ\dot x^2.
$$
So as long as the particle the system describes is in motion, it will lose energy and move down to one of the minima $x=\pm\sqrt{a}$, which both are stable equilibrium points of the equation.

A: Hint.
This DE can be written as
$$
\dot x = y\\
\dot y = a x-x^3-\epsilon y
$$
with equilibrium points
$$
\left[
\begin{array}{ccc}
x & y & \text{type} \\
 0 & 0 & \text{saddle}\\
 -\sqrt{a} & 0 & \text{sink}\\
 \sqrt{a} & 0 & \text{sink}\\
\end{array}
\right]
$$
This qualification is done according to the jacobian eigenvalues
$$
J = \left(
\begin{array}{cc}
 0 & 1 \\
 a-3 x^2 & -\epsilon \\
\end{array}
\right)
$$

Attached an orbit for $a = 1, \epsilon = 0.1, x_0 = 2, y_0 = 1$


Q: Difference between 2 DTD tag I want to know what is difference between this 2 ELEMENT tag :
<!ELEMENT bank (account*, customer*, depositor*)>

and
<!ELEMENT bank (account | customer | depositor )*>

thanks.

A: In a nutshell, the first ELEMENT declaration is saying the child elements have to be in a specific order. The second ELEMENT declaration is saying the child elements can be in any order.
The following means: a bank element containing zero or more account elements, followed by zero or more customer elements, followed by zero or more depositor elements. (In that specific order.)
<!ELEMENT bank (account*, customer*, depositor*)>

The following means: a bank element containing zero or more account or customer or depositor elements (in any order).
<!ELEMENT bank (account | customer | depositor )*>

The ',' means "followed by" and the '|' means "or". The '*' means zero or more. Also, a '+' means one or more (at least one).

A: It denotes a regular expression. Though I'm not very good at that, I think the second  tag accepts sub-element of either account or customer or depositor.


Q: Parsley Form Validation Error Okay,
I'm still a javascript student so I need some help. I'm using parsley.js for form validation and then jquery ajax to submit the form. I keep getting this luke warm message in the console to bind parsley to an existing element. I've followed all the instructions but continue to get  a warning.
How can I get rid of the warning?
Code can be seen here: http://madmen6raphics.com/clients/marble/
thanks in advance.
Here is the code:
HTML:
<form action='mail_form.php' data-parsley-validate id='newsletter_signup' method='post' name='newsletter_signup' novalidate>
            <fieldset>
              <legend>Joing our mailing list!</legend>
              name:
              <input data-parsley-minlength='5' id='name' name='name' placeholder='John Doe' required type='text'>
              email:
              <input id='email' name='email' placeholder='johndoe@me.com' required type='email'>
              <input name='Submit' type='submit'>
            </fieldset>
          </form>

javascript:

$('#newsletter_signup').parsley();

A: You are getting two errors of

You must bind Parsley on an existing element.

but those errors are not related to the code you posted.
In your ...js/site.js you have the following code:
$(document).ready(function() {
    $('.slider').flexslider({controlNav: false,slideshowSpeed: 3000,directionNav: true});
    $('input').iCheck({checkboxClass: 'icheckbox_square-yellow',radioClass: 'iradio_square-yellow',increaseArea: '20%'});
    $('#newsletter_signup').parsley();
    $('#request_a_quote').parsley();
    $('#contact').parsley();
    var form = $('#newsletter_signup');
    (...)

You are binding parsley to three elements with the following ids: newsletter_signup, request_a_quote and contact.
The thing is, in the current page you only have the element newsletter_signup. If you do a console.log($('#request_a_quote')) you will see an empty object.
So, to fix your issue, you need to remove the code that binds parsley to non-existent elements. Or you could change your code in order to bind parsley only if the element exist. Something like this:
$(document).ready(function() {
    $('.slider').flexslider({controlNav: false,slideshowSpeed: 3000,directionNav: true});
    $('input').iCheck({checkboxClass: 'icheckbox_square-yellow',radioClass: 'iradio_square-yellow',increaseArea: '20%'});
    if ($('#newsletter_signup').length > 0 )
        $('#newsletter_signup').parsley();
    if ($('#request_a_quote').length > 0 )
        $('#request_a_quote').parsley();
    if ($('#contact').length > 0 )
        $('#contact').parsley();
    var form = $('#newsletter_signup');
    (...)


Q: WPF DataGrid selected row stays highlighted even when user clicks another control Is it possible to turn off the selected row highlighting when a user clicks another control in the window?
Thanks in advance.

A: You could set the SelectedIndex to -1 in the LostFocus event, thus losing the selected item and removing the highlight.


Q: Quickstart.py - failed to connect to all addresses I installed the Python libraries on my local PC, I also added my GA-4 Property ID. When I attempt to run the script I get the following error, note that the error actually makes sense because the IP Address failing doesn't have a valid SSL certificate:
Traceback (most recent call last):
  File "\\usalbodd01\bod_Share\BODS_Tools\google\api_core\grpc_helpers.py", line 72, in error_remapped_callable
    return callable_(*args, **kwargs)
  File "\\usalbodd01\bod_Share\BODS_Tools\grpc\_channel.py", line 946, in __call__
    return _end_unary_response_blocking(state, call, False, None)
  File "\\usalbodd01\bod_Share\BODS_Tools\grpc\_channel.py", line 849, in _end_unary_response_blocking
    raise _InactiveRpcError(state)
grpc._channel._InactiveRpcError: <_InactiveRpcError of RPC that terminated with:
        status = StatusCode.UNAVAILABLE
        details = "failed to connect to all addresses; last error: UNKNOWN: ipv4:142.250.190.10:443: Ssl handshake failed: SSL_ERROR_SSL: error:1000007d:SSL routines:OPENSSL_internal:CERTIFICATE_VERIFY_FAILED"
        debug_error_string = "UNKNOWN:failed to connect to all addresses; last error: UNKNOWN: ipv4:142.250.190.10:443: Ssl handshake failed: SSL_ERROR_SSL: error:1000007d:SSL routines:OPENSSL_internal:CERTIFICATE_VERIFY_FAILED {grpc_status:14, created_time:"2022-11-28T18:41:22.060505311+00:00"}"
>

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "\\usalbodd01\bod_Share\BODS_Tools\GoogleQuickstart.py", line 51, in <module>
    sample_run_report("")
  File "\\usalbodd01\bod_Share\BODS_Tools\GoogleQuickstart.py", line 43, in sample_run_report
    response = client.run_report(request)
  File "\\usalbodd01\bod_Share\BODS_Tools\google\analytics\data_v1beta\services\beta_analytics_data\client.py", line 511, in run_report
    response = rpc(
  File "\\usalbodd01\bod_Share\BODS_Tools\google\api_core\gapic_v1\method.py", line 154, in __call__
    return wrapped_func(*args, **kwargs)
  File "\\usalbodd01\bod_Share\BODS_Tools\google\api_core\grpc_helpers.py", line 74, in error_remapped_callable
    raise exceptions.from_grpc_error(exc) from exc
google.api_core.exceptions.ServiceUnavailable: 503 failed to connect to all addresses; last error: UNKNOWN: ipv4:142.250.190.10:443: Ssl handshake failed: SSL_ERROR_SSL: error:1000007d:SSL routines:OPENSSL_internal:CERTIFICATE_VERIFY_FAILED

Have any of you run into this when attempting to run the quickstart.py script locally?
Regards,
Greg
I attempted to run the script after following the "TODOS". I installed the Google certificates locally. I then tested the IP Address the script is failing on, the address is not secured.
Your connection isn't private
Attackers might be trying to steal your information from 142.250.190.10 (for example, passwords, messages, or credit cards).
NET::ERR_CERT_AUTHORITY_INVALID


Q: mootools Fx.slide not working IE6 I have some javascript that is built on top of mootools that is basically giving a div some show/hide functionality.
window.addEvent('domready', function(){
/*var mySlide = new Fx.Slide('customise_text').hide()
var mySlide2 = new Fx.Slide('customise_link').hide()
$('customise').addEvent('click', function(e){
    $('customise').addClass('active');
    mySlide.toggle(); //show-hide login panel
    mySlide2.toggle(); //show-hide login panel
    e.preventDefault();
});*/

/*$('moodal_close').addEvent('click', function(){
    alert("1");
});*/
//alert("hello")
var vertical_slide = $('vertical_slide');
var checkoutVerticalSlide = $('vertical_slide_checkout');
var v_toggle_checkout = $('v_toggle_checkout');

if(!vertical_slide || !checkoutVerticalSlide || !v_toggle_checkout) {
    return;
} else {

    var status = {
        'true': 'open',
        'false': 'close'
    };
    //-vertical
    var myVerticalSlide = new Fx.Slide('vertical_slide').hide();
    $('v_toggle').addEvent('click', function(e){
        e.preventDefault();
        myVerticalSlide.toggle();
    });

    // When Vertical Slide ends its transition, we check for its status
    // note that complete will not affect 'hide' and 'show' methods
    myVerticalSlide.addEvent('complete', function() {
        if(status[myVerticalSlide.open] == 'open')
        {
            $('v_toggle').addClass('open');
        } else {
            $('v_toggle').removeClass('open');
        }
    });

    var checkout_status = {
        'true': 'open',
        'false': 'close'
    };

    var checkoutVerticalSlide = new Fx.Slide('vertical_slide_checkout').hide();
    $('v_toggle_checkout').addEvent('click', function(e) {
        e.preventDefault();
        checkoutVerticalSlide.toggle();
    });

    checkoutVerticalSlide.addEvent('complete', function() {
        if(status[checkoutVerticalSlide.open] == 'open')
        {
            $('v_toggle_checkout').addClass('open');
        } else {
            $('v_toggle_checkout').removeClass('open');
        }
    });
}

In IE6 I get page loaded with errors and get an error of Object does not support this method or property

A: This could be due to the fact that IE6 does not support the preventDefault method.
Where you make use of this method (e.preventDefault()), replace the call with the following
if (e.preventDefault) { e.preventDefault(); } else { e.returnValue = false; }

See if that works for you :)
While it feels warm and fuzzy to be able to support all browsers, IE6 is not a warm and fuzzy kind of browser. You will keep running into problems if you want to fully support IE6, I'm afraid.


Q: Pandas merge columns, but not the 'key' column This may seem like a stupid question, but this has been bugging me for some time.
df1:
imp_type    value
1           abc
2           def
3           ghi

df2:
id          value2
1           123
2           345
3           567

Merginge the 2 df's:
df1.merge(df2, left_on='imp_type',right_on='id')

yields:
imp_type    value    id    value2
1           abc      1     123
2           def      2     345
3           ghi      3     567

Then I need to drop the id column since it's essentially a duplicate of the imp_type column. Why does merge pull in the join key between the 2 dataframes by default? I would think there should at least be a param to set to False if you don't want to pull in the join key. Is there something like this already or something I'm doing wrong?

A: I agree it would be nice if one of the columns were dropped. Of course, then there is the question of what to name the remaining column.
Anyway, here is a workaround. Simply rename one of the columns so that the joined column(s) have the same name:
In [23]: df1 = pd.DataFrame({'imp_type':[1,2,3], 'value':['abc','def','ghi']})

In [27]: df2 = pd.DataFrame({'id':[1,2,3], 'value2':[123,345,567]})

In [28]: df2.columns = ['imp_type','value2']

In [29]: df1.merge(df2, on='imp_type')
Out[29]:
   imp_type value  value2
0         1   abc     123
1         2   def     345
2         3   ghi     567

Renaming the columns is a bit of a pain, especially (as DSM points out) compared to .drop('id', 1). However, if you can arrange for the joined columns to have the same name from the very beginning, then df1.merge(df2, on='imp_type') would be easiest.


Q: Inno Setup for Windows service? I have a .Net Windows service. I want to create an installer to install that windows service.
Basically, it has to do the following:

*

*Pack installutil.exe (Is it required?)

*Run installutil.exe MyService.exe

*Start MyService

Also, I want to provide an uninstaller which runs the following command:
installutil.exe /u MyService.exe

How to do these using Inno Setup?

A: Here's how i did it:
Exec(ExpandConstant('{dotnet40}\InstallUtil.exe'), ServiceLocation, '', SW_HIDE, ewWaitUntilTerminated, ResultCode);

Apparently, Inno setup has the following constants for referencing the .NET folder on your system:

*

*{dotnet11}

*{dotnet20}

*{dotnet2032}

*{dotnet2064}

*{dotnet40}

*{dotnet4032}

*{dotnet4064}

More information available here.

A: You can use
Exec(
    ExpandConstant('{sys}\sc.exe'),
    ExpandConstant('create "MyService" binPath= {app}\MyService.exe start= auto DisplayName= "My Service" obj= LocalSystem'),
    '',
    SW_HIDE,
    ewWaitUntilTerminated,
    ResultCode
    )

to create a service. See "sc.exe" on how to start, stop, check service status, delete service, etc.

A: You don't need installutil.exe and probably you don't even have rights to redistribute it.
Here is the way I'm doing it in my application:
using System;
using System.Collections.Generic;
using System.Configuration.Install;
using System.IO;
using System.Linq;
using System.Reflection;
using System.ServiceProcess;
using System.Text;

static void Main(string[] args)
{
    if (System.Environment.UserInteractive)
    {
        string parameter = string.Concat(args);
        switch (parameter)
        {
            case "--install":
                ManagedInstallerClass.InstallHelper(new string[] { Assembly.GetExecutingAssembly().Location });
                break;
            case "--uninstall":
                ManagedInstallerClass.InstallHelper(new string[] { "/u", Assembly.GetExecutingAssembly().Location });
                break;
        }
    }
    else
    {
        ServiceBase.Run(new WindowsService());
    }
}

Basically you can have your service to install/uninstall on its own by using ManagedInstallerClass as shown in my example.
Then it's just matter of adding into your InnoSetup script something like this:
[Run]
Filename: "{app}\MYSERVICE.EXE"; Parameters: "--install"

[UninstallRun]
Filename: "{app}\MYSERVICE.EXE"; Parameters: "--uninstall"

A: If you want to avoid reboots when the user upgrades then you need to stop the service before copying the exe and start again after.
There are some script functions to do this at Service - Functions to Start, Stop, Install, Remove a Service

A: have a look at topshelf
http://topshelf-project.com/

*

*it lets you develop your service as a console application

*adds a start/stop service as an API to your service...

*... that you can call from InnoSetup
[Run] Filename: "{app}\myservice.exe"; Parameters: "stop"  ; Flags : waituntilterminated Filename: "{app}\myservice.exe"; Parameters: "uninstall" ; Flags : waituntilterminated Filename: "{app}\myservice.exe"; Parameters: "install -description ""myservice""" ; Flags : waituntilterminated


Q: libpcap or PF_PACKET? I understand this question has been discussed many times: Should I use libpcap or PF_PACKET (the data link socket) to capture packets?
Based on my research, libpcap is suggested over PF_PACKET almost everywhere, mainly due to its portability.
However, for my current project (which is used in a production system), portability is not a concern at all, all I care about is performance (speed, packet loss ratio). My program is running on CentOS 5.10 (kernel 2.6.18)
As far as I know, libpcap put a timestamp on each packet. Does this cause big performance loss?
Are there other factors that make libpcap unsuitable in a high-speed network?

A:
As far as I know, libpcap put a timestamp on each packet.

No, libpcap gets a timestamp for the packet from the OS packet capture mechanism that it uses - which, on Linux is...
...PF_PACKET sockets.
The Linux kernel time stamps incoming packets.  PF_PACKET sockets have multiple ways of reading from them:

*

*regular socket receives, for which you can either get a time stamp with an explicit ioctl (so you can avoid fetching it to userland, but you can't avoid the kernel time stamping the packet in the first place; libpcap, when using regular socket receives, always asks for the time stamp);

*memory-mapped access, which always supplies the time stamp.

Libpcap uses memory-mapped access whenever it's available; if you care about capture performance, you probably want to do so as well.  It's not easy to use, however.


Q: Can we add an uncountable number of positive elements, and can this sum be finite? Can we add an uncountable number of positive elements, and can this sum be finite?
I always have trouble understanding mathematical operations when dealing with an uncountable number of elements. Any help would be great.

A: We have the next proposition
Proposition 1. Let $X$ be an at most countable set, and let $f\colon X\to\mathbf R$ be a function. Then the series $\sum_{x\in X} f(x)$ is absolutely convergent if and only if $$\sup\left\{\sum_{x\in A}|f(x)|:A\subseteq X,  A\text{ finite}\right\}<\infty.$$
Inspired  by  this  proposition,  we  may  now  define  the  concept  of an  absolutely  convergent  series  even  when  the  set  $X$  could  be uncountable.
Definition 2. Let $X$ be a set (which could be uncountable), and let $f\colon X\to\mathbf R$ be a function. We say that the series $\sum_{x\in X} f(x)$ is absolutely convergent if and only if $$\sup\left\{\sum_{x\in A}|f(x)|:A\subseteq X,  A\text{ finite}\right\}<\infty.$$
Note  that  we  have  not  yet  said  what  the  series $\sum_{x\in X} f(x)$ is equal  to.  This  shall  be  accomplished  by  the  following proposition.
Proposition 3. Let  $X$  be  a  set  (which  could  be  uncountable),  and let  $f\colon X\to\mathbf R$ be  a  function  such  that  the  series  $\sum_{x\in X} f(x)$  is absolutely  convergent.  Then  the set $\{x\in X:f(x)\ne0\}$  is  at  most countable.
Because  of  this,  we  can  define  the  value  of $\sum_{x\in X} f(x)$  for  any absolutely  convergent  series  on  an  uncountable  set  $X$  by  the  formula $$\sum_{x\in X} f(x):=\sum_{x\in X:f(x)\ne0} f(x),$$ since  we  have  replaced  a  sum  on  an  uncountable  set  $X$  by  a  sum on  the  countable  set $\{x\in X:f(x)\ne0\}$.  (Note  that  if  the former  sum  is  absolutely  convergent,  then  the  latter  one  is  also.) Note  also  that  this  definition  is  consistent  with  the  definitions  for  series  on  countable  sets.
Remark. The definition of series on countable sets that are use is
Definition 4. Let  $X$  be  a  countable set,  and  let  $f\colon X\to\mathbf R$  be  a  function.  We  say  that  the  series $\sum_{x\in X}f(x)$  is  absolutely  convergent  iff  for  some  bijection  $g\colon\mathbf N\to X$,  the  sum $\sum_{n=0}^\infty  f(g(n))$  is  absolutely  convergent.  We  then  define the  sum  of $\sum_{x\in X}f(x)$ by  the  formula $$\sum_{x\in X}f(x)=\sum_{n=0}^\infty  f(g(n)).$$

A: Suppose $\{s_i : i\in\mathcal I\}$ is a family of positive numbers.$^\dagger$  We can define
$$
\sum_{i\in\mathcal I} s_i = \sup\left\{ \sum_{i\in\mathcal I_0} s_i : \mathcal I_0 \subseteq \mathcal I\ \&\ \mathcal I_0 \text{ is finite.} \right\}
$$
(If both positive and negative numbers are involved, then we have to talk about a limit rather than about a supremum, and then the definition is more complicated and we have questions of conditional convergence and rearrangements.)
Now consider
\begin{align}
& \{i\in\mathcal I : s_i \ge 1\} \\[4pt]
& \{i\in\mathcal I : 1/2 \le s_i < 1 \} \\[4pt]
& \{i\in\mathcal I : 1/3 \le s_i < 1/2 \} \\[4pt]
& \{i\in\mathcal I : 1/4 \le s_i < 1/3 \} \\[4pt]
& \quad \quad \quad \vdots
\end{align}
If one of these sets is infinite, then $\sum_{i\in\mathcal I} s_i=\infty$.  But if all are finite, then $\mathcal I$ is at most countably infinite.
Thus the sum of uncountably many positive numbers is infinite.
I don't know whether by some arguments about rearrangements one could somehow have some sensible definition of a sum of numbers not all having the same sign that could give us a somehow well defined sum of uncountably many numbers and get a finite number.

$^\dagger$ In the initial edition of this answer, I said "Let $S$ be a set of positive numbers and then went on to say
$$
\sum S = \left\{ \sum S_0 : S_0\subseteq S\ \&\ S_0\text{ is finite.} \right\}
$$
However, Dustan Levenstein pointed out in comments that "this definition fails to allow for the same number to occur twice in a sum".  Rather than "twice", I'd say "more than once", since a number might even occur an uncountably infinite number of times.

A: Let $H$ be a positive unlimited integer of nonstandard analysis. Then, for example, the sum
$$ \sum_{n=1}^H n = \frac{H(H+1)}{2}$$
is a sum of uncountably many positive numbers... but it's a hyperfinite nonstandard sum, so it exists by the usual methods of nonstandard analysis. The sum is unlimited, though. Other sums can be finite: e.g.
$$ \sum_{n=1}^H \frac{1}{n!}$$
is a finite nonstandard real number that is infinitesimally close to $e$.
That said, IMO, thinking of hyperfinite sums from nonstandard analysis as being sums of uncountably many elements isn't a particularly fruitful line of thought. (also, the sum only works for internal sequences of elements anyways; you can't take an arbitrary uncountable collection)

I bring this up mainly to show that uncountable sums can make sense in some contexts, even if you can't really do much in a standard setting. Each summation operator one might define can have its own sorts of pecularities.

A: Here is the more general definition of the sum of any function $f:I\rightarrow E$, where $I=$any non empty set and $E$ is a real or complex topological vector space.
Definition 1 We say that the family $f=(f(i))_{i\in I}$ is summable in $E$ of sum $\omega\in E$ if and only if, for all neighborhood $V$ of $\omega$, there exists a finite subset $A\subset I$ of $I$ such that for all finite parts $K$ of $I$ containing $A$, we have $\sum_{i\in L}f(i)-\omega\in V$. f is said to be absolutely summable if and only if $\|f\|=(\|f(i)\|)_{i\in I}$ is summable in $\mathbb{F}=\mathbb{R}$ or $\mathbb{C}$.
Remark 2 This definition does not guarantee the uniqueness of the sum of a given family. The topological vector space $E$ mus be separable for the uniqueness to hold, in which case we write
$$\sum_{i\in I}f(i)=\omega.$$
Proposition 3 If $E$ is a normed space, then a family $f=(f(i))_{i\in I}$ is summable of sum $\omega$ if and only if for any $0<\varepsilon\in \mathbb{R}$ there exists a finite part $A$ of $I$ such that for all finite part $K$ of $I$ with $A\subset K$, we have:
$$\|\sum_{i\in K}f(i)-\omega\|<\varepsilon.$$
Remark 4 If $f=(f(i))_{i\in I}$ is a family in $E$, we can definie $\mathcal{F}(I)=\{A\subset I:~A~\text{is finite}\}$. Embedding $\mathcal{F}(I)$ with the direction ``$\leq$'' defined by $A\leq B$ in $\mathcal{F}$ iff $A\subset B$, we make $\mathcal{F}(I)$ a directed set (or Riesz space). The if we definite $S:\mathcal{F}(I)\rightarrow E$, by $$S(K)=\sum_{i\in K} f(i),$$ we get a net in $E$. We have the following:
Proposition 5 $f$ is summable if and only if the set $S(K)$, defined above, is convergent.
Notice that here we have defined the sum of any kind of number, countable or uncountable. But it is proved that in case $E=\mathbb{F}$ and $I=\mathbb{N}$, the summability coincide with the absolute summability, which in turns coincide with the commutative convergence of the series $\sum_{n=1}^{+\infty}f(n)$, and the value of the sum of the family is the same as the value of this series.