text:
Q: Failure sending Mail in asp.net mvc4 smtp.Send(mail) I find out number of posts regarding to this Issue in stackoverflow, But Still my problem was not solved. I tried to send a mail using the below code:
In Controller:
try
         {
        MailMessage mail = new MailMessage();
        mail.To.Add("mailto@gmail.com");
        mail.From = new MailAddress("mailfrom@gmail.com");
        mail.Subject = "Feedback for Website";
        string Body = "Name:";
        mail.Body = Body;
        mail.IsBodyHtml = true;
        SmtpClient smtp = new SmtpClient();
        smtp.Host = "smtp.gmail.com";
        smtp.EnableSsl = true;
        smtp.Credentials = new System.Net.NetworkCredential("mailTo@gmail.com", "topassword");
        smtp.Send(mail);

    }
    catch (Exception ex)
    {
       Response.Write(ex.Message);

    }

web.config:
<system.net>
<mailSettings>
  <smtp deliveryMethod="PickupDirectoryFromIis">
    <network defaultCredentials="true" host="localhost" port="25"/>
  </smtp>
</mailSettings>

I tried this also:
<smtp from="mymail@gmail.com">
 <network enableSsl="true" host="smtp.gmail.com" port="587" userName="mymail@gmail.com" password="mypassword" />

While debugging In my output:
Step into: Stepping over non-user code 'System.Net.Mail.MailMessage.MailMessage'
Step into: Stepping over non-user code 'System.Net.Mail.MailMessage.To.get'
Step into: Stepping over non-user code 'System.Net.Mail.MailAddress.MailAddress'
Step into: Stepping over non-user code 'System.Net.Mail.MailMessage.Subject.set'
Step into: Stepping over non-user code 'System.Net.Mail.MailMessage.Body.set'
Step into: Stepping over non-user code 'System.Net.Mail.MailMessage.IsBodyHtml.set'
Step into: Stepping over non-user code 'System.Net.Mail.SmtpClient.SmtpClient'
Step into: Stepping over non-user code 'System.Net.Mail.SmtpClient.Host.set'
Step into: Stepping over non-user code 'System.Net.Mail.SmtpClient.EnableSsl.set'
The thread '<Thread Ended>' (0x1f38) has exited with code 0 (0x0).
'iisexpress.exe' (Managed (v4.0.30319)): Loaded 'C:\Windows\assembly\GAC_MSIL\Microsoft.VisualStudio.Debugger.Runtime\11.0.0.0__b03f5f7f11d50a3a\Microsoft.VisualStudio.Debugger.Runtime.dll'
Step into: Stepping over non-user code 'System.Net.NetworkCredential.NetworkCredential'
The thread '<No Name>' (0x23d8) has exited with code 0 (0x0).
Step into: Stepping over non-user code 'System.Net.Mail.SmtpClient.Send'
A first chance exception of type 'System.Net.Mail.SmtpException' occurred in System.dll
The thread '<Thread Ended>' (0x1474) has exited with code 0 (0x0).

How to solve this.. Please help me..

A: Finally after long searches I solved the issue:
Host = "172.**.*.***",
Port = 25,
EnableSsl = false,

Changed host from smtp.gmail.com to "172.**.*.***"(my mail server IP)
port changed from 587 to 25
and set false to EnableSsl

It was working for local.. By using local server host.

A: Try next settings.
enable ssl in code:
smtp.EnableSsl = true;

set config as follows:
<mailSettings>
      <smtp deliveryMethod="Network" from="username@gmail.com">
        <network defaultCredentials="false" host="smtp.gmail.com" port="587" userName="mymail@gmail.com" password="mypassword" />
      </smtp>
</mailSettings>


text:
Q: How to run 'ufw' without interactive mode? I want to run ufw Uncomplicated Firewall from python script but it usually runs in interactive mode. Example:
subprocess.check_output(["ufw", "enable"])

Has the following output:
'Command may disrupt existing ssh connections. Proceed with operation (y|n)? Aborted'

Is there a way to run ufw without interactive mode?

A: Use
ufw --force enable

You may want to have a look at the Gufw source code, it's written in Python.
At least in Ubuntu 14.10 the  calls to ufw are in the file gufw/model/ufw_backend.py.
You can download the source code using
apt-get source gufw

redpajama_set_name: RedPajamaStackExchange


text:
Q: Ajax Product Filter z-index I've got what seems to be a bug on my product filter.
Essentially there is a fixed z-index:10!important; coming from somewhere which I can't find at all.
A solution I think to get around it was to change the .js files of the filter in where it adds css but add !important to that to overwrite it.
I've tried this and it's not having it
Example -
t.parent().find('div.filterscan').css('z-index', '-1', 'important').animate({
any ideas?
Edit 1
So I think that z-index:10!important; entry shouldn't exist because when it's disabled it works perfectly
Css dev

A: Don't use the style sheet. Use Design (paintbrush) -> Customizer -> custom css


text:
Q: EnterpriseLibrary Error I'm receiving reports of a rare and intermittent error in our live environment. I have been unsuccessful in my attempts to reproduce it, and the error itself is a slight mystery. Add to that, it seems to be something involving Enterprise Library tracing (we're using version 5.0) - all in all, a bit of a pain. This is happening on Windows Sever 2008, application is on .Net Framework 4.0 (WPF).
The error message and the stack trace follow:
ArgumentNullException: Value cannot be null. Parameter name: category

<StackTrace>
  Server stack trace:
  at Microsoft.Practices.EnterpriseLibrary.Logging.LogEntry.BuildCategoriesCollection(String category)
  at Microsoft.Practices.EnterpriseLibrary.Logging.Tracer.WriteTraceMessage(String message, String entryTitle, TraceEventType eventType)
  at Microsoft.Practices.EnterpriseLibrary.Logging.Tracer.WriteTraceEndMessage(String entryTitle)
  at Microsoft.Practices.EnterpriseLibrary.Logging.Tracer.Dispose()
  at TestApplication.ViewModelTest.<UpdateUsers>d__1a.MoveNext()

  Exception rethrown at [0]:
  at System.Runtime.CompilerServices.AsyncVoidMethodBuilder.<SetException>b__1(Object state)
  at System.Threading.QueueUserWorkItemCallback.WaitCallback_Context(Object state)
  at System.Threading.ExecutionContext.runTryCode(Object userData)
  at System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData)
  at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
  at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
  at System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem()
  at System.Threading.ThreadPoolWorkQueue.Dispatch()
  at System.Threading._ThreadPoolWaitCallback.PerformWaitCallback()
</StackTrace>

Can anyone shed any light on what might be causing this?
EDIT:
I'm not modifying LogEntry.BuildCategoriesCollection. The input to the method BuildCategoriesCollection(String category) is null.
The UpdateUsers method is as follows:
async void UpdateUsers()
{
    Processing = true;

    using (traceMgr.StartTrace("Trace"))
        using (var engine = new EngineClient())
        {
            Users = new List<UserMasterDataModel> { _blankUser };
            var users = await engine.GetPossibleTagsTask(SelectedOutcomeId, _queue.SystemCd, _queue.QueueCd);
            Users.AddRange(users);
        }

    if (SelectedUser != _blankUser)
    {
        // If null user selected then initialize to the case's tag, otherwise try to find the previously selected UserName
        var userNameToFind = SelectedUser == null ? _details.TagTo : SelectedUser.UserName;
        SelectedUser = Users.FirstOrDefault(user => user.UserName == userNameToFind) ?? _blankUser;

        OnPropertyChanged("SelectedUser");
    }
}

A: This problem seem to be a known bug for E-Lib in previous versions too.
Known as: Unhandled exception when using the logging AB from multiple threads.
"The underlying issue is that in .NET 2.0 RTM a parent thread's operation stack was shared with its children if such a stack existed by the time the children were created."
Read more here:
http://entlib.codeplex.com/workitem/9592
Hard to suggest a generic solution to this as it is very depends on the architecture of your app.


text:
Q: Garbage in primus with nvidia bumblebee on Trusty The following appears when running optirun glxgears with primus and nvidia-331-updates configured in bumblebee.conf:

This is on 14.04 Trusty Tahr, upgraded from 13.10. The application seems to run on the nvidia gpu, but doesn't display correctly as it did in the previous distro version. I suspect this is a bug in primus in the 14.04 repos, unless one of my packages is poorly configured.
The window does refresh and display part of the glxgears image, but only when I shrink the window, and once per frame that the window is being resized. The GL viewport is scaled incorrectly in this process as well.
Continuing some testing, the PRIMUS_UPLOAD=1 flag seems to make the window refresh properly and everything works as intended. This is not a permanent solution though.

A: I would recommend using "Nvidia Prime Indicator".
First Remove Bumblebee
You need to get rid of Bumblebee and the Nvidia driver. Bumblebee does not run well on my Optimus machine, same problems, get Prime indicator. Also the nvidia-331-updates will be installed with sudo apt-get upgrade after this install.
This is my guide from another thread, try it, I feel it could work.
Carefull on next steps, do only the necessary steps:
To remove and purge bumblebee run terminal (if you got black screen, press Ctrl+Alt+F2) and type:
sudo apt-get remove --purge bumblebee

To install Prime run all 3 rows of command:
sudo add-apt-repository ppa:nilarimogard/webupd8 &&
sudo apt-get update && sudo apt-get install prime-indicator

It should work out from the box with Prime Indicator.
If not, purge them all with:
sudo apt-get remove 'nvidia.*' prime-indicator && sudo apt-get autoremove

and start from scratch with:
sudo apt-get install nvidia-331 indicator-prime

When you get it work, install mesa-utils which allows us to recognize the GPUs:
sudo apt-get install mesa-utils

You have Nvidia Optimus, next steps for Intel driver:
Switch to Intel GPU from Prime Indicator and get Intel Graphics Installer .deb file, install it via Software Center, find the Installer in Dash and run it to update your Intel 4000 with latest drivers.
EDIT: After installing the Intel package, IF sudo apt-get update fails on download.01.org public key, run this in terminal:
This will add the correct Key.
sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys A902DDA375E52366

A: Use GitHub retrieve method to check your specs.
$ lspci -vnn | grep '\''[030[02]\]'
00:02.0 VGA compatible controller [0300]: Intel Corporation Haswell-ULT Integrated Graphics Controller [8086:0a16] (rev 09) (prog-if 00 [VGA controller])
08:00.0 3D controller [0302]: NVIDIA Corporation GK208M [GeForce GT 740M] [10de:1292] (rev a1)

*

*Notice the notation 08:00.0 with a single dote.

Only laptops have these kind of nVidia Optimus card, so this project won't apply to desktops (for now). Cards from the 4xxM and newer series are all Optimus-enabled. The M stands for "Mobile". But having a 4xxM card isn't enough to be sure that you're having an Optimus laptop. There must also be an integrated video controller in your processor. To check that, run this command in a [terminal][1]:

Ubuntu way to go with Bumblebee (Wiki)

*

*Basic Setup for 12.04 - 13.04

you need to purge the ppa if you've installed it.

*

*Basic_Setup_for_13.10_and_later

Terminal on, and enter the commands below:
-- UbuntuWiki instructions

*

*Enable the Universe and Multiverse repositories - you need to do this to allow the bumblebee and nvidia packages respectively to be installed.

*sudo apt-get install bumblebee bumblebee-nvidia primus linux-headers-generic

*Reboot
now
Fist make sure nvidia-current version is 304 is really cool.
After installation--
$ ls -l /etc/bumblebee/
-rw-r--r-- 1 root root 2957 Dez  1 00:38 bumblebee.conf
drwxr-xr-x 2 root root 4096 Nov 30 23:57 xorg.conf.d
-rw-r--r-- 1 root root  513 Dez  1 00:37 xorg.conf.nouveau
-rw-r--r-- 1 root root 1380 Dez  1 00:37 xorg.conf.nvidia

REMEMBER 08:00.0?
$ cat /etc/bumblebee/xorg.conf.n*
$ view /etc/bumblebee/xorg.conf.nouveau # and
$ view /etc/bumblebee/xorg.conf.nvidia  # and change the last dot in

BusID "PCI:08:00.0"
Next:
 $ view /etc/bumblebee/bumblebee.conf
 [bumblebeed]
 VirtualDisplay=:8       # refers to PCI:08:00.0, the 1st left 0 is ignored
 KeepUnusedXServer=false
 ServerGroup=bumblebee
 TurnCardOffAtExit=false
 NoEcoModeOverride=false
 Driver=nvidia           # changed
 XorgConfDir=/etc/bumblebee/xorg.conf.d

 [optirun]
 Bridge=auto
 VGLTransport=proxy
 PrimusLibraryPath=/usr/lib/x86_64-linux-gnu/primus:/usr/lib/i386-linux-gnu/primus
 AllowFallbackToIGC=false

 [driver-nvidia]
 KernelDriver=nvidia-current
 PMMethod=bbswitch       # changed
 LibraryPath=/usr/lib/nvidia-current:/usr/lib32/nvidia-current
 XorgModulePath=/usr/lib/nvidia-current/xorg,/usr/lib/xorg/modules
 XorgConfFile=/etc/bumblebee/xorg.conf.nvidia

 [driver-nouveau]
 KernelDriver=nouveau
 PMMethod=auto
 XorgConfFile=/etc/bumblebee/xorg.conf.nouveau

Wanning: I removed the original comments (intrunctions) as a backup.
 Do it too or browse the file and change the values without touching comments.
Test primus
 DRI_PRIME=0 glxgears -info | grep "GL_VENDOR"
 DRI_PRIME=1 glxgears -info | grep "GL_VENDOR"

 $ DRI_PRIME=:8 glxgears # and finaly do it

After that follow the information provided in--
Example_update_to_nvidia-319_driver at UbuntuWiki.
You will adjust the driver version and paths too in the file above.
Works very well to me.


text:
Q: Align vertically list items in inline-block list I have been messing with this for more time then I was expecting. I am trying to align these list items vertically and I can't do it for some reason. I feel like this should have been easy but it's not. I have been even searching on here for the answer but could not find the right solution for me. what am I doing wrong?

body {
background-color: black;
}

.recommend {
  text-align: center;
  position: absolute;
  margin: 0 auto;
  left: 0;
  right: 0;
  top: 0;
}

.recommend span{
  color: #fff;
}

.media-icons {
  left: 0px;
  top: 0px;
  height: 72px;
}

.recommend ul {
  margin: 0;
  padding: 0;
}

.recommend li {
  display: inline-block;
  height: 72px;
}

  network tv stations

A: add this code to css file li img {vertical-align: middle;}

body {
background-color: black;
}

.recommend {
  text-align: center;
  position: absolute;
  margin: 0 auto;
  left: 0;
  right: 0;
  top: 0;
}

.recommend span{
  color: #fff;
}

.media-icons {
  left: 0px;
  top: 0px;
  height: 72px;
}

.recommend ul {
  margin: 0;
  padding: 0;
}

.recommend li {
  display: inline-block;
  height: 72px;
}
li img {vertical-align: middle;}

  network tv stations


text:
Q: How to completely disable the logger I know about this post to disable the log4net logger: Stackoverflow: How to completely disable log4net.
But I wonder whether the logger is actually inactive, when I use code like this:
log.debug("some debug text");

I think about an extra solution to set something like a config switch in the config file (app.config), that signals my program to omit or use the part of source code for output logging, for example:
i.e. in my app.config
<appSettings>
  <add key="enableLog" value="true"/>
</appSettings>

then in the source code:
... determine the value from the config and put it in an local variable and...
if (enableLog) log.debug("some debug text");
What do you think, do I need such kind of solution for more performance or is it a stupid idea?

A: This is exactly what log4net does already. When you call

log.debug("some debug text");

it internally checks the log4net.xml configuration file for
<log4net threshold="OFF" /> //it could also be ALL, DEBUG, INFO etc..

and if it is switched off, it won't continue any further with the logging.
In my opinion there's no need for such an optimization since log4net already does it. I wouldn't say that an extra layer of checks will bring up a noticeable improvement on performance. It depends on what your application is about and if 1 millisecond is vital. I could also say that log4net is pretty optimized and I never needed to make such optimizations on my projects.

A: Given that you are thinking of using an app.config setting...i think you'll find log4net provides similar options anyway. You could always check the IsDebugEnabled flag which you control in your log4net config by setting the Log level.
if (Log.IsDebugEnabled)
     Log.DebugFormat("My text");

You could also use a filter to prevent all logging anyway.
Something like
<filter type="log4net.Filter.DenyAllFilter" />

Hope that's of help.


text:
Q: Which school of reporting function failures is better Very often you have a function, which for given arguments can't generate valid result or it can't perform some tasks. Apart from exceptions, which are not so commonly used in C/C++ world, there are basically two schools of reporting invalid results.
First approach mixes valid returns with a value which does not belong to codomain of a function  (very often -1) and indicates an error
int foo(int arg) {
    if (everything fine)
        return some_value;
    return -1; //on failure
}

The scond approach is to return a function status and pass the result within a reference
bool foo(int arg, int & result) {
     if (everything fine) {
         result = some_value;
         return true;
     }
     return false;  //on failure
}

Which way do you prefer and why. Does additional parameter in the second method bring notable performance overhead?

A: boost optional is a brilliant technique. An example will assist.
Say you have a function that returns an double and you want to signify
an error when that cannot be calculated.
double divide(double a, double b){
    return a / b;
}

what to do in the case where b is 0;
boost::optional<double> divide(double a, double b){
    if ( b != 0){
        return a / b;
    }else{
        return boost::none;
    }
}

use it like below.
boost::optional<double> v = divide(a, b);
if(v){
    // Note the dereference operator
    cout << *v << endl;
}else{
    cout << "divide by zero" << endl;
}

A: The idea of special return values completely falls apart when you start using templates. Consider:
template <typename T>
T f( const T & t ) {
   if ( SomeFunc( t ) ) {
      return t;
   }
   else {         // error path
     return ???;  // what can we return?
   }
}

There is no obvious special value we can return in this case, so throwing an exception is really the only way.  Returning boolean types which must be checked and passing the really interesting values back by reference leads to an horrendous coding style..

A: Quite a few books, etc., strongly advise the second, so you're not mixing roles and forcing the return value to carry two entirely unrelated pieces of information.
While I sympathize with that notion, I find that the first typically works out better in practice. For one obvious point, in the first case you can chain the assignment to an arbitrary number of recipients, but in the second if you need/want to assign the result to more than one recipient, you have to do the call, then separately do a second assignment. I.e.,
 account1.rate = account2.rate = current_rate();

vs.:
set_current_rate(account1.rate);
account2.rate = account1.rate;

or:
set_current_rate(account1.rate);
set_current_rate(account2.rate);

The proof of the pudding is in the eating thereof. Microsoft's COM functions (for one example) chose the latter form exclusively. IMO, it is due largely to this decision alone that essentially all code that uses the native COM API directly is ugly and nearly unreadable. The concepts involved aren't particularly difficult, but the style of the interface turns what should be simple code into an almost unreadable mess in virtually every case.
Exception handling is usually a better way to handle things than either one though. It has three specific effects, all of which are very good. First, it keeps the mainstream logic from being polluted with error handling, so the real intent of the code is much more clear. Second, it decouples error handling from error detection. Code that detects a problem is often in a poor position to handle that error very well. Third, unlike either form of returning an error, it is essentially impossible to simply ignore an exception being thrown. With return codes, there's a nearly constant temptation (to which programmers succumb all too often) to simply assume success, and make no attempt at even catching a problem -- especially since the programmer doesn't really know how to handle the error at that part of the code anyway, and is well aware that even if he catches it and returns an error code from his function, chances are good that it will be ignored anyway.

A: In C, one of the more common techniques I have seen is that a function returns zero on success, non-zero (typically an error code) on error.  If the function needs to pass data back to the caller, it does so through a pointer passed as a function argument.  This can also make functions that return multiple pieces of data back to the user more straightforward to use (vs. return some data through a return value and some through a pointer).
Another C technique I see is to return 0 on success and on error, -1 is returned and errno is set to indicate the error.
The techniques you presented each have pros and cons, so deciding which one is "best" will always be (at least partially) subjective.  However, I can say this without reservations: the technique that is best is the technique that is consistent throughout your entire program.  Using different styles of error reporting code in different parts of a program can quickly become a maintenance and debugging nightmare.

A: Don't ignore exceptions, for exceptional and unexpected errors.
However, just answering your points, the question is ultimately subjective. The key issue is to consider what will be easier for your consumers to work with, whilst quietly nudging them to remember to check error conditions. In my opinion, this is nearly always the "Return a status code, and put the value in a separate reference", but this is entirely one mans personal view. My arguments for doing this...

*

*If you choose to return a mixed value, then you've overloaded the concept of return to mean "Either a useful value or an error code". Overloading a single semantic concept can lead to confusion as to the right thing to do with it.

*You often cannot easily find values in the function's codomain to co-opt as error codes, and so need to mix and match the two styles of error reporting within a single API.

*There's almost no chance that, if they forget to check the error status, they'll use an error code as if it were actually a useful result. One can return an error code, and stick some null like concept in the return reference that will explode easily when used. If one uses the error/value mixed return model, it's very easy to pass it into another function in which the error part of the co-domain is valid input (but meaningless in the context).

Arguments for returning the mixed error code/value model might be simplicity - no extra variables floating around, for one. But to me, the dangers are worse than the limited gains - one can easily forget to check the error codes. This is one argument for exceptions - you literally can't forget to handle them (your program will flame out if you don't).

A: There shouldn't be much, if any, performance difference between the two.  The choice depends on the particular use. You cannot use the first if there is no appropriate invalid value.
If using C++, there are many more possibilities than these two, including exceptions and using something like boost::optional as a return value.

A: You missed a method: Returning a failure indication and requiring an additional call to get the details of the error.
There's a lot to be said for this.
Example:
int count;
if (!TryParse("12x3", &count))
  DisplayError(GetLastError());

edit
This answer has generated quite a bit of controversy and downvoting.  To be frank, I am entirely unconvinced by the dissenting arguments.  Separating whether a call succeeded from why it failed has proven to be a really good idea.  Combining the two forces you into the following pattern:
HKEY key;
long errcode = RegOpenKey(HKEY_CLASSES_ROOT, NULL, &key);
if (errcode != ERROR_SUCCESS)
  return DisplayError(errcode);

Contrast this with:
HKEY key;
if (!RegOpenKey(HKEY_CLASSES_ROOT, NULL, &key))
  return DisplayError(GetLastError());

(The GetLastError version is consistent with how the Windows API generally works, but the version that returns the code directly is how it actually works, due to the registry API not following that standard.)
In any case, I would suggest that the error-returning pattern makes it all too easy to forget about why the function failed, leading to code such as:
HKEY key;
if (RegOpenKey(HKEY_CLASSES_ROOT, NULL, &key) != ERROR_SUCCESS)
  return DisplayGenericError();

edit
Looking at R.'s request, I've found a scenario where it can actually be satisfied.
For a general-purpose C-style API, such as the Windows SDK functions I've used in my examples, there is no non-global context for error codes to rest in.  Instead, we have no good alternative to using a global TLV that can be checked after failure.
However, if we expand the topic to include methods on a class, the situation is different.  It's perfectly reasonable, given a variable reg that is an instance of the RegistryKey class, for a call to reg.Open to return false, requiring us to then call reg.ErrorCode to retrieve the details.
I believe this satisfies R.'s request that the error code be part of a context, since the instance provides the context.  If, instead of a RegistryKey instance, we called a static Open method on RegistryKeyHelper, then the retrieval of the error code on failure would likewise have to be static, which means it would have to be a TLV, albeit not an entirely global one.  The class, as opposed to an instance, would be the context.
In both of these cases, object orientation provides a natural context for storing error codes.  Having said that, if there is no natural context, I would still insist on a global, as opposed to trying to force the caller to pass in an output parameter or some other artificial context, or returning the error code directly.

A: C traditionally used the first approach of coding magic values in valid results - which is why you get fun stuff like strcmp() returning false (=0) on a match.
Newer safe versions of a lot of the standard library functions use the second approach - explicitly returning a status.
And no exceptions aren't an alternative here. Exceptions are for exceptional circumstances which the code might not be able to deal with - you don't raise an exception for a string not matching in strcmp()

A: It's not always possible, but regardless of which error reporting method you use, the best practice is to, whenever possible, design a function so that it does not have failure cases, and when that's not possible, minimize the possible error conditions. Some examples:

*

*Instead of passing a filename deep down through many function calls, you could design your program so that the caller opens the file and passes the FILE * or file descriptor. This eliminates checks for "failed to open file" and report it to the caller at each step.

*If there's an inexpensive way to check (or find an upper bound) for the amount of memory a function will need to allocate for the data structures it will build and return, provide a function to return that amount and have the caller allocate the memory. In some cases this may allow the caller to simply use the stack, greatly reducing memory fragmentation and avoiding locks in malloc.

*When a function is performing a task for which your implementation may require large working space, ask if there's an alternate (possibly slower) algorithm with O(1) space requirements. If performance is non-critical, simply use the O(1) space algorithm. Otherwise, implement a fallback case to use it if allocation fails.
These are just a few ideas, but applying the same sort of principle all over can really reduce the number of error conditions you have to deal with and propagate up through multiple call levels.

A: For C++ I favour a templated solution that prevents the fugliness of out parameters and the fugliness of "magic numbers" in combined answers/return codes.  I've expounded upon this  while answering another question.  Take a look.
For C, I find the fugly out parameters less offensive than fugly "magic numbers".

A: I think there is no right answer to this. It depends on your needs, on the overall application design etc. I personally use the first approach though.

A: I think a good compiler would generate almost the same code, with the same speed. It's a personal preference. I would go on first.

A: If you have references and the bool type, you must be using C++. In which case, throw an exception. That's what they're for. For a general desktop environment, there's no reason to use error codes. I have seen arguments against exceptions in some environments, like dodgy language/process interop or tight embedded environment. Assuming neither of those, always, always throw an exception.

A: Well, the first one will compile either in C and C++, so to do portable code it's fine.
The second one, although it's more "human readable" you never know truthfully which value is the program returning, specifying it like in the first case gives you more control, that's what I think.

A: I prefer using return code for the type of error occured. This helps the caller of the API to take appropriate error handling steps.
Consider GLIB APIs which most often return the error code and the error message along with the boolean return value.
Thus when you get a negative return to a function call, you can check the context from the GError variable.
A failure in the second approach specified by you will not help the caller to take correct actions. Its different case when your documentation is very clear. But in other cases it will be a headache to find how to use the API call.

A: For a "try" function, where some "normal" type of failure is reasonably expected, how about accepting either a default return value or a pointer to a function which accepts certain parameters related to the failure and returns such a value of the expected type?

A:
Apart from doing it the correct way, which of these two stupid ways do you prefer?

I prefer to use exceptions when I'm using C++ and need to throw an error, and in general, when I don't want to force all calling functions to detect and handle the error.  I prefer to use stupid special values when there is only one possible error condition, and that condition means there is no way the caller can proceed, and every conceivable caller will be able to handle it.. which is rare. I prefer to use stupid out parameters when modifying old code and for some reason I can change the number of parameters but not change the return type or identify a special value or throw an exception, which so far has been never.

Does additional parameter in the
  second method bring notable
  performance overhead?

Yes! Additional parameters cause your 'puter to slow down by at least 0 nanoseconds. Best to use the "no-overhead" keyword on that parameter. It's a GCC extension __attribute__((no-overhead)), so YMMV.


text:
Q: Pass variable from a function to another I got a controller who has a function who recieve a param and I want to use it to in another function into it, but with no luck for now. How could I do it?
   <?php

namespace App\Http\Controllers;

use App\Book;

class BookController extends Controller
{
    public function viewSlug($slug){ // I recive the variable here
        $book = \Cache::remember('asd',1,function($slug){ // Trying to use the variable here
            return Book::where('slug', str_slug($slug))->firstOrFail();
        });
        $writer = $book->writer;
        return view('bookInfo', ['book' => $book, 'writer' => $writer]);
    }
}

Getting
"Type error: Too few arguments to function App\Http\Controllers\BookController::App\Http\Controllers\{closure}(), 0 passed in D:\laragon30\www\books\vendor\laravel\framework\src\Illuminate\Cache\Repository.php on line 327 and exactly 1 expected ◀"

A: First, I don't know Laravel, but just because you define a function to accept an argument doesn't automatically make it passed.  Try use():
$book = \Cache::remember('asd',1,function() use($slug){
            return Book::where('slug', str_slug($slug))->firstOrFail();
        });

But why a function?
$book = \Cache::remember('asd', 1, Book::where('slug', str_slug($slug))->firstOrFail());


text:
Q: Two PickerViews with different values This is my code for two pickerviews in one view controller. However its not working for me.
#pragma mark UIPickerViewDelegate methods
    //PickerViewController.m
    - (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)thePickerView {
        return 1;
    }

    - (NSInteger)pickerView:(UIPickerView *)thePickerView numberOfRowsInComponent:(NSInteger)component {

        switch ([thePickerView tag]) {
            case 1: //purpose picker
                return [m_arrPurpose count];
            case 2:  //second picker
                return [m_arrSweep count];
            default:
                return 0;
                break;
        }
    }

    - (NSString *)pickerView:(UIPickerView *)thePickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {

        switch ([thePickerView tag]) {
            case 1: //purpose picker
            {
                //cost.text = @"Test";
                Purpose *prp = [m_arrPurpose objectAtIndex:row];
                return [prp m_purposeName];
            }
            case 2:  //second picker
            {
                OpenActivity *opn = [m_arrSweep objectAtIndex:row];
                return [opn m_ahhaName];
            }
            default:
                return @"";
                break;
        }
}
can any1 help me with this please..
thanks

A: It sounds like either your tags aren't set correctly or you havent connected the datasource and delegate methods for both pickers.
Add some NSLog statements in the numberOfRowsInComponent and titleForRow: methods.
Include the picker view object and the picker view's tag in the log, e.g.
NSLog(@"Rows in component for %@, tag %d",thePickerView,[thePickerView tag]);

And a different text in the titleForRow.
You should see two different objects - if not, your delegate and datasource are not connected. You should see tags 1 and 2 - if not, your tags are not set properly.

A: With this problem there was nothing wrong with my code It's just that I forgot to set tag's value to 1 and 2 in XIB.


text:
Q: Shopware 6.3 - How to change domain name while transferring shop from one domain to another domain I have website running on Shopware 6 under domain - http://www.mycurrentdomain.com
Now, I would like to transfer it into new domain - http://www.newfuturedomain.com
For now, I have copied source code and setup Database as well.
Does anyone know apart from this actions, do i need to perform any settings like db changes or apache settings (server changes)?

A: You need to change the Sales Channel Domain for your storefront to recognize, which sales channel to use for which domain.
You could technically change the entry in the sales_channel_domain table in your DB, but I highly recommend you to change this via administration gui, as stated before by @S.D.


text:
Q: Dart module import I´m new to DART/FLUTTER. I read the documentation and lot´s of posts, but am still confused about the concept of dart imports. The documentation on dart.dev is much about building and using packages, but not very clear on general aspects of 'import'. Some explanations are spread somewhere in the text. But I´m still missing a clear language definition. There is a DartLangSpec-v2.10.pdf, which is not helpful to understand the basic concepts.
On dart.dev we find two types of import:

*

*import 'dart:xxx' -> Multi-platform libraries, Native platform libraries, Web platform libraries. So this are the core libraries !?

*import 'package:xxx' -> libraries from packages. All kinds of third party libraries we can install from pub.dev.

So, that´s pretty much all we find about imports. There is some explanation in the language tour, a post on stackoverflow and tutorialspoint.
Is there a more detailed explanation or reference of the concepts and syntax of dart imports somewhere?
What I found:

*

*You can use libraries similar to code modules in JS, beside some differences in the use of namespaces. The library file has to start with 'library + name', definitions are imported directly, as long as you do not use 'import .. as'.

*definitions beginning with an underscore are not exported

Questions:

*

*can I use an absolute path for a library? Just found relative path definitions

*can we use URL´s in a path definition to read a library from the web?

*what happens, if a library is imported multiple times in different modules?

*can we have different libraries with the same name, but different path?

*are there any limitations in the data types we can use in a library file?

Maybe I simply missed a source, but from other posts it seems, I´m not the only one looking for this information.


text:
Q: How can I replace a java mutable class with its immutable couterpart in scala? I'm trying to understand how to use immutable classes in scala as a replacement for mutable java classes.
My example use case is searching for contacts in a database.
When programming imperatively you would pull each field from the database table and set it on the java object.
How would you do this in Scala using immutable types and functional style?
I know I could use a constructor and create a new instance of the object passing all required data to it, but for large complex data structures this doesn't seem elegant.
What is the "Scala" / "Functional" way to accomplish this?
Or what are some best practices related to constructing complex immutable types?
public List<Contact> search(String firstName, String lastName) throws SQLException {
    List<Contact> contacts = new ArrayList<Contact>();

    Connection con = null;
    PreparedStatement ps = null;
    ResultSet rs = null;
    try {
        con = dataSource.getConnection();

        ps = con.prepareStatement("select * from contacts where first_name like ? and last_name like ?");
        ps.setString(1, "%" + firstName + "%");
        ps.setString(1, "%" + lastName + "%");
        rs = ps.executeQuery();

        while (rs.next()) {
            Contact contact = new Contact();
            contact.setFirstName(rs.getString("first_name"));
            contact.setMiddleName(rs.getString("middle_name"));
            contact.setLastName(rs.getString("last_name"));
            Date birthday = rs.getDate("birthday");
            if (birthday != null) {
                contact.setBirthday(new Date(birthday.getTime()));
            }
            contacts.add(contact);
        }

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        rs.close();
        ps.close();
        con.close();
    }
    return contacts;
}

Contact POJO
import java.util.Date;

public class Contact {
    private String firstName;
    private String middleName;
    private String lastName;
    private Date birthday;

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getMiddleName() {
        return middleName;
    }

    public void setMiddleName(String middleName) {
        this.middleName = middleName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }
}

A: The quick answer is that you call the constructor with your parameters. In Java:
public class Contact {
  private final String firstName;
  private final String middleName;
  private final String lastName;
  private final Date birthday;

  public Contact(
    String firstName,
    String middleName,
        String lastName,
    Date birthday
  ) {
    this.firstName = firstName;
    this.middleName = middleName;
    this.lastName = lastName;
    this.birthday = birthday;
  }
  … // getters
}

  … inside while loop:
  contacts.add(new Contact(
    rs.getString("first_name"),
    rs.getString("middle_name"),
    rs.getString("last_name"),
    new Date(birthday.getTime())
   );

I left out the optional birthday for now, we'll add it back in the Scala version.
We still have a mutable Contacts list though, so lets look at making it properly immutable. We'll use a Scala list. First, the scala data object:
case class Contact(
  first: String,
  middle: String,
  last: String,
  birthday: Option[Date])

We have optional birthday as part of the type-sig as a bonus.
Now lets define a simple extractor method, given a resultSet:
def contacts(rs: ResultSet) = {
  @annotation.tailrec def loop(cs: List[Contact]): List[Contact] =
    if (!rs.next()) cs else loop(
      Contact(
        rs.getString("first_name"),
        rs.getString("middle_name"),
        rs.getString("last_name"),
        Option(rs.getLong("birthday"))
      ) :: cs)
  loop(Nil)
}

This version recursively builds up a singly-linked list of all contacts in your ResultSet. This is immutable.

A: You can also have a mutable builder which makes the immutable object you are looking for. There's nothing wrong with having temporary mutable objects if they stay in their creation scope and they are not propagated elsewhere. The Scala standard library implementation use plenty of those.
Here is a simple example (although this solution is more useful when constructors are big):
// Here is the immutable class
case class Person( name: String, age: Int, married: Boolean )

// Here comes the mutable builder
class PersonBuilder {
  private var name: Option[String] = None
  private var age: Option[Int] = None
  private var married: Option[Boolean] = None

  def setName( n: String ) = { name = Some(n); this }
  def setAge( a: Int ) = { age = Some(a); this }
  def setMarried( m: Boolean ) = { married = Some(m); this }

  def build() = {
    val person = for( n <- name; a <- age; m <- married )
                   yield { Person( n, a, m ) }
    person getOrElse { throw new IllegalStateException( /*msg*/ ) }
  }
}

It can be used as:
val builder = new PersonBuilder
builder setName "Alex"
builder setAge 42
builder setMarried false
val person = builder build  // The immutable instance


text:
Q: Is there a way to access headers & cookies in Service? I have a feathersjs style ToDo service configured in node and it needs to make REST call to a a JAVA bases API end point. It needs to pass cookies and header info that came from the web. However in the service find method I get params which do not have any of the info I need.
I have tried to look into implementing hooks but the context object doesn't seem to have such info as well.
module.exports = class ToDo {
  constructor() { }
  find(params) {
    return new Promise((resolve, reject) => {
      ...run some business logic
      const reqConfig = { path: path, header:, cookies:)

      restService.request(reqConfig).then(() {//business logic});
  }
};

restService is a internal utility which requires config object with BE . API path, headers & cookies.
I expect to be able to pass headers & cookies. So far I have not found a way.

A: From the FAQ:

If you still need something from the request object (for example, the requesting IP address) you can simply tack it on to the req.feathers object as described here:

  app.use(function(req, res, next) {
    req.feathers.fromMiddleware = 'Hello world';
    next();
  });


text:
Q: Error saving data into sql server using Entity Framework after deletingcolumn I've deleted a column in my sql server and updated the entity framework diagram in my vs2015. However I'm getting the following error:

My table looks like this:

And my diagram in EF looks like this:

What i've tried so far:
Updating & refreshing my model in vs2015.
Deleting the particular table in my model and re-adding it by updating my model.
I've read about this problem many times but I cant find a solution that fixes mine.
Hope someone can help!


text:
Q: FullCalendar - Date Sorting Multiple Event Sources in a Custom View I am working on a project utilizing FullCalendar that has multiple event sources. This is working very well for FullCalendar's default views, however for custom views I am noticing that the dates are not being sorted, and instead I am only getting results in the order of each array. I have created a CodePen to illustrate. Notice that "My View" does not sort properly, but that all of the default views work without issue. Any advice would be greatly appreciated.
  var calendarEl = document.getElementById("calendar");

  var calendar = new FullCalendar.Calendar(calendarEl, {
    headerToolbar: {
      left: "prev next today",
      center: "title",
      right: "dayGridMonth timeGridWeek timeGridDay MyView"
    },
    views: {
      MyView: {
        duration: {
          days: 365
        },
        visibleRange: {
          start: '2021-01-01',
          end: '2021-12-31'
        }
      }
    },
    plugins: [CustomViewPlugin_MyView],
    eventSources: [
      calSourceClasses,
      calSourceEvents
    ]
  });

  calendar.render();
});

Code Pen Example


text:
Q: RichTextBox Vertical Scrollbar manipulation in visual studio I've searched through related questions but can't find what I need.
I have a richtextbox control. I need to trigger an event when the vertical scrollbar reaches a certain position (say 90% down to the bottom). I've been playing around with the events for the rich textbox but have yet to find anything.
Any help would be greatly appreciated.

A: You can handle VScoll event to detect vertical scrolling and use function
private static double GetRichTextBoxScrolPos(RichTextBox textBox)
{
    if(textBox1.TextLength == 0) return 0;
    var p1 = textBox.GetPositionFromCharIndex(0);
    var p2 = textBox.GetPositionFromCharIndex(textBox.TextLength - 1);

    int scrollPos = -p1.Y;
    int maxScrolPos = p2.Y - p1.Y - textBox.ClientSize.Height;

    if(maxScrolPos <= 0) return 0;

    double d = 100.0 * (double)scrollPos / (double)maxScrolPos;
    if(d < 0) d = 0;
    else if(d > 100) d = 100;

    return d;
}

to determine scroll position. Result is in % (100% = fully scrolled to bottom).
Important note: This function is not absolutely accurate, but you may find result accurate enougth. It can be further improved by measuring bottom line height (using Graphics object for example). 100% reliable way is to aquire VScrollBar handle and query its position using WinAPI, but that will requre much more work.


text:
Q: SwiftUI NavigationLink I'm working on a SwiftUI practice app and I ran into an issue with the NavigationView/NavigationLink. I am currently using the Metropolitan Museum of Art API and I wanted to make a list of departments that segues to another list of objects in that department, then that list segues to the object's information. Currently the NavigationView/NavigationLink setup I have is creating multiple NavigationViews and is resulting in multiple back buttons/navigation bars. Is there a way to have the new NavigationView replace the old one or have them work in line with one another? The only way I know how to create a segue in SwiftUI is through a NavigationView/NavigationLink but creating it twice seems to be the wrong way to go about things. I have a screen shot of the current state of my app.
App Image
This is my code at the moment.
struct ContentView: View {

@ObservedObject var model = DepartmentListViewModel()

var body: some View {
    NavigationView {
        List {
            ForEach(model.departments, id: \.self) { department in
                NavigationLink(destination: DetailView(viewModel: DetailListViewModel(selectedDepartment: department))) {
                    Text(department.displayName)
                }
            }
        }
        .navigationBarTitle("Departments")
    }
}
}
struct DetailView: View {
@ObservedObject var viewModel: DetailListViewModel

init(viewModel: DetailListViewModel) {
    self.viewModel = viewModel
}

var body: some View {
  NavigationView {
      List {
        ForEach(viewModel.objects, id: \.self) { object in
            NavigationLink(destination: ObjectView(viewModel: ObjectListViewModel(selectedObject: object))) {
                Text(String(object))
            }
          }
      }
      .navigationBarTitle("ObjectIDs")
  }
}
}

A: You don't need NavigationView in your DetailView anymore, the first one handle it


text:
Q: multiple User.IsInRole on same page i faced this problem
when i multiple this condition on different position on same page i'v got error
@if(User.IsInRole("admin"))
{
    @Html.ActionLink("Edit", "Edit", new { id = category.id }) |
    @Html.ActionLink("Details", "Details", new { id = category.id }) |
    @Html.ActionLink("Delete", "Delete", new { id = category.id })
}

A: If I understood your intent I would use for example (my understanding is that you want to render a list of actions with a | character between each action) :
@Html.ActionLink("Edit", "Edit", new { id = category.id }) |
text is a Razor syntax to force switching back to the HTML context.


text:
Q: asset_sync Gem Causes Heroku to Hang on precompile I'm using the asset_sync gem with a Heroku deployment (Rails 3.2.3). Precompilation works nicely locally (pushing assets up to my AWS bucket without issues), but when I push to Heroku, it hangs during asset precompilation.
Preparing app for Rails asset pipeline
Running: rake assets:precompile
AssetSync: using default configuration from built-in initializer

Then eventually it times out with no explaination:
/app/slug-compiler/lib/utils.rb:66:in `block (2 levels) in spawn': command='/app/slug-compiler/lib/../../tmp/buildpacks/ruby/bin/compile /tmp/build_33de6far26atq /app/tmp/repo.git/.cache' exit_status=0 out='' at=timeout elapsed=900.1074194908142 (Utils::TimeoutError)
    from /app/slug-compiler/lib/utils.rb:52:in `loop'
    from /app/slug-compiler/lib/utils.rb:52:in `block in spawn'
    from /app/slug-compiler/lib/utils.rb:47:in `popen'
    from /app/slug-compiler/lib/utils.rb:47:in `spawn'
    from /app/slug-compiler/lib/buildpack.rb:38:in `block in compile'
    from /app/slug-compiler/lib/buildpack.rb:36:in `fork'
    from /app/slug-compiler/lib/buildpack.rb:36:in `compile'
    from /app/slug-compiler/lib/slug.rb:487:in `block in run_buildpack'
    from /app/slug-compiler/lib/utils.rb:121:in `log'
    from /app/slug-compiler/lib/slug.rb:743:in `log'
    from /app/slug-compiler/lib/slug.rb:486:in `run_buildpack'
    from /app/slug-compiler/lib/slug.rb:116:in `block (2 levels) in compile'
    from /app/slug-compiler/lib/utils.rb:102:in `block in timeout'
    from /usr/local/lib/ruby/1.9.1/timeout.rb:58:in `timeout'
    from /app/slug-compiler/lib/utils.rb:102:in `rescue in timeout'
    from /app/slug-compiler/lib/utils.rb:97:in `timeout'
    from /app/slug-compiler/lib/slug.rb:104:in `block in compile'
    from /app/slug-compiler/lib/utils.rb:121:in `log'
    from /app/slug-compiler/lib/slug.rb:743:in `log'
    from /app/slug-compiler/lib/slug.rb:103:in `compile'
    from /app/slug-compiler/bin/slugc:85:in `block in <main>'
    from /app/slug-compiler/lib/slug.rb:495:in `block in lock'
    from /app/slug-compiler/lib/repo_lock.rb:44:in `call'
    from /app/slug-compiler/lib/repo_lock.rb:44:in `run'
    from /app/slug-compiler/lib/slug.rb:495:in `lock'
    from /app/slug-compiler/bin/slugc:66:in `<main>'
 !     Heroku push rejected, failed to compile Ruby/rails app

$ heroku config shows that I have set the following ENVs which I have checked again and again. I know they are the correct values because they work when I precompile locally:
AWS_ACCESS_KEY_ID:          XXXX
AWS_SECRET_ACCESS_KEY:      XXXX
FOG_DIRECTORY:              XXXX
FOG_PROVIDER:               AWS
FOG_REGION:                 eu-west-1

I do not have my public/assets folder checked in, and I have the following setup in my production.rb:
  # Disable Rails's static asset server (Apache or nginx will already do this)
  config.serve_static_assets = false

  # Compress JavaScripts and CSS
  config.assets.compress = true

  # Don't fallback to assets pipeline if a precompiled asset is missed (This would involve live compilation and a big performance issue)
  config.assets.compile = false

  # Generate digests for assets URLs (Fingerprinting)
  config.assets.digest = true

  # (Heroku requires that this be false)
  config.assets.initialize_on_precompile = false

  # AWS Bucket
  config.action_controller.asset_host = "http://#{ENV['FOG_DIRECTORY']}.s3.amazonaws.com"

I have set the following on Heroku as mentioned in asset_sync's README:
$heroku labs:enable user-env-compile -a myapp

What might be causing these issues and/or how can I debug them further. I can't see a way of getting more information about why the precompilation is hanging on Heroku.

A: Turns out it was a problem in the Sass compiler. It was choking on something without throwing any kind of error. I managed to get a bit more information using the steps outlined here, by waiting until it was hung, then quitting the process. That gave me a stack trace back to the sass parser. Think it was some kind of circular dependency.


text:
Q: Delete Request in react not deleting So I am trying to do a delete method in React on the front end UI I get the 200 ok request but I may be doing something wrong so here is my front end and back end code and screen shot of the Ui

 front end

import React, {Component} from 'react';
    import './App.css';
    import axios from 'axios';
    export default class TableRow extends Component {
    constructor(props) {
      super(props);
     this.deletestudent = this.deletestudent.bind(this);
    }
       deletestudent(student_id) {

     axios.post('http://localhost:3200/students/deleteStudent')
     .then(console.log('Student Deleted'))
     .catch(err => console.log(err));
   }
  render(){
    return(

            {this.props.object._id}
            {this.props.object.role_num}
             {this.props.object.first_name}
            {this.props.object.last_name}
            <button className = 'btn-btn-danger'>Update</button>
            <button onClick={this.deletestudent} className = 'btn-btn-danger' color='blue'> Remove</button>

    );
  }
}

back end
second.post('/students/deleteStudent', (req, res) => {

   res.send('delete student'+req.body._id);
    try {
     db.collection('students').deleteOne( { "_id" : ObjectID(req.body._id) } );
  } catch (e) {
   console.log(e);
  }
     res.send('delete student');
  });

Also when I click on the response I get delete student undefined do I need to change my back end I know I need to delete by id but can not figure out how

A: Two correction needed here.

*

*Pass _.id as student_id to deletestudent function or use it from props.

*Pass that student_id in your axios post call.

CODE
import React, { Component } from 'react';
import './App.css';
import axios from 'axios';
export default class TableRow extends Component {
    constructor(props) {
        super(props);
        this.deletestudent = this.deletestudent.bind(this);
    }
    deletestudent() {
        axios.post('http://localhost:3200/students/deleteStudent', {
            '_id': this.props.object._id
        })
            .then(console.log('Student Deleted'))
            .catch(err => console.log(err));
    }
    render() {
        return (

                {this.props.object._id}
                {this.props.object.role_num}
                {this.props.object.first_name}
                {this.props.object.last_name}
                <button className='btn-btn-danger'>Update</button>
                <button onClick={this.deletestudent} className='btn-btn-danger' color='blue'> Remove</button>

        );
    }
}


text:
Q: Do Keyboard Hooks always noticeably slow down the keyboard? I've been playing around with a global keyboard hook using C++, and when the hook is running keyboard input is EXTREMELY slow.  I'm not even doing anything with the hook yet since I'm only playing around with it to learn about hooks.  I'm wondering if it is something wrong with my code or is this just normal for global keyboard hooks?
Here is my code:
DLL file
#include<Windows.h>
#include<stdio.h>
#include "keyDLL.h"

using namespace std;

LRESULT CALLBACK HookProcedure(int code, WPARAM wParam, LPARAM lParam)
    {

        return CallNextHookEx(0, code, wParam, lParam);
    }

DLL header file
#include "windows.h"

extern "C" __declspec(dllexport) LRESULT CALLBACK HookProcedure(int code, WPARAM wParam, LPARAM lParam);

EXE file
#include <iostream>
#include <cstdlib>
#include "windows.h"

using namespace std;

static HHOOK hhandle;
static HMODULE dllHandle;
HOOKPROC hookProcAddress;

int main()
{
        dllHandle = LoadLibrary(TEXT("C:\\logger\\keyDLL\\Debug\\keyDLL.dll"));
        hookProcAddress = (HOOKPROC)GetProcAddress(dllHandle, "_HookProcedure@12");
        hhandle = SetWindowsHookEx(WH_KEYBOARD_LL, hookProcAddress, dllHandle, 0);
        Sleep(INFINITE);
}

As you can see all I am doing with the hook is CallNextHookEx, so nothing at all.  The result is that I can typ an entire sentence and only the first two words will have made it onto the screen when I'm done and it takes several seconds for the rest to catch up.


text:
Q: Selenium Chromedriver launches Chrome, but doesn't open website (new Chromedriver, same old issue) I am having trouble using Selenium Chromedriver on Windows 7. To display the problem, I've boiled it down to a simple script to simply launch the New York Times website:
from selenium import webdriver

# --LOCATIONS --
# The Chrome app:
# C:\Program Files (x86)\Google\Chrome\Application\chrome.exe
# The Chrome binary:
# C:\Python27\Scripts\chromedriver.exe

chromedriver_path = "C:\Python27\Scripts\chromedriver.exe"

driver = webdriver.Chrome(executable_path=chromedriver_path)

driver.get('https://www.nytimes.com/')

The Chrome Browser launches (leading me to speculate that there's nothing with the Chrome application path), but rather than going to the NYT website, the following happens:

The string data:, appears in the URL address bar, and 2 alert notifications come up: one that says "You are using an unsupported command-line flag: --ignore-certificate-errors. Stability and security will suffer." and another that says "Disable developer mode extensions: Extensions running in developer mode can harm your computer. If you're not a developer, you should disable these extensions running in developer mode to stay safe."
This didn't happen when I used Selenium for Firefox- so I'm not sure what to do with Chrome. I've tried looking this issue up on the internet beforehand, but all the issues/solutions are dated from a few years back (2014-2015), and I believe the Selenium packages and Chromedriver binaries have been updated since then.
Does anyone know how I can get my code working? Thank you in advance.

A: I'd have to see your computer to examine how Chromedriver is installed, but as that's not quite feasible, I would at least recommend uninstalling any chromedriver executables on your computer and then downloading it into your project's directory.
It's really just an IT rule-of-thumb; if you've ruled out every other issue that you're aware of, then there's a good chance the problem is something you're not recognizing. Start at square 1 and reinstall Chromedriver.

A: You can disable Developer mode extension by following code(java)
ChromeOptions options = new ChromeOptions();
options.addArguments("chrome.switches","--disable-extensions");
System.setProperty("webdriver.chrome.driver","F:\\Stuff\\Jars\\chromedriver.exe");
driver = new ChromeDriver(options);
driver.manage().window().maximize();
driver.get("https://www.nytimes.com/");


text:
Q: Adsense Is Not Working I have a little problem with my adsense code that doesn't want to show up on my Wordpress site.
It is the first time that i got an adsense code in iframe.
So I'm completely new at this.
Here is the code:
iframe allowtransparency="true" src="thewebsite.com/ad.aspx?bid=7783&pid=2779907" width="980" height="240" marginwidth="0" marginheight="0" hspace="0" vspace="0" frameborder="0" scrolling="no">/iframe>

And i want to place it in the head tag of my site but it's not showing up somehow.
Do you guys have any tricks or solution to make this work?
Thank you.

A: An iframe is specifically something that displays something visual on your site. In essence it embeds a remote resource, "another website", into your site. You need to put it exactly where you want it to appear. Putting it in the head means it's never going to visually show up anywhere. You need to place it somewhere in the <body>.

A: @deceze gave you very good technical explanation, but there is another problem: we are not allowed to place AdSense ads in (i)frames.

Is it violating program policy if I place ads on iframe webpages in my
  software?
Yes, it does violate our policies. Firstly, you're not allowed to
  place ads in a frame within another page. Exceptions to our policies
  are permitted only with authorization from Google for the valid use of
  iframes. Secondly, you're not allowed to put ads in your software,
  e.g., if you control both a website with ads and an app that loads
  that website, we will take action against it.

AdSense policy FAQs > Part 2: Ad implementation
https://support.google.com/adsense/answer/3394713?hl=en#2
http://adsense.blogspot.rs/2011/06/clarifying-our-ad-implementation.html


text:
Q: Does FFMPEG support user data section injection when encoding? The MPEG and H.264 standards both define a mechanism for the injection of an arbitrary metadata stream into video frames. I've google'd a bit and am unable to determine if FFMPEG supports this. Does it?

A: No, it does not support this. That said, it really isn't that hard to implement this yourself and inject the metadata in to the encoded frames post encoding.


text:
Q: How to combine partitioned dataset to single dataset? I have been doing some Machine learning research on Microarray dataset. So, I downloaded breast cancer dataset from "http://datam.i2r.a-star.edu.sg/datasets/krbd/BreastCancer". The problem here is , this dataset is partioned to "test" and "Train" set. So I have few questions related to this.
1) Why do they want to partition the dataset to "Train" and "Test". Why can't they provide a single dataset file.
2) Is there any advantage on using partitioned dataset ?
3) How can I do crossvalidaton on Partioned dataset ?
4) If I want a single dataset file, Can I combine both "Test" and "Train" to single file and use it ? Does this make any problems ?
Any help on this regard will be greatly appreciated.
Also, I am new to Machine Learning field, Please excuse if there are any mistakes in the question.

A: Before initiating your ML research, you must question yourself. What kind of Learning it is? In case of supervised learning e.g. Classifying weather a certain medical record falls into certain pre-defined Class i.e. A: "ITS A Breast Cancer" or B: "Its not a breast cancer". In order to do that, an algorithm must be trained (supervised) with some records or experience. And this supervision is conducted with the Training data. And once, It is trained with that data(becomes a ML model), It is applied to the Test dataset to get predictions. In case of Unsupervised kind of learning, e.g. Clustering a group of students into some cluster based on some attributes similarity, e.g. marks, ages. The training part is skipped since ML model is not supervised with any training dataset. It can be applied to a whole dataset to get cluster centres. This Quora link would be helpful: https://www.quora.com/What-is-the-difference-between-supervised-and-unsupervised-learning-algorithms

A: I will be using information from Manish's answer to answer your query
1) Why do they want to partition the dataset to "Train" and "Test". Why can't they provide a single dataset file.
Because they can ;-). The idea is you train your classifier on the training data and report your results on the test data. In these divisions test data is untouched and never used in training.
2) Is there any advantage on using partitioned dataset ?
Yes! As I said above this test data is never seen by training algorithm so it can be considered as a true generalisation error. This is similar to the concept of three-way split.
3) How can I do crossvalidaton on Partioned dataset ?
Take only the training dataset, run cross-validation to identify appropriate variables and parameters for the models (model selection). Then train a final model from all training dataset. Finally, use that model to predict on the test dataset. The prediction accuracy or any other metric that you use would resemble the true generalisation error of the system.
4) If I want a single dataset file, Can I combine both "Test" and "Train" to single file and use it ? Does this make any problems ?
Yes! You can combine them and run 10 fold cross-validation on them and if you are using some unsupervised algorithms (eg. clustering), it is good idea to do that. It doesn't create any problems but the process I described above in 3 is the accepted norm in reporting when datasets are already split into training and test sets.


text:
Q: the name ds does not exit in the content try catch try
{
    string str = ConfigurationManager.ConnectionStrings["e_con_connection"].ConnectionString;
    SqlConnection con = new SqlConnection(str);
    SqlCommand cmd = new SqlCommand("GetProduct",con);

    cmd.CommandType = System.Data.CommandType.StoredProcedure;
    cmd.Parameters.AddWithValue("@ProductId", productid);

    SqlDataAdapter da = new SqlDataAdapter();
    DataSet ds = new DataSet();
    da.Fill(ds);

}
catch (Exception e)
{
    //throw new Exception( message.ex);

    HttpContext.Current.Response.Redirect("~/Error.aspx?err=" + e.Message);

}

return ds;

i write my code above but show this error whenever i use same code without try catch its work great
the name ds does not exit in the content

A: You must define ds outside the try{} block
 DataSet ds = new DataSet();
    try
    {
       //...
    }
    catch(Exception e)
    {
       //...
    }

A: You are returning ds which mean it needs to be defined before your try starts.  There is no guarantee that a specific line inside your try catch block will exist.
Try defining the variable before the try catch and see if that works for you.
DataSet ds = null;
try
{
    string str = ConfigurationManager.ConnectionStrings["e_con_connection"].ConnectionString;
    SqlConnection con = new SqlConnection(str);
    SqlCommand cmd = new SqlCommand("GetProduct",con);

    cmd.CommandType = System.Data.CommandType.StoredProcedure;
    cmd.Parameters.AddWithValue("@ProductId", productid);

    SqlDataAdapter da = new SqlDataAdapter();
    ds = new DataSet();
    da.Fill(ds);
}
catch (Exception e)
{
    //throw new Exception( message.ex);
    HttpContext.Current.Response.Redirect("~/Error.aspx?err=" + e.Message);
}

return ds;


text:
Q: Word-wrap in TeXmaker editor (how to NOT have a whole paragraph as one line) I am new to LaTeX and am using TeXmaker on Windows 7.
Now, I would like to know how to wrap text in this software. Because now I have written a whole paragraph, which, however, has only one line number.
(See the example - the whole paragraph is line 1)

I tried the solution in this answer, I went to User -> Run script -> hardwordwrap_selection_80col - but it (as name suggests) only works on a selection.
Is there any way to make it work for the whole document?

A: Options -> Configure TeXmaker -> Editor tab, like this:


text:
Q: Groovy map creation, use value assigned to previous key Is there a way to use the values assigned to the previous key in map, for eg:
def x = [
        a: someList.sum(),
        b: anotherList.sum(),
        c: someList.sum() / anotherList.sum()
]

I want the value of 'c' to be a/b, so is there a shortcut so that I don't have to recompute the sums while computing  'c'

A: In order to use previously-added key/values to compute new key/values, you must be able to control the order in which the keys/values are added. I know that's obvious, but what may not be obvious is that Groovy Map declarations do not take order into account. For example, if you write this...
def x = [
        a: 8,
        b: 2,
        c: a / b
]

..., when evaluating the expression for the value of key c, Groovy will attempt to access a variable or property named a, which will fail because the variable/property does not exist. However, you can take advantage of that property lookup and do this:
def x = [:].with {
    a = 8
    b = 2
    c = a / b

    delegate
}

You start by creating an empty Map. Then, use with(Closure) to execute putAt() and get() against the Map. The example above is the equivalent to...
def x = [:].with {
    putAt('a', 8)
    putAt('b', 2)
    putAt('c', get('a') / get('b'))

    delegate
}

Finally, return the Map itself so that it's assigned to x.


text:
Q: Search multi select dropdown angular 4 and material 2 Hi I am using angular 4 and material 2. I have a drop down with multi select options. I am able to display the dropdown with multi select option. Now I want to implement search/filter option in select dropdown. Could you please let me know, Is there any way to achieve this in material2 or I need to implement my own searchable component? Is there any thing like < mat-select-header >?

A: Search textbox hasbeen added inside select box for filter
<mat-form-field>
    <mat-select (openedChange)="openedChange($event)" placeholder="selectFormControl" [formControl]="selectFormControl" multiple>
        <mat-select-trigger>
            {{selectFormControl.value ? selectFormControl.value[0] : ''}}
             1" class="additional-selection">
        (+{{selectFormControl.value.length - 1}} {{selectFormControl.value?.length === 2 ? 'other' : 'others'}})

    </mat-select-trigger>

    <mat-optgroup >
  <mat-form-field style="width:100%;">
    <input #search autocomplete="off" placeholder="Search" aria-label="Search" matInput [formControl]="searchTextboxControl">
    <button [disableRipple]="true" *ngIf="search.value" mat-button matSuffix mat-icon-button aria-label="Clear" (click)="clearSearch($event)">
    <mat-icon >close</mat-icon>
  </button>
         </mat-form-field>
    </mat-optgroup>
    <mat-optgroup *ngIf="(filteredOptions | async).length == 0">

No results found!

    </mat-optgroup>
 <mat-option (optionSelectionChanges)="selectionChange($event)" *ngFor="let option of filteredOptions | async" [value]="option">
        {{option}}
      </mat-option>

</mat-select>
</mat-form-field>

Go to below link to see implementation
https://stackblitz.com/edit/angular-searchable-multiselect-select

A:
Try this:

<md2-select formControlName="some_id"  [multiple]="true">
<md2-select-header class="md2-select-header">
    <input #searchContact name="some_id" class="select-search"
           placeholder="Select Contact">
</md2-select-header>
<md2-option
    *ngFor="let contact of contacts | search:searchContact.value"
    [value]="contact.id">
    {{ user.address1 }}
</md2-option>

A: There's an official npm package that aims to achieve this called ngx-mat-select-search
You can see the demo here.
From issue 5697 of the Angular Material Github, it looks like they want to add this into the official angular material repo, but for now we'll have to make due with this external package.

A: This is not supported at the moment. There is an open feature request for "search/filter in select" and another for "Add select header to the md-select". However, you can take a look at this comment which includes an example of how it can be solved if you don't want to wait.

A: I would think creating an answer would be very simple, a matinput that has a search query and then using a basic search filter pipe on the array list of items that the list holds (I am at work, but when I get home I could possibly write up an example)


text:
Q: Python class members with dynamic names I've seen a class in python which does something of this kind:
obj = Class( name = "somename" )
obj.somename = something
Namely the class initialisation created a member called as the argument string.
I cannot manage to reproduce this behaviour. Any ideas?
I managed to do something similar using globals()["name"] = value. But in this case the created object is son of the module not of the "Class" object. And it's callable as module.somename instead of obj.somename.

A: You can easily create a dynamically named member by using setattr:
>>> class Foo(object):
...     def __init__(self, name):
...         setattr(self, name, 42)
...
>>> f = Foo('bar')
>>> f.bar
42
>>> f.bar = 'hello'
>>> f.bar
'hello'

Note however, that just setting any attribute on an instance of a class is possible for any regular class (that doesn't define __slots__):
>>> class Qux(object):
...     pass
...
>>> q = Qux()
>>> q.foobar = 'hello'
>>> q.foobar
'hello'

A: You can either create a dynamically named fixed value property like this:
class MyClass():
    def __init__(self, attr):
        self.__dict__[attr] = 'some_value'

Or create as many properties as the calling function wants:
class MyClass():
    def __init__(self, *argv, **kwargs):
        for key,value in kwargs.items():
            self.__dict__[key] = value


text:
Q: epson stylus office bx305fw plus How to scan I have a epson stylus office bx305fw plus, But i don't now where the scan option is in the default printer application in Ubuntu
How can i scan with my printer?

A: I just got my Epson Stylus Office bx305fw plus to scan using simple scan. I plugged in to the printer/all in one via usb and the scan worked I then tried it wirelessly and it worked. I'm using Ubuntu 12.04 LTS and a thinkpad t61.I had downloaded the epson driver from here http://avasys.jp/eng/linux_driver/download/lsb/epson-inkjet/escpr/
I hope this helps.
Tiernan

A: Whilst this may not answer your question it will certainly get you started.
"simple-scan" is what I use for a similar HP scanner/printer. You may need to install it, I can't remember if it's installed by default.
This will tell you if the scanner is detected by your computer.
You can also type dmesg in a terminal after you plug in the scanner and see what the kernel is telling you about the hardware and driver situation.
From that message you can Google for solutions.
Richard

A: Download Printer Driver  ESC/P Driver (full feature)
Product name:   Epson Stylus Office BX305
Driver-Version: Ver. latest(02-2012)

Older Drivers just in case! Search query: BX305
In addition you can download useful packages, using synaptic package-manager, to monitor your ink-level and printer status.


text:
Q: Simple glob command not returning anything in print statement I have this code to return a list of paths to files I am interested in. However, when I run this code in putty, no print statements are returned; on the command line nothing happens.
I know that the path provided should return an output, as  have used it onn the command line successfully.
Here is the code:
from glob import glob

#using glob package to find files for models

file_list = glob.glob('/soge-home/data/model/cmip6/CMIP6/CMIP/*/*/historical/r1i1p1f1/Amon/pr/gn/latest/*.nc', recursive=True)
file_list.sort()

#printing file names

for ifile in file_list:
    print(ifile)

A: You are importing glob.glob already. Don't call glob.glob(), use glob() instead
from glob import glob

#using glob package to find files for models

file_list = glob('/soge-home/data/model/cmip6/CMIP6/CMIP/*/*/historical/r1i1p1f1/Amon/pr/gn/latest/*.nc', recursive=True)
file_list.sort()

#printing file names

for ifile in file_list:
    print(ifile)


text:
Q: AutoCompleteTextField not Showing json Data Flutter Here i am trying to show all collage name in textfield through json and i dont't know why it not showing me allcollagename List data is showing in my debug console but it is not visible in AutoCompleteTextField
here's the api which i am using to fetch data for collage names
var api = 'http://universities.hipolabs.com/search';

here's my fetch data function.
fetchData() async {
    try {
      var res = await http.get(api);
      var data = jsonDecode(res.body);
      List<CollageName> collageNameList = data.map<CollageName>((sup) {
        return CollageName.fromJson(sup);
      }).toList();

      allCollageList = collageNameList;
      return allCollageList;
    } catch (err) {
      return Future.error("Connection Error Restart App");
    }
  }

i am calling this  fetch data function in initState
and here's my code for AutoCompleteTextField
 Container(
            child: AutoCompleteTextField(
                key: key,
                controller: _suggetionTextFieldController,
                suggestions: allCollageList,
                clearOnSubmit: false,
                style: TextStyle(fontSize: 10),
                itemFilter: (item, query) {
                  return item.name
                      .toLowerCase()
                      .startsWith(query.toLowerCase());
                },
                itemSorter: (a, b) {
                  return a.name.compareTo(b.name);
                },
                itemSubmitted: (item) {
                  _suggetionTextFieldController.text = item.name;
                },
                itemBuilder: (context, item) {
                  return Container(
                    child: Text(item.name),
                  );
                })),

CollageName(model class)
class CollageName {
  String country;
  String stateProvince;
  String name;
  List<dynamic> webPages;
  List<dynamic> domains;
  String alphaTwoCode;

  CollageName(
      {this.country,
      this.stateProvince,
      this.name,
      this.webPages,
      this.domains,
      this.alphaTwoCode});

  CollageName.fromJson(Map<String, dynamic> json) {
    country = json['country'] ?? "ohh bhai tu fir aa gaya";
    stateProvince = json['state-province'];
    name = json['name'] ?? "ohh bhai tu fir aa gaya";
    webPages = json['web_pages'].cast<String>();
    domains = json['domains'].cast<String>();
    alphaTwoCode = json['alpha_two_code'] ?? "ohh Bhai";
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['country'] = this.country;
    data['state-province'] = this.stateProvince;
    data['name'] = this.name;
    data['web_pages'] = this.webPages;
    data['domains'] = this.domains;
    data['alpha_two_code'] = this.alphaTwoCode;
    return data;
  }
}

init State
 @override
  void initState() {
    super.initState();
    fetchData();
    print(allCollageList.toString());
  }

A: Make a few changes to your fetchData() method
fetchData() async {

    try {
      var res = await http.get(api);
      var data = jsonDecode(res.body);

      List<CollageName> collageNameList = data.map<CollageName>((sup) {
        return CollageName.fromJson(sup);
      }).toList();

      // added these 3 lines also, notice that I have used .addAll() method instead of using the assignment operator
      setState(() {
        allCollageList.addAll(collageNameList);
      });

    } catch (err) {
      return Future.error("Connection Error Restart App: " + err);
    }
  }

A: I think you have missed to setState after setting the variable.
Try something like this,
fetchData() async {
    try {
      var res = await http.get(api);
      var data = jsonDecode(res.body);
      List<CollageName> collageNameList = data.map<CollageName>((sup) {
        return CollageName.fromJson(sup);
      }).toList();

     setState((){  allCollageList = collageNameList });

    } catch (err) {
      return Future.error("Connection Error Restart App");
    }
  }

and also in your fromJson implementation. It should return the instances.
factory CollageName.fromJson(Map<String, dynamic> json) {

    return CollageName(
      country : json['country'] ?? "ohh bhai tu fir aa gaya",
      stateProvince : json['state-province'],
      name : json['name'] ?? "ohh bhai tu fir aa gaya",
      webPages : json['web_pages'],
      domains : json['domains'],
      alphaTwoCode : json['alpha_two_code'] ?? "ohh Bhai"
    );

 }

Hope that works!


text:
Q: I need to match the unique value of rows from one dataset to the columns matching in another dataset and provide the dataframe Below is the dataframe example where id is the index
df:

id
A
B
C

1
False
False
NA

2
True
False
NA

3
False
True
True

df2:

A
B
C
D

True
False
NA
True

False
True
False
False

False
True
True
True

False
True
True
True

False
True
True
True

False
True
True
True

False
True
True
True

False
True
True
True

Output:
Here we are matching the unique row if the id of df matches with the columns of df2 and has true
values in df2 columns then sum it per id of df and provide the data frame of the same index and ignoring d column in df2

id
A
B
C
Sum of matched true values in columns of df2

1
False
False
NA
0

2
True
False
NA
2

3
False
True
True
6

match_df = try_df.merge(df, on= list_new , how='outer',suffixes=('', '_y'))
match_df.drop(match_df.filter(regex='_y$').columns, axis=1, inplace=True)
df_grouped = match_df.groupby('CIS Sub Controls')[list_new].agg(['sum', 'count'])
df_final = pd.concat([df_grouped['col1']['sum'], df_grouped['col2']['sum'], df_grouped['col3']['sum'], df_grouped['col4']['sum'], df_grouped['col1']['count'], df_grouped['col2']['count'], df_grouped['col3']['count'], df_grouped['col4']['count']], axis=1).join(df_grouped.index)
This is not how it goes

A: You can use value_counts and merge:
cols = df1.columns.intersection(df2.columns)

out = (df1.merge(df2[cols].value_counts(dropna=False).reset_index(name='sum'),
                 how='left')
          .fillna({'sum': 0}, downcast='infer')
      )

Output:
   id      A      B     C  sum
0   1  False  False   NaN    0
1   2   True  False   NaN    1
2   3  False   True  True    6


text:
Q: Why does json_decode without assoc work different on PHP 5.6 and PHP 7.2 i have now spen hours to analyse arrays on different servers.
my little code:
echo "Current PHP version: " . phpversion() . "\r\n";

$return = '{"status":"ok","message":"","code":"200","data":{"1234":{"sid":1,"name":"foo"},"4321":{"sid":2,"name":"bar"}}}';
$nr = "1234";

$json_data = json_decode($return, true);
$data = $json_data['data'];
if(isset($data[$nr])){
    echo "$nr found.\r\n";
}else{
    echo "$nr not found.\r\n";
}

$json_data = json_decode($return);
$data = (array) $json_data->data;
if(isset($data[$nr])){
    echo "$nr found.\r\n";
}else{
    echo "$nr not found.\r\n";
}

Produces different output:

Current PHP version: 7.2.0
1234 found.
1234 found.

Current PHP version: 5.6.8
1234 found.
1234 not found.

so why is:
$json_data = json_decode($return, true);
$data = $json_data['data'];

not the same as
$json_data = json_decode($return);
$data = (array) $json_data->data;

on Servers with PHP 5.6
on both is $data an array, but on PHP 5.6 the isset does not work
on the array properly.


text:
Q: Python - Doing double as much in a single loops vs 2 loops This is probably a silly question but what is the benefit of having a setup such as:
for i in list:
 do task 1
 do task 2

vs
for i in list:
 do task 1

for j in list:
 do task 2

I presume there is no performance difference between the two for large lists, but is there any convention as to which is better. I guess 2 can be parallelised more easily and is easier to catch errors, but has the redundancy of effectively a repeated line

A: There is hardly any performance difference between the two because the same number of tasks is being performed by each, but there is a logical difference. The first alternates between task 1 and task 2. The second piece of code does task 1 for each item in the list, before doing each task 2.
I would choose between the two solely on the basis of this logical difference.


text:
Q: Sigma algebra generated by a quadratic function I have a little difficulty determining what $\sigma(F)$ looks like for $$F: [0,1] \ni x \mapsto 1- |2x^2-1| \in [0,1]$$
I know that $F(x)=F(y) \iff x = \sqrt{1-y^2}, \ \ x,y \in [0,1]$.
$\sigma(F) = \sigma( \{F^{-1}(B) : B\in \mathcal{B}_{[0,1]} \})$ where $\mathcal{B}_{[0,1]} $ are borel sets on $[0,1]$ is not enough.
I need a more direct representation of $\sigma(F)$ as a family of sets satisfying certain conditions, because I will need to integrate over them later.
The problem is that the graph is not symmetric, the peak is at $x =\frac{\sqrt{2}}{2}$ and to every value, except for $y=1$ we have two arguments, as mentioned above.
Could you help me find out what $\sigma(F)$ is in this case?

A: $\sigma(F)=\{\sqrt{X/2} \cup \sqrt{2-X/2}: X \in \cal{B}([0,1])\}$.


text:
Q: How to continuously vibrate phone in both android and IOS using flutter I am using vibration: ^1.7.5 package in which we have to specify the time in milliseconds.
I am now using this to vibrate the device till 10 minutes
Vibration.vibrate(duration: 600000, amplitude: 255);
but is there any way by which we can keep vibrating the device continuously until
we want?

A: You can use repeat with a pattern like below which will continue the vibration until cancelled.
Vibration.vibrate(pattern: [100, 200, 400], repeat: 1)

Link to the source
Github Link


text:
Q: Apply Sentence Case to string which might contain HTML I have a series of strings which I need to convert to "sentence case", but what makes it more complicated is that the string could have html anchor tags.
One might contain html like this:
foo is a word. this is another word, and bar is another.

And I would like to apply sentence case with output as follows:
Foo is a word. This is another word, and bar is another.

I can use any solution which utilizes js or vbscript.

A: I suppose that you could build a rather naive approach that simply iterates through the string and flags conditions based on what it encounters (i.e. it sets an inHtml flag to indicate that it is in an HTML tag and sets another shouldCapitalize flag to determine if it's at the start of a sentence :
function titleCaseHtmlSentence(s){
    // A temporary string to hold your results
    var result = '';
    // Iterate through the sentence and check each character to determine if
    // it is the start of a sentence, ignore this
    var shouldCapitalize = true;
    var inHtml = false;
    for(var i = 0; i < s.length; i++){
        // If this is any non tag, punctuation or letter or we are in HTML
        // and haven't encountered a closing tag
        if(/[^a-zA-Z\?\.\>\\<\!]/.test(s[i]) || (inHtml && s[i] != '>')){
            result += s[i];
            continue;
        }
        // If we should capitalize, check if we can
        if(shouldCapitalize && /[a-zA-Z]/.test(s[i])){
            // Capitalize this character
            result += s[i].toUpperCase();
            shouldCapitalize = false;
            continue;
        }
        else{
            result += s[i];
            // If this character is '<', then we are in HTML, so ignore these
            if(s[i] == '<'){
                inHtml = true;
                continue;
            }
            // If the character is a closing tag '>', then start paying attention again
            if(s[i] == '>'){
                inHtml = false;
                continue;
            }

            // Determine if we hit punctuation to start a new sentence
            if(/[\?\!\.]/.test(s[i])){
                shouldCapitalize = true;
                continue;
            }
        }
    }
    return result;
}

I threw it together rather hastily, so I am sure that's far from optimal in any sense, but it should work as seen in this example.

A: In case someone is looking, here is a port of Rion Williams logic to a vbScript function. I used a few functions from my own class library, so Including just the needed parts of those as well, for reference.
As Rion said, it is just a start, and will need lots of fine tuning.
Function toSentenceCase(byVal x)
    Dim i, r, s, bCapitalize, bInHtml

    bCapitalize = True
    bInHtml = False

    Set r = New regularExpression
    Set s = New adoStream

    For i = 1 To Len(x)
        sChar = Mid(x, i, 1)
        Do
            'If this is any non tag, punctuation or letter or we are in HTML and haven't encountered a closing tag
            If r.test("[^a-zA-Z\?\.\>\\<\!]", sChar) Or (bInHtml And sChar <> ">") Then
                s sChar
                Exit Do
            End If

            'if we should capitalize, check if we can, and if yes, then capitalize
            If bCapitalize And r.test("[a-zA-Z]", sChar) Then
                s uCase(sChar)
                bCapitalize = False
                Exit Do
            Else
                s sChar

                'if this character is '<', then we are in HTML, so ignore these
                If sChar = "<" Then
                    bInHtml = True
                    Exit Do
                End If

                'if the character is a closing tag '>', then start paying attention again
                If sChar = ">" Then
                    bInHtml = False
                    Exit Do
                End If

                'determine if we hit punctuation to start a new sentence
                If r.test("[\?\!\.]", sChar) Then
                    bCapitalize = True
                    Exit Do
                End If

            End If

        Loop While False
    Next

    toSentenceCase = s.Value
End Function

Class adoStream
    'string builder class. adodb streams are way faster than appending to/editing content of string variables
    Private stream

    Private Sub Class_Initialize()
        Set stream = CreateObject("ADODB.Stream")
        stream.Type = 2 '2 = text stream
        stream.Open
    End Sub

    Private Sub Class_Terminate()
        stream.Close
        Set stream = Nothing
    End Sub

    Public Default Sub Add(byVal addString) 'add string to existing stream
        stream.WriteText addString
    End Sub

    Public Sub Update(byVal addString) 'update existing stream and set it to a new value. clear existing stream and set it = new value
        Clear
        stream.WriteText addString
    End Sub

    Public Property Get Value 'returns full stream
        stream.Position = 0
        Value = stream.ReadText()
    End Property

    Public Function Clear() 'resets stream
        stream.Position = 0
        Call stream.SetEOS()
    End Function
End Class

Class regularExpression
    'class containing a set of vbscript regex routines
    Private oRegex
    Private Sub Class_Initialize()
        Set oRegex = New RegExp
        oRegex.Global = True    'e.g. findall
        oRegex.IgnoreCase = True
    End Sub

    Private Sub Class_Terminate()
        Set oRegex = Nothing
    End Sub

    'test
    Public Function test(byVal sPattern, byVal sTestString) 'return t/f
        If isNull(sTestString) Then
            test = False
            Exit Function
        End If
        oRegex.Pattern = sPattern
        test = oRegex.test(sTestString)
    End Function
End Class


text:
Q: combining st_contains with st_buffer gives very slow query I have a layer with roads (4000 features) and a layer with routes (80 features). I want to select every road located on a route, combined with the route-type.
Normaly I would use select road.geom, road.id, route.type from road, route where st_contains(route.geom, road.geom).
Because the routes are not properly digitized I need to buffer the routes to select all roads contained by a route.  So when I do select road.geom, road.id, route.type from road, route where st_contains(st_buffer(route.geom, 3), road.geom) the query keeps running for a long time without result.
How can I make this query running faster?

A: Ensuring the geom is spatially indexed in the road and route tables will be essential to the speed of this query.
Assuming this is already in place I would recommend trying ST_DWithin which 'Returns true if the geometries are within the specified distance of one another.'
ST_DWithin(route.geom, road.geom, 3);

To ensure only geometries that are fully within the specified distance, ST_DFullyWithin can be used instead.
ST_DFullyWithin(route.geom, road.geom, 3);


text:
Q: Convert timezone offset to hours & minutes preserving sign Suppose I have an offset like this:
$secOffset =  -28800

I need it to convert in a format that is usable with MYSQL function convert_tz()
If I use gmdate("h:i", secOffset) I got 16:00 that is almost correct but It miss the minus - (that is quite important)
Alternative approach:
Suppose I have a time string America/Los_Angeles and I want to convert in a offset useful for MYSQL function convert_tz()
The final expected output is the offset from GMT so given a timezone.
For ex, having a timezone like America/Los_Angeles, the output should be:
−08:00
I'm on Magento/Zend so if any available function is on Zend I can accept answer based on it.

A: You should use the DateTimeZone and DateInterval classes for this:
$tzid = 'America/Los_Angeles';

$tz = new DateTimeZone($tzid);
$date = new DateTime('now', $tz);

// create a new date offset by the timezone offset
// gets the interval as hours & minutes
$offset = $tz->getOffset($date) . ' seconds';
$dateOffset = clone $date;
$dateOffset->sub(DateInterval::createFromDateString($offset));

$interval = $dateOffset->diff($date);
$formatted = $interval->format('%R%H:%I');

This is a little convoluted, as you first get the timezone offset in seconds, and then use DateTime to help convert that interval into hours/mins.


text:
Q: Access to list element on codebehind from aspx I have the following method on codebehind
Public List<object> Exec()
{
    List<object> result = New List<object>();
    DataTable results = New DataTable();

    // methodToExecuteSP is = public DataSet
    results = methodToExecuteSP;

    foreach (DataRow i in results.Rows)
    {
        result.Add(new { Name = i["Name"] });
    }

    return result;
}

Then on my aspx I have the following html and C# code

    <% foreach (var item in Exec()) { %>

<%=item.Name %>

    <% } %>

This shows the following error message:

Object does not contain a definition for Name.

What I'm doing wrong?
PD: If I change item.Name to item I can see my entire list properly.

A: This is the expected behavior. Note the return type of the method Exec, it is object. This type has not any property called Name. That you need is to change this return type to an object with the property you want to use, Name or to just return a List<string>, if the only property you are going to use is the Name.
first approach:
public class Person
{
    public string Name { get; set; }
}

public List<Person> Exec()
{
    var persons = new List<Person>();

    var results = New DataTable();

    // methodToExecuteSP is = public DataSet
    results = methodToExecuteSP;

    foreach (DataRow row in results.Rows)
    {
        result.Add(new Person { Name = row["Name"].ToString() });
    }

    return persons;
}

<% foreach (var person in Exec()) { %>

<%=person.Name %>

<% } %>

second approach:
public List<string> Exec()
{
    var names = new List<string>();

    var results = New DataTable();

    // methodToExecuteSP is = public DataSet
    results = methodToExecuteSP;

    foreach (DataRow row in results.Rows)
    {
        result.Add(row["Name"].ToString());
    }

    return names;
}

<% foreach (var name in Exec()) { %>

<%=name%>

<% } %>


text:
Q: What's the different between (Type) and Get.Type() Why are these both different when called on same object?
protected override Type GetType(MethodInfo methodInfo, object[] arguments)
{
    var typeOne = (Type)arugments.Single();
    Debug.WriteLine(typeOne.ToString()); // This gives me NewWorld.OldWorld.Class

    var typeTwo = arugments.Single().GetType();
    Debug.WriteLine(typeTwo.ToString()); // This gives me System.RuntimeType

    return typeOne;
}

A: This is going to get really meta...
Assuming your arguments is actually an array of Types, the expression (Type)arguments.Single() makes the compile-time type of the single argument become Type.
The type Type represents a type. In this case, you got NewWorld.OldWorld.Class, which most likely is the fully qualified name of a class. The single element in arguments (which is of type Type) represents the type NewWord.OldWorld.Class.
The second expression in question, arguments.Single().GetType() gets the runtime type of the object on which GetType is called, as an instance of Type. In this case, This will return the runtime type of arguments.Single(), which is RuntimeType, a subclass of Type.
Basically:

*

*(Type)arguments.Single() tells the compiler that arguments contains a single element that is of type Type. It evaluates to a Type object that represents NewWord.OldWord.Class.

*arguments.Single().GetType() gets the type of argument.Single(). This is not the same as what type arguments.Single() represents. It represents the type Class, but its type is RuntimeType. If you are still confused, here's an example with integers.
int[] array = new int[] { 10 };

array.Single() represents the number 10 but its type is System.Int32.


text:
Q: Error in discrete_scale with unused argument when using ggplot2 and ggflags I have a strange error when using the ggplot2 add-on package ggflags, one that only affects my work computer; at home I can write charts using ggflags with no issues.
The ggflags documentation is here: https://github.com/baptiste/ggflags
And this is the suggested example code:
library(ggplot2)
library(ggflags)

set.seed(1234)
d <- data.frame(x=rnorm(50), y=rnorm(50),
            country=sample(c("ar","fr", "nz", "gb", "es", "ca"), 50, TRUE),
            stringsAsFactors = FALSE)
ggplot(d, aes(x=x, y=y, country=country, size=x)) +
  geom_flag() +
  scale_country()

At home, this runs with no problem, reproducing the graph shown on the README on Github, however on my work machine I get the following error message:

Error in discrete_scale("country", "identity", scales::identity_pal(),  :
  unused argument (super = ScaleDiscreteIdentity)

This seems to be a fairly obscure error, and I am not finding any results on Stack Overflow to explain why this (pretty basic) bit of code will work on one machine and not on the other. I've tried uninstalling and reinstalling RStudio, as well as deleting and reinstalling the relevant packages from my package library, but I've had no joy in getting this package to work on my office machine. Any suggestions?