2D from 3D points in HALCON

Question: Given a 3D point coordinate, the internal and the external camera parameters in a calibrated stereo camera setup, is there a HALCON method that gives me the 2D pixel coordinates on each camera?
Regards,
MSK
Answer: You can project the coordinates into 2D world, if the camera parameters are known, using the following:
<code>* Project 3D points into image.
project_3d_point(X, Y, Z, CameraParam, Row, Column)
</code>
Please refer to description here
Comment: @Philip why was my link-fix edit rejected and the same link-fix subsequently applied?
Comment: @MattM because I find the name "Project 3D Point (HALCON docs)" redundant, which was also missing from the original response

2D from 3D points in HALCON


Access an object properties without casting to a type

Question: i am using LINQ to entity to return a list of objects
            var st = personsList.Select(p => new
            {
                ID = p.Id,
                Key = p.Key,
                Name = p.Name,
                Address = p.Address,
                City = p.City,
                PhoneNumber = p.PhoneNumber
            })
            return st.ToList();

after i get the list in another class how can I access each property?
something like
foreach(object s in St)
{
    string name = s.Name;
}

I have no predefined class to cast the object to it.
Can this be done without having to create a class and cast the object to that class type?
Thanks
Comment: http://msmvps.com/blogs/jon_skeet/archive/2009/01/09/horrible-grotty-hack-returning-an-anonymous-type-instance.aspx
Comment: @GeorgeDuckett: Yes, i think jon's title is self-explanatory: _"Horrible grotty hack: returning an anonymous type instance"_
Comment: @TimSchmelter: TL;DR: Just because you can doesn't mean you should. :)
Answer: Are you using C# 4? You could try using dynamic:
foreach(dynamic s in St)
{
    string name = s.Name;
}

The risk is, of course, that if you try to access a property that the object doesn't have you'll only find out at runtime.
As an aside, wouldn't it make more sense in this case to actually create a class that has all these properties? You clearly need them in several places and you'd get the benefits of type-safety and compile-time errors.
Answer: You could use the follwing
foreach(object s in St)
{
   Type type = s.GetType();
   PropertyInfo property = type.GetProperty("Name");
   if(property !=null)
   {
       string name= (string )property.GetValue(s, null);
   }
}

you have to add the namespace System.Reflection to the class
Answer: C# 3.0 has the var type which allows implicit casting.
Comment: It's still strongly typed (the type of `var foo = new Foo()` is `Foo`), and you can't use it to return a value though. Also it's implicit typing, not casting.
Answer: The complier is creating you an anonymous type which can be used within the scope of the method. If you need to pass the results of LINQ query around then it's best to create a domain object to represent that information like PersonSummary and assign the results of the query to that. C# is strongly typed take advantage of that.


Example of a function $f$ which is Lebesgue integrable on $[0,1]$, but max{$f,0$} is NOT Lebesgue integrable?

Question: Can anyone come up with an example of a function $f$ which is Lebesgue integrable on $[0,1]$, but max{$f,0$} is NOT Lebesgue integrable? Thanks.
Answer: By definition $f$ is Lebesgue integrable if and only if the functions $f_+ =\max\{ f ,0\}$ and $f_- =\max\{-f ,0\}$ are integrable.
Comment: Does that mean that there is NO function that satisfies the conditions that I mentioned in my question? Please let me know
Comment: Yes it means that there is NO function that satisfies the conditions


Failed to import python module from different directory

Question: I have this code structure in python3:
- datalake
  __init__.py
  utils
     __init__.py
     utils.py
  lambdas
     __init__.py
     my-lambdas.py
- tests
    __init__.py
    demo.py

All init__.py files are empty.
My problem is how I can import datalake module from tests/demo.py?
I tried from datalake.utils import utils in demo.py but when I run python tests/demo.py from command line, I get this error ModuleNotFoundError: No module named 'datalake'.
If I use this code:
from ..datalake.utils import utils

I will get error ValueError: attempted relative import beyond top-level package.
I also tried to import the module utils from my-lambda.py file which also failed. The code in my-lambda.py is from datalake.utils import utils but I get ModuleNotFoundError: No module named 'datalake' error when run python datalake/lambda/my-lambda.py from command line.
How can I import the module?
Comment: It is not. Do I have to add the path on `PYTHONPATH` as environment variable?
Comment: Is the parent directory (the one containing both datalake and tests) on your PYTHONPATH? I think if it is, it should find the module.
Answer: When you run a command like python tests/demo.py, the folder you are in does not get added to the PYTHONPATH, the script folder does. So a top-level import like import datalake will fail. To get around this you can run your tests as a module:
Python 2:
python -m tests/demo

Python 3:
python -m tests.demo

and any datalake imports in demo.py will work.
It sounds like what you really want to do is have a folder with tests separate to your main application and run them. For this I recommend py.test, for your case you can read Tests Outside Application Code for how to do it. TL;DR is run your tests from your top level project folder with python -m py.test and it will work.
Comment: I got this error `No module named tests/demo'` when run `python -m tests/demo. Do I need to change anything else?
Comment: @ZhaoYi are you in the top project folder? so that `tests/demo.py` exists from the folder you are currently in?
Comment: Yes the file `tests/demo.py` exists in the current directory which is the root of project
Comment: @ZhaoYi sorry it seems this syntax only works in python 2. use `python -m tests.demo` instead.
Answer: First of all, my-lambdas.py is not importable with the import statement as hyphens are not valid in Python identifiers. Try to follow PEP-8's naming conventions, such as mylambdas.py.
Otherwise the package structure looks good, and it should be importable as long as you are at the level above datalake/, e.g., if you were in the directory myproject/ below:
myproject
├── datalake
│   ├── __init__.py
│   ├── utils
│   │   ├── __init__.py
│   │   └── utils.py
│   └── lambdas
│       ├── __init__.py
│       └── mylambdas.py
└── tests
    ├── __init__.py
    └── demo.py

Then this should work:
~/myproject$ python -c 'from datalake import utils'

Otherwise, setting the environment variable PYTHONPATH to the path above datalake/ or modifying sys.path are both ways of changing where Python can import from. See the official tutorial on modules for more information.
Also some general advice: I've found it useful to stick with simple modules rather than packages (directories) until there is a need to expand. Then you can change foo.py into a foo/ directory with an __init__.py file and import foo will work as before, although you may need to add some imports to the __init__.py to maintain API compatibility. This would leave you with a simpler structure:
myproject
├── datalake
│   ├── __init__.py
│   ├── utils.py
│   └── lambdas.py
└── tests
    ├── __init__.py
    └── demo.py

Comment: How do I run the `tests/demo.py` from command line? If I am currently in `myproject` directory, run `python -m tests/demo` gives me `No module named tests/demo` error.
Comment: If these are unit tests, the unit testing framework often has a runner that discovers these. For example with [pytest](http://pytest.org/) (which is great, btw), you just run `pytest` from `myproject/` and it will discover appropriately named files (but they should be named something like `test_lambdas.py`). If `demo.py` is something you want to interactively run, try `python -m tests.demo`. Note the dot (`.`) instead of slash (`/`) in the module path.
Comment: They are not unit tests. they are demo code to run our project from command line.
Answer: You can add the module directory into your sys.path:
import sys
sys.path.append("your/own/modules/folder")  # like sys.path.append("../tests")

but this is a one-shot method, which is just valid at this time, the added path is not permanent, it will be eliminated after the code completed execution.
Answer: One of the ways to import the file directly instead of using from, like import util
Answer: you can try run :
python -m datalake.lambda.my-lambda

follow: https://docs.python.org/3.7/using/cmdline.html#cmdoption-m


sql server: How to find exact match in all the database objects?

Question: select B.* from sys.sql_modules A
JOIN  SYS.objects B ON A.object_id=B.object_id
WHERE definition LIKE '%Packages%'

I want to find all the occurrences of word 'Packages' in all my databse results. I want to only get back results which have this exact match 'Packages' and not other which has this as substring?
Right now i get SPs with 'SPAPacakges' etc which have 'Packages' as substring. I want to remove these.
How do i do that?
SELECT referencing_schema_name, referencing_entity_name,
referencing_id, referencing_class_desc
FROM sys.dm_sql_referencing_entities ('dbo.Packages', 'OBJECT');

This is working for me. But i am not sure whether its perfect. I don't understand its complete meaning.
Answer: If you want to find all occurrences of the word Packages, possibly with whitespace before or after it (i.e. the word by itself in isolation), then you can try the following WHERE condition:
WHERE definition LIKE ' Packages' OR
      definition LIKE 'Packages ' OR
      definition LIKE ' Packages ' OR
      definition LIKE 'Packages'

Comment: It is not returning any results.
Comment: You should also show us some sample records from your tables.
Comment: My original posted query returns me results with words like 'TC_SoldRSAPackages'. When i modified it like you suggested, its not giving any results. Although i ahve multiple SP's that have words like 'Packages'.
Comment: This is why it is so critical for you to show us what you are trying to match (which you still haven't done).  I had to make an assumption to give you answer.  Show us sample data and your desired outcome.
Comment: Apologies if i didn't made myself clear. But i mentioned in first line-I want to find all the occurrences of word 'Packages' in all my databse results.
Answer: Just remove wildcards % from 'Packages' and you could add LTRIM and RTRIM to avoid issues with whitespaces, in following:
select B.* from sys.sql_modules A
JOIN  SYS.objects B ON A.object_id=B.object_id
WHERE LTRIM(RTRIM(definition)) LIKE 'Packages'

Comment: It is not returning any results.


Fretless bass buzz

Question: I have a new fretless bass guitar, a new Ibanez SRF700 Portamento, with stock D'Addario Chromes flatwound strings. I am having trouble with string buzz in one specific part of the fingerboard. When I play F on the A string (8th position), the string buzzes between my finger and the nut. It sounds and feels similar to fret buzz, except there are no frets, and it comes from the nut side, not the bridge side. I don't see any obvious defects in the fingerboard, and sighting down the neck it looks straight with a little relief.
What can I do to troubleshoot this? Do I need to adjust the instrument or my technique? I've found that I can silence the buzzing by muting above the finger playing F, anywhere above the 7th position, but that doesn't seem like a practical solution. I suspect that there is a small defect in the fingerboard or string between the E and F, although I could not find one with a straight edge.
It's difficult to pinpoint, but the buzzing seems most intense between my finger and the E harmonic node right behind it. Muting doesn't help unless I mute between the harmonic node and the nut. If I stop muting, the buzz returns immediately. The buzz seems less if I use my pinky finger or if I barre the strings, more if I use the bony tips of my strong fingers. I suspect that using the pads of my fingers mutes the buzz somewhat. It does not help consistently enough to tell for certain.
Bending the A string away from the spot seems to eliminate the buzz. Bending the D string over the spot seems to make it buzz. Again, I can't get that to happen consistently, so I am not sure what actually makes a difference. All I can tell for sure is that it happens anywhere within about 50–75 cents of F on the A string.
Update: I adjusted the action, which significantly changed the fingerboard buzzing but didn't entirely eliminate it. I removed most of the relief and evened out the action. Now the A string buzzes less, and closer to the octave instead of the F. Based on my research, the buzzing might move around more, and get better or worse, depending on the exact setup and environmental conditions like temperature and humidity.
Comment: Does the buzz come through your amp as well, or is it like an electric guitar where you get buzzes acoustically which aren't heard when amplified?
Comment: With all due respect, reading the wording, do you mean it buzzes behind your finger, in the part between finger and nut, or between finger and saddle? Just a thought.'Above' to me means fret 7 towards the bridge.
Comment: At that point on the fingerboard, the 'note' trying to sound between nut and finger is close to an octave above the played note. Depending exactly where the finger is, a mm either way. There could be some sympathetic vibration going on, but it would manifest itself at the same point on other strings, too, I'd have guessed.
Comment: Is this happening with all pup positions, and acoustically?  It may be inconsequential, but is the intonation accurate?
Comment: The buzzing is mechanical, not electronic. It happens anywhere above E to a little above F, even when the (active) pickups are off.
Comment: Sounds like you might need to either adjust the truss rod/action or have the fingerboard looked at.. it might need to be refinished if you can't get rid of the buzz with truss rod or action adjustments.
Comment: @Charles, could you please flesh that out a bit and post it as an answer? I suspect it's not an action problem *per se,* since it's buzzing on the nut side, but it could be the nut or the relief.
Comment: [Here's a fellow with a very similar problem.](http://www.sputnikmusic.com/forums/showthread.php?t=485843) It sounds like the first step in troubleshooting is a good setup with a straight neck. If that doesn't work, there's likely a flaw in the fingerboard that a good tech can level. So please post an answer @Charles as your advice sounds like the main troubleshooting that I can do myself!
Comment: [And here's some additional interesting information that may be helpful for answering.](http://badassbassplayers.com/forum/viewtopic.php?f=31&t=5599#p43263) Looks like the fingerboard is likely to change over time, so the correct course of action might simply be to give it time and some gentle adjustment. I'd appreciate any advice that folks could offer from actual experience with fretless basses.
Comment: @Charles I did adjust the relief and action as you suggested, and it helped but didn't entirely fix the problem. Could you please post an answer so that I can vote it up and possibly accept it?
Answer: I'll expand a bit on my comment at the request of OP. I haven't had this exact problem on any of my fretless basses but I can tell you what steps I would take if I did encounter something like this. Since you said the buzzing is coming from the nut side of the note, it might be some sort of mechanical buzz either from the tuners on the headstock or the truss rod. I had a guitar whose truss rod buzzed for certain notes, but a 1/8 of a turn to tighten the rod solved that. As for the tuners, try to replicate the buzzing and put your finger on each of the tuners to see if holding them still stops the buzz. You basically want to go over all the hardware on the instrument and make sure it's screwed in tight and doesn't wiggle. Hold/dampen different parts of the bass/neck/headstock while playing to see if you can isolate where the buzz is coming from. Also open up the control cavity to make sure nothing is loose, as a battery or some other component could be causing the problem.
If you can't find a mechanical source, the setup is the next thing you are going to want to dial in to make sure the action, bridge, and neck are all adjusted properly. I won't go into too much detail on this because there is a lot of good info out there on setting up a fretless bass (here is a great guide, also check Youtube), but I'll give you some places to look.
From your update to the question, you mentioned you adjusted the action and removed most of the relief. Does this mean you also adjusted the truss rod? Usually relief is affected more by the truss rod than the height of the strings at the bridge. Check your relief first, and adjust the truss rod as needed (see the link above for detailed info on truss rod adjustments for fretless bass). Usually if there is buzzing in the low frets you loosen the truss rod, and buzzing above fret 12 you tighten (and don't turn the rod more than about 1/4 turn a day.. let it settle after each adjustment, re-tune, and check the relief until it's where you want it). That's an oversimplification but do some reading on the subject and you'll be able to figure out if your rod is set up properly or not.
The truss rod should be the first thing you check. Once the truss rod/relief is setup properly, then you move on to the bridge and work on getting the string heights correct. I usually put the strings as low as possible without buzzing, and be sure to check notes up and down the neck as you adjust the height to make sure they all sound without buzzing. There should be a point if you raise the strings enough they should stop buzzing. If not, and they still buzz even when the action is very high (and relief is correct), then it is likely a fingerboard issue.
All of that being said, if you can't find the buzz it would probably be worth a trip to a guitar/bass tech who does good work with fretless basses. You might need to have the nut adjusted or the fingerboard refinished because it's possible there is a dent or bump somewhere along the fingerboard that is causing the buzz. These are things you want a luthier or bass tech to look at, because it's not so easy to do it yourself. They can set it up for you and hopefully get rid of the buzz. Chances are the bass will play better than ever after some professional attention.
Comment: Yes, I adjusted the truss rod to remove the relief, as I wanted to see what it was like playing on a very flat neck, and I also wanted to see how it would affect this problem.
Comment: Generally you want a *little* bit of relief, so perfectly flat isn't ideal. Have you determined it's definitely not some mechanical hardware buzz?
Comment: Not yet, I'll check that when I get a chance. It hadn't occurred to me as I was able to mute the buzzing via strings, but I can see how that could mean something is loose elsewhere.
Comment: Also, I didn't remove the relief entirely; I left in just enough to be sure I hadn't created a back bow. But I have not played a bass with zero relief before, and I've heard that fretless is a good instrument to try it on, so I got it as close as possible without going over.
Comment: Ok, I would check hardware next, then if that's not it try to raise the strings until the buzz stops. If raising them as high as you can doesn't stop it, it's likely a fingerboard problem.
Answer: Possibly you are far more used to playing fretted bass, and need to press harder. On fretted, the string vibrates from fretwire to saddle, but of course, the wire isn't there on fretless. If you are not firm with your fingering, the rest of the string can vibrate as well, but maybe only becomes noticeable around that area of the neck. If it's still under warranty — probably, I hope — then a trip to the supplier would have been my first move. A fretboard problem may be detected using a ruler to check straightness at certain points.
In the meantime, damp the string/s behind the 'fret' you're playing on. It's often a good technique to use anyway. If you are using your index finger, try to find other ways and places to play the note/s in question. Become adaptable!
Comment: Bradd is right; answers are not the place for editorializing.  And shopping advice is off-topic.  His problem is valid and not going to be sorted by talking about what he should have bought.  I've cleaned up the comments.
Comment: Thanks for the edits and the troubleshooting tips, +1. Unfortunately, they haven't turned up any solutions so far. Hoping to avoid solutions that involve warranties and returns, as I already made some modifications to the guitar before discovering the string buzz.

Fretless bass buzz


Facebook login is not working correctly for another person

Question: I am doing log in facebook using facebook sdk in my application in which authorize person (through which I have created example on facebook) doing log in successfully but when another person doing log in then he is not able to log in (I think session is created but session state is closed) now I am confused what I do.
my code is below
<code> public class MainFragment extends Fragment{

    private static final String TAG = "deepak";
    private UiLifecycleHelper uiHelper;
    Boolean isInternetPresent;
    private TextView albumTextView;
    private static String APP_ID = "xxxxxxxxxxxxxxxxx";
    Facebook facebook;
    Session session;
    private boolean flag = false;
    static ArrayList<String> allNames;
    static  ArrayList<String> uid;
    static ArrayList<String> picUrl;

//    String[] pics =  new String[]{};
//    String[] uids;
//    String[] allnames;

    JSONArray jArray;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
         Bundle savedInstanceState) {
        // TODO Auto-generated method stub
         View view = inflater.inflate(R.layout.activity_main, container, false);
         LoginButton authButton = (LoginButton) view.findViewById(R.id.authButton);
         authButton.setReadPermissions(Arrays.asList("read_friendlists", "user_photos", "friends_photos"));
         albumTextView = (TextView) view.findViewById(R.id.text_viet_albul);
         authButton.setFragment(this);
         facebook = new Facebook(APP_ID);
         allNames = new ArrayList<String>();
         uid = new ArrayList<String>();
         picUrl = new ArrayList<String>();

         ConnectionDetector cd = new ConnectionDetector(getActivity());
         isInternetPresent = cd.isConnectingToInternet();
         checkInternetConnection();

         return view;
    }

    private void checkInternetConnection() {
        // TODO Auto-generated method stub
        if(!isInternetPresent) {
            // Internet connection is not present
            // Ask user to connect to Internet
            showAlertDialog(getActivity(), "No Internet Connection", "You don't have internet connection.", false);
            }
        }

     public void showAlertDialog(Context context, String title, String message, Boolean status) {
         AlertDialog alertDialog = new AlertDialog.Builder(context).create();
         // Setting Dialog Title
         alertDialog.setTitle(title);
         // Setting Dialog Message
         alertDialog.setMessage(message);
         // Setting alert dialog icon
         //alertDialog.setIcon((status) ? R.drawable.success : R.drawable.fail);
         // Setting OK Button
         alertDialog.setButton("OK", new DialogInterface.OnClickListener()
         {
             public void onClick(DialogInterface dialog, int which)
             {
                 MainActivity.finishIfNetworkIsNotWorking();
             }
         });
         // Showing Alert Message
         alertDialog.show();

     }

    private void onSessionStateChange(Session session, SessionState state, Exception exception) {
        if (state.isOpened()) {
            Log.i(TAG, "Logged in...");
        } else if (state.isClosed()) {
            Log.i(TAG, "Logged out...");

        }
    }

    private Session.StatusCallback callback = new Session.StatusCallback()
    {
        @Override
        public void call(Session session, SessionState state, Exception exception)
        {
            onSessionStateChange(session, state, exception);

        }
    };

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

        uiHelper = new UiLifecycleHelper(getActivity(), callback);
        uiHelper.onCreate(savedInstanceState);

    }

    @Override
    public void onResume() {
        super.onResume();

        Session session = Session.getActiveSession();
        if (session != null &&
               (session.isOpened() || session.isClosed()) ) {
            onSessionStateChange(session, session.getState(), null);
        }
       uiHelper.onResume();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        uiHelper.onActivityResult(requestCode, resultCode, data);
        Session.getActiveSession().onActivityResult(getActivity(), requestCode, resultCode, data);

    }

    @Override
    public void onPause() {
        super.onPause();
        uiHelper.onPause();

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        uiHelper.onDestroy();

    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        uiHelper.onSaveInstanceState(outState);

    }
}
</code>
Comment: when in i debugg then it goes inside  else if (state.isClosed()) {
         Log.i(TAG, "Logged out...");

     }   in  onSessionStateChange(Session session, SessionState state, Exception exception)  and logged out not log in...)
Answer: Do you do log out when you change user? Sometimes your tokens or session is saving in share preferences, and when you run your app it load tokens from file and create your session.
Your method log out must be like next:
<code> private void onClickLogout() {
    Session session = Session.getActiveSession();
    if (!session.isClosed()) {
        session.closeAndClearTokenInformation();
    }
}
</code>
Do you get active session?
Comment: and when you log in with another user what is happens?
Comment: when another user doing log in then this part of program run  it goes inside else if (state.isClosed()) { Log.i(TAG, "Logged out..."); } in onSessionStateChange(Session session, SessionState state, Exception exception) and logged out not log in...)
Answer: Use
<code>Session.getActiveSession().closeAndClearTokenInformation();
</code>
after you get the enough details or process is done with the logged in account. So when login  again it automatically looks for a new Token from facebook user.
Comment: try calling it in ondestroy.


Drupal assuming admin created user, when user registered normally

Question: This is something that I'm pretty sure worked when in beta, but doesn't work now anymore.
I have setup the user registration to be allowed by visitors, but a confirmation by the admin is required. Email verification isn't required. I have composed all the necessary emails.
Now, when a user registers, two things go wrong:

no mail is sent to the admin
the wrong mail is sent to the new user

The new user receives a mail stating that the admin created his account and that he can use the one-time login link to change his password. When he clicks on this link, he doesn't have access to the page, because the account isn't active yet.
The user should receive the mail telling him he registered succesfully and his registration is waiting for approval. The admin should receive the mail that a new user was created.
Sometime, the admin will create the users, so both mechanisms will be used. But I get the impression Drupal thinks it was always the admin that created the user, even if it was a normal user registration.
I have a rule setup (from the Rules module) for when a new user registers, to add him to certain roles. But this worked in beta, now it doesn't anymore. Also, disabling this rule, or disabling the rules module entirely didn't help.
Any ideas where I can start looking?
Comment: Is there any chance that we could look at the site? this is pretty interesting.
Answer: As it turns out, a custom-made module conflicted with the normal behavior in a sneaky way.
In D7, when you create a user as an admin, the checkbox to send an email with a one-time login link is not selected by default. As the person creating users is not a technical person, I thought it might be user friendly if this was checked by default.
After a bit of searching, I found a small module that could help. What this piece of code did was:
<code>if ($form_id == 'user_register_form') {
    $form['account']['notify']['#default_value'] = TRUE;
}
</code>
However, as you can see there is no check if the current user is the admin. So Drupal assumes the admin is creating the user, even for a normal registration by a visitor. Subsequently, the visitor gets a mail that the admin created his/her account.
I explained this for the author also, and hope someone fixes it (or I'll try myself when I find the time).


WebRequest doesnt send passed CookieContianer that was made from a CookieCollection

Question: I made a server that listen to a port for POST requests.
It handles a JSON and it deserializes to a class containing some strings and a CookieCollection
All correct there, but when I pass the CookieCollection to a CookieContainer and use that container on a request it is sending without the cookies.
Json example:
"loginContainer":[
  {
     "Comment":"",
     "CommentUri":null,
     "HttpOnly":true,
     "Discard":false,
     "Domain":"removed",
     "Expired":false,
     "Expires":"2026-07-02T12:42:43+02:00",
     "Name":"locale",
     "Path":"/",
     "Port":"",
     "Secure":false,
     "TimeStamp":"2021-07-03T12:42:14.8645637+02:00",
     "Value":"removed",
     "Version":0
  }

Collection to CookieContainer:
CookieContainer loginContainer = new CookieContainer();

foreach (Cookie cookie in root.LoginContainer)
{
     Console.WriteLine(cookie.Name + " " + cookie.Value);
     loginContainer.Add(cookie);
}

Request:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;

request.CookieContainer = loginContainer;

using (HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync())
using (MemoryStream ms = new MemoryStream())
{
     response.GetResponseStream().CopyTo(ms);
     listLabels.Add(ms.ToArray(), labels.Phrase);
}

Answer: Solved it by looping the CookieCollection and inserting inside the CookieContainer a new made Cookie with the CookieCollection values, not the one from the CookieCollection.
foreach (Cookie cookie in root.LoginContainer)
{
    loginContainer.Add(new Cookie() { Name = cookie.Name, Value = cookie.Value, Path = cookie.Path, Domain = cookie.Domain });
}


Powershell saída de arquivo .CSV apos Foreach

Question: Boa tarde!
Eu tenho um scritp simples em powershell que realiza o teste de conexão entre domains controllers e suas respectivas portas de serviços conforme a baixo:
<code>$servers = Get-Content -Path 'C:\DC Health\Domains_Controllers.txt'
$IP_TCPs = Get-Content -Path 'C:\DC Health\TCP_Ports.txt'
foreach($IP_TCP in $IP_TCPs){
foreach($server in $servers){

$socket = New-Object Net.Sockets.tcpClient

Try{
    $socket.Connect($server, $IP_TCP)
Write-Host $server $IP_TCP Conectado
}
Catch{
Write-Host $server $IP_TCP Desconectado
}

Finally{
    $socket.Close()
    $socket.Dispose()

}
}
}
</code>
Queria ter a saída em algum arquivo como .txt ou .csv, porem o arquivo sempre sai em branco.
Existe alguma possibilidade de alteração ou acrescentar para esta saída?
Desde já agradeço.
Answer: Alerta: Testes realizados no windows 10 com powershell 5.1.
Aviso: "Write-Host" não redireciona para arquivo e sim para a console.
Dica: A utilização da cláusula "Try" deve ser evitada pois afeta o objeto "$Error". Sempre que possível, utilize comandos que testem a situação. No seu caso em particular, você poderia usar "Test-NetConnection"
Então, eu trocaria o código interno para:
<code>$Resposta = ( Test-NetConnection -ComputerName $server -Port $IP_TCP ).TcpTestSucceeded
$Objeto = [PSCustomObject]@{
    Servidor = $server
    PortaTCP = $IP_TCP
    Situação = @( 'Desconectado', 'Conectado' )[ [Boolean]$Resposta ]
}
Export-Csv -InputObject $Objeto -LiteralPath '[caminho]\[nome do arquivo].csv' -Append
</code>
Agora, respondendo seu questionamento:
1) Antes da cláusula "Try", crie um objeto personalizado:
<code>$Objeto = [PSCustomObject]@{
    Servidor = $server
    PortaTCP = $IP_TCP
    Situação = ''
}
</code>
2) Depois da chamada do soquete:
2.1) Atualize o objeto:
<code>$Objeto.Situação = 'Conectado'
</code>
2.2) Remova a cláusula "Write-Host"
3) Na cláusula "Catch":
3.1) Atualize o objeto:
<code>$Objeto.Situação = 'Desconectado'
</code>
3.2) Remova a cláusula "Write-Host"
4) Na cláusula "Finally", exporte o objeto para um arquivo CSV:
<code>Export-Csv -InputObject $Objeto -LiteralPath '[caminho]\[nome do arquivo].csv' -Append
</code>
Answer: Para exportar o resultado diretamente para um arquivo de texto, pode usar o comando pipeline Out-File
Exemplo de uso:
<code>"$server $IP_TCP Conectado" | Out-File -FilePath "c:\\temp\\test.txt" -Append
</code>


How to play Audio using raw data in iOS?

Question: I have been working on Audio capture and playback, I am trying to play audio using a buffer. I will get buffer as character pointer I have to read from the buffer and play if anything is present in that buffer. I came to know about AudioQueue, I am not sure AudioQueue will be the correct way for my task. Can anyone done this before, Please suggest some ideas where to start?
Answer: Yes, AudioQueues are fine for playback and recording of LPCM audio data signals. You've a lot to learn about audio signals and CoreAudio APIs before you will understand how this all works (an audio signal and AudioQueue crash course is way too big for one SO answer).
Start with some AudioQueue examples and tutorials. Reserve a good amount of time.


Equivalence between different forms of the Axiom of Infinity

Question: In Zermelo-Frankel set theory, the Axiom of Infinity is often stated as

"There exists a set $X$ such that $\emptyset \in X$ and such that if $y\in X$ then $S^{+}_1(y)\in X$",

where we take the successor function as $S^{+}_1(y) = y\cup \{y\}$. I believe the original formulation for the Axiom of Infinity by Zermelo had a different form, where the successor function was instead $S^{+}_2(y) = \{y\}$.
Let's call the form of the Axiom of Infinity with $S^{+}_1$ "Infinity 1" and the form with $S^{+}_2$ "Infinity 2". Changing from "Infinity 2" to "Infinity 1" made the axiom easier to work with, but the two formulations should be equivalent.
How can we prove that "Infinity 1" and "Infinity 2" are equivalent under the remaining ZF axioms?
Comment: As @Nishant notes, we can recursively define maps from the finite von Neumann ordinals ($0$, $n +1 = n \cup \{n\}$) and the finite Zermelo ordinals ($0$, $n+ 1 = \{ n\}$). Replacement then implies that the set of the former exist iff the set of the latter do. But it's worth noting that in the absence of Replacement this can fail in both directions. See http://www.jstor.org/stable/421182?seq=8&uid=3738032&uid=2&uid=4&sid=21106300019561#page_scan_tab_contents
Comment: Did Zermelo even had an axiom of infinity?
Comment: @AsafKaragila If the wikipedia page for Zermelo set theory is to be believed, then yep; and it was Infinity 2.
Comment: @GME: Interesting, I somehow recalled that there wasn't something like that; but maybe I was thinking about the very early axiomatizations, and maybe I was just thinking about how the Zermelo encoding of $\Bbb N$ cannot be extended transfinitely.
Comment: @AsafKaragila What do you think goes wrong in the transfinite case? (Assuming we take unions at limits.)
Comment: @GME: Yes, taking unions. But it doesn't "reflect" the nature of the construction. The natural limit would be to have some $\{x\}$ such that every Zermelo-integer is in the transitive closure of that set; but this is impossible since the construction leads to a set $x=\{x\}$, which is already transitive.
Answer: If you're allowed to use Replacement, you can recursively define a map from an inductive set of the second kind to an inductive set of the first kind by just setting $f(\varnothing)=\varnothing, f(S_2^+(y))=S_1^+(f(y))$, and then the image, which is a set by Replacement, will be an inductive set of the first kind.


Como concatenar linhas?

Question: Como concatenar todos os resultados de uma query no SQL Server a fim de retornar toda a informação em uma variável?
Por exemplo, considerando uma tabela cliente com a seguinte composição:
╔═══╦════════════╗
║   ║ Nome       ║
╠═══╬════════════╣
║ 1 ║ José       ║
║ 2 ║ Luis       ║
║ 3 ║ Antônio    ║
╚═══╩════════════╝

O resultado desejado seria:
José, Luis, Antonio

Answer: Uma forma (anterior ao SQL 2012) é utilizar uma variável para concatenar os resultados da linha da seguinte forma:
DECLARE @texto varchar(max);

SELECT @texto = ISNULL(@texto + ', ', '') + cli.nome
  FROM cliente cli;

print @texto;

Onde o ISNULL garante que a vírgula só será inserida caso exista valor anterior atribuído a variável (No caso começando a colocar a vírgula apenas após o José).

Uma outra forma é usar a sintaxe FOR XML PATH(''):
SELECT DISTINCT SUBSTRING((SELECT ',' + cli.nome AS [text()]
                             FROM cliente cli
                              FOR XML PATH ('')), 2, 8000) AS texto
  FROM cliente cli2

A partir da versão 2017 do SQL Server você pode utilizar a função STRING_AGG:
SELECT STRING_AGG(cli.nome, ',') AS texto
  FROM cliente cli;

STRING_AGG
Concatena os valores das expressões de cadeia de caracteres e coloca os valores de separador entre eles. O separador não é adicionado ao final da cadeia de caracteres.

Referências:

Resposta para a pergunta SQL, How to Concatenate results? no SOen;

Resposta para a pergunta Concatenate many rows into a single text string? no SOen;

Script funcional disponível no GitHub.

Como concatenar linhas?


Show that the real part of complex number is $-1$

Question: The complex number z satisfies the equation $\vert z \vert=\vert z+2\vert$.
Show that the real part is $-1$.
I know that $\vert z \vert = \sqrt{x^2+y^2}$ so I took
$\begin {align}\vert z \vert&=\vert z+2\vert \\\sqrt{x^2+y^2} &=\sqrt {x^2+y^2+2^2} \\ x^2+y^2&=x^2+y^2+2^2 \end {align}$
So after cancelling $x^2$ and $y^2$ from both sides of the equation, I am left wih $0=2^2$, which makes no sense.
How should I solve this question?
The second part of the question is as follows (which I also need help solving):
The complex number $z$ also satisfies $\vert z \vert -3=0$. Represent the two possible values of $z$ in an Argand diagram. Calculate also the two possible values of arg $z$.
Answer: It is not true that $|z+2|^{2}=x^{2}+y^{2}+2$. What is true is $|z+2|^{2}=|(x+2)+iy)|^{2}=(x+2)^{2}+y^{2}=x^{2}+y^{2}+2^{2}+4x$. So we get $4x+4=0$ or $x=-1$.
Answer: $$ |z + 2| = \sqrt{(x+2)^2 + y^2} = \sqrt{x^2 + y^2}$$
$$ x^2 + 4x + 4 = x^2$$
Comment: I believe you meant $4x$ instead of $2x$
Comment: Oops sorry, fixed!
Answer: I believe there's a mistake when you start expanding the modulus expressions. In particular, $|z+2| = |x+iy + 2| = \sqrt{(x+2)^2 + y^2}$. Try using this and see if it fixes your results.
Answer: So, $z$ are the intersections of two circle with equal radius centered at $(0,0)$ and $(-2,0)$. Quite straightforward that $z$ lies on the line $x=-1$.
Part two basically tell You the radius is $3$, intersections are $-1\pm i2\sqrt{2}$
Answer: You've miscalculated the length of $z+2$.
Equal the squares of the lengths to obtain
$$z\bar z=(z+2)(\overline{z+2})$$
hence
$$z+\bar z=2,$$
which proves the statement.


Acquia Drush Access

Question: We are hosting a couple of sites on Acquia Cloud.  Up to now I have SSH into the servers when I needed to execute any drush commands, but I want to start using drush on my local dev machine to execute commands on the servers.
Some of the commands work without an problems drush ac-site-list, but as soon as a SSH key is required (for example drush @site.env status I get a Permission denied (publickey). error message.  I know this means that the public SSH key being used is not valid, and I also know why this is happening.  I have only one SSH key for all the Acquia servers, but because there are different servers for the different sites, and in addition to that I have a couple of 'personal or private' key's; SSH does not know which key to use when I execute Drush.
For other SSH access (SSH in generate to other servers), I use a config file in my .ssh folder with aliases.
The problem is that I do not know how to tell Drush which 'ssh alias' from the .ssh/config file to use.
How can I achieve this?
Comment: It depends a bit on the structure of the alias file Acquia provides, and it would be helpful if you could update your question with the structure of it.
Answer: The Drush alias file has an option to provide additional parameters:

'ssh-options': If the target requires special options, such as a non- standard port, alternative identity file, or alternative
  authentication method, ssh-options can contain a string of extra
  options that are used with the ssh command, eg "-p 100"

Source: https://github.com/drush-ops/drush/blob/master/examples/example.aliases.drushrc.php
To have SSH use the right SSH key you can append it with ssh -i path/to/key.pem user@server. So in your alias file you should be able to add:
$aliases['alias'] = array(
  ...
  'ssh-options' => '-i path/to/key.pem',
  ...
);

I am not sure if you can use the keys defined in .ssh/config, because the config file automatically connects the SSH key with the host. So you'd be able to call ssh user@server and SSH should append the key. Therefore I doubt it can be used as I'd assume drush will automatically use remote-host and remote-user to build the SSH connection: ssh remote-user@remote-host and the keys from .ssh/config shoud be applied at that point.
Comment: perfect.  Added the ssh-options key to each of the alias arrays and it worked.  Thanks

Acquia Drush Access


Webdriver execution is not working (Webdriverexception) is given

Question: I have written a very basic script to just login to an application and logout. The script stop working as soon as it logs in to the application and an exception is given and I cant figure out the reason for this. This is the script.
<code>public class Login {

WebDriver driver = new FirefoxDriver();
String url = "http://xxxxxxxxx";

@Test
public void login_class() {

    driver.get(url + "/Web/guest/login.aspx");
    driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
    driver.findElement(By.id("txtUserName")).clear();
    driver.findElement(By.id("txtUserName")).sendKeys("firstname.lastname@example.com");
    driver.findElement(By.id("txtPassword")).clear();
    driver.findElement(By.id("txtPassword")).sendKeys("xxxxx123");
    driver.findElement(By.id("btnLogin")).click();
    driver.get(url + "Web/guest/home/default.aspx");
    driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
    driver.findElement(
            By.cssSelector("span.menu-icons-sprite.menu-icon-signout"))
            .click();

}

@BeforeTest
public void create_driver() {

    driver.get(url);
    driver.manage().window().maximize();

}

@AfterTest
public void exit() {

    driver.quit();
}
</code>
}
And the exception given is followed
FAILED: login_class
org.openqa.selenium.WebDriverException: f.QueryInterface is not a function
Command duration or timeout: 5.10 seconds
Build info: version: '2.48.2', revision: '41bccdd', time: '2015-10-09 19:55:52'
System info: host: 'xxxxx-PC', ip: '10.0.0.192', os.name: 'Windows 7', os.arch: 'amd64', os.version: '6.1', java.version: '1.7.0_45'
Session ID: 1e311cd0-34d1-4dd2-9cde-e52cbb9fb52e
Driver info: org.openqa.selenium.firefox.FirefoxDriver
Capabilities [{platform=WINDOWS, acceptSslCerts=true, javascriptEnabled=true, cssSelectorsEnabled=true, databaseEnabled=true, browserName=firefox, handlesAlerts=true, nativeEvents=false, webStorageEnabled=true, rotatable=false, locationContextEnabled=true, applicationCacheEnabled=true, takesScreenshot=true, version=42.0}]
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
    at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:206)
    at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:158)
    at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:647)
    at org.openqa.selenium.remote.RemoteWebDriver.get(RemoteWebDriver.java:311)
    at bileetaTest.Login.login_class(Login.java:27)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:85)
    at org.testng.internal.Invoker.invokeMethod(Invoker.java:639)
    at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:816)
    at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1124)
    at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:125)
    at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:108)
    at org.testng.TestRunner.privateRun(TestRunner.java:774)
    at org.testng.TestRunner.run(TestRunner.java:624)
    at org.testng.SuiteRunner.runTest(SuiteRunner.java:359)
    at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:354)
    at org.testng.SuiteRunner.privateRun(SuiteRunner.java:312)
    at org.testng.SuiteRunner.run(SuiteRunner.java:261)
    at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
    at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
    at org.testng.TestNG.runSuitesSequentially(TestNG.java:1215)
    at org.testng.TestNG.runSuitesLocally(TestNG.java:1140)
    at org.testng.TestNG.run(TestNG.java:1048)
    at org.testng.remote.RemoteTestNG.run(RemoteTestNG.java:112)
    at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:205)
    at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:176)
Caused by: org.openqa.selenium.WebDriverException: f.QueryInterface is not a function
Build info: version: '2.48.2', revision: '41bccdd', time: '2015-10-09 19:55:52'
System info: host: 'xxxx-PC', ip: 'xxxxxxx', os.name: 'Windows 7', os.arch: 'amd64', os.version: '6.1', java.version: '1.7.0_45'
Driver info: driver.version: unknown
    at .FirefoxDriver.prototype.get(file:///C:/firstname.lastname@example.com/components/driver-component.js:10523)
===============================================
    Default test
    Tests run: 1, Failures: 1, Skips: 0
Answer: The issue was I have to add another "/" before the Path I had provided.
Comment: Why are you navigating like this. why dont you click the home button instead ?
Comment: The home button is in a separate menu and I just thought of doing it this way.. no special need and practically I will be clicking on the home button later.
Comment: If that url changes you have to change the code. But if you click the home button then no need to change your code. Thats the advantage of clicking the home button


Regression coefficients between vector-valued variables

Question: Sorry for the basic question, but I'm a bit confused on the notation.
Let say we have a random vector of $m$ predictors variables ${\bf X} = (X_1,\ldots,X_m)^{\intercal}$ that are used to predict $n$ variables indicated with ${\bf Y} = (Y_1,\ldots,Y_n)^{\intercal}$
The general linear regression model can be written as
\begin{equation}
    Y_i = \sum_{j=1}^m A_{ij}X_j + \epsilon_i \qquad i = 1,\ldots,n~,
\end{equation}
or in vector form
\begin{equation}
{\bf Y} = A{\bf X} + {\bf \epsilon}.
\end{equation}
I call $\Sigma({\bf Y},{\bf X})$ the cross-covariance matrix $n\times m$ of elements $\text{cov}(Y_i,X_j)$ and $\Sigma({\bf X})$ the covariance matrix of ${\bf X}$.
Given this premises and notation, I found written that the $n\times m$ matrix of regression coefficients is simply
\begin{equation}
    A = \Sigma({\bf Y},{\bf X}) \Sigma({\bf X})^{-1}~,
\end{equation}
but I don't understand where this formula came from.
I read that should be possible to derive this formula easily via Yule-Walker procedure, but I don't understand how.
Why don't we use the standard approach of ordinary least square methods, where we found the regression coefficients by minimizing the residuals?
Comment: Isn't this just $n$ separate ordinary least squares regression of the rows of $Y$ against the same design matrix $X$?
Comment: Thanks for replying, I was confusing the design matrix ${\bf x}$ with the random vector ${\bf X}$, but they are basically the same thing when you write them in components, right?
Answer: Thanks to @whuber that made me notice that this problem must be equivalent to $n$ separate ordinary least square regressions, where the coefficients of the $k$-th regression are given by the $k$-th row of $A(k,:)$.
If this is the case, I should be able to compare the standard OLS estimator with $A = \Sigma({\bf Y},{\bf X}) \Sigma({\bf X})^{-1}$ and obtain the same result.
So the standard OLS estimator is
$$A(k,:) = \hat{\beta}_k = {\bf x}^\intercal y_k({\bf x} {\bf x}^\intercal)^{-1}$$
where I denoted with ${\bf x}$ the $m\times N$ design matrix, where each column is one of the $N$ realizations of the random vector ${\bf X}$. Now I realize that the two things are equivalent, since writing in components $\Sigma({\bf X})_{ij} = \sum_{t=1}^N x_{i,t}x_{j,t} = ({\bf x}{\bf x}^\intercal )_{ij}$ and the same happen for $\Sigma({\bf Y},{\bf X})$.


Date converter in JAVA

Question: I have date like Tue Mar 19 00:41:00 GMT 2013, how to convert it to 2013-03-19 06:13:00?
final DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
final Date date = bdate;
Date ndate = formatter.parse(formatter.format(date));
System.out.println(ndate);

gives the same date.
Comment: You start by searching StackOverflow for one of the millionth posts about date conversions in Java.
Comment: Have you tried anything?
Comment: @evening: Well why not fix the question so that the times are right? You're asking for people's help here - the least you can do is make sure you ask a sensible question.
Comment: @JonSkeet: okay, please check again
Comment: @evening: Okay, that's better. Now why would you *expect* a formatter with a format of "yyyy-MM-dd HH:mm:ss" to be able to parse a value of "Tue Mar 19 00:41:00 GMT 2013"?
Comment: The format "E M d hh:mm:ss z yyyy" will parse that format I think. Not "yyyy-MM-dd HH:mm:ss" format.
Comment: @JonSkeet: I don't know... It outprints the correct date if I don't use the formatter.parse, but i need to convert it to date. Please help or I'll die. You can really save my life. Please.
Comment: @evening: Hyperbole will get you nothing. You've got perfectly good answers already.
Answer: Use two SimpleDateFormat objects with appropriate formats and use the first to parse the string into a date and the second to format the date into a string again.
Answer: As the first answer says. First parse your date with SimpleDateFormat like this:
Date from = new SimpleDateFormat("E M d hh:mm:ss z yyyy").parse("Tue Mar 19 00:41:00 GMT 2013");

Then use that to format the resulting date object with another instance of SimpleDateFormat like this:
String to = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(from);

See the javadoc of SimpleDateFormat here. Hope that helps.
Comment: JUst one thing left, how to convert string to date? thanks
Comment: String to date is the first line. Just use parse on SimpleDateFormat.
Comment: oplease check thread again, thank you veyr muich
Answer: One major thing that the others have left out is dealing with the timezone (TZ). Anytime you use a SimpleDateFormat to go to/from a string representation of the date, you really need to be aware of what TZ you're dealing with. Unless you explicitly set the TZ on the SimpleDateFormat, it will use the default TZ when formatting/parsing. Unless you only deal with date strings in the default timezone, you'll run into problems.
Your input date is representing a date in GMT. Assuming that you also want the output to be formatted as GMT, you need to make sure to set the TZ on the SimpleDateFormat:
public static void main(String[] args) throws Exception
{
    String inputDate = "Tue Mar 19 00:41:00 GMT 2013";
    // Initialize with format of input
    SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
    // Configure the TZ on the date formatter. Not sure why it doesn't get set
    // automatically when parsing the date since the input includes the TZ name,
    // but it doesn't. One of many reasons to use Joda instead
    sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
    Date date = sdf.parse(inputDate);
    // re-initialize the pattern with format of desired output. Alternatively,
    // you could use a new SimpleDateFormat instance as long as you set the TZ
    // correctly
    sdf.applyPattern("yyyy-MM-dd HH:mm:ss");
    System.out.println(sdf.format(date));
}

Answer: Use SimpleDateFormat in this way:
final DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
final Date date = new Date();
System.out.println(formatter.format(date));

Comment: @evening: Date class stores the date as a long value, but when you print it, it displays it in a readable format, that is: "Tue Mar 19 00:41:00 GMT 2013". You don't need to do anything with that format until you decide to display it to the user. In that moment need to format that date to the way you would like to display it, and you do it with the SimpleDateFormat, that returns a String in the format you specified, in your case "2013-03-19 06:13:00" (using the posted pattern).
Comment: How to convert formatter.format(date) to date?
Comment: @evening: with formatter.parse(String), giving it a string in the same format.
Comment: final DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            final Date date = bdate;

            Date ndate = formatter.parse(formatter.format(date));

            System.out.println(ndate);
Comment: @evening: Yes, they are inverse operations.
Comment: @evening: The date you are printing in your last comment is not formatted, that's the reason you get the default output for date: "Tue Mar 19 00:41:00 GMT 2013". For displaying it in other way, you need to format, as posted.
Answer: If you do any calculations or parsing with dates please use JodaTime because the standard JAVA date support is really buggy
Comment: Buggy? Is an awful implementation, but I don't know those bugs.
Comment: Yes, JodaTime or any JSR 310 implementations is a must when doing date/time calcluations.
Comment: @stenrs: JSR310 is still in development as i know and it will replace the data api in JAVA 8. Stephen Colebourne created JodaTime and is developing JSR310
Comment: @emd: Also, it's this one: https://github.com/ThreeTen/threeten.
Comment: @stenrs - you're right

Date converter in JAVA


Unable to upload files. Though the maximum file size limit is 80 MB, can't upload even 50 kb files

Question: I copied a site from localhost to AWS server. I can easily upload files in localhost but when I try uploading in the live site it gives me the error
"An unrecoverable error occurred. The uploaded file likely exceeded the maximum file size (80 MB) that this server supports."
In php.ini and .htaccess and settings.php I have changed upload_max_filesize to 80MB and post_max_size to 164 MB.
And according to this link, , I also disabled mod_security module in apache.
Here  it says, this could be AJAX/Jquery error.
Is there something else that could be the cause for this error?
Comment: Note, it should be `upload_max_filesize = 80M` _not_ `upload_max_filesize = 80MB` (M vs MB) same with `post_max_size` Also, check your error logs for e.g suhosin patch error.
Comment: Too broad to be answered from afar. In the end it's Apache's mod_security. Who knows?
Answer: Some things that can break file uploads:

upload_max_filesize and post_max_size ;
memory_limit ;
Unwritable tmp directory.
Comment: I have already tried with increasing upload_max_filesize, post_max_size and memory_limit. I have also given 777 permissions to tmp directory. Still getting the same error.
Answer: Try increasing MaxRequestLen to 80MB as well. You will need it done for you by the administrators if you use a shared host environment though.


Measuring variable with different number of Likert scale

Question: I have 5 latent variable which 3 of them are measured using 5 point Likert Scale and the other 2 measured using 7 point Likert scale. is this going to be a problem when I make regression for my modmed (moderated/mediated) model?
I am planning to use SPSS.
Answer: I believe you can just convert both scales into one scale, so that for each value you do something like this, so you take the 5 point Likert scale and convert to a 10-point, for example, and do the same for the 7 point Likert scale:
<code>FinalValue = (((OldValue - OldMininum) * (NewMaximum - NewMinimum)) / (OldMaximum - OldMinimum)) + NewMinimum
</code>
Comment: How are you defining "old," "new," "minimum," and so on?
Comment: Old = current value, new = new scale max, and min = new scale min...
Comment: Sorry. It's still not clear what you're recommending. Are you doing this at the level of the individual respondent? Maybe you could work through an example?


Does the plectrum you play with make a difference in your guitar sound?

Question: Does the plectrum you play with make a difference in your guitar sound? Is it just the thickness of the pick or does materials also make a difference if at all?
What would be the science behind this?
Comment: There are loads of wooden ones out there, and someone uses an old sixpence, I believe, good question!
Comment: Brian May uses a sixpence and BIlly Gibbons uses a shaped peso: http://kkguitar.com/wp-content/uploads/2014/07/Billy_Gibson_ZZ_Top_holdi_470efc4239812.jpg
Comment: http://music.stackexchange.com/q/1573/28
Answer: Oh god yes it makes a difference. And thickness, shape, and material all make a difference. You can easily do tons of home experiments on this. Go buy a selection of picks at your local music store and then find some coins. Coins have been used as picks by some famous guitarists and have a very distinct sound.
The science (a little bit at least): A good first approximation of the sound that a guitar string makes is the shape that is made by the string when it is moved from its rest position right before it is released. With any given pick, plucking closer to the bridge makes a different kind of triangular shape from picking close to the 12th fret, and the difference in tone there is obvious.
Now think about the shape of the point of the triangle where the pick is (the triangle is formed by the bridge, nut, and pick, with the string making up two sides and the rest position of the string making the third). If the pick is more rounded and/or more flexible, that point of the triangle will be more rounded. If the pick is hard and/or more pointed, that point of the triangle will have a sharper pointed shape.
When the string is released, the sharper shapes are released also and form tiny little waves that run up and down the string. The sharper the point, the more and tinier waves are formed. They don't last as long as the overall wave motion of the string, but they are picked up by the pickup and/or transferred to the body by the bridge and are clearly audible. More tiny waves are also created by plucking closer to the bridge as opposed to closer to the 12th fret. The tiny ripples give a brighter sound, and a lack of tiny ripples gives a darker, more rounded sound.
This is also tied into the difference in sound between bridge and neck pickups in terms of how big the little ripples are in relation to the larger overall string motion.


PHP remove/fix module not found or already loaded warnings?

Question: When i run a php script from the command line like below
php test.php

i get following output
PHP Warning:  Module 'memcache' already loaded in Unknown on line 0
PHP Warning:  Module 'apc' already loaded in Unknown on line 0

how do i fix or remove these module warnings ? I checked the php.ini in
etc/php.ini

output of
php -i | grep php.ini
PHP Warning:  Module 'memcache' already loaded in Unknown on line 0
PHP Warning:  Module 'apc' already loaded in Unknown on line 0
Configuration File (php.ini) Path => /etc
Loaded Configuration File => /etc/php.ini

i dont see any loading or any reference to these two modules in there ...
please help
Comment: Have you tried this ? http://www.somacon.com/p520.php ? Also my php.ini for command line is located in  /etc/php5/cli/php.ini . Maybe you have also an other configuration somewhere else
Answer: When you install php5-memcache it adds it's own memcache.ini file which is set to load that extension already. So Just remove/comment the loading of the extension from your php.ini.
 ;extension=memcache.so

Similar with APC (Alternative PHP Cache Module).
 ;extension=apc.so

Comment: as i said in my question, i dont have that line in my php.ini so where shodul i look to ?
Comment: @mahen3d , it is probably loaded in from another, ini file dedicated to memcache, so check something like

    /etc/php5/cli/conf.d/memcache.ini
Comment: You probably looking @ wrong php.ini. Have you tried php -i | grep php.ini ?
Comment: no there is only one and only php.ini file, output for yoru command is

PHP Warning:  Module 'memcache' already loaded in Unknown on line 0
PHP Warning:  Module 'apc' already loaded in Unknown on line 0
Configuration File (php.ini) Path => /etc
Loaded Configuration File => /etc/php.ini
Answer: I had the same situation. In my case the problem was that I had two configuration files for memcache in /etc/php5/cli/conf.d/.
php -i | grep memcache.ini

In my case the result was:
/etc/php5/cli/conf.d/20-memcache.ini,
/etc/php5/cli/conf.d/memcache.ini

To get rid of the warning message I removed the line extension=memcache.so from the memcache.ini file.
Answer: If you are using php5.4 (CentOS 6.5),

Goto /etc/php.d/
in memcache.ini comment the extension
;extension=memcache.so

likewise in apc.ini
;extension=apc.so

Answer: I came here looking for a solution to a similar error i.e. Warning: Module 'pdo_pgsql' already loaded in Unknown on line 0.
After looking at various sites, here's the solution I came up with.
It worked for me, hope it does for someone with a similar issue.

Locate the folder conf.d, mine was in the directory
/usr/local/etc/php/7.0/conf.d.
In this folder, there's a file called ext-pdo_pgsql.ini.
Type sudo nano ext-pdo_pgsql.ini to edit it.
There should be a line extension="/usr/local/opt/php70-pdo-pgsql/pdo_pgsql.so". Comment it
out by adding semi-colon to the beginning of the line i.e.
;extension="/usr/local/opt/php70-pdo-pgsql/pdo_pgsql.so".
Save the file. (I usually run control + O, control + M).
Exit the file (control + X).
Answer: Its possible that these modules are listed twice and so you get error "Already loaded".
Find out which configuration files are loaded
php -i | grep 'Loaded Configuration File'
php -i | grep 'ini'

This will tell you which .ini files are loaded and parsed (Additional .ini files parsed).
Look at the specific files and comment out the second occurrence (as follows)
;extension=memcache.so
;extension=apc.so

Answer: there are configuration files modules /etc/php5/mods-available
Open file pdo_mysql.ini and comment line pdo_mysql.so
After service apache2 | php5-fpm restart depending on whether you are using you
Answer: I was getting same error,
Module 'sphinx' already loaded

You need to find module (.ini) which is getting loaded more than once and delete one of them,
ubuntu@webserver:~$ grep -R "sphinx" /etc/php5/*

/etc/php5/fpm/conf.d/sphinx.ini:extension=sphinx.so
/etc/php5/fpm/conf.d/20-sphinx.ini:extension=sphinx.so

ubuntu@webserver:~$ sudo rm /etc/php5/fpm/conf.d/sphinx.ini

Answer: if you dont whants to update in config file,
just add on top of your page or constructor "error_reporting(0)"


Converting a binary vector into a decimal array

Question: I've created a method to generate random binary numbers with n-digits up to 256 digits. In order to continue with my program I need to take the vector with my binary value and put it into a decimal array and then convert that number into a int decimal. Here's the following function that creates the random binary vector and my attempt to convert to decimal. I'm having trouble converting my binary vector to a decimal.
int random_binary(int n, int m){

   vector<int> binary;

   for(int i = 0; i < n; i++)
   {
      m = rand() % 2;

      binary.push_back(m);
   }

   binary.push_back(1);

   int j;

   for(j = 0; j < binary.size(); j++)
   {
       cout << binary[j];
   }
   cout <<"\n";

   int len = binary.size();
   int a = binary[len];   //having trouble right here

   int decimalValue = 0;

   for (int i = len-1; i>= 0; i--)
   {
       decimalValue = decimalValue + binary[i]*pow(2,len-i-1);
   }

   return decimalValue;
}

If anybody could help figure this out that would be much appreciated.
Comment: @ClaytonTM9 -- 1) `int len = binary.size();  int a = binary[len];`  This is not valid C++.  Arrays must be declared using a constant as the number of entries.  2) `pow(2,len-i-1)` -- Do not use `pow` if the [exponent will be an integer](http://stackoverflow.com/questions/25678481/why-does-pown-2-return-24-when-n-5-with-my-compiler-and-os)
Comment: Errr, numbers are numbers, number representations are number representations? I prefer base 20 BTW, having ten fingers and ten toes.
Comment: @ClaytonTM9 You have a major hypo it seems.
Answer: The code isn't all that bad, but it does have a few problems:

An int value can only hold 32 bits on most platforms, 31 bits if you only want non-negative values.  So for 256 binary digits, you will need to use something else.
int a = binary[len];   //having trouble right here - I think @PaulMcKenzie interprets this as an attempt to declare an array of int with a variable number of elements (int a[len];).  I see it as probably initializing an int variable to the element in binary one past the last entry.  Either way is wrong -- but you never use a anyway, and I don't see any possible use for it.  So just delete that line.
Not a bug, but you should understand that int decimalValue isn't decimal, it is an integer, which is most likely stored inside the computer as a set of bits, and only appears as a decimal number when converted and displayed a certain way, like when printed using std::cout.
In the sum loop, std::pow should not be used for integer values, but luckily the bit left shift operator can be used to get integer powers of 2:
decimalValue = decimalValue + binary[i] * (1<<(len-i-1));
Comment: Thanks so much, question on the first bullet you pointed out. What would I need to use in order to hold values larger than 32 without it going to a negative value?
Comment: Well 31 bits gives you the numbers 0 to 2,147,483,647.  The biggest common unsigned integer type is `unsigned long long`, with 64 bits on all platforms I'm aware of, so this gives you 0 to 18,446,744,073,709,551,615.  For more bits, you might need to use an array or vector of values, and make your own math functions for it.  `std::bitset` is a data type from the standard library which will hold any number of bits you want, limited by the capabilities of your platform.


Drush cc all 'Killed'

Question: With a D6 instllation I am seeing 'Killed' returned whenever I try to clear the Drupal cache.
Verbose output gives me this:
Initialized Drupal 6.30 root directory at /var/www [notice]
Intialized Drupal site default at sites/default [notice]
Undefined variable: may_cache feed_field.module 12 [notice]
Killed
Answer: The string "Killed" doesn't exist in the Drupal 6.30 codebase.
You might have a custom/contrib module which is responsible, or perhaps a Drush extension.
If that's the case, to find it:
grep -nr "Killed" /path/to/drupal/root
grep -nr "Killed" /path/to/drush/extension/folder

(The extension path will probably be ~/.drush)
Comment: You also might want to search for `trigger_error`, which is probably the function that's ultimately responsible. You'll see it in database.mysql.inc, but unless your error message contains a query string, you can be pretty sure that's not where it's coming from
Answer: I increased the PHP memory_limit to form 196M to 256M in the php.ini and the command now executes as expected so it was a memory issue as suspected by @awm.
I'm not sure what had changed to cause Drush to consume more memory however and whether it's safe to allow php scripts to consume so much memory.
For for the help all.
Answer: This is most likely a system issue. I have had similar issues when using middleware on our db servers. For example, if you are using tungsten as a db replicator, it could be configured to disable certain queries or anything that takes longer than a predefined value. This is a mysql or middle ware configuration that is killing a process that takes longer than expected.
Similarly, from another SA question

you might be triggering the Linux out-of-memory (OOM) killer. Check
  dmesg for messages about it. It says which process was killed when
  this happens.

You can use dmesg | grep php for further information
Comment: The output from dmesg | grep php has the following message repeatd a few times: Out of memory: Kill process 3980 (php) score 249 or sacrifice child. Strange because this was not a problem before.

Drush cc all 'Killed'


If statements accept anything

Question: I am new to Java and programming in general.
In my program, I use if statements to read specific user input. But, when I enter the code
"75832", it processes it as if I entered "24231". Also, if I enter anything besides those numbers, it processes it as if I entered "24231". I've done some other basic programs like this before, but I don't know what I did or am doing wrong.
Any help?
static void gateMethod() throws InterruptedException
{

String stageCode;
int randomChunk;

Random generator = new Random();
Scanner input = new Scanner (System.in);

randomChunk = generator.nextInt(6);
System.out.println("Welcome to Datahub v.1");
System.out.println("\rEnter a phrase or number: ");
stageCode = input.nextLine();

if (stageCode.equals("24231"));
{
    if(randomChunk == 0)
    {
        System.out.println("Data Chunk found! Please wait...");
        Thread.sleep(2000);
        System.out.println("Chunk 1/6:");
        System.out.println("text");
        Thread.sleep(2000);
        System.out.println("");
        gateMethod();

    }
    else if(randomChunk == 1)
    {
        System.out.println("Data Chunk found! Please wait...");
        Thread.sleep(2000);
        System.out.println("Chunk 2/6;");
        System.out.println("text");
        Thread.sleep(2000);
        System.out.println("");
        gateMethod();

    }
    else if(randomChunk == 2)
    {
        System.out.println("Data Chunk found! Please wait...");
        Thread.sleep(2000);
        System.out.println("Chunk 3/6:");
        System.out.println("text");
        Thread.sleep(2000);
        System.out.println("");
        gateMethod();
    }
    else if(randomChunk == 3)
    {
        System.out.println("Data Chunk found! Please wait...");
        Thread.sleep(2000);
        System.out.println("Chunk 4/6:");
        System.out.println("text");
        Thread.sleep(2000);
        System.out.println("");
        gateMethod();
    }
    else if(randomChunk == 4)
    {
        System.out.println("Data Chunk found! Please wait...");
        Thread.sleep(2000);
        System.out.println("Chunk 5/6:");
        System.out.println("text");
        Thread.sleep(2000);
        System.out.println("");
        gateMethod();
    }
    else if(randomChunk == 5)
    {
        System.out.println("Data Chunk found! Please wait...");
        Thread.sleep(2000);
        System.out.println("Chunk 6/6:");
        System.out.println("text");
        Thread.sleep(2000);
        System.out.println("");
        gateMethod();
    }
}
if (stageCode.equals("75832"));
{
    System.out.println("");
    System.out.println("Data correct! Please wait...");
    Thread.sleep(2000);
    System.out.println("text");
    System.out.println("more text");
}

}
Comment: While I try to work it out, just a tip, you could cut out that whole big if/else if chunk using `System.out.println("Chunk " + (randomChunk + 1) + "/6;");`
Answer: Remove the semicolon from the end of this line:
if (stageCode.equals("24231"));

and from this line:
if (stageCode.equals("75832"));

Java will treat the semicolon as the entire body of the if condition here.  Then the block in braces following it will always be executed, because it's not attached to the if condition as you expected it to be.
Comment: This is the second similar situation I've seen posted here in the last couple weeks.  Is there a compiler option that detects this potential error and displays a warning?  If so, maybe we should encourage people to use it.  If not, maybe we should encourage someone to add one!!
Comment: @ajb I don't think there's a compiler option for that, but a good IDE should detect it.  IntelliJ IDEA detects these cases this way by highlighting the `if` as a warning and remarking `'if' statement has empty body`.
Comment: Checkstyle or pmd or findbugs.

If statements accept anything


Date difference in timestamp and normal dates in MYSQL

Question: I have a table that has 2 date columns, one is the timestamp value(eg 1359380165) and the other in normal datetime value (eg. 2013-01-28 08:32:53).
I want to find the time lapse between now (Current) and these dates listed above. So the results will be eg.

Daniel changed his password 5mins ago
Jeniffer deleted her phone number 3days ago.

Any ideas?
Answer: This function should do something similar to what you're after, give it a try, it just needs a unix timestamp passed to it like your '1359380165' one.
function getRelativeTime($timestamp)
{
    $timeDifference = time() - $timestamp;
    $timePeriods    = array('second', 'minute', 'hour', 'day', 'week','month', 'years', 'decade');
    $timeLengths    = array('60', '60', '24', '7', '4.35', '12', '10');

    if ($timeDifference > 0)
    {
            $timeSuffix = 'ago';
    }
    else
    {
        $timeDifference = -$timeDifference;
        $timeSuffix     = 'to go';
    }

    for($i = 0; $timeDifference >= $timeLengths[$i]; $i++)
    {
        $timeDifference/= $timeLengths[$i];
        $timeDifference = round($timeDifference);
    }

    if($timeDifference != 1) $timePeriods[$i].= 's';

    return $timeDifference . ' ' . $timePeriods[$i] . ' ' . $timeSuffix;
}

Answer: Assuming a table like this:
mytable
id int unsigned not null auto_increment primary key
username varchar(45) not null
utime int
dtime timestamp

Why not just structure the query so that PHP receives both timestamps in the same format?  Something like this:
SELECT id, username, FROM_UNIXTIME(utime, '%Y-%m-%d %H.%i.%s') AS ut, dtime AS dt FROM mytable;

or
SELECT id, username, utime AS ut, UNIX_TIMESTAMP(dtime) as dt FROM mytable;

Then you can process both ut and dt the same way.
There is a nice relative time function here. It takes a unix timestamp.


Extract https urls using jsoup

Question: I have the following code that extracts urls from a given page using jsoup.
import org.jsoup.Jsoup;
import org.jsoup.helper.Validate;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;

/**
 * Example program to list links from a URL.
 */
public class ListLinks {
    public static void main(String[] args) throws IOException {

        String url = "http://shopping.yahoo.com";
        print("Fetching %s...", url);

        Document doc = Jsoup.connect(url).get();
        Elements links = doc.getElementsByTag("a");

        print("\nLinks: (%d)", links.size());
        for (Element link : links) {
       print(" * a: <%s>  (%s)", link.absUrl("href") /*link.attr("href")*/, trim(link.text(), 35));
        }
    }

    private static void print(String msg, Object... args) {
        System.out.println(String.format(msg, args));
    }

    private static String trim(String s, int width) {
        if (s.length() > width)
            return s.substring(0, width-1) + ".";
        else
            return s;
    }
}

What I'm trying to do, is to build a crawler that extracts only https site. I give the crawler a seed link to start with, then it should extracts all https site, then take each of the extracted link and do the same with them until reaching a certain number of collected urls.
My questions: The above code can extract all links in a given page. I need to extract links that starts with https:// only, what do I need to do in order to achieve this ?
Comment: There are sites that automatically redirect user to HTTPS site if they come from HTTP site, do you want such links? (It is a bit harder in this case, since you must initiate HTTP request here).
Comment: Thanks. No. I just want to collect https sites from the Internet.
Answer: You can use selectors of jsoup. They are pretty powerful.
doc.select("a[href*=https]");//(This is the one you are looking for)selects if value of href contatins https
doc.select("a[href^=www]");//selects if value of href starts with www
doc.select("a[href$=.com]");//selects if value of href ends with .com.

etc.. Experiment with them, you will find out the correct one.

Extract https urls using jsoup


Como proceder regressão não linear pelo modelo mitscherlich?

Question: Olá, boa tarde!
preciso realizar uma análise de regressão não linear nls(), e me sugeriram o modelo mitscherlich:

Não sei como realizar, gostaria da ajuda de vocês!
segue exemplo dos dados:
dados<-structure(list(TEMPO = c(4, 4, 4, 7, 7, 7, 10, 10, 10, 15, 15,
15, 20, 20, 20, 25, 25, 25, 30, 30, 30, 35, 35, 35, 40, 40, 40
), COM = c(102.7408349, 46.42860925, 46.42860925, 193.9867874,
77.78158526, 77.78158526, 259.2226911, 142.9585464, 142.9585464,
338.2513753, 201.6268249, 201.6268249, 540.8096753, 230.0649675,
230.0649675, 621.6945295, 243.5781577, 356.2446836, 678.4896365,
303.6745224, 532.1778946, 731.7253377, 317.1877126, 621.6366503,
794.4532011, 353.1853056, 688.7228286)), class = "data.frame", row.names = 82:108)

Comment: Um primeiro passo é rodar `?nls` dentro do console do R. Veja os exemplos de uso da função e, caso não entenda algo, edite a sua pergunta com sua dúvida.
Comment: não consigo rodar nls(), normalmente sempre pede chutes iniciais, e não sei como colocar essa fórmula dentro da função nls(), aparentemente alfa significa o valor máximo esperado, como não existe, estou utilizando o máximo encontrado, gama seria "b" não sei ao certo, e theta pelo pouco que consegui entender tem haver com a inclinação da reta (nem sei se é uma reta), vi vários trabalhos que utilizam o modelo porém não explicam como utilizam :/ gostaria de ajuda! a variável x é o "TEMPO", e a variável resposta é "COM". Os valores reference à total de carbono orgânico mineralizado.
Answer: O ajuste não é bom mas segue:
fm <- nls(COM ~ Alfa*(1-10^(-Gama*(TEMPO+Tetha))),
                 data = dados,
                 start = list(Alfa = 900, Gama = .1, Tetha = 1))
summary(fm)

# Parameters:
#   Estimate Std. Error t value Pr(>|t|)
# Alfa   1.785e+03  3.844e+03   0.464    0.647
# Gama   4.703e-03  1.265e-02   0.372    0.713
# Tetha -6.293e-01  4.629e+00  -0.136    0.893

plot(COM~TEMPO,dados)
lines(dados$TEMPO,predict(fm),col=3)

Comment: O ajuste não é assim tão mau quanto isso, `hist(resid(fm))` dá gaussiano.
Comment: Nesse caso como devo proceder infelizmente não tenho conhecimento estatístico sobre análises não lineares :/
Comment: Esses dados são reais, são várias medições por período? A análise do modelo é similar aos outros modelos lineares
Comment: esses dados são apenas um desmembramento de um fatorial 3, o tempo ai representa dias de inoculação, quando se roda, a anova para fatorial 3, o ajuste tende para uma regressão quadrática, com platô, por isso segundo ela sua orientadora, que não é da área de estatística solicitou uma ajuste para um modelo de distribuição assintótica, indicando o de  mitscherlich, que viu que o Pimentel-Gomes apresenta no livro: Estatística Aplicada a experimentos agropecuários e Florestais.
Answer: Seguindo a equação escrita por @Robert, o exemplo abaixo adiciona a curva usando a função geom_smooth() do pacote ggplot2:
ggplot(dados, aes(TEMPO, COM))+
  geom_point()+
  geom_smooth(method = "nls",
              formula = y~Alfa*(1-10^(-Gama*(x+Tetha))),
              method.args = list(start = c(Alfa = 900, Gama = .1, Tetha = 1)),
              data=dados,
              se=F)


how to fix this Drupal\commerce\CommerceEntityViewsData' not found

Question: installed Commerce reports using composer. On enabling the module got an error:
"Fatal error: Class 'Drupal\commerce\CommerceEntityViewsData' not found".
what is the solution for this i searched for CommerceEntityViewsData but i couldnot find what exactly it is please help me.
i'm a newbie
Thanks
Comment: Is your project structured using https://github.com/drupal-composer/drupal-project/? Did you installed commerce_reports using `composer require drupal/commerce_reports`?
Comment: yes i installed using composer require drupal/commerce_reports only also the project is structured using drupal-composer
Answer: Make sure you're using Drupal Commerce 8.x-2.6+
CommerceEntityViewsData was added in https://www.drupal.org/node/2882374
Comment: not able to update commerce to 8.6 from 8.3  give error for commerce_product
Comment: What kind of error? How do you update the module?


Executar Function somente quando a div aparecer

Question: Olá galera tenho um contador e queria que ele só começasse quando a div #horario começar a aparecer na tela

JS DO PLUGIM

/**
 * jQuery Spincrement plugin
 *
 * Plugin structure based on: http://blog.jeremymartin.name/2008/02/building-your-first-jquery-plugin-that.html
 * Leveraging of jQuery animate() based on: http://www.bennadel.com/blog/2007-Using-jQuery-s-animate-Method-To-Power-Easing-Based-Iteration.htm
 * Easing function from jQuery Easing plugin: http://gsgd.co.uk/sandbox/jquery/easing/
 * Thousands separator code: http://www.webmasterworld.com/forum91/8.htm
 *
 * @author John J. Camilleri
 * @version 1.2
 */

/* global jQuery */

(function ($) {
  // Custom easing function
  $.extend($.easing, {
    // This is ripped directly from the jQuery easing plugin (easeOutExpo), from: http://gsgd.co.uk/sandbox/jquery/easing/
    spincrementEasing: function (x, t, b, c, d) {
      return (t === d) ? b + c : c * (-Math.pow(2, -10 * t / d) + 1) + b
    }
  })

  // Spincrement function
  $.fn.spincrement = function (opts) {
    // Default values
    var defaults = {
      from: 0,
      to: null,
      decimalPlaces: null,
      decimalPoint: '.',
      duration: 1000, // ms; TOTAL length animation
      leeway: 50, // percent of duraion
      easing: 'spincrementEasing',
      fade: true,
      complete: null
    }
    var options = $.extend(defaults, opts)

    // Function for formatting number
    var re_thouSep = new RegExp(/^(-?[0-9]+)([0-9]{3})/)
    function format (num, dp) {
      num = num.toFixed(dp) // converts to string!

      // Non "." decimal point
      if ((dp > 0) && (options.decimalPoint !== '.')) {
        num = num.replace('.', options.decimalPoint)
      }

      // Thousands separator
      if (options.thousandSeparator) {
        while (re_thouSep.test(num)) {
          num = num.replace(re_thouSep, '$1' + options.thousandSeparator + '$2')
        }
      }
      return num
    }

    // Apply to each matching item
    return this.each(function () {
      // Get handle on current obj
      var obj = $(this)

      // Set params FOR THIS ELEM
      var from = options.from
      if (obj.attr('data-from')) {
        from = parseFloat(obj.attr('data-from'))
      }

      var to
      if (obj.attr('data-to')) {
        to = parseFloat(obj.attr('data-to'))
      } else if (options.to !== null) {
        to = options.to
      } else {
        var re = new RegExp(options.thousandSeparator, 'g')
        to = parseFloat(obj.text().replace(re, ''))
      }

      var duration = options.duration
      if (options.leeway) {
        // If leeway is set, randomise duration a little
        duration += Math.round(options.duration * ((Math.random() * 2) - 1) * options.leeway / 100)
      }

      var dp
      if (obj.attr('data-dp')) {
        dp = parseInt(obj.attr('data-dp'), 10)
      } else if (options.decimalPlaces !== null) {
        dp = options.decimalPlaces
      } else {
        var ix = obj.text().indexOf(options.decimalPoint)
        dp = (ix > -1) ? obj.text().length - (ix + 1) : 0
      }

      // Start
      obj.css('counter', from)
      if (options.fade) obj.css('opacity', 0)
      obj.animate(
        {
          counter: to,
          opacity: 1
        },
        {
          easing: options.easing,
          duration: duration,

          // Invoke the callback for each step.
          step: function (progress) {
            obj.html(format(progress * to, dp))
          },
          complete: function () {
            // Cleanup
            obj.css('counter', null)
            obj.html(format(to, dp))

            // user's callback
            if (options.complete) {
              options.complete(obj)
            }
          }
        }
      )
    })
  }
})(jQuery)

MINHA DIV:

1454

HORAS TRABALHADAS

489463

PROJETOS FINALIZADOS

56464

METROS DE IMPRESSÃO

18500

XÍCARAS DE CAFÉ

Answer: Chame o jQuery.ready da tua div e não do document.
$("#divHorario").ready(function (){
  $('.spincrement').spincrement({
    from: 0.0,
    decimalPlaces:0 ,
    duration: 5000,
  });
});

Utilizando o jQuery.show()
$("#divHorario").show(function (){
  $('.spincrement').spincrement({
    from: 0.0,
    decimalPlaces:0 ,
    duration: 5000,
  });
});

Por padrão deixe sua div oculta e no momento que desejar mostrá-la utilize o show e passe como parâmetro na função o comportamento que desejar.
Comment: ja tentei também não deu certo, a animação para se eu coloco DIV em vez de document
Comment: Mostra algum erro ou feedback no console?
Comment: desculpa falei errado, ele faz do mesmo jeito do que com o document, a pagina carregando ele ja começa a animação, e não não aparece nenhum erro no console
Comment: Esse evento só vai ser disparado quando a div tiver carregado. Se você está exibindo tua div no momento que cria o documento, a div será "iniciada" logo depois do load da página. Tenta explicar na tua pergunta de forma mais detalhada o que você está fazendo e qual o resultado esperado.
Comment: A div HORARIO ja carrega junto com a pagina, é onde a animação vai acontecer. ESSA ANIMAÇÃO é apenas que faça os numeros que está dentro da UL LI da div #horario que estao com a classe .spincrement AUMENTAREM ATÉ O NUMERO QUE COLOQUEI.
Comment: Sugiro que use a função [jQuery.show](http://api.jquery.com/show/) em algum momento no load da tua página e passe uma função na função. Veja o exemplo no [jsFiddle](https://jsfiddle.net/PetrusStarken/Lysrxw43/)
Comment: a animação para... se eu deixo oculto ela não mostra quando desce até a div.
Comment: Não sei como te ajudar =/. Como disse antes, informe mais detalhes do que você está fazendo, o que você precisa, quanto mais detalhes mais fácil alguém tentar te ajudar. Pode editar sua pergunta e colocar tudo o que julgar necessário.
Comment: entendi... mas é apenas algo facil que não ta indo.
Fazer essa função inciiar quando a div horario aparecer na tela.
Answer: Creio que isso funciona
 $('.spincrement').spincrement({
          from: 0.0,
          decimalPlaces:0 ,
          duration: 5000,
          complete: function (e) {
             alert('Faz algo ao aparecer a DIV')
          }
 });

Comment: Parou a animação desse jeito:
Comment: Elabore mais o que aconteceu.
Comment: Dentro de uma div tenho a animação do spincrement, onde faz os numeros fazeres animação de como estivesse aumentando até o numero que coloquei. Porem quero que essa animação só comece quando a div aparecer na tela
Comment: O plugin spincrement nao tem essa opção?
Comment: Não consegui encontrar
Comment: @kaiquemix Atualizei, da uma olhada.
Comment: assim ele funciona com o normal que postei, porem ele começa a animação assim que a pagina carrega e não quando a div aparece na tela.
Comment: com o .bind a animação não funciona nem o alert.
Comment: Se deste modo nao funciona, então nao sei.,
Comment: ok, obrigado pela ajuda amigo :)


How to move specific column one row up?

Question: I have the following text file:
 ...                .....               .....              .......

 Ca28               0.97222484          7.48500210         18.99362895

 Ca30               1.78544464          4.99000140          3.81528863

 Ca32               7.93680381          4.99000140          9.88662475

 Co1                1.67818190          3.65539564         25.52346192

 Co2                1.67818190          8.64539704         25.52346192

 C2                 5.91285159          2.49500070          9.88662475

 O2                 6.70274792          1.85423438         10.66624532

 O4                 4.75829822          1.85423438         16.73758145

 ..                 .....               ....               ....

I wonder how to move with awk the first column one row up to obtain:
 ...
           .....               .....              .......

 Ca28
           0.97222484          7.48500210         18.99362895

 Ca30
           1.78544464          4.99000140          3.81528863

 Ca32
           7.93680381          4.99000140          9.88662475

 Co1
           1.67818190          3.65539564         25.52346192

 Co2
           1.67818190          8.64539704         25.52346192

 C2
           5.91285159          2.49500070          9.88662475

 O2
           6.70274792          1.85423438         10.66624532

 O4
           4.75829822          1.85423438         16.73758145
 ..
           .....               ....               ....

I asked before to do the inverse with awk 'NR%2!=0{prev=$0;next} {print prev, $0}' file but now I don't know how to do that with the same code.
Any suggestions?
Thank you in advance
Comment: @Ed Morton You are right, sorry about that, I'm not a native english speaker so I can be missunderstood. Apologise.
Comment: Do you REALLY have a blank line between every data line of your input?
Comment: @Ed Morton It doesn't really matter, but with the sat solution is enought.
Comment: yes, it does matter, but if you're happy with the solution you have and fully understand what the impact will be of executing it (it will NOT, for example, produce the output you say you want from the input file you posted), then enough said.
Comment: No problem and language isn't the real issue, it's that you posted input and output that don't reflect your real data. Just make sure you post accurate, testable input and output in future and if you'd be happy with output other than what you post, just say that too.
Answer: You can use this awk,
awk '{ $1 = $1 RS }1' yourfile

Explanation:
RS - Record Separator. \n is awk default value.
1  - prints $0(whole line)
Comment: Thank you again sat. You are the boss :)

How to move specific column one row up?


Problemas com contact form 7 - função on_sent_ok obsoleta

Question: Tenho alguns formulários usando o plugin contact form 7 e cada um redirecionando para uma pagina de sucesso especifica, eu usava o on_sent_ok, entretanto ele não quer funcionar fui verificar e descobri que ele esta obsoleto e o correto agora é utilizar o dom, porém simplesmente não acontece nada ao tentar colocar o dom.
Estou tentando usar o seguinte código, inclui ele no functions.php:
add_action( 'wp_footer', 'mycustom_wp_footer' );

function mycustom_wp_footer() {
?>

<?php
}

Answer: Tente substituir wpcf7submit por apenas submit, porque wpcf7submit  não é um evento.
add_action( 'wp_footer', 'mycustom_wp_footer' );

function mycustom_wp_footer() {
?>

<?php
}

Comment: Ainda nada so retorna como se fosse get na url esse parametro site.com.br/#wpcf7-f238-p242-o1
Comment: Fiz uma alteração, se não funcionar eu irei remover minha respotar @Fernando
Comment: não funcionou achei que era por conflito por isso adaptei o codigo, porém ate agora nada
Comment: add_action( 'wp_footer', 'mycustom_wp_footer' );

function mycustom_wp_footer() {
?>

<?php
}
Answer: wpcf7invalid - Dispara quando um envio do formulário Ajax é concluído com êxito, mas o email não foi enviado porque existem campos com entrada inválida.
wpcf7spam - Dispara quando um envio do formulário Ajax é concluído com êxito, mas o email não foi enviado porque uma possível atividade de spam foi detectada.
wpcf7mailsent - Dispara quando um envio do formulário Ajax é concluído com êxito e o email é enviado.
wpcf7mailfailed - Dispara quando um envio do formulário Ajax foi concluído com êxito, mas falhou no envio de email.
wpcf7submit - Dispara quando um envio do formulário Ajax é concluído com êxito, independentemente de outros incidentes.
fonte: https://contactform7.com/dom-events/


Site Down for few minutes after clearing cache

Question: My site is going down every time whenever I am clearing the cache. Site will works again in 5-10 minutes after refreshing web page 2-3 times.
Also I am getting 500 internal server error after clearing the cache.
After refreshing web page 2-3 times site is working fine as before.
Additional information as follow.

Drupal 7
Boost
APC
Apache web server

Can any one put some light on above issue.
Edited
Apache error logs
[Tue Jul 07 08:51:12 2015] [warn] mod_fcgid: read data timeout in 40 seconds, referer: xxxxxxxxx.com
[Tue Jul 07 08:51:12 2015] [error] [client xx.xx.xx.xx] Premature end of script headers: index.php, referer: xxxxxxxxx.com PHP Warning: Module 'apc' already loaded in Unknown on line 0
[Tue Jul 07 08:51:18 2015] [warn] mod_fcgid: process 26541 graceful kill fail, sending SIGKILL PHP Warning: Module 'apc' already loaded in Unknown on line 0 PHP Warning: Module 'apc' already loaded in Unknown on line 0
Comment: HTTP 500 means "See server logs for real error message", Apache even tells you so on 500 screen if you don't configure it otherwise, so please do it and post what you find.
Comment: Error logs [Tue Jul 07 08:51:12 2015] [warn] mod_fcgid: read data timeout in 40 seconds, referer: http://xxxxxxxxx.com
[Tue Jul 07 08:51:12 2015] [error] [client xx.xx.xx.xx] Premature end of script headers: index.php, referer: http://xxxxxxxxx.com
PHP Warning:  Module 'apc' already loaded in Unknown on line 0
[Tue Jul 07 08:51:18 2015] [warn] mod_fcgid: process 26541 graceful kill fail, sending SIGKILL
PHP Warning:  Module 'apc' already loaded in Unknown on line 0
PHP Warning:  Module 'apc' already loaded in Unknown on line 0
Comment: Please edit it into your question.
Answer: Have you installed "Memcache" module ? If no then :
First of all, check mysql slow query log. Also install "Memcache" module which will help you to reduce mysql server load.
Please refer this link for Drupal Memcache installation.


How to set margin for cell in tableView?

Question: I tried to set a margin for a certain cell in my TableView by using code as below:
cell.layoutMargin.left = 20

However, when I launched the application, it changes nothing on the appearance. Is there any way I could achieve this?
Comment: Can you confirm that the content you added has the constraint related to the margin
Comment: Is your tableView static or dynamic?
Comment: it's dynamic @Xcoder
Comment: Update in Swift 4 : cell.layoutMargins.left = 20
Answer: For margins to take effect in any UIView, any constraints must have the "Constrain to margins" checked. Otherwise, the margins will not change any subview's constraints on the superview.

If you are adding constraints with Swift, here is an example of adding constraints relative to margins from Apple. The key part is:
// Get the superview's layout
let margins = view.layoutMarginsGuide

// Pin the leading edge of myView to the margin's leading edge
myView.leadingAnchor.constraint(equalTo: margins.leadingAnchor).isActive = true

Ensure that your view is being updated and that any changes you are making to UIView is from the main thread.
To give a more thorough answer, more data is needed on your current auto layout setup.
Answer: I found a solution or alternative for this problem after getting help from my colleague, what we did was creating an IBOutlet for the constraint (which I just discover).  So in UITableviewCell class, i add this line of code :
@IBOutlet var boxLeadingContraint: NSLayoutConstraint!

And in UITableView I set the margin for the specified cell like this:
cell.boxLeadingContraint.constant = 10

Note: I did this on a UIImageView inside the cell not on the cell itself. Any feedback or advice will be appreciated.


Remove individual points and find slope

Question: I am trying to delete one pair of x and y coordinates from a set of 10 data points and get the slope for the other 9 points.
How do I go about this issue?
Attached herewith is an image of what I am trying to figure out:

In the above image, column B is x-axis and column C is y-axis.
Column D has multiple slopes for every datapoint removed.
The comment section says how each slope was obtained.
Example: Slope of 0.3741 was obtained by removing out B6 and C6 from the dataset.
This is an extremely challenging topic for me to figure out which path to follow. Any help on this aspect is deeply appreciated.

It is similar to go find a pair of x and y coordinates, delete the pair and then give the slope of the other 9 points.

Thanks for reading.
Comment: If you're looking for a software-only answer, please post this question on [SO].  If you're looking for an analysis, explanation, and/or formula, then you have come to the right place here on CV.
Answer: This seems like more of a StackOverflow question than CV. If you're using pandas, you can use pandas.DataFrame.drop, or you can take a slice. For instance, one way of doing this would be
 df['Output slope'] = [find_slope(df.loc[df.index !=i]) for i in df.index]

Where find_slope is whatever algorithm you're using to find the slope.
Comment: @Accumulation, thanks for the reply. I get confused many times as to which forum to post to. Thanks for guiding me this time :)

Remove individual points and find slope