Programs & Examples On #Smtpd

0

5.7.57 SMTP - Client was not authenticated to send anonymous mail during MAIL FROM error

In my situation, our IT department made MFA mandatory for our domain. This means we can only use option 3 in this Microsoft article to send email. Option 3 involves setting up an SMTP relay using an Office365 Connector.

PHPMailer - SMTP ERROR: Password command failed when send mail from my server

I face the same problem, and think that I do know why this happens.

The gmail account that I use is normally used from India, and the webserver that I use is located in The Netherlands.

Google notifies that there was a login attempt from am unusualy location and requires to login from that location via a web browser.

Furthermore I had to accept suspicious access to the gmail account via https://security.google.com/settings/security/activity

But in the end my problem is not yet solved, because I have to login to gmail from a location in The Netherlands.

I hope this will help you a little! (sorry, I do not read email replies on this email address)

Gmail Error :The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required

I'm a google apps for business subscriber and I spend the last couple hours just dealing with this, even after having all the correct settings (smtp, port, enableSSL, etc). Here's what worked for me and the web sites that were throwing the 5.5.1 error when trying to send an email:

  1. Login to your admin.google.com
  2. Click SECURITY <-- if this isn't visible, then click 'MORE CONTROLS', and add it from the list
  3. Click Basic Settings
  4. Scroll to the bottom of the Basic Settings box, click the link: 'Go to settings for less secure apps'
  5. Select the option #3 : Enforce access to less secure apps for all users (Not Recommended)
  6. Press SAVE at the bottom of the window

After doing this my email forms from the website were working again. Good luck!

SmtpException: Unable to read data from the transport connection: net_io_connectionclosed

For anyone who stumbles across this post looking for a solution and you've set up SMTP sendgrid via Azure.

The username is not the username you set up when you've created the sendgrid object in azure. To find your username;

  • Click on your sendgrid object in azure and click manage. You will be redirected to the SendGrid site.
  • Confirm your email and then copy down the username displayed there.. it's an automatically generated username.
  • Add the username from SendGrid into your SMTP settings in the web.config file.

Hope this helps!

How to link home brew python version and set it as default

The problem with me is that I have so many different versions of python, so it opens up a different python3.7 even after I did brew link. I did the following additional steps to make it default after linking

First, open up the document setting up the path of python

 nano ~/.bash_profile

Then something like this shows up:

# Setting PATH for Python 3.7
# The original version is saved in .bash_profile.pysave
PATH="/Library/Frameworks/Python.framework/Versions/3.7/bin:${PATH}"
export PATH

# Setting PATH for Python 3.6
# The original version is saved in .bash_profile.pysave
PATH="/Library/Frameworks/Python.framework/Versions/3.6/bin:${PATH}"
export PATH

The thing here is that my Python for brew framework is not in the Library Folder!! So I changed the framework for python 3.7, which looks like follows in my system

# Setting PATH for Python 3.7
# The original version is saved in .bash_profile.pysave
PATH="/usr/local/Frameworks/Python.framework/Versions/3.7/bin:${PATH}"
export PATH

Change and save the file. Restart the computer, and typing in python3.7, I get the python I installed for brew.

Not sure if my case is applicable to everyone, but worth a try. Not sure if the framework path is the same for everyone, please made sure before trying out.

Mail not sending with PHPMailer over SSL using SMTP

Firstly, use these settings for Google:

$mail->IsSMTP();
$mail->Host = "smtp.gmail.com";
$mail->SMTPAuth = true;
$mail->SMTPSecure = "tls"; //edited from tsl
$mail->Username = "myEmail";
$mail->Password = "myPassword";
$mail->Port = "587";

But also, what firewall have you got set up?

If you're filtering out TCP ports 465/995, and maybe 587, you'll need to configure some exceptions or take them off your rules list.

https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting

The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required?

I've searched and tried different things for hours.. To summarize, I had to take into consideration the following points:

  1. Use smtp.gmail.com instead of smtp.google.com
  2. Use port 587
  3. Set client.UseDefaultCredentials = false; before setting credentials
  4. Turn on the Access for less secure apps
  5. Set client.EnableSsl = true;

If these steps didn't help, check this answer.
Perhaps, you can find something useful on this System.Net.Mail FAQ too.

SMTP Connect() failed. Message was not sent.Mailer error: SMTP Connect() failed

You must to have installed php_openssl.dll, if you use wampserver it's pretty easy, search and apply the extension for PHP.

In the example change this:

    //Set the hostname of the mail server
    $mail->Host = 'smtp.gmail.com';

    //Set the SMTP port number - 587 for authenticated TLS, a.k.a. RFC4409 SMTP submission 465 ssl
    $mail->Port = 465;

    //Set the encryption system to use - ssl (deprecated) or tls
    $mail->SMTPSecure = 'ssl';

and then you recived an email from gmail talking about to enable the option to Less Safe Access Applications here https://www.google.com/settings/security/lesssecureapps

I recommend you change the password and encrypt it constantly

Mailbox unavailable. The server response was: 5.7.1 Unable to relay Error

WE had this issue. everything was setup fine in terms of permissions and security.

after MUCH needling around in the haystack. the issue was some sort of heuristics. in the email body , anytime a certain email address was listed, we would get the above error message from our exchange server.

it took 2 days of crazy testing and hair pulling to find this.

so if you have checked everything out, try changing the email body to only the word 'test'. If after that, your email goes out fine, you are having some sort of spam/heuristic filter issue like we were

phpmailer: Reply using only "Reply To" address

I have found the answer to this, and it is annoyingly/frustratingly simple! Basically the reply to addresses needed to be added before the from address as such:

$mail->addReplyTo('[email protected]', 'Reply to name');
$mail->SetFrom('[email protected]', 'Mailbox name');

Looking at the phpmailer code in more detail this is the offending line:

public function SetFrom($address, $name = '',$auto=1) {
   $address = trim($address);
   $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim
   if (!self::ValidateAddress($address)) {
     $this->SetError($this->Lang('invalid_address').': '. $address);
     if ($this->exceptions) {
       throw new phpmailerException($this->Lang('invalid_address').': '.$address);
     }
     echo $this->Lang('invalid_address').': '.$address;
     return false;
   }
   $this->From = $address;
   $this->FromName = $name;
   if ($auto) {
      if (empty($this->ReplyTo)) {
         $this->AddAnAddress('ReplyTo', $address, $name);
      }
      if (empty($this->Sender)) {
         $this->Sender = $address;
      }
   }
   return true;
}

Specifically this line:

if (empty($this->ReplyTo)) {
   $this->AddAnAddress('ReplyTo', $address, $name);
}

Thanks for your help everyone!

Why do I get "'property cannot be assigned" when sending an SMTP email?

Just need to try this:

string smtpAddress = "smtp.gmail.com";
int portNumber = 587;
bool enableSSL = true;
string emailFrom = "companyemail";
string password = "password";
string emailTo = "Your email";
string subject = "Hello!";
string body = "Hello, Mr.";
MailMessage mail = new MailMessage();
mail.From = new MailAddress(emailFrom);
mail.To.Add(emailTo);
mail.Subject = subject;
mail.Body = body;
mail.IsBodyHtml = true;
using (SmtpClient smtp = new SmtpClient(smtpAddress, portNumber))
{
   smtp.Credentials = new NetworkCredential(emailFrom, password);
   smtp.EnableSsl = enableSSL;
   smtp.Send(mail);
}

How to send email via Django?

I had actually done this from Django a while back. Open up a legitimate GMail account & enter the credentials here. Here's my code -

from email import Encoders
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email.MIMEMultipart import MIMEMultipart

def sendmail(to, subject, text, attach=[], mtype='html'):
    ok = True
    gmail_user = settings.EMAIL_HOST_USER
    gmail_pwd  = settings.EMAIL_HOST_PASSWORD

    msg = MIMEMultipart('alternative')

    msg['From']    = gmail_user
    msg['To']      = to
    msg['Cc']      = '[email protected]'
    msg['Subject'] = subject

    msg.attach(MIMEText(text, mtype))

    for a in attach:
        part = MIMEBase('application', 'octet-stream')
        part.set_payload(open(attach, 'rb').read())
        Encoders.encode_base64(part)
        part.add_header('Content-Disposition','attachment; filename="%s"' % os.path.basename(a))
        msg.attach(part)

    try:
        mailServer = smtplib.SMTP("smtp.gmail.com", 687)
        mailServer.ehlo()
        mailServer.starttls()
        mailServer.ehlo()
        mailServer.login(gmail_user, gmail_pwd)
        mailServer.sendmail(gmail_user, [to,msg['Cc']], msg.as_string())
        mailServer.close()
    except:
        ok = False
    return ok

Sending emails through SMTP with PHPMailer

Try to send an e-mail through that SMTP server manually/from an interactive mailer (e.g. Mozilla Thunderbird). From the errors, it seems the server won't accept your credentials. Is that SMTP running on the port, or is it SSL+SMTP? You don't seem to be using secure connection in the code you've posted, and I'm not sure if PHPMailer actually supports SSL+SMTP.

(First result of googling your SMTP server's hostname: http://podpora.ebola.cz/idx.php/0/006/article/Strucny-technicky-popis-nastaveni-sluzeb.html seems to say "SMTPs mail sending: secure SSL connection,port: 465" . )

It looks like PHPMailer does support SSL; at least from this. So, you'll need to change this:

define('SMTP_SERVER', 'smtp.ebola.cz');

into this:

define('SMTP_SERVER', 'ssl://smtp.ebola.cz');

Problem with SMTP authentication in PHP using PHPMailer, with Pear Mail works

strange issue that i solved by comment this line

//$mail->IsSmtp();

whit the last phpmailer version (5.2)

Sending email through Gmail SMTP server with C#

If you have 2-Step Verification step up on your Gmail account, you will need to generate an App password. https://support.google.com/accounts/answer/185833?p=app_passwords_sa&hl=en&visit_id=636903322072234863-1319515789&rd=1 Select How to generate an App password option and follow the steps provided. Copy and paste the generated App password somewhere as you will not be able to recover it after you click DONE.

How to sign in kubernetes dashboard?

All the previous answers are good to me. But a straight forward answer on my side would come from https://github.com/kubernetes/dashboard/wiki/Creating-sample-user#bearer-token. Just use kubectl -n kube-system describe secret $(kubectl -n kube-system get secret | grep admin-user | awk '{print $1}'). You will have many values for some keys (Name, Namespace, Labels, ..., token). The most important is the token that corresponds to your name. copy that token and paste it in the token box. Hope this helps.

What is ".NET Core"?

.NET Core is a free and open-source, managed computer software framework for Windows, Linux, and macOS operating systems. It is an open source, cross platform successor to .NET Framework.

.NET Core applications are supported on Windows, Linux, and macOS. In a nutshell .NET Core is similar to .NET framework, but it is cross-platform, i.e., it allows the .NET applications to run on Windows, Linux and MacOS. .NET framework applications can only run on the Windows system. So the basic difference between .NET framework and .NET core is that .NET Core is cross platform and .NET framework only runs on Windows.

Furthermore, .NET Core has built-in dependency injection by Microsoft and you do not have to use third-party software/DLL files for dependency injection.

Creating a dynamic choice field

As pointed by Breedly and Liang, Ashok's solution will prevent you from getting the select value when posting the form.

One slightly different, but still imperfect, way to solve that would be:

class waypointForm(forms.Form):
    def __init__(self, user, *args, **kwargs):
        self.base_fields['waypoints'].choices = self._do_the_choicy_thing()
        super(waypointForm, self).__init__(*args, **kwargs)

This could cause some concurrence problems, though.

Add the loading screen in starting of the android application

You can use splash screen in your first loading Activity like this:

@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.splash);

        Thread welcomeThread = new Thread() {

            @Override
            public void run() {
                try {
                    super.run();
                    sleep(10000);  //Delay of 10 seconds
                } catch (Exception e) {

                } finally {

                    Intent i = new Intent(SplashActivity.this,
                            MainActivity.class);
                    startActivity(i);
                    finish();
                }
            }
        };
        welcomeThread.start();
    }

Hope this code helps you.

Registering for Push Notifications in Xcode 8/Swift 3.0?

I had issues with the answers here in converting the deviceToken Data object to a string to send to my server with the current beta of Xcode 8. Especially the one that was using deviceToken.description as in 8.0b6 that would return "32 Bytes" which isn't very useful :)

This is what worked for me...

Create an extension on Data to implement a "hexString" method:

extension Data {
    func hexString() -> String {
        return self.reduce("") { string, byte in
            string + String(format: "%02X", byte)
        }
    }
}

And then use that when you receive the callback from registering for remote notifications:

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    let deviceTokenString = deviceToken.hexString()
    // Send to your server here...
}

How do you delete a column by name in data.table?

For a data.table, assigning the column to NULL removes it:

DT[,c("col1", "col1", "col2", "col2")] <- NULL
^
|---- Notice the extra comma if DT is a data.table

... which is the equivalent of:

DT$col1 <- NULL
DT$col2 <- NULL
DT$col3 <- NULL
DT$col4 <- NULL

The equivalent for a data.frame is:

DF[c("col1", "col1", "col2", "col2")] <- NULL
      ^
      |---- Notice the missing comma if DF is a data.frame

Q. Why is there a comma in the version for data.table, and no comma in the version for data.frame?

A. As data.frames are stored as a list of columns, you can skip the comma. You could also add it in, however then you will need to assign them to a list of NULLs, DF[, c("col1", "col2", "col3")] <- list(NULL).

Using a Python subprocess call to invoke a Python script

If 'somescript.py' isn't something you could normally execute directly from the command line (I.e., $: somescript.py works), then you can't call it directly using call.

Remember that the way Popen works is that the first argument is the program that it executes, and the rest are the arguments passed to that program. In this case, the program is actually python, not your script. So the following will work as you expect:

subprocess.call(['python', 'somescript.py', somescript_arg1, somescript_val1,...]).

This correctly calls the Python interpreter and tells it to execute your script with the given arguments.

Note that this is different from the above suggestion:

subprocess.call(['python somescript.py'])

That will try to execute the program called python somscript.py, which clearly doesn't exist.

call('python somescript.py', shell=True)

Will also work, but using strings as input to call is not cross platform, is dangerous if you aren't the one building the string, and should generally be avoided if at all possible.

Launch an app from within another (iPhone)

As Kevin points out, URL Schemes are the only way to communicate between apps. So, no, it's not possible to launch arbitrary apps.

But it is possible to launch any app that registers a URL Scheme, whether it's Apple's, yours, or another developer's. The docs are here:

Defining a Custom URL Scheme for Your App

As for launching the phone, looks like your tel: link needs to have least three digits before the phone will launch. So you can't just drop into the app without dialing a number.

Invalid default value for 'create_date' timestamp field

Default values should start from the year 1000.

For example,

ALTER TABLE mytable last_active DATETIME DEFAULT '1000-01-01 00:00:00'

Hope this helps someone.

Unsupported Media Type in postman

Http 415 Media Unsupported is responded back only when the content type header you are providing is not supported by the application.

With POSTMAN, the Content-type header you are sending is Content type 'multipart/form-data not application/json. While in the ajax code you are setting it correctly to application/json. Pass the correct Content-type header in POSTMAN and it will work.

pow (x,y) in Java

^ is the bitwise exclusive OR (XOR) operator in Java (and many other languages). It is not used for exponentiation. For that, you must use Math.pow.

Java Keytool error after importing certificate , "keytool error: java.io.FileNotFoundException & Access Denied"

This could happen if you are not running the command prompt in administrator mode. If you are using windows 7, you can go to run, type cmd and hit Ctrl+Shift+enter. This will open the command prompt in administrator mode. If not, you can also go to start -> all programs -> accessories -> right click command prompt and click 'run as administrator'.

How to get the current logged in user Id in ASP.NET Core

use can use

string userid = User.FindFirst("id").Value;

for some reason NameIdentifier now retrieve the username (.net core 2.2)

The connection to adb is down, and a severe error has occurred

I had exactly the same problem with you. And after two days wondering why this occurs to me, I finally got through this by moving the adb.exe from the unreliable software list of the COMODO anti-virus to its reliable software list. At that time, I had tried at least 5 kinds of measures to make the adb work, including all above...

Fluid or fixed grid system, in responsive design, based on Twitter Bootstrap

Interesting discussion. I was asking myself this question too. The main difference between fluid and fixed is simply that the fixed layout has a fixed width in terms of the whole layout of the website (viewport). If you have a 960px width viewport each colum has a fixed width which will never change.

The fluid layout behaves different. Imagine you have set the width of your main layout to 100% width. Now each column will only be calculated to it's relative size (i.e. 25%) and streches as the browser will be resized. So based on your layout purpose you can select how your layout behaves.

Here is a good article about fluid vs. flex.

How to push objects in AngularJS between ngRepeat arrays

Try this one also...

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
_x000D_
<body>_x000D_
_x000D_
  <p>Click the button to join two arrays.</p>_x000D_
_x000D_
  <button onclick="myFunction()">Try it</button>_x000D_
_x000D_
  <p id="demo"></p>_x000D_
  <p id="demo1"></p>_x000D_
  <script>_x000D_
    function myFunction() {_x000D_
      var hege = [{_x000D_
        1: "Cecilie",_x000D_
        2: "Lone"_x000D_
      }];_x000D_
      var stale = [{_x000D_
        1: "Emil",_x000D_
        2: "Tobias"_x000D_
      }];_x000D_
      var hege = hege.concat(stale);_x000D_
      document.getElementById("demo1").innerHTML = hege;_x000D_
      document.getElementById("demo").innerHTML = stale;_x000D_
    }_x000D_
  </script>_x000D_
_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

Remove duplicates in the list using linq

Try this extension method out. Hopefully this could help.

public static class DistinctHelper
{
    public static IEnumerable<TSource> DistinctBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
    {
        var identifiedKeys = new HashSet<TKey>();
        return source.Where(element => identifiedKeys.Add(keySelector(element)));
    }
}

Usage:

var outputList = sourceList.DistinctBy(x => x.TargetProperty);

VS 2017 Metadata file '.dll could not be found

After facing so many troubles, here is the solution that I found.

  1. open your project folder.
  2. find Your_Project_Name.csproj[Visual C# Project file (.csproj)]
  3. open that file in any text editor and find your missing file ItemGroup.

    <ItemGroup> <None Include="..." /> </ItemGroup>

  4. remove that ItemGroup and open once again your project and build

  5. If that reference is important for you then add once again.

Java Multiple Inheritance

Problem not solved. To sufficiently model this out and to prevent code replication you'd either need multiple inheritance or mixins. Interfaces with default functions are not sufficient because you cannot hold members in interfaces. Interface modeling leads to code replication in subclasses or statics, which is both evil.

All you can do is to use a custom construction and split it up in more components and compose it all together...

toy language

How to prevent custom views from losing state across screen orientation changes

The answers here already are great, but don't necessarily work for custom ViewGroups. To get all custom Views to retain their state, you must override onSaveInstanceState() and onRestoreInstanceState(Parcelable state) in each class. You also need to ensure they all have unique ids, whether they're inflated from xml or added programmatically.

What I came up with was remarkably like Kobor42's answer, but the error remained because I was adding the Views to a custom ViewGroup programmatically and not assigning unique ids.

The link shared by mato will work, but it means none of the individual Views manage their own state - the entire state is saved in the ViewGroup methods.

The problem is that when multiple of these ViewGroups are added to a layout, the ids of their elements from the xml are no longer unique (if its defined in xml). At runtime, you can call the static method View.generateViewId() to get a unique id for a View. This is only available from API 17.

Here is my code from the ViewGroup (it is abstract, and mOriginalValue is a type variable):

public abstract class DetailRow<E> extends LinearLayout {

    private static final String SUPER_INSTANCE_STATE = "saved_instance_state_parcelable";
    private static final String STATE_VIEW_IDS = "state_view_ids";
    private static final String STATE_ORIGINAL_VALUE = "state_original_value";

    private E mOriginalValue;
    private int[] mViewIds;

// ...

    @Override
    protected Parcelable onSaveInstanceState() {

        // Create a bundle to put super parcelable in
        Bundle bundle = new Bundle();
        bundle.putParcelable(SUPER_INSTANCE_STATE, super.onSaveInstanceState());
        // Use abstract method to put mOriginalValue in the bundle;
        putValueInTheBundle(mOriginalValue, bundle, STATE_ORIGINAL_VALUE);
        // Store mViewIds in the bundle - initialize if necessary.
        if (mViewIds == null) {
            // We need as many ids as child views
            mViewIds = new int[getChildCount()];
            for (int i = 0; i < mViewIds.length; i++) {
                // generate a unique id for each view
                mViewIds[i] = View.generateViewId();
                // assign the id to the view at the same index
                getChildAt(i).setId(mViewIds[i]);
            }
        }
        bundle.putIntArray(STATE_VIEW_IDS, mViewIds);
        // return the bundle
        return bundle;
    }

    @Override
    protected void onRestoreInstanceState(Parcelable state) {

        // We know state is a Bundle:
        Bundle bundle = (Bundle) state;
        // Get mViewIds out of the bundle
        mViewIds = bundle.getIntArray(STATE_VIEW_IDS);
        // For each id, assign to the view of same index
        if (mViewIds != null) {
            for (int i = 0; i < mViewIds.length; i++) {
                getChildAt(i).setId(mViewIds[i]);
            }
        }
        // Get mOriginalValue out of the bundle
        mOriginalValue = getValueBackOutOfTheBundle(bundle, STATE_ORIGINAL_VALUE);
        // get super parcelable back out of the bundle and pass it to
        // super.onRestoreInstanceState(Parcelable)
        state = bundle.getParcelable(SUPER_INSTANCE_STATE);
        super.onRestoreInstanceState(state);
    } 
}

How to include multiple js files using jQuery $.getScript() method

Append scripts with async=false

Here's a different, but super simple approach. To load multiple scripts you can simply append them to body.

  • Loads them asynchronously, because that's how browsers optimize the page loading
  • Executes scripts in order, because that's how browsers parse the HTML tags
  • No need for callback, because scripts are executed in order. Simply add another script, and it will be executed after the other scripts

More info here: https://www.html5rocks.com/en/tutorials/speed/script-loading/

var scriptsToLoad = [
   "script1.js", 
   "script2.js",
   "script3.js",
]; 
    
scriptsToLoad.forEach(function(src) {
  var script = document.createElement('script');
  script.src = src;
  script.async = false;
  document.body.appendChild(script);
});

Changing the image source using jQuery

I have the same wonder today, I did on this way :

//<img src="actual.png" alt="myImage" class=myClass>
$('.myClass').attr('src','').promise().done(function() {
$(this).attr('src','img/new.png');  
});

List of macOS text editors and code editors

I've tried Komodo out a bit, and I really like it so far. Aptana, an Eclipse variant, is also rather useful for a wide variety of things. There's always good ole' VI, too!

How to write a cursor inside a stored procedure in SQL Server 2008

You can create a trigger which updates NoofUses column in Coupon table whenever couponid is used in CouponUse table

query :

CREATE TRIGGER [dbo].[couponcount] ON [dbo].[couponuse]
FOR INSERT
AS
if EXISTS (SELECT 1 FROM Inserted)
  BEGIN
UPDATE dbo.Coupon
SET NoofUses = (SELECT COUNT(*) FROM dbo.CouponUse WHERE Couponid = dbo.Coupon.ID)
end 

Java associative-array

Object[][] data = {
{"mykey1", "myval1"},
{"mykey2", "myval2"},
{new Date(), new Integer(1)},
};

Yes, this require iteration for searchting value by key, but if you need all of them, this will be the best choice.

Hyper-V: Create shared folder between host and guest with internal network

Share Files, Folders or Drives Between Host and Hyper-V Virtual Machine

Prerequisites

  1. Ensure that Enhanced session mode settings are enabled on the Hyper-V host.

    Start Hyper-V Manager, and in the Actions section, select "Hyper-V Settings".

    hyper-v-settings

    Make sure that enhanced session mode is allowed in the Server section. Then, make sure that the enhanced session mode is available in the User section.

    use-enhanced-session-mode

  2. Enable Hyper-V Guest Services for your virtual machine

    Right-click on Virtual Machine > Settings. Select the Integration Services in the left-lower corner of the menu. Check Guest Service and click OK.

    enable-guest-services

Steps to share devices with Hyper-v virtual machine:

  1. Start a virtual machine and click Show Options in the pop-up windows.

    connect-to-vm

    Or click "Edit Session Settings..." in the Actions panel on the right

    edit-session-sessions

    It may only appear when you're (able to get) connected to it. If it doesn't appear try Starting and then Connecting to the VM while paying close attention to the panel in the Hyper-V Manager.

  2. View local resources. Then, select the "More..." menu.

    click-more

  3. From there, you can choose which devices to share. Removable drives are especially useful for file sharing.

    choose-the-devices-that-you-want-to-use

  4. Choose to "Save my settings for future connections to this virtual machine".

    save-my-settings-for-future-connections-to-this-vm

  5. Click Connect. Drive sharing is now complete, and you will see the shared drive in this PC > Network Locations section of Windows Explorer after using the enhanced session mode to sigh to the VM. You should now be able to copy files from a physical machine and paste them into a virtual machine, and vice versa.

    shared-drives-from-local-pc

Source (and for more info): Share Files, Folders or Drives Between Host and Hyper-V Virtual Machine

How to calculate rolling / moving average using NumPy / SciPy?

I use either the accepted answer's solution, slightly modified to have same length for output as input, or pandas' version as mentioned in a comment of another answer. I summarize both here with a reproducible example for future reference:

import numpy as np
import pandas as pd

def moving_average(a, n):
    ret = np.cumsum(a, dtype=float)
    ret[n:] = ret[n:] - ret[:-n]
    return ret / n

def moving_average_centered(a, n):
    return pd.Series(a).rolling(window=n, center=True).mean().to_numpy()

A = [0, 0, 1, 2, 4, 5, 4]
print(moving_average(A, 3))    
# [0.         0.         0.33333333 1.         2.33333333 3.66666667 4.33333333]
print(moving_average_centered(A, 3))
# [nan        0.33333333 1.         2.33333333 3.66666667 4.33333333 nan       ]

Remove item from list based on condition

If your collection type is a List<stuff>, then the best approach is probably the following:

prods.RemoveAll(s => s.ID == 1)

This only does one pass (iteration) over the list, so should be more efficient than other methods.

If your type is more generically an ICollection<T>, it might help to write a short extension method if you care about performance. If not, then you'd probably get away with using LINQ (calling Where or Single).

Loop through an array php

Starting simple, with no HTML:

foreach($database as $file) {
    echo $file['filename'] . ' at ' . $file['filepath'];
}

And you can otherwise manipulate the fields in the foreach.

VueJS conditionally add an attribute for an element

It's notable to understand that if you'd like to conditionally add attributes you can also add a dynamic declaration:

<input v-bind="attrs" />

where attrs is declared as an object:

data() {
    return {
        attrs: {
            required: true,
            type: "text"
        }
    }
}

Which will result in:

<input required type="text"/>

Ideal in cases with multiple attributes.

Expression must be a modifiable L-value

lvalue means "left value" -- it should be assignable. You cannot change the value of text since it is an array, not a pointer.

Either declare it as char pointer (in this case it's better to declare it as const char*):

const char *text;
if(number == 2) 
    text = "awesome"; 
else 
    text = "you fail";

Or use strcpy:

char text[60];
if(number == 2) 
    strcpy(text, "awesome"); 
else 
    strcpy(text, "you fail");

String, StringBuffer, and StringBuilder

Personally, I don't think there is any real world use for StringBuffer. When would I ever want to communicate between multiple threads by manipulating a character sequence? That doesn't sound useful at all, but maybe I have yet to see the light :)

Static Initialization Blocks

I would say static block is just syntactic sugar. There is nothing you could do with static block and not with anything else.

To re-use some examples posted here.

This piece of code could be re-written without using static initialiser.

Method #1: With static

private static final HashMap<String, String> MAP;
static {
    MAP.put("banana", "honey");
    MAP.put("peanut butter", "jelly");
    MAP.put("rice", "beans");
  }

Method #2: Without static

private static final HashMap<String, String> MAP = getMap();
private static HashMap<String, String> getMap()
{
    HashMap<String, String> ret = new HashMap<>();
    ret.put("banana", "honey");
    ret.put("peanut butter", "jelly");
    ret.put("rice", "beans");
    return ret;
}

HTML form with multiple "actions"

As @AliK mentioned, this can be done easily by looking at the value of the submit buttons.

When you submit a form, unset variables will evaluate false. If you set both submit buttons to be part of the same form, you can just check and see which button has been set.

HTML:

<form action="handle_user.php" method="POST" />
  <input type="submit" value="Save" name="save" />
  <input type="submit" value="Submit for Approval" name="approve" />
</form>

PHP

if($_POST["save"]) {
  //User hit the save button, handle accordingly
}
//You can do an else, but I prefer a separate statement
if($_POST["approve"]) {
  //User hit the Submit for Approval button, handle accordingly
}

EDIT


If you'd rather not change your PHP setup, try this: http://pastebin.com/j0GUF7MV
This is the JavaScript method @AliK was reffering to.

Related:

Fetching distinct values on a column using Spark DataFrame

Well to obtain all different values in a Dataframe you can use distinct. As you can see in the documentation that method returns another DataFrame. After that you can create a UDF in order to transform each record.

For example:

val df = sc.parallelize(Array((1, 2), (3, 4), (1, 6))).toDF("age", "salary")

// I obtain all different values. If you show you must see only {1, 3}
val distinctValuesDF = df.select(df("age")).distinct

// Define your udf. In this case I defined a simple function, but they can get complicated.
val myTransformationUDF = udf(value => value / 10)

// Run that transformation "over" your DataFrame
val afterTransformationDF = distinctValuesDF.select(myTransformationUDF(col("age")))

What are the differences between json and simplejson Python modules?

The builtin json module got included in Python 2.6. Any projects that support versions of Python < 2.6 need to have a fallback. In many cases, that fallback is simplejson.

When is each sorting algorithm used?

First, a definition, since it's pretty important: A stable sort is one that's guaranteed not to reorder elements with identical keys.

Recommendations:

Quick sort: When you don't need a stable sort and average case performance matters more than worst case performance. A quick sort is O(N log N) on average, O(N^2) in the worst case. A good implementation uses O(log N) auxiliary storage in the form of stack space for recursion.

Merge sort: When you need a stable, O(N log N) sort, this is about your only option. The only downsides to it are that it uses O(N) auxiliary space and has a slightly larger constant than a quick sort. There are some in-place merge sorts, but AFAIK they are all either not stable or worse than O(N log N). Even the O(N log N) in place sorts have so much larger a constant than the plain old merge sort that they're more theoretical curiosities than useful algorithms.

Heap sort: When you don't need a stable sort and you care more about worst case performance than average case performance. It's guaranteed to be O(N log N), and uses O(1) auxiliary space, meaning that you won't unexpectedly run out of heap or stack space on very large inputs.

Introsort: This is a quick sort that switches to a heap sort after a certain recursion depth to get around quick sort's O(N^2) worst case. It's almost always better than a plain old quick sort, since you get the average case of a quick sort, with guaranteed O(N log N) performance. Probably the only reason to use a heap sort instead of this is in severely memory constrained systems where O(log N) stack space is practically significant.

Insertion sort: When N is guaranteed to be small, including as the base case of a quick sort or merge sort. While this is O(N^2), it has a very small constant and is a stable sort.

Bubble sort, selection sort: When you're doing something quick and dirty and for some reason you can't just use the standard library's sorting algorithm. The only advantage these have over insertion sort is being slightly easier to implement.


Non-comparison sorts: Under some fairly limited conditions it's possible to break the O(N log N) barrier and sort in O(N). Here are some cases where that's worth a try:

Counting sort: When you are sorting integers with a limited range.

Radix sort: When log(N) is significantly larger than K, where K is the number of radix digits.

Bucket sort: When you can guarantee that your input is approximately uniformly distributed.

Trying to get property of non-object - Laravel 5

I implemented a hasOne relation in my parent class, defined both the foreign and local key, it returned an object but the columns of the child must be accessed as an array.
i.e. $parent->child['column']
Kind of confusing.

How can I convert a DateTime to an int?

dateDate.Ticks

should give you what you're looking for.

The value of this property represents the number of 100-nanosecond intervals that have elapsed since 12:00:00 midnight, January 1, 0001, which represents DateTime.MinValue. It does not include the number of ticks that are attributable to leap seconds.

DateTime.Ticks


If you're really looking for the Linux Epoch time (seconds since Jan 1, 1970), the accepted answer for this question should be relevant.


But if you're actually trying to "compress" a string representation of the date into an int, you should ask yourself why aren't you just storing it as a string to begin with. If you still want to do it after that, Stecya's answer is the right one. Keep in mind it won't fit into an int, you'll have to use a long.

What is a regular expression which will match a valid domain name without a subdomain?

I know that this is a bit of an old post, but all of the regular expressions here are missing one very important component: the support for IDN domain names.

IDN domain names start with xn--. They enable extended UTF-8 characters in domain names. For example, did you know "?.com" is a valid domain name? Yeah, "love heart dot com"! To validate the domain name, you need to let http://xn--c6h.com/ pass the validation.

Note, to use this regex, you will need to convert the domain to lower case, and also use an IDN library to ensure you encode domain names to ACE (also known as "ASCII Compatible Encoding"). One good library is GNU-Libidn.

idn(1) is the command line interface to the internationalized domain name library. The following example converts the host name in UTF-8 into ACE encoding. The resulting URL https://nic.xn--flw351e/ can then be used as ACE-encoded equivalent of https://nic.??/.

  $ idn --quiet -a nic.??
  nic.xn--flw351e

This magic regular expression should cover most domains (although, I am sure there are many valid edge cases that I have missed):

^((?!-))(xn--)?[a-z0-9][a-z0-9-_]{0,61}[a-z0-9]{0,1}\.(xn--)?([a-z0-9\-]{1,61}|[a-z0-9-]{1,30}\.[a-z]{2,})$

When choosing a domain validation regex, you should see if the domain matches the following:

  1. xn--stackoverflow.com
  2. stackoverflow.xn--com
  3. stackoverflow.co.uk

If these three domains do not pass, your regular expression may be not allowing legitimate domains!

Check out The Internationalized Domain Names Support page from Oracle's International Language Environment Guide for more information.

Feel free to try out the regex here: http://www.regexr.com/3abjr

ICANN keeps a list of tlds that have been delegated which can be used to see some examples of IDN domains.


Edit:

 ^(((?!-))(xn--|_{1,1})?[a-z0-9-]{0,61}[a-z0-9]{1,1}\.)*(xn--)?([a-z0-9][a-z0-9\-]{0,60}|[a-z0-9-]{1,30}\.[a-z]{2,})$

This regular expression will stop domains that have '-' at the end of a hostname as being marked as being valid. Additionally, it allows unlimited subdomains.

Preventing an image from being draggable or selectable without using JS

I've been forgetting to share my solution, I couldn't find a way to do this without using JS. There are some corner cases where @Jeffery A Wooden's suggested CSS just wont cover.

This is what I apply to all of my UI containers, no need to apply to each element since it recuses on all the child elements.

CSS:

.unselectable {
    /* For Opera and <= IE9, we need to add unselectable="on" attribute onto each element */
    /* Check this site for more details: http://help.dottoro.com/lhwdpnva.php */
    -moz-user-select: none; /* These user-select properties are inheritable, used to prevent text selection */
    -webkit-user-select: none;
    -ms-user-select: none; /* From IE10 only */
    user-select: none; /* Not valid CSS yet, as of July 2012 */

    -webkit-user-drag: none; /* Prevents dragging of images/divs etc */
    user-drag: none;
}

JS:

var makeUnselectable = function( $target ) {
    $target
        .addClass( 'unselectable' ) // All these attributes are inheritable
        .attr( 'unselectable', 'on' ) // For IE9 - This property is not inherited, needs to be placed onto everything
        .attr( 'draggable', 'false' ) // For moz and webkit, although Firefox 16 ignores this when -moz-user-select: none; is set, it's like these properties are mutually exclusive, seems to be a bug.
        .on( 'dragstart', function() { return false; } );  // Needed since Firefox 16 seems to ingore the 'draggable' attribute we just applied above when '-moz-user-select: none' is applied to the CSS 

    $target // Apply non-inheritable properties to the child elements
        .find( '*' )
        .attr( 'draggable', 'false' )
        .attr( 'unselectable', 'on' ); 
};

This was way more complicated than it needed to be.

Bootstrap 3: How do you align column content to bottom of row

Vertical align bottom and remove the float seems to work. I then had a margin issue, but the -2px keeps them from getting pushed down (and they still don't overlap)

.profile-header > div {
  display: inline-block;
  vertical-align: bottom;
  float: none;
  margin: -2px;
}
.profile-header {
  margin-bottom:20px;
  border:2px solid green;
  display: table-cell;
}
.profile-pic {
  height:300px;
  border:2px solid red;
}
.profile-about {
  border:2px solid blue;
}
.profile-about2 {
  border:2px solid pink;
}

Example here: http://www.bootply.com/125740#

Setting an int to Infinity in C++

This is a message for me in the future:

Just use: (unsigned)!((int)0)

It creates the largest possible number in any machine by assigning all bits to 1s (ones) and then casts it to unsigned

Even better

#define INF (unsigned)!((int)0)

And then just use INF in your code

sqlalchemy: how to join several tables by one query?

This function will produce required table as list of tuples.

def get_documents_by_user_email(email):
    query = session.query(
       User.email, 
       User.name, 
       Document.name, 
       DocumentsPermissions.readAllowed, 
       DocumentsPermissions.writeAllowed,
    )
    join_query = query.join(Document).join(DocumentsPermissions)

    return join_query.filter(User.email == email).all()

user_docs = get_documents_by_user_email(email)

Performing SQL queries on an Excel Table within a Workbook with VBA Macro

Building on Joan-Diego Rodriguez's routine with Jordi's approach and some of Jacek Kotowski's code - This function converts any table name for the active workbook into a usable address for SQL queries.

Note to MikeL: Addition of "[#All]" includes headings avoiding problems you reported.

Function getAddress(byVal sTableName as String) as String 

    With Range(sTableName & "[#All]")
        getAddress= "[" & .Parent.Name & "$" & .Address(False, False) & "]"
    End With

End Function

Example of Named Pipes

using System;
using System.IO;
using System.IO.Pipes;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            StartServer();
            Task.Delay(1000).Wait();


            //Client
            var client = new NamedPipeClientStream("PipesOfPiece");
            client.Connect();
            StreamReader reader = new StreamReader(client);
            StreamWriter writer = new StreamWriter(client);

            while (true)
            {
                string input = Console.ReadLine();
                if (String.IsNullOrEmpty(input)) break;
                writer.WriteLine(input);
                writer.Flush();
                Console.WriteLine(reader.ReadLine());
            }
        }

        static void StartServer()
        {
            Task.Factory.StartNew(() =>
            {
                var server = new NamedPipeServerStream("PipesOfPiece");
                server.WaitForConnection();
                StreamReader reader = new StreamReader(server);
                StreamWriter writer = new StreamWriter(server);
                while (true)
                {
                    var line = reader.ReadLine();
                    writer.WriteLine(String.Join("", line.Reverse()));
                    writer.Flush();
                }
            });
        }
    }
}

When 1 px border is added to div, Div size increases, Don't want to do that

We can also use css calc() function

width: calc(100% - 2px);

subtracting 2px for borders

How to find out what the date was 5 days ago?

Simply do this...hope it help

$fifteendaysago = date_create('15 days ago');
echo date_format($fifteendaysago, 'Y-m-d');

input checkbox true or checked or yes

Only checked and checked="checked" are valid. Your other options depend on error recovery in browsers.

checked="yes" and checked="true" are particularly bad as they imply that checked="no" and checked="false" will set the default state to be unchecked … which they will not.

How to add CORS request in header in Angular 5

The following worked for me after hours of trying

      $http.post("http://localhost:8080/yourresource", parameter, {headers: 
      {'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*' } }).

However following code did not work, I am unclear as to why, hopefully someone can improve this answer.

          $http({   method: 'POST', url: "http://localhost:8080/yourresource", 
                    parameter, 
                    headers: {'Content-Type': 'application/json', 
                              'Access-Control-Allow-Origin': '*',
                              'Access-Control-Allow-Methods': 'POST'} 
                })

How to add/subtract dates with JavaScript?

Code:

_x000D_
_x000D_
var date = new Date('2011', '01', '02');_x000D_
alert('the original date is ' + date);_x000D_
var newdate = new Date(date);_x000D_
_x000D_
newdate.setDate(newdate.getDate() - 7); // minus the date_x000D_
_x000D_
var nd = new Date(newdate);_x000D_
alert('the new date is ' + nd);
_x000D_
_x000D_
_x000D_

Using Datepicker:

$("#in").datepicker({
    minDate: 0,
    onSelect: function(dateText, inst) {
       var actualDate = new Date(dateText);
       var newDate = new Date(actualDate.getFullYear(), actualDate.getMonth(), actualDate.getDate()+1);
        $('#out').datepicker('option', 'minDate', newDate );
    }
});

$("#out").datepicker();?

JSFiddle Demo

Extra stuff that might come handy:

getDate()   Returns the day of the month (from 1-31)
getDay()    Returns the day of the week (from 0-6)
getFullYear()   Returns the year (four digits)
getHours()  Returns the hour (from 0-23)
getMilliseconds()   Returns the milliseconds (from 0-999)
getMinutes()    Returns the minutes (from 0-59)
getMonth()  Returns the month (from 0-11)
getSeconds()    Returns the seconds (from 0-59)

Good link: MDN Date

An implementation of the fast Fourier transform (FFT) in C#

Here's another; a C# port of the Ooura FFT. It's reasonably fast. The package also includes overlap/add convolution and some other DSP stuff, under the MIT license.

https://github.com/hughpyle/inguz-DSPUtil/blob/master/Fourier.cs

How do I implement Toastr JS?

I investigate i knew that the jquery script need to load in order that why it not worked in your case. Because $ symbol mentioned in code not understand unless you load Jquery 1.9.1 at first. Load like follows

<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/2.0.1/css/toastr.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/2.0.1/js/toastr.js"></script>

Then it will work fine

Django MEDIA_URL and MEDIA_ROOT

(at least) for Django 1.8:

If you use

if settings.DEBUG:
  urlpatterns.append(url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}))

as described above, make sure that no "catch all" url pattern, directing to a default view, comes before that in urlpatterns = []. As .append will put the added scheme to the end of the list, it will of course only be tested if no previous url pattern matches. You can avoid that by using something like this where the "catch all" url pattern is added at the very end, independent from the if statement:

if settings.DEBUG:
    urlpatterns.append(url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}))

urlpatterns.append(url(r'$', 'views.home', name='home')),

How to log in to phpMyAdmin with WAMP, what is the username and password?

In my case it was

username : root
password : mysql

Using : Wamp server 3.1.0

MongoDB "root" user

There is a Superuser Roles: root, which is a Built-In Roles, may meet your need.

In Jenkins, how to checkout a project into a specific directory (using GIT)

Furthermore, if in the same Jenkins project we need to checkout several private GitHub repositories into several separate dirs under a project root. How can we do it please?

The Jenkin's Multiple SCMs Plugin has solved the several repositories problem for me very nicely. I have just got working a project build that checks out four different git repos under a common folder. (I'm a bit reluctant to use git super-projects as suggested previously by Lukasz Rzanek, as git is complex enough without submodules.)

Error creating bean with name 'entityManagerFactory' defined in class path resource : Invocation of init method failed

I faced the same issue. I was using Java 9 and the following dependency in pom file:

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-jdbc</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>com.h2database</groupId>
        <artifactId>h2</artifactId>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

The issue was resolved after adding the dependency below in pom:

<dependency>
    <groupId>javax.xml.bind</groupId>
    <artifactId>jaxb-api</artifactId>
    <version>2.3.0</version>
</dependency>

convert pfx format to p12

I had trouble with a .pfx file with openconnect. Renaming didn't solve the problem. I used keytool to convert it to .p12 and it worked.

keytool -importkeystore -destkeystore new.p12 -deststoretype pkcs12 -srckeystore original.pfx

In my case the password for the new file (new.p12) had to be the same as the password for the .pfx file.

Authentication issues with WWW-Authenticate: Negotiate

The web server is prompting you for a SPNEGO (Simple and Protected GSSAPI Negotiation Mechanism) token.

This is a Microsoft invention for negotiating a type of authentication to use for Web SSO (single-sign-on):

  • either NTLM
  • or Kerberos.

See:

Assigning multiple styles on an HTML element

In HTML the style tag has the following syntax:

style="property1:value1;property2:value2"

so in your case:

<h2 style="text-align:center;font-family:tahoma">TITLE</h2>

Hope this helps.

Mockito verify order / sequence of method calls

InOrder helps you to do that.

ServiceClassA firstMock = mock(ServiceClassA.class);
ServiceClassB secondMock = mock(ServiceClassB.class);

Mockito.doNothing().when(firstMock).methodOne();   
Mockito.doNothing().when(secondMock).methodTwo();  

//create inOrder object passing any mocks that need to be verified in order
InOrder inOrder = inOrder(firstMock, secondMock);

//following will make sure that firstMock was called before secondMock
inOrder.verify(firstMock).methodOne();
inOrder.verify(secondMock).methodTwo();

Firefox "ssl_error_no_cypher_overlap" error

I had similar issues browsing to secure sites (https://) when using Burp (or at least an issue that would bring you to this page when searching Google):

  • ssl_error_no_cypher_overlap in Firefox
  • ERR_SSL_VERSION_OR_CIPHER_MISMATCH in Chrome

It turned out to be an issue with using Java 8. When I switched to Java 7, the problem stopped.

How do I resize an image using PIL and maintain its aspect ratio?

I was trying to resize some images for a slideshow video and because of that, I wanted not just one max dimension, but a max width and a max height (the size of the video frame).
And there was always the possibility of a portrait video...
The Image.thumbnail method was promising, but I could not make it upscale a smaller image.

So after I couldn't find an obvious way to do that here (or at some other places), I wrote this function and put it here for the ones to come:

from PIL import Image

def get_resized_img(img_path, video_size):
    img = Image.open(img_path)
    width, height = video_size  # these are the MAX dimensions
    video_ratio = width / height
    img_ratio = img.size[0] / img.size[1]
    if video_ratio >= 1:  # the video is wide
        if img_ratio <= video_ratio:  # image is not wide enough
            width_new = int(height * img_ratio)
            size_new = width_new, height
        else:  # image is wider than video
            height_new = int(width / img_ratio)
            size_new = width, height_new
    else:  # the video is tall
        if img_ratio >= video_ratio:  # image is not tall enough
            height_new = int(width / img_ratio)
            size_new = width, height_new
        else:  # image is taller than video
            width_new = int(height * img_ratio)
            size_new = width_new, height
    return img.resize(size_new, resample=Image.LANCZOS)

Test if a property is available on a dynamic variable

In my case, I needed to check for the existence of a method with a specific name, so I used an interface for that

var plugin = this.pluginFinder.GetPluginIfInstalled<IPlugin>(pluginName) as dynamic;
if (plugin != null && plugin is ICustomPluginAction)
{
    plugin.CustomPluginAction(action);
}

Also, interfaces can contain more than just methods:

Interfaces can contain methods, properties, events, indexers, or any combination of those four member types.

From: Interfaces (C# Programming Guide)

Elegant and no need to trap exceptions or play with reflexion...

Error Installing Homebrew - Brew Command Not Found

You can use this:

ruby -e "$(curl -fsSL https://raw.github.com/Homebrew/homebrew/go/install)" 

to install homebrew.

How to import a class from default package

  1. Create a new package.
  2. Move your files from the default package to the new one.

How to make a variable accessible outside a function?

Your variable declarations and their scope are correct. The problem you are facing is that the first AJAX request may take a little bit time to finish. Therefore, the second URL will be filled with the value of sID before the its content has been set. You have to remember that AJAX request are normally asynchronous, i.e. the code execution goes on while the data is being fetched in the background.

You have to nest the requests:

$.getJSON("https://prod.api.pvp.net/api/lol/eune/v1.1/summoner/by-name/"+input+"?api_key=API_KEY_HERE"  , function(name){   obj = name;   // sID is only now available!   sID = obj.id;   console.log(sID); }); 


Clean up your code!

  • Put the second request into a function
  • and let it accept sID as a parameter, so you don't have to declare it globally anymore! (Global variables are almost always evil!)
  • Remove sID and obj variables - name.id is sufficient unless you really need the other variables outside the function.


$.getJSON("https://prod.api.pvp.net/api/lol/eune/v1.1/summoner/by-name/"+input+"?api_key=API_KEY_HERE"  , function(name){   // We don't need sID or obj here - name.id is sufficient   console.log(name.id);    doSecondRequest(name.id); });  /// TODO Choose a better name function doSecondRequest(sID) {   $.getJSON("https://prod.api.pvp.net/api/lol/eune/v1.2/stats/by-summoner/" + sID + "/summary?api_key=API_KEY_HERE", function(stats){         console.log(stats);   }); } 

Hapy New Year :)

Cannot change column used in a foreign key constraint

The type and definition of foreign key field and reference must be equal. This means your foreign key disallows changing the type of your field.

One solution would be this:

LOCK TABLES 
    favorite_food WRITE,
    person WRITE;

ALTER TABLE favorite_food
    DROP FOREIGN KEY fk_fav_food_person_id,
    MODIFY person_id SMALLINT UNSIGNED;

Now you can change you person_id

ALTER TABLE person MODIFY person_id SMALLINT UNSIGNED AUTO_INCREMENT;

recreate foreign key

ALTER TABLE favorite_food
    ADD CONSTRAINT fk_fav_food_person_id FOREIGN KEY (person_id)
          REFERENCES person (person_id);

UNLOCK TABLES;

EDIT: Added locks above, thanks to comments

You have to disallow writing to the database while you do this, otherwise you risk data integrity problems.

I've added a write lock above

All writing queries in any other session than your own ( INSERT, UPDATE, DELETE ) will wait till timeout or UNLOCK TABLES; is executed

http://dev.mysql.com/doc/refman/5.5/en/lock-tables.html

EDIT 2: OP asked for a more detailed explanation of the line "The type and definition of foreign key field and reference must be equal. This means your foreign key disallows changing the type of your field."

From MySQL 5.5 Reference Manual: FOREIGN KEY Constraints

Corresponding columns in the foreign key and the referenced key must have similar internal data types inside InnoDB so that they can be compared without a type conversion. The size and sign of integer types must be the same. The length of string types need not be the same. For nonbinary (character) string columns, the character set and collation must be the same.

How to set a time zone (or a Kind) of a DateTime value?

While the DateTime.Kind property does not have a setter, the static method DateTime.SpecifyKind creates a DateTime instance with a specified value for Kind.

Altenatively there are several DateTime constructor overloads that take a DateTimeKind parameter

HTML img align="middle" doesn't align an image

You don't need align="center" and float:left. Remove both of these. margin: 0 auto is sufficient.

How would you do a "not in" query with LINQ?

 DynamicWebsiteEntities db = new DynamicWebsiteEntities();
    var data = (from dt_sub in db.Subjects_Details
                                //Sub Query - 1
                            let sub_s_g = (from sg in db.Subjects_In_Group
                                           where sg.GroupId == groupId
                                           select sg.SubjectId)
                            //Where Cause
                            where !sub_s_g.Contains(dt_sub.Id) && dt_sub.IsLanguage == false
                            //Order By Cause
                            orderby dt_sub.Subject_Name

                            select dt_sub)
                           .AsEnumerable();
                  
                                SelectList multiSelect = new SelectList(data, "Id", "Subject_Name", selectedValue);

    //======================================OR===========================================

    var data = (from dt_sub in db.Subjects_Details

                               
                            //Where Cause
                            where !(from sg in db.Subjects_In_Group
                                           where sg.GroupId == groupId
                                           select sg.SubjectId).Contains(dt_sub.Id) && dt_sub.IsLanguage == false

                            //Order By Cause
                            orderby dt_sub.Subject_Name

                            select dt_sub)

                           .AsEnumerable();

Return string Input with parse.string

If you're really bent upon converting Integer to String value, I suggest use String.valueOf(YourIntegerVariable). More details can be found at: http://www.tutorialspoint.com/java/java_string_valueof.htm

Selecting Values from Oracle Table Variable / Array?

The sql array type is not neccessary. Not if the element type is a primitive one. (Varchar, number, date,...)

Very basic sample:

declare
  type TPidmList is table of sgbstdn.sgbstdn_pidm%type;
  pidms TPidmList;
begin
  select distinct sgbstdn_pidm
  bulk collect into pidms
  from sgbstdn
  where sgbstdn_majr_code_1 = 'HS04'
  and sgbstdn_program_1 = 'HSCOMPH';

  -- do something with pidms

  open :someCursor for
    select value(t) pidm
    from table(pidms) t;
end;

When you want to reuse it, then it might be interesting to know how that would look like. If you issue several commands than those could be grouped in a package. The private package variable trick from above has its downsides. When you add variables to a package, you give it state and now it doesn't act as a stateless bunch of functions but as some weird sort of singleton object instance instead.

e.g. When you recompile the body, it will raise exceptions in sessions that already used it before. (because the variable values got invalided)

However, you could declare the type in a package (or globally in sql), and use it as a paramter in methods that should use it.

create package Abc as
  type TPidmList is table of sgbstdn.sgbstdn_pidm%type;

  function CreateList(majorCode in Varchar, 
                      program in Varchar) return TPidmList;

  function Test1(list in TPidmList) return PLS_Integer;
  -- "in" to make it immutable so that PL/SQL can pass a pointer instead of a copy
  procedure Test2(list in TPidmList);
end;

create package body Abc as

  function CreateList(majorCode in Varchar, 
                      program in Varchar) return TPidmList is
    result TPidmList;
  begin
    select distinct sgbstdn_pidm
    bulk collect into result
    from sgbstdn
    where sgbstdn_majr_code_1 = majorCode
    and sgbstdn_program_1 = program;

    return result;
  end;

  function Test1(list in TPidmList) return PLS_Integer is
    result PLS_Integer := 0;
  begin
    if list is null or list.Count = 0 then
      return result;
    end if;

    for i in list.First .. list.Last loop
      if ... then
        result := result + list(i);
      end if;
    end loop;
  end;

  procedure Test2(list in TPidmList) as
  begin
    ...
  end;

  return result;
end;

How to call it:

declare
  pidms constant Abc.TPidmList := Abc.CreateList('HS04', 'HSCOMPH');
  xyz PLS_Integer;
begin
  Abc.Test2(pidms);
  xyz := Abc.Test1(pidms);
  ...

  open :someCursor for
    select value(t) as Pidm,
           xyz as SomeValue
    from   table(pidms) t;
end;

Two Radio Buttons ASP.NET C#

Set the GroupName property of both radio buttons to the same value. You could also try using a RadioButtonGroup, which does this for you automatically.

How can I implement a tree in Python?

Another tree implementation loosely based off of Bruno's answer:

class Node:
    def __init__(self):
        self.name: str = ''
        self.children: List[Node] = []
        self.parent: Node = self

    def __getitem__(self, i: int) -> 'Node':
        return self.children[i]

    def add_child(self):
        child = Node()
        self.children.append(child)
        child.parent = self
        return child

    def __str__(self) -> str:
        def _get_character(x, left, right) -> str:
            if x < left:
                return '/'
            elif x >= right:
                return '\\'
            else:
                return '|'

        if len(self.children):
            children_lines: Sequence[List[str]] = list(map(lambda child: str(child).split('\n'), self.children))
            widths: Sequence[int] = list(map(lambda child_lines: len(child_lines[0]), children_lines))
            max_height: int = max(map(len, children_lines))
            total_width: int = sum(widths) + len(widths) - 1
            left: int = (total_width - len(self.name) + 1) // 2
            right: int = left + len(self.name)

            return '\n'.join((
                self.name.center(total_width),
                ' '.join(map(lambda width, position: _get_character(position - width // 2, left, right).center(width),
                             widths, accumulate(widths, add))),
                *map(
                    lambda row: ' '.join(map(
                        lambda child_lines: child_lines[row] if row < len(child_lines) else ' ' * len(child_lines[0]),
                        children_lines)),
                    range(max_height))))
        else:
            return self.name

And an example of how to use it:

tree = Node()
tree.name = 'Root node'
tree.add_child()
tree[0].name = 'Child node 0'
tree.add_child()
tree[1].name = 'Child node 1'
tree.add_child()
tree[2].name = 'Child node 2'
tree[1].add_child()
tree[1][0].name = 'Grandchild 1.0'
tree[2].add_child()
tree[2][0].name = 'Grandchild 2.0'
tree[2].add_child()
tree[2][1].name = 'Grandchild 2.1'
print(tree)

Which should output:

                        Root node                        
     /             /                      \              
Child node 0  Child node 1           Child node 2        
                   |              /              \       
             Grandchild 1.0 Grandchild 2.0 Grandchild 2.1

How to align an indented line in a span that wraps into multiple lines?

span is a inline element which means if you use <br/> it'll b considered as one line anyway.

Change span to a block element or add display:block to your class.

http://www.jsfiddle.net/tZtpr/1/

ASP.NET MVC Html.ValidationSummary(true) does not display model errors

@Html.ValidationSummary(false,"", new { @class = "text-danger" })

Using this line may be helpful

Cannot find libcrypto in Ubuntu

I solved this on 12.10 by installing libssl-dev.

sudo apt-get install libssl-dev

Why can't Visual Studio find my DLL?

try "configuration properties -> debugging -> environment" and set the PATH variable in run-time

How to return a value from pthread threads in C?

Here is a correct solution. In this case tdata is allocated in the main thread, and there is a space for the thread to place its result.

#include <pthread.h>
#include <stdio.h>

typedef struct thread_data {
   int a;
   int b;
   int result;

} thread_data;

void *myThread(void *arg)
{
   thread_data *tdata=(thread_data *)arg;

   int a=tdata->a;
   int b=tdata->b;
   int result=a+b;

   tdata->result=result;
   pthread_exit(NULL);
}

int main()
{
   pthread_t tid;
   thread_data tdata;

   tdata.a=10;
   tdata.b=32;

   pthread_create(&tid, NULL, myThread, (void *)&tdata);
   pthread_join(tid, NULL);

   printf("%d + %d = %d\n", tdata.a, tdata.b, tdata.result);   

   return 0;
}

Homebrew: Could not symlink, /usr/local/bin is not writable

If you go to the folder in finder, right click and select "Get Info" you can go to the "Sharing and Permissions" section for the folder and allow "Read & Write" to "everyone"

This is what I do to make symlinks pass with this error. Also brew seems to reset the permissions on the folder also as if you hadn't altered anything

How do I change the text of a span element using JavaScript?

For some reason, it seems that using "text" attribute is the way to go with most browsers. It worked for me

$("#span_id").text("text value to assign");

How do I write to a Python subprocess' stdin?

To clarify some points:

As jro has mentioned, the right way is to use subprocess.communicate.

Yet, when feeding the stdin using subprocess.communicate with input, you need to initiate the subprocess with stdin=subprocess.PIPE according to the docs.

Note that if you want to send data to the process’s stdin, you need to create the Popen object with stdin=PIPE. Similarly, to get anything other than None in the result tuple, you need to give stdout=PIPE and/or stderr=PIPE too.

Also qed has mentioned in the comments that for Python 3.4 you need to encode the string, meaning you need to pass Bytes to the input rather than a string. This is not entirely true. According to the docs, if the streams were opened in text mode, the input should be a string (source is the same page).

If streams were opened in text mode, input must be a string. Otherwise, it must be bytes.

So, if the streams were not opened explicitly in text mode, then something like below should work:

import subprocess
command = ['myapp', '--arg1', 'value_for_arg1']
p = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
output = p.communicate(input='some data'.encode())[0]

I've left the stderr value above deliberately as STDOUT as an example.

That being said, sometimes you might want the output of another process rather than building it up from scratch. Let's say you want to run the equivalent of echo -n 'CATCH\nme' | grep -i catch | wc -m. This should normally return the number characters in 'CATCH' plus a newline character, which results in 6. The point of the echo here is to feed the CATCH\nme data to grep. So we can feed the data to grep with stdin in the Python subprocess chain as a variable, and then pass the stdout as a PIPE to the wc process' stdin (in the meantime, get rid of the extra newline character):

import subprocess

what_to_catch = 'catch'
what_to_feed = 'CATCH\nme'

# We create the first subprocess, note that we need stdin=PIPE and stdout=PIPE
p1 = subprocess.Popen(['grep', '-i', what_to_catch], stdin=subprocess.PIPE, stdout=subprocess.PIPE)

# We immediately run the first subprocess and get the result
# Note that we encode the data, otherwise we'd get a TypeError
p1_out = p1.communicate(input=what_to_feed.encode())[0]

# Well the result includes an '\n' at the end, 
# if we want to get rid of it in a VERY hacky way
p1_out = p1_out.decode().strip().encode()

# We create the second subprocess, note that we need stdin=PIPE
p2 = subprocess.Popen(['wc', '-m'], stdin=subprocess.PIPE, stdout=subprocess.PIPE)

# We run the second subprocess feeding it with the first subprocess' output.
# We decode the output to convert to a string
# We still have a '\n', so we strip that out
output = p2.communicate(input=p1_out)[0].decode().strip()

This is somewhat different than the response here, where you pipe two processes directly without adding data directly in Python.

Hope that helps someone out.

What I can do to resolve "1 commit behind master"?

Before you begin, if you are uncomfortable with a command line, you can do all the following steps using SourceTree, GitExtension, GitHub Desktop, or your favorite tool.

To solve the issue, you might have two scenarios:

1) Fix only remote repository branch which is behind commit

Example: Both branches are on the remote side

ahead === Master branch

behind === Develop branch

Solution:

  1. Clone the repository to the local workspace: this will give you the Master branch which is ahead with commit

    git clone repositoryUrl
    
  2. Create a branch with Develop name and checkout to that branch locally

    git checkout -b DevelopBranchName // this command creates and checkout the branch
    
  3. Pull from the remote Develop branch. Conflict might occur. if so, fix the conflict and commit the changes.

     git pull origin DevelopBranchName
    
  4. Merge the local Develop branch with the remote Develop branch

      git merge origin develop
    
  5. Push the merged branch to the remote Develop branch

      git push origin develop
    

2) Local Master branch is behind the remote Master branch

This means every locally created branch is behind.

Before preceding, you have to commit or stash all the changes you made on the branch that is behind commits.

Solution:

  1. Checkout your local Master branch

    git checkout master
    
  2. Pull from remote Master branch

    git pull origin master
    

Now your local Master is in sync with the remote Branch but other local branches, that branched from the local Master branch, are not in sync with your local Master branch because of the above command. To fix that:

  1. Checkout the branch that is behind your local Master branch

    git checkout BranchNameBehindCommit
    
  2. Merge with the local Master branch

    git merge master  // Now your branch is in sync with local Master branch
    

If this branch is on the remote repository, you have to push your changes

    git push origin branchBehindCommit

Assign variable in if condition statement, good practice or not?

I would consider this more of an old-school C style; it is not really good practice in JavaScript so you should avoid it.

The authorization mechanism you have provided is not supported. Please use AWS4-HMAC-SHA256

With boto3, this is the code :

s3_client = boto3.resource('s3', region_name='eu-central-1')

or

s3_client = boto3.client('s3', region_name='eu-central-1')

How to install cron

Installing Crontab on Ubuntu

sudo apt-get update

We download the crontab file to the root

wget https://pypi.python.org/packages/47/c2/d048cbe358acd693b3ee4b330f79d836fb33b716bfaf888f764ee60aee65/crontab-0.20.tar.gz

Unzip the file crontab-0.20.tar.gz

tar xvfz crontab-0.20.tar.gz

Login to a folder crontab-0.20

cd crontab-0.20*

Installation order

python setup.py install

See also here:.. http://www.syriatalk.im/crontab.html

How to add a WiX custom action that happens only on uninstall (via MSI)?

There are multiple problems with yaluna's answer, also property names are case sensitive, Installed is the correct spelling (INSTALLED will not work). The table above should've been this:

enter image description here

Also assuming a full repair & uninstall the actual values of properties could be:

enter image description here

The WiX Expression Syntax documentation says:

In these expressions, you can use property names (remember that they are case sensitive).

The properties are documented at the Windows Installer Guide (e.g. Installed)

EDIT: Small correction to the first table; evidently "Uninstall" can also happen with just REMOVE being True.

Passing arrays as url parameter

**in create url page**

$data = array(
        'car' => 'Suzuki',
        'Model' => '1976'
        );
$query = http_build_query(array('myArray' => $data));
$url=urlencode($query); 

echo" <p><a href=\"index2.php?data=".$url."\"> Send </a><br /> </p>";

**in received page**

parse_str($_GET['data']);
echo $myArray['car'];
echo '<br/>';
echo $myArray['model'];

Import-CSV and Foreach

$IP_Array = (Get-Content test2.csv)[0].split(",")
foreach ( $IP in $IP_Array){
    $IP
}

Get-content Filename returns an array of strings for each line.

On the first string only, I split it based on ",". Dumping it into $IP_Array.

$IP_Array = (Get-Content test2.csv)[0].split(",")
foreach ( $IP in $IP_Array){
  if ($IP -eq "2.2.2.2") {
    Write-Host "Found $IP"
  }
}

c# open file with default application and parameters

Please add Settings under Properties for the Project and make use of them this way you have clean and easy configurable settings that can be configured as default

How To: Create a New Setting at Design Time

Update: after comments below

  1. Right + Click on project
  2. Add New Item
  3. Under Visual C# Items -> General
  4. Select Settings File

How to change Screen buffer size in Windows Command Prompt from batch script

I'm expanding upon a comment that I posted here as most people won't notice the comment.

https://lifeboat.com/programs/console.exe is a compiled version of the Visual Basic program described at https://stackoverflow.com/a/4694566/1752929. My version simply sets the buffer height to 32766 which is the maximum buffer height available. It does not adjust anything else. If there is a lot of demand, I could create a more flexible program but generally you can just set other variables in your shortcut layout tab.

Following is the target I use in my shortcut where I wish to start in the f directory. (I have to set the directory this way as Windows won't let you set it any other way if you wish to run the command prompt as administrator.)

C:\Windows\System32\cmd.exe /k "console & cd /d c:\f"

Common Header / Footer with static HTML

You can do it with javascript, and I don't think it needs to be that fancy.

If you have a header.js file and a footer.js.

Then the contents of header.js could be something like

document.write("<div class='header'>header content</div> etc...")

Remember to escape any nested quote characters in the string you are writing. You could then call that from your static templates with

<script type="text/javascript" src="header.js"></script>

and similarly for the footer.js.

Note: I am not recommending this solution - it's a hack and has a number of drawbacks (poor for SEO and usability just for starters) - but it does meet the requirements of the questioner.

Regex: ignore case sensitivity

You also can lead your initial string, which you are going to check for pattern matching, to lower case. And using in your pattern lower case symbols respectively .

jQuery.click() vs onClick

<whatever onclick="doStuff();" onmouseover="in()" onmouseout="out()" />

onclick, onmouseover, onmouseout, etc. events are actually bad for performance (in Internet Explorer mainly, go figure). If you code using Visual Studio, when you run a page with these, every single one of these will create a separate SCRIPT block taking up memory, and thus slowing down performance.

Not to mention you should have a separation of concerns: JavaScript and layouts should be separated!

It is always better to create evenHandlers for any of these events, one event can capture hundreds/thousands of items, instead of creating thousands of separate script blocks for each one!

(Also, everything everyone else is saying.)

Difference between xcopy and robocopy

I have written lot of scripts to automate daily backups etc. Previously I used XCopy and then moved to Robocopy. Anyways Robocopy and XCopy both are frequently used in terms of file transfers in Windows. Robocopy stands for Robust File Copy. All type of huge file copying both these commands are used but Robocopy has added options which makes copying easier as well as for debugging purposes.

Having said that lets talk about features between these two.

  • Robocopy becomes handy for mirroring or synchronizing directories. It also checks the files in the destination directory against the files to be copied and doesn't waste time copying unchanged files.

  • Just like myself, if you are into automation to take daily backups etc, "Run Hours - /RH" becomes very useful without any interactions. This is supported by Robocopy. It allows you to set when copies should be done rather than the time of the command as with XCopy. You will see robocopy.exe process in task list since it will run background to monitor clock to execute when time is right to copy.

  • Robocopy supports file and directory monitoring with the "/MON" or "/MOT" commands.

  • Robocopy gives extra support for copying over the "archive" attribute on files, it supports copying over all attributes including timestamps, security, owner, and auditing information.

Hope this helps you.

Validating parameters to a Bash script

Use set -u which will cause any unset argument reference to immediately fail the script.

Please, see the article: Writing Robust Bash Shell Scripts - David Pashley.com.

"unadd" a file to svn before commit

For Files - svn revert filename

For Folders - svn revert -R folder

Python - 'ascii' codec can't decode byte

"??".encode('utf-8')

encode converts a unicode object to a string object. But here you have invoked it on a string object (because you don't have the u). So python has to convert the string to a unicode object first. So it does the equivalent of

"??".decode().encode('utf-8')

But the decode fails because the string isn't valid ascii. That's why you get a complaint about not being able to decode.

What does the regex \S mean in JavaScript?

\s matches whitespace (spaces, tabs and new lines). \S is negated \s.

Save bitmap to file function

Here is the function which help you

private void saveBitmap(Bitmap bitmap,String path){
        if(bitmap!=null){
            try {
                FileOutputStream outputStream = null;
                try {
                    outputStream = new FileOutputStream(path); //here is set your file path where you want to save or also here you can set file object directly

                    bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream); // bitmap is your Bitmap instance, if you want to compress it you can compress reduce percentage
                    // PNG is a lossless format, the compression factor (100) is ignored
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    try {
                        if (outputStream != null) {
                            outputStream.close();
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }    
        }
    }

Add line break to ::after or ::before pseudo-element content

Add line break to ::after or ::before pseudo-element content

.yourclass:before {
    content: 'text here first \A  text here second';
    white-space: pre;
}

How to fix 'Unchecked runtime.lastError: The message port closed before a response was received' chrome issue?

I disabled Chrome extension "Coupons at Checkout" and this problem was solved.

How to get main window handle from process id?

Though it may be unrelated to your question, take a look at GetGUIThreadInfo Function.

Number of days in particular month of particular year?

public class Main {

    private static LocalDate local=LocalDate.now();
    public static void main(String[] args) {

            int month=local.lengthOfMonth();
            System.out.println(month);

    }
}

How to specify jackson to only use fields - preferably globally

for jackson 1.9.10 I use

ObjectMapper mapper = new ObjectMapper();

mapper.setVisibility(JsonMethod.ALL, Visibility.NONE);
mapper.setVisibility(JsonMethod.FIELD, Visibility.ANY);

to turn of auto dedection.

Undefined variable: $_SESSION

You need make sure to start the session at the top of every PHP file where you want to use the $_SESSION superglobal. Like this:

<?php
  session_start();
  echo $_SESSION['youritem'];
?>

You forgot the Session HELPER.

Check this link : book.cakephp.org/2.0/en/core-libraries/helpers/session.html

PDO closing connection

$conn=new PDO("mysql:host=$host;dbname=$dbname",$user,$pass);
    // If this is your connection then you have to assign null
    // to your connection variable as follows:
$conn=null;
    // By this way you can close connection in PDO.

How to use sbt from behind proxy?

I found that starting IntelliJ IDEA from terminal let me connect and download over the internet. To start from terminal, type in:

$ idea

CASE in WHERE, SQL Server

You can simplify to:

WHERE a.Country = COALESCE(NULLIF(@Country,0), a.Country);

Can you have a <span> within a <span>?

Yes. You can have a span within a span. Your problem stems from something else.

Better way to convert an int to a boolean

int i = 0;
bool b = Convert.ToBoolean(i);

How do I block or restrict special characters from input fields with jquery?

Yes you can do by using jQuery as:

<script>
$(document).ready(function()
{
    $("#username").blur(function()
    {
        //remove all the class add the messagebox classes and start fading
        $("#msgbox").removeClass().addClass('messagebox').text('Checking...').fadeIn("slow");
        //check the username exists or not from ajax
        $.post("user_availability.php",{ user_name:$(this).val() } ,function(data)
        {
          if(data=='empty') // if username is empty
          {
            $("#msgbox").fadeTo(200,0.1,function() //start fading the messagebox
            { 
              //add message and change the class of the box and start fading
              $(this).html('Empty user id is not allowed').addClass('messageboxerror').fadeTo(900,1);
            });
          }
          else if(data=='invalid') // if special characters used in username
          {
            $("#msgbox").fadeTo(200,0.1,function() //start fading the messagebox
            { 
              //add message and change the class of the box and start fading
              $(this).html('Sorry, only letters (a-z), numbers (0-9), and periods (.) are allowed.').addClass('messageboxerror').fadeTo(900,1);
            });
          }
          else if(data=='no') // if username not avaiable
          {
            $("#msgbox").fadeTo(200,0.1,function() //start fading the messagebox
            { 
              //add message and change the class of the box and start fading
              $(this).html('User id already exists').addClass('messageboxerror').fadeTo(900,1);
            });     
          }
          else
          {
            $("#msgbox").fadeTo(200,0.1,function()  //start fading the messagebox
            { 
              //add message and change the class of the box and start fading
              $(this).html('User id available to register').addClass('messageboxok').fadeTo(900,1); 
            });
          }

        });

    });
});
</script>
<input type="text" id="username" name="username"/><span id="msgbox" style="display:none"></span>

and script for your user_availability.php will be:

<?php
include'includes/config.php';

//value got from the get method
$user_name = trim($_POST['user_name']);

if($user_name == ''){
    echo "empty";
}elseif(preg_match('/[\'^£$%&*()}{@#~?><>,|=_+¬-]/', $user_name)){
    echo "invalid";
}else{
    $select = mysql_query("SELECT user_id FROM staff");

    $i=0;
    //this varible contains the array of existing users
    while($fetch = mysql_fetch_array($select)){
        $existing_users[$i] = $fetch['user_id'];
        $i++;
    }

    //checking weather user exists or not in $existing_users array
    if (in_array($user_name, $existing_users))
    {
        //user name is not availble
        echo "no";
    } 
    else
    {
        //user name is available
        echo "yes";
    }
}
?>

I tried to add for / and \ but not succeeded.


You can also do it by using javascript & code will be:

<!-- Check special characters in username start -->
<script language="javascript" type="text/javascript">
function check(e) {
    var keynum
    var keychar
    var numcheck
    // For Internet Explorer
    if (window.event) {
        keynum = e.keyCode;
    }
    // For Netscape/Firefox/Opera
    else if (e.which) {
        keynum = e.which;
    }
    keychar = String.fromCharCode(keynum);
    //List of special characters you want to restrict
    if (keychar == "'" || keychar == "`" || keychar =="!" || keychar =="@" || keychar =="#" || keychar =="$" || keychar =="%" || keychar =="^" || keychar =="&" || keychar =="*" || keychar =="(" || keychar ==")" || keychar =="-" || keychar =="_" || keychar =="+" || keychar =="=" || keychar =="/" || keychar =="~" || keychar =="<" || keychar ==">" || keychar =="," || keychar ==";" || keychar ==":" || keychar =="|" || keychar =="?" || keychar =="{" || keychar =="}" || keychar =="[" || keychar =="]" || keychar =="¬" || keychar =="£" || keychar =='"' || keychar =="\\") {
        return false;
    } else {
        return true;
    }
}
</script>
<!-- Check special characters in username end -->

<!-- in your form -->
    User id : <input type="text" id="txtname" name="txtname" onkeypress="return check(event)"/>

How to force Laravel Project to use HTTPS for all routes?

Here are several ways. Choose most convenient.

  1. Configure your web server to redirect all non-secure requests to https. Example of a nginx config:

    server {
        listen 80 default_server;
        listen [::]:80 default_server;
        server_name example.com www.example.com;
        return 301 https://example.com$request_uri;
    }
    
  2. Set your environment variable APP_URL using https:

    APP_URL=https://example.com
    
  3. Use helper secure_url() (Laravel5.6)

  4. Add following string to AppServiceProvider::boot() method (for version 5.4+):

    \Illuminate\Support\Facades\URL::forceScheme('https');
    

Update:

  1. Implicitly setting scheme for route group (Laravel5.6):

    Route::group(['scheme' => 'https'], function () {
        // Route::get(...)->name(...);
    });
    

Is it safe to expose Firebase apiKey to the public?

I am making a blog website on github pages. I got an idea to embbed comments in the end of every blog page. I understand how firebase get and gives you data.

I have tested many times with project and even using console. I am totally disagree the saying vlit is vulnerable. Believe me there is no issue of showing your api key publically if you have followed privacy steps recommend by firebase. Go to https://console.developers.google.com/apis and perfrom a security steup.

ASP.NET: HTTP Error 500.19 – Internal Server Error 0x8007000d

Error 0x8007000d means URL rewriting module (referenced in web.config) is missing or proper version is not installed.

Just install URL rewriting module via web platform installer.

I recommend to check all dependencies from web.config and install them.

Invalidating JSON Web Tokens

This is primarily a long comment supporting and building on the answer by @mattway

Given:

Some of the other proposed solutions on this page advocate hitting the datastore on every request. If you hit the main datastore to validate every authentication request, then I see less reason to use JWT instead of other established token authentication mechanisms. You've essentially made JWT stateful, instead of stateless if you go to the datastore each time.

(If your site receives a high volume of unauthorized requests, then JWT would deny them without hitting the datastore, which is helpful. There are probably other use cases like that.)

Given:

Truly stateless JWT authentication cannot be achieved for a typical, real world web app because stateless JWT does not have a way to provide immediate and secure support for the following important use cases:

User's account is deleted/blocked/suspended.

User's password is changed.

User's roles or permissions are changed.

User is logged out by admin.

Any other application critical data in the JWT token is changed by the site admin.

You cannot wait for token expiration in these cases. The token invalidation must occur immediately. Also, you cannot trust the client not to keep and use a copy of the old token, whether with malicious intent or not.

Therefore: I think the answer from @matt-way, #2 TokenBlackList, would be most efficient way to add the required state to JWT based authentication.

You have a blacklist that holds these tokens until their expiration date is hit. The list of tokens will be quite small compared to the total number of users, since it only has to keep blacklisted tokens until their expiration. I'd implement by putting invalidated tokens in redis, memcached or another in-memory datastore that supports setting an expiration time on a key.

You still have to make a call to your in-memory db for every authentication request that passes initial JWT auth, but you don't have to store keys for your entire set of users in there. (Which may or may not be a big deal for a given site.)

A circular reference was detected while serializing an object of type 'SubSonic.Schema .DatabaseColumn'.

I had the same problem and solved by using Newtonsoft.Json;

var list = JsonConvert.SerializeObject(model,
    Formatting.None,
    new JsonSerializerSettings() {
        ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
});

return Content(list, "application/json");

Passing command line arguments to R CMD BATCH

After trying the options described here, I found this post from Forester in r-bloggers . I think it is a clean option to consider.

I put his code here:

From command line

$ R CMD BATCH --no-save --no-restore '--args a=1 b=c(2,5,6)' test.R test.out &

Test.R

##First read in the arguments listed at the command line
args=(commandArgs(TRUE))

##args is now a list of character vectors
## First check to see if arguments are passed.
## Then cycle through each element of the list and evaluate the expressions.
if(length(args)==0){
    print("No arguments supplied.")
    ##supply default values
    a = 1
    b = c(1,1,1)
}else{
    for(i in 1:length(args)){
      eval(parse(text=args[[i]]))
    }
}

print(a*2)
print(b*3)

In test.out

> print(a*2)
[1] 2
> print(b*3)
[1]  6 15 18

Thanks to Forester!

How to display length of filtered ng-repeat data

You can do it with 2 ways. In template and in Controller. In template you can set your filtered array to another variable, then use it like you want. Here is how to do it:

<ul>
  <li data-ng-repeat="user in usersList = (users | gender:filterGender)" data-ng-bind="user.name"></li>
</ul>
 ....
<span>{{ usersList.length | number }}</span>

If you need examples, see the AngularJs filtered count examples/demos

How can I change Eclipse theme?

The best way to Install new themes in any Eclipse platform is to use the Eclipse Marketplace.

1.Go to Help > Eclipse Marketplace

2.Search for "Color Themes"

3.Install and Restart

4.Go to Window > Preferences > General > Appearance > Color Themes

5.Select anyone and Apply. Restart.

How to create our own Listener interface in android?

I have created a Generic AsyncTask Listener which get result from AsycTask seperate class and give it to CallingActivity using Interface Callback.

new GenericAsyncTask(context,new AsyncTaskCompleteListener()
        {
             public void onTaskComplete(String response) 
             {
                 // do your work. 
             }
        }).execute();

Interface

interface AsyncTaskCompleteListener<T> {
   public void onTaskComplete(T result);
}

GenericAsyncTask

class GenericAsyncTask extends AsyncTask<String, Void, String> 
{
    private AsyncTaskCompleteListener<String> callback;

    public A(Context context, AsyncTaskCompleteListener<String> cb) {
        this.context = context;
        this.callback = cb;
    }

    protected void onPostExecute(String result) {
       finalResult = result;
       callback.onTaskComplete(result);
   }  
}

Have a look at this , this question for more details.

Get values from an object in JavaScript

To access the properties of an object without knowing the names of those properties you can use a for ... in loop:

for(key in data) {
    if(data.hasOwnProperty(key)) {
        var value = data[key];
        //do something with value;
    }
}

Calling stored procedure from another stored procedure SQL Server

First of all, if table2's idProduct is an identity, you cannot insert it explicitly until you set IDENTITY_INSERT on that table

SET IDENTITY_INSERT table2 ON;

before the insert.

So one of two, you modify your second stored and call it with only the parameters productName and productDescription and then get the new ID

EXEC test2 'productName', 'productDescription'
SET @newID = SCOPE_IDENTIY()

or you already have the ID of the product and you don't need to call SCOPE_IDENTITY() and can make the insert on table1 with that ID

How to convert DateTime to a number with a precision greater than days in T-SQL?

You can use T-SQL to convert the date before it gets to your .NET program. This often is simpler if you don't need to do additional date conversion in your .NET program.

DECLARE @Date DATETIME = Getdate()
DECLARE @DateInt INT = CONVERT(VARCHAR(30), @Date, 112)
DECLARE @TimeInt INT = REPLACE(CONVERT(VARCHAR(30), @Date, 108), ':', '')
DECLARE @DateTimeInt BIGINT = CONVERT(VARCHAR(30), @Date, 112) + REPLACE(CONVERT(VARCHAR(30), @Date, 108), ':', '')
SELECT @Date as Date, @DateInt DateInt, @TimeInt TimeInt, @DateTimeInt DateTimeInt

Date                    DateInt     TimeInt     DateTimeInt
------------------------- ----------- ----------- --------------------
2013-01-07 15:08:21.680 20130107    150821      20130107150821

Creating NSData from NSString in Swift

In swift 5

let data = Data(YourString.utf8)

Convert NSNumber to int in Objective-C

You should stick to the NSInteger data types when possible. So you'd create the number like that:

NSInteger myValue = 1;
NSNumber *number = [NSNumber numberWithInteger: myValue];

Decoding works with the integerValue method then:

NSInteger value = [number integerValue];

How to change permissions for a folder and its subfolders/files in one step?

chmod -R 755 directory_name works, but how would you keep new files to 755 also? The file's permissions becomes the default permission.

How to Access Hive via Python?

None of the answers demonstrate how to fetch and print the table headers. Modified the standard example from PyHive which is widely used and actively maintained.

from pyhive import hive
cursor = hive.connect(host="localhost", 
                      port=10000, 
                      username="shadan", 
                      auth="KERBEROS", 
                      kerberos_service_name="hive"
                      ).cursor()
cursor.execute("SELECT * FROM my_dummy_table LIMIT 10")
columnList = [desc[0] for desc in cursor.description]
headerStr = ",".join(columnList)
headerTuple = tuple(headerStr.split (",")
print(headerTuple)
print(cursor.fetchone())
print(cursor.fetchall())

What is Android keystore file, and what is it used for?

Android Market requires you to sign all apps you publish with a certificate, using a public/private key mechanism (the certificate is signed with your private key). This provides a layer of security that prevents, among other things, remote attackers from pushing malicious updates to your application to market (all updates must be signed with the same key).

From The App-Signing Guide of the Android Developer's site:

In general, the recommended strategy for all developers is to sign all of your applications with the same certificate, throughout the expected lifespan of your applications. There are several reasons why you should do so...

Using the same key has a few benefits - One is that it's easier to share data between applications signed with the same key. Another is that it allows multiple apps signed with the same key to run in the same process, so a developer can build more "modular" applications.

Display MessageBox in ASP

<% response.write("<script language=""javascript"">alert('Hello!');</script>") %>

How to handle notification when app in background in Firebase

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {

}

is not called every time it is called only when app is in forground

there is one override method this method is called every time , no matter what app is in foreground or in background or killed but this method is available with this firebase api version

this is the version u have to import from gradle

compile 'com.google.firebase:firebase-messaging:10.2.1'

this is the method

@Override
public void handleIntent(Intent intent) {
    super.handleIntent(intent);

    // you can get ur data here 
    //intent.getExtras().get("your_data_key") 


}

with previous firebase api this method was not there so in that case fire base handle itself when app is in background .... now u have this method what ever u want to do ... u can do it here in this method .....

if you are using previous version than default activity will start in that case u can get data same way

if(getIntent().getExtras() != null && getIntent().getExtras().get("your_data_key") != null) {
String strNotificaiton = getIntent().getExtras().get("your_data_key").toString();

// do what ever u want .... }

generally this is the structure from server we get in notification

{
    "notification": {
        "body": "Cool offers. Get them before expiring!",
        "title": "Flat 80% discount",
        "icon": "appicon",
        "click_action": "activity name" //optional if required.....
    },
    "data": {
        "product_id": 11,
        "product_details": "details.....",
        "other_info": "......."
    }
}

it's up to u how u want to give that data key or u want give notification anything u can give ....... what ever u will give here with same key u will get that data .........

there are few cases if u r not sending click action in that case when u will click on notification default activity will open , but if u want to open your specific activity when app is in background u can call your activity from this on handleIntent method because this is called every time

How is Pythons glob.glob ordered?

Order is arbitrary, but there are several ways to sort them. One of them is as following:

#First, get the files:
import glob
import re
files =glob.glob1(img_folder,'*'+output_image_format)
# if you want sort files according to the digits included in the filename, you can do as following:
files = sorted(files, key=lambda x:float(re.findall("(\d+)",x)[0]))

HttpWebRequest-The remote server returned an error: (400) Bad Request

400 Bad request Error will be thrown due to incorrect authentication entries.

  1. Check if your API URL is correct or wrong. Don't append or prepend spaces.
  2. Verify that your username and password are valid. Please check any spelling mistake(s) while entering.

Note: Mostly due to Incorrect authentication entries due to spell changes will occur 400 Bad request.

How to disable keypad popup when on edittext?

       <TextView android:layout_width="match_parent"
                 android:layout_height="wrap_content"

                 android:focusable="true"
                 android:focusableInTouchMode="true">

                <requestFocus/>
      </TextView>

      <EditText android:layout_width="match_parent"
                android:layout_height="wrap_content"/>

pros and cons between os.path.exists vs os.path.isdir

Just like it sounds like: if the path exists, but is a file and not a directory, isdir will return False. Meanwhile, exists will return True in both cases.

Understanding dispatch_async

All of the DISPATCH_QUEUE_PRIORITY_X queues are concurrent queues (meaning they can execute multiple tasks at once), and are FIFO in the sense that tasks within a given queue will begin executing using "first in, first out" order. This is in comparison to the main queue (from dispatch_get_main_queue()), which is a serial queue (tasks will begin executing and finish executing in the order in which they are received).

So, if you send 1000 dispatch_async() blocks to DISPATCH_QUEUE_PRIORITY_DEFAULT, those tasks will start executing in the order you sent them into the queue. Likewise for the HIGH, LOW, and BACKGROUND queues. Anything you send into any of these queues is executed in the background on alternate threads, away from your main application thread. Therefore, these queues are suitable for executing tasks such as background downloading, compression, computation, etc.

Note that the order of execution is FIFO on a per-queue basis. So if you send 1000 dispatch_async() tasks to the four different concurrent queues, evenly splitting them and sending them to BACKGROUND, LOW, DEFAULT and HIGH in order (ie you schedule the last 250 tasks on the HIGH queue), it's very likely that the first tasks you see starting will be on that HIGH queue as the system has taken your implication that those tasks need to get to the CPU as quickly as possible.

Note also that I say "will begin executing in order", but keep in mind that as concurrent queues things won't necessarily FINISH executing in order depending on length of time for each task.

As per Apple:

https://developer.apple.com/library/content/documentation/General/Conceptual/ConcurrencyProgrammingGuide/OperationQueues/OperationQueues.html

A concurrent dispatch queue is useful when you have multiple tasks that can run in parallel. A concurrent queue is still a queue in that it dequeues tasks in a first-in, first-out order; however, a concurrent queue may dequeue additional tasks before any previous tasks finish. The actual number of tasks executed by a concurrent queue at any given moment is variable and can change dynamically as conditions in your application change. Many factors affect the number of tasks executed by the concurrent queues, including the number of available cores, the amount of work being done by other processes, and the number and priority of tasks in other serial dispatch queues.

Basically, if you send those 1000 dispatch_async() blocks to a DEFAULT, HIGH, LOW, or BACKGROUND queue they will all start executing in the order you send them. However, shorter tasks may finish before longer ones. Reasons behind this are if there are available CPU cores or if the current queue tasks are performing computationally non-intensive work (thus making the system think it can dispatch additional tasks in parallel regardless of core count).

The level of concurrency is handled entirely by the system and is based on system load and other internally determined factors. This is the beauty of Grand Central Dispatch (the dispatch_async() system) - you just make your work units as code blocks, set a priority for them (based on the queue you choose) and let the system handle the rest.

So to answer your above question: you are partially correct. You are "asking that code" to perform concurrent tasks on a global concurrent queue at the specified priority level. The code in the block will execute in the background and any additional (similar) code will execute potentially in parallel depending on the system's assessment of available resources.

The "main" queue on the other hand (from dispatch_get_main_queue()) is a serial queue (not concurrent). Tasks sent to the main queue will always execute in order and will always finish in order. These tasks will also be executed on the UI Thread so it's suitable for updating your UI with progress messages, completion notifications, etc.

Difference between InvariantCulture and Ordinal string comparison

Although the question is about equality, for quick visual reference, here the order of some strings sorted using a couple of cultures illustrating some of the idiosyncrasies out there.

Ordinal          0 9 A Ab a aB aa ab ss Ä Äb ß ä äb ? ? ? ? ? A
IgnoreCase       0 9 a A aa ab Ab aB ss ä Ä äb Äb ß ? ? ? ? ? A
--------------------------------------------------------------------
InvariantCulture 0 9 a A A ä Ä aa ab aB Ab äb Äb ss ß ? ? ? ? ?
IgnoreCase       0 9 A a A Ä ä aa Ab aB ab Äb äb ß ss ? ? ? ? ?
--------------------------------------------------------------------
da-DK            0 9 a A A ab aB Ab ss ß ä Ä äb Äb aa ? ? ? ? ?
IgnoreCase       0 9 A a A Ab aB ab ß ss Ä ä Äb äb aa ? ? ? ? ?
--------------------------------------------------------------------
de-DE            0 9 a A A ä Ä aa ab aB Ab äb Äb ß ss ? ? ? ? ?
IgnoreCase       0 9 A a A Ä ä aa Ab aB ab Äb äb ss ß ? ? ? ? ?
--------------------------------------------------------------------
en-US            0 9 a A A ä Ä aa ab aB Ab äb Äb ß ss ? ? ? ? ?
IgnoreCase       0 9 A a A Ä ä aa Ab aB ab Äb äb ss ß ? ? ? ? ?
--------------------------------------------------------------------
ja-JP            0 9 a A A ä Ä aa ab aB Ab äb Äb ß ss ? ? ? ? ?
IgnoreCase       0 9 A a A Ä ä aa Ab aB ab Äb äb ss ß ? ? ? ? ?

Observations:

  • de-DE, ja-JP, and en-US sort the same way
  • Invariant only sorts ss and ß differently from the above three cultures
  • da-DK sorts quite differently
  • the IgnoreCase flag matters for all sampled cultures

The code used to generate above table:

var l = new List<string>
    { "0", "9", "A", "Ab", "a", "aB", "aa", "ab", "ss", "ß",
      "Ä", "Äb", "ä", "äb", "?", "?", "?", "?", "A", "?" };

foreach (var comparer in new[]
{
    StringComparer.Ordinal,
    StringComparer.OrdinalIgnoreCase,
    StringComparer.InvariantCulture,
    StringComparer.InvariantCultureIgnoreCase,
    StringComparer.Create(new CultureInfo("da-DK"), false),
    StringComparer.Create(new CultureInfo("da-DK"), true),
    StringComparer.Create(new CultureInfo("de-DE"), false),
    StringComparer.Create(new CultureInfo("de-DE"), true),
    StringComparer.Create(new CultureInfo("en-US"), false),
    StringComparer.Create(new CultureInfo("en-US"), true),
    StringComparer.Create(new CultureInfo("ja-JP"), false),
    StringComparer.Create(new CultureInfo("ja-JP"), true),
})
{
    l.Sort(comparer);
    Console.WriteLine(string.Join(" ", l));
}

Function names in C++: Capitalize or not?

Since C++11, you may want to use either snake_case or camelCase for function names.

This is because to make a class work as the range-expression in a range-based for-loop, you have to define functions called begin and end (case-sensitive) for that class.

Consequently, using e.g. PascalCase for function names means you have to break the naming consistency in your project if you ever need to make a class work with the range-based for.

How do I delete unpushed git commits?

Do a git rebase -i FAR_ENOUGH_BACK and drop the line for the commit you don't want.

Getting and removing the first character of a string

See ?substring.

x <- 'hello stackoverflow'
substring(x, 1, 1)
## [1] "h"
substring(x, 2)
## [1] "ello stackoverflow"

The idea of having a pop method that both returns a value and has a side effect of updating the data stored in x is very much a concept from object-oriented programming. So rather than defining a pop function to operate on character vectors, we can make a reference class with a pop method.

PopStringFactory <- setRefClass(
  "PopString",
  fields = list(
    x = "character"  
  ),
  methods = list(
    initialize = function(x)
    {
      x <<- x
    },
    pop = function(n = 1)
    {
      if(nchar(x) == 0)
      {
        warning("Nothing to pop.")
        return("")
      }
      first <- substring(x, 1, n)
      x <<- substring(x, n + 1)
      first
    }
  )
)

x <- PopStringFactory$new("hello stackoverflow")
x
## Reference class object of class "PopString"
## Field "x":
## [1] "hello stackoverflow"
replicate(nchar(x$x), x$pop())
## [1] "h" "e" "l" "l" "o" " " "s" "t" "a" "c" "k" "o" "v" "e" "r" "f" "l" "o" "w"

How do I remove the last comma from a string using PHP?

rtrim function

rtrim($my_string,',');

Second parameter indicates that comma to be deleted from right side.

How to find out what character key is pressed?

"Clear" JavaScript:

_x000D_
_x000D_
function myKeyPress(e){
  var keynum;

  if(window.event) { // IE                  
    keynum = e.keyCode;
  } else if(e.which){ // Netscape/Firefox/Opera                 
    keynum = e.which;
  }

  alert(String.fromCharCode(keynum));
}
_x000D_
<input type="text" onkeypress="return myKeyPress(event)" />
_x000D_
_x000D_
_x000D_

JQuery:

_x000D_
_x000D_
$("input").keypress(function(event){
  alert(String.fromCharCode(event.which)); 
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input/>
_x000D_
_x000D_
_x000D_

ImportError: DLL load failed: %1 is not a valid Win32 application

The ImportError message is a bit misleading because of the reference to Win32, whereas the problem was simply the opencv DLLs were not found.

This problem was solved by adding the path the opencv binaries to the Windows PATH environment variable (as an example, on my computer this path is : C:\opencv\build\bin\Release).

How do I Validate the File Type of a File Upload?

Ensure that you always check for the file extension in server-side to ensure that no one can upload a malicious file such as .aspx, .asp etc.

Uncaught TypeError: .indexOf is not a function

I ran across this error recently using a javascript library which changes the parameters of a function based on conditions.

You can test an object to see if it has the function. I would only do this in scenarios where you don't control what is getting passed to you.

if( param.indexOf != undefined ) {
   // we have a string or other object that 
   // happens to have a function named indexOf
}

You can test this in your browser console:

> (3).indexOf == undefined;
true

> "".indexOf == undefined;
false

Django - makemigrations - No changes detected

INSTALLED_APPS = [

    'blog.apps.BlogConfig',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

]

make sure 'blog.apps.BlogConfig', (this is included in your settings.py in order to make your app migrations)

then run python3 manage.py makemigrations blog or your app name

Can attributes be added dynamically in C#?

If you need something to be able to added dynamically, c# attributes aren't the way. Look into storing the data in xml. I recently did a project that i started w/ attributes, but eventually moved to serialization w/ xml.

Make scrollbars only visible when a Div is hovered over?

One trick for this, for webkit browsers, is to create an invisible scrollbar, and then make it appear on hover. This method does not affect the scrolling area width as the space needed for the scrollbar is already there.

Something like this:

_x000D_
_x000D_
body {_x000D_
  height: 500px;_x000D_
  &::-webkit-scrollbar {_x000D_
    background-color: transparent;_x000D_
    width: 10px;_x000D_
  }_x000D_
  &::-webkit-scrollbar-thumb {_x000D_
    background-color: transparent;_x000D_
  }_x000D_
}_x000D_
_x000D_
body:hover {_x000D_
  &::-webkit-scrollbar-thumb {_x000D_
    background-color: black;_x000D_
  }_x000D_
}_x000D_
_x000D_
.full-width {_x000D_
  width: 100%;_x000D_
  background: blue;_x000D_
  padding: 30px;_x000D_
  color: white;_x000D_
}
_x000D_
some content here_x000D_
_x000D_
<div class="full-width">does not change</div>
_x000D_
_x000D_
_x000D_

How to terminate a python subprocess launched with shell=True

As Sai said, the shell is the child, so signals are intercepted by it -- best way I've found is to use shell=False and use shlex to split the command line:

if isinstance(command, unicode):
    cmd = command.encode('utf8')
args = shlex.split(cmd)

p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)

Then p.kill() and p.terminate() should work how you expect.

How can I check for "undefined" in JavaScript?

In this article I read that frameworks like Underscore.js use this function:

function isUndefined(obj){
    return obj === void 0;
}

Fitting a histogram with python

Here is an example that uses scipy.optimize to fit a non-linear functions like a Gaussian, even when the data is in a histogram that isn't well ranged, so that a simple mean estimate would fail. An offset constant also would cause simple normal statistics to fail ( just remove p[3] and c[3] for plain gaussian data).

from pylab import *
from numpy import loadtxt
from scipy.optimize import leastsq

fitfunc  = lambda p, x: p[0]*exp(-0.5*((x-p[1])/p[2])**2)+p[3]
errfunc  = lambda p, x, y: (y - fitfunc(p, x))

filename = "gaussdata.csv"
data     = loadtxt(filename,skiprows=1,delimiter=',')
xdata    = data[:,0]
ydata    = data[:,1]

init  = [1.0, 0.5, 0.5, 0.5]

out   = leastsq( errfunc, init, args=(xdata, ydata))
c = out[0]

print "A exp[-0.5((x-mu)/sigma)^2] + k "
print "Parent Coefficients:"
print "1.000, 0.200, 0.300, 0.625"
print "Fit Coefficients:"
print c[0],c[1],abs(c[2]),c[3]

plot(xdata, fitfunc(c, xdata))
plot(xdata, ydata)

title(r'$A = %.3f\  \mu = %.3f\  \sigma = %.3f\ k = %.3f $' %(c[0],c[1],abs(c[2]),c[3]));

show()

Output:

A exp[-0.5((x-mu)/sigma)^2] + k 
Parent Coefficients:
1.000, 0.200, 0.300, 0.625
Fit Coefficients:
0.961231625289 0.197254597618 0.293989275502 0.65370344131

gaussian plot with fit

Create a Cumulative Sum Column in MySQL

Sample query

SET @runtot:=0;
SELECT
   q1.d,
   q1.c,
   (@runtot := @runtot + q1.c) AS rt
FROM
   (SELECT
       DAYOFYEAR(date) AS d,
       COUNT(*) AS c
    FROM  orders
    WHERE  hasPaid > 0
    GROUP  BY d
    ORDER  BY d) AS q1

Is Django for the frontend or backend?

It seems you're actually talking about an MVC (Model-View-Controller) pattern, where logic is separated into various "tiers". Django, as a framework, follows MVC (loosely). You have models that contain your business logic and relate directly to tables in your database, views which in effect act like the controller, handling requests and returning responses, and finally, templates which handle presentation.

Django isn't just one of these, it is a complete framework for application development and provides all the tools you need for that purpose.

Frontend vs Backend is all semantics. You could potentially build a Django app that is entirely "backend", using its built-in admin contrib package to manage the data for an entirely separate application. Or, you could use it solely for "frontend", just using its views and templates but using something else entirely to manage the data. Most usually, it's used for both. The built-in admin (the "backend"), provides an easy way to manage your data and you build apps within Django to present that data in various ways. However, if you were so inclined, you could also create your own "backend" in Django. You're not forced to use the default admin.

Truststore and Keystore Definitions

You may also be interested in the write-up from Sun, as part of the standard JSSE documentation:

http://docs.oracle.com/javase/8/docs/technotes/guides/security/jsse/JSSERefGuide.html#Stores

Typically, the trust store is used to store only public keys, for verification purposes, such as with X.509 authentication. For manageability purposes, it's quite common for admins or developers to simply conflate the two into a single store.

Error: 'int' object is not subscriptable - Python

When you write x = 0, x is an int...so you can't do x[age1] because x is int

What is the difference between <p> and <div>?

DIV is a generic block level container that can contain any other block or inline elements, including other DIV elements, whereas P is to wrap paragraphs (text).

Cannot find module '../build/Release/bson'] code: 'MODULE_NOT_FOUND' } js-bson: Failed to load c++ bson extension, using pure JS version

The marked answer is completely wrong. All that does is hide the console log statement and does nothing whatsoever do address the actually issue. You can also close your eyes and it will achieve the same result.

The issue is caused by node-gyp and only that. Its purpose is to compile native extensions for certain modules such as bson.

If it fails to do so then the code will fallback to the JS version and kindly tell you so through the informative message:

Failed to load c++ bson extension, using pure JS version

I assume the question is really about how to compile the native C++ extension rather that just not seeing the message so let's address that.

In order for node-gyp to work your node-gyp must be up to date with your node and C++ compiler (that will differ based on your OS). Just as important your module must also be up to date.

First uninstall and reinstall node-gyp

npm un node-gyp -g;npm i node-gyp -g

Now you will need to fully uninstall and reinstall any node module in your app (that includes modules installed by requirements as well) that have bson. That should take care of the error. You can search for 'Release/bson' and find the culprits.

find node_modules/ -type 'f' -exec grep -H 'Release/bson' {} \;

And then uninstall and reinstall these modules.

Easier is to just redo the entire node_modules folder:

 rm -rf node_modules
 npm cache clear
 npm i

If you still experience issues then either 1) your module is out of date - check issue tracker in their repo or 2) you have a potential conflict - sometimes we may have a local node-gyp for example. You can run node-gyp by itself and verify versions.

MVC Razor @foreach

a reply to @DarinDimitrov for a case where i have used foreach in a razor view.

<li><label for="category">Category</label>
        <select id="category">
            <option value="0">All</option>
            @foreach(Category c in Model.Categories)
            {
                <option title="@c.Description" value="@c.CategoryID">@c.Name</option>
            }
        </select>
</li>

How can I set a css border on one side only?

#testDiv{
    /* set green border independently on each side */
    border-left: solid green 2px;
    border-right: solid green 2px;
    border-bottom: solid green 2px;
    border-top: solid green 2px;
}

Node.js heap out of memory

I just want to add that in some systems, even increasing the node memory limit with --max-old-space-size, it's not enough and there is an OS error like this:

terminate called after throwing an instance of 'std::bad_alloc'
  what():  std::bad_alloc
Aborted (core dumped)

In this case, probably is because you reached the max mmap per process.

You can check the max_map_count by running

sysctl vm.max_map_count

and increas it by running

sysctl -w vm.max_map_count=655300

and fix it to not be reset after a reboot by adding this line

vm.max_map_count=655300

in /etc/sysctl.conf file.

Check here for more info.

A good method to analyse the error is by run the process with strace

strace node --max-old-space-size=128000 my_memory_consuming_process.js

Retrieve data from website in android app

You can do the HTML parsing but it is not at all recommended instead ask the website owners to provide web services then you can parse that information.

Getting json body in aws Lambda via API gateway

I am using lambda with Zappa; I am sending data with POST in json format:

My code for basic_lambda_pure.py is:

import time
import requests
import json
def my_handler(event, context):
    print("Received event: " + json.dumps(event, indent=2))
    print("Log stream name:", context.log_stream_name)
    print("Log group name:",  context.log_group_name)
    print("Request ID:", context.aws_request_id)
    print("Mem. limits(MB):", context.memory_limit_in_mb)
    # Code will execute quickly, so we add a 1 second intentional delay so you can see that in time remaining value.
    print("Time remaining (MS):", context.get_remaining_time_in_millis())

    if event["httpMethod"] == "GET":
        hub_mode = event["queryStringParameters"]["hub.mode"]
        hub_challenge = event["queryStringParameters"]["hub.challenge"]
        hub_verify_token = event["queryStringParameters"]["hub.verify_token"]
        return {'statusCode': '200', 'body': hub_challenge, 'headers': 'Content-Type': 'application/json'}}

    if event["httpMethod"] == "post":
        token = "xxxx"
    params = {
        "access_token": token
    }
    headers = {
        "Content-Type": "application/json"
    }
        _data = {"recipient": {"id": 1459299024159359}}
        _data.update({"message": {"text": "text"}})
        data = json.dumps(_data)
        r = requests.post("https://graph.facebook.com/v2.9/me/messages",params=params, headers=headers, data=data, timeout=2)
        return {'statusCode': '200', 'body': "ok", 'headers': {'Content-Type': 'application/json'}}

I got the next json response:

{
"resource": "/",
"path": "/",
"httpMethod": "POST",
"headers": {
"Accept": "*/*",
"Accept-Encoding": "deflate, gzip",
"CloudFront-Forwarded-Proto": "https",
"CloudFront-Is-Desktop-Viewer": "true",
"CloudFront-Is-Mobile-Viewer": "false",
"CloudFront-Is-SmartTV-Viewer": "false",
"CloudFront-Is-Tablet-Viewer": "false",
"CloudFront-Viewer-Country": "US",
"Content-Type": "application/json",
"Host": "ox53v9d8ug.execute-api.us-east-1.amazonaws.com",
"Via": "1.1 f1836a6a7245cc3f6e190d259a0d9273.cloudfront.net (CloudFront)",
"X-Amz-Cf-Id": "LVcBZU-YqklHty7Ii3NRFOqVXJJEr7xXQdxAtFP46tMewFpJsQlD2Q==",
"X-Amzn-Trace-Id": "Root=1-59ec25c6-1018575e4483a16666d6f5c5",
"X-Forwarded-For": "69.171.225.87, 52.46.17.84",
"X-Forwarded-Port": "443",
"X-Forwarded-Proto": "https",
"X-Hub-Signature": "sha1=10504e2878e56ea6776dfbeae807de263772e9f2"
},
"queryStringParameters": null,
"pathParameters": null,
"stageVariables": null,
"requestContext": {
"path": "/dev",
"accountId": "001513791584",
"resourceId": "i6d2tyihx7",
"stage": "dev",
"requestId": "d58c5804-b6e5-11e7-8761-a9efcf8a8121",
"identity": {
"cognitoIdentityPoolId": null,
"accountId": null,
"cognitoIdentityId": null,
"caller": null,
"apiKey": "",
"sourceIp": "69.171.225.87",
"accessKey": null,
"cognitoAuthenticationType": null,
"cognitoAuthenticationProvider": null,
"userArn": null,
"userAgent": null,
"user": null
},
"resourcePath": "/",
"httpMethod": "POST",
"apiId": "ox53v9d8ug"
},
"body": "eyJvYmplY3QiOiJwYWdlIiwiZW50cnkiOlt7ImlkIjoiMTA3OTk2NDk2NTUxMDM1IiwidGltZSI6MTUwODY0ODM5MDE5NCwibWVzc2FnaW5nIjpbeyJzZW5kZXIiOnsiaWQiOiIxNDAzMDY4MDI5ODExODY1In0sInJlY2lwaWVudCI6eyJpZCI6IjEwNzk5NjQ5NjU1MTAzNSJ9LCJ0aW1lc3RhbXAiOjE1MDg2NDgzODk1NTUsIm1lc3NhZ2UiOnsibWlkIjoibWlkLiRjQUFBNHo5RmFDckJsYzdqVHMxZlFuT1daNXFaQyIsInNlcSI6MTY0MDAsInRleHQiOiJob2xhIn19XX1dfQ==",
"isBase64Encoded": true
}

my data was on body key, but is code64 encoded, How can I know this? I saw the key isBase64Encoded

I copy the value for body key and decode with This tool and "eureka", I get the values.

I hope this help you. :)

How to ignore a property in class if null, using json.net

Here's an option that's similar, but provides another choice:

public class DefaultJsonSerializer : JsonSerializerSettings
{
    public DefaultJsonSerializer()
    {
        NullValueHandling = NullValueHandling.Ignore;
    }
}

Then, I use it like this:

JsonConvert.SerializeObject(postObj, new DefaultJsonSerializer());

The difference here is that:

  • Reduces repeated code by instantiating and configuring JsonSerializerSettings each place it's used.
  • Saves time in configuring every property of every object to be serialized.
  • Still gives other developers flexibility in serialization options, rather than having the property explicitly specified on a reusable object.
  • My use-case is that the code is a 3rd party library and I don't want to force serialization options on developers who would want to reuse my classes.
  • Potential drawbacks are that it's another object that other developers would need to know about, or if your application is small and this approach wouldn't matter for a single serialization.

ASP.NET IIS Web.config [Internal Server Error]

If you have python, you can use a package called iis_bridge that solves the problem. To install:

pip install iis_bridge

then in the python console:

import iis_bridge as iis
iis.install()

How to add months to a date in JavaScript?

Split your date into year, month, and day components then use Date:

var d = new Date(year, month, day);
d.setMonth(d.getMonth() + 8);

Date will take care of fixing the year.

Setting the target version of Java in ant javac

You may also set {{ant.build.javac.target=1.5}} ant property to update default target version of task. See http://ant.apache.org/manual/javacprops.html#target

Bootstrap: Position of dropdown menu relative to navbar item

This is the effect that we're trying to achieve:

A right-aligned menu

The classes that need to be applied changed with the release of Bootstrap 3.1.0 and again with the release of Bootstrap 4. If one of the below solutions doesn't seem to be working double check the version number of Bootstrap that you're importing and try a different one.

Bootstrap 3

Before v3.1.0

You can use the pull-right class to line the right hand side of the menu up with the caret:

<li class="dropdown">
  <a class="dropdown-toggle" href="#">Link</a>
  <ul class="dropdown-menu pull-right">
     <li>...</li>
  </ul>
</li>

Fiddle: http://jsfiddle.net/joeczucha/ewzafdju/

After v3.1.0

As of v3.1.0, we've deprecated .pull-right on dropdown menus. To right-align a menu, use .dropdown-menu-right. Right-aligned nav components in the navbar use a mixin version of this class to automatically align the menu. To override it, use .dropdown-menu-left.

You can use the dropdown-right class to line the right hand side of the menu up with the caret:

<li class="dropdown">
  <a class="dropdown-toggle" href="#">Link</a>
  <ul class="dropdown-menu dropdown-menu-right">
     <li>...</li>
  </ul>
</li>

Fiddle: http://jsfiddle.net/joeczucha/1nrLafxc/

Bootstrap 4

The class for Bootstrap 4 are the same as Bootstrap > 3.1.0, just watch out as the rest of the surrounding markup has changed a little:

<li class="nav-item dropdown">
  <a class="nav-link dropdown-toggle" href="#">
    Link
  </a>
  <div class="dropdown-menu dropdown-menu-right">
    <a class="dropdown-item" href="#">...</a>
  </div>
</li>

Fiddle: https://jsfiddle.net/joeczucha/f8h2tLoc/

Android Studio Image Asset Launcher Icon Background Color

You have two ways:

1) In Background Layer > Scaling, reduce the Resize to 1

enter image description here

and then in Legacy > Legacy Icon set Shape as None

enter image description here


2) in Background Layer > Scaling > Source Asset, you can set an image as a 1x1 pixel (or any size) transparent.png image (you've already created).

enter image description here

and then in Legacy > Legacy Icon set Shape as None

enter image description here

Use of Finalize/Dispose method in C#

Note that any IDisposable implementation should follow the below pattern (IMHO). I developed this pattern based on info from several excellent .NET "gods" the .NET Framework Design Guidelines (note that MSDN does not follow this for some reason!). The .NET Framework Design Guidelines were written by Krzysztof Cwalina (CLR Architect at the time) and Brad Abrams (I believe the CLR Program Manager at the time) and Bill Wagner ([Effective C#] and [More Effective C#] (just take a look for these on Amazon.com:

Note that you should NEVER implement a Finalizer unless your class directly contains (not inherits) UNmanaged resources. Once you implement a Finalizer in a class, even if it is never called, it is guaranteed to live for an extra collection. It is automatically placed on the Finalization Queue (which runs on a single thread). Also, one very important note...all code executed within a Finalizer (should you need to implement one) MUST be thread-safe AND exception-safe! BAD things will happen otherwise...(i.e. undetermined behavior and in the case of an exception, a fatal unrecoverable application crash).

The pattern I've put together (and written a code snippet for) follows:

#region IDisposable implementation

//TODO remember to make this class inherit from IDisposable -> $className$ : IDisposable

// Default initialization for a bool is 'false'
private bool IsDisposed { get; set; }

/// <summary>
/// Implementation of Dispose according to .NET Framework Design Guidelines.
/// </summary>
/// <remarks>Do not make this method virtual.
/// A derived class should not be able to override this method.
/// </remarks>
public void Dispose()
{
    Dispose( true );

    // This object will be cleaned up by the Dispose method.
    // Therefore, you should call GC.SupressFinalize to
    // take this object off the finalization queue 
    // and prevent finalization code for this object
    // from executing a second time.

    // Always use SuppressFinalize() in case a subclass
    // of this type implements a finalizer.
    GC.SuppressFinalize( this );
}

/// <summary>
/// Overloaded Implementation of Dispose.
/// </summary>
/// <param name="isDisposing"></param>
/// <remarks>
/// <para><list type="bulleted">Dispose(bool isDisposing) executes in two distinct scenarios.
/// <item>If <paramref name="isDisposing"/> equals true, the method has been called directly
/// or indirectly by a user's code. Managed and unmanaged resources
/// can be disposed.</item>
/// <item>If <paramref name="isDisposing"/> equals false, the method has been called by the 
/// runtime from inside the finalizer and you should not reference 
/// other objects. Only unmanaged resources can be disposed.</item></list></para>
/// </remarks>
protected virtual void Dispose( bool isDisposing )
{
    // TODO If you need thread safety, use a lock around these 
    // operations, as well as in your methods that use the resource.
    try
    {
        if( !this.IsDisposed )
        {
            if( isDisposing )
            {
                // TODO Release all managed resources here

                $end$
            }

            // TODO Release all unmanaged resources here



            // TODO explicitly set root references to null to expressly tell the GarbageCollector
            // that the resources have been disposed of and its ok to release the memory allocated for them.


        }
    }
    finally
    {
        // explicitly call the base class Dispose implementation
        base.Dispose( isDisposing );

        this.IsDisposed = true;
    }
}

//TODO Uncomment this code if this class will contain members which are UNmanaged
// 
///// <summary>Finalizer for $className$</summary>
///// <remarks>This finalizer will run only if the Dispose method does not get called.
///// It gives your base class the opportunity to finalize.
///// DO NOT provide finalizers in types derived from this class.
///// All code executed within a Finalizer MUST be thread-safe!</remarks>
//  ~$className$()
//  {
//     Dispose( false );
//  }
#endregion IDisposable implementation

Here is the code for implementing IDisposable in a derived class. Note that you do not need to explicitly list inheritance from IDisposable in the definition of the derived class.

public DerivedClass : BaseClass, IDisposable (remove the IDisposable because it is inherited from BaseClass)


protected override void Dispose( bool isDisposing )
{
    try
    {
        if ( !this.IsDisposed )
        {
            if ( isDisposing )
            {
                // Release all managed resources here

            }
        }
    }
    finally
    {
        // explicitly call the base class Dispose implementation
        base.Dispose( isDisposing );
    }
}

I've posted this implementation on my blog at: How to Properly Implement the Dispose Pattern

Change package name for Android in React Native

The init script generates a unique identifier for Android based on the name you gave it (e.g. com.acmeapp for AcmeApp).

You can see what name was generated by looking for the applicationId key in android/app/build.gradle.

If you need to change that unique identifier, do it now as described below:

In the /android folder, replace all occurrences of com.acmeapp by com.acme.app

Then change the directory structure with the following commands:

mkdir android/app/src/main/java/com/acme

mv android/app/src/main/java/com/acmeapp android/app/src/main/java/com/acme/app

You need a folder level for each dot in the app identifier.

Source: https://blog.elao.com/en/dev/from-react-native-init-to-app-stores-real-quick/

You need to use a Theme.AppCompat theme (or descendant) with this activity

Change the theme of the desired Activity. This works for me:

<activity
            android:name="HomeActivity"
            android:screenOrientation="landscape"
            android:theme="@style/Theme.AppCompat.Light"
            android:windowSoftInputMode="stateHidden" />

How do I install cURL on cygwin?

If you don't see a certain package, you can access to a full list of ports (also unnoficials, the packages you see on the web) launching the setup.exe with -k argument with value http://cygwinports.org/ports.gpg (example: C:\cygwin\setup\setup-x86.exe -K http://cygwinports.org/ports.gpg).

Doing so, you can choose a lot of extra packages, also extra versions of cURL (compat one). I do that to get Apache, cUrl, php5, php5-curl and some others :)

I don't know if apt-cyg can get those extra packages.

Declare variable in table valued function

There are two flavors of table valued functions. One that is just a select statement and one that can have more rows than just a select statement.

This can not have a variable:

create function Func() returns table
as
return
select 10 as ColName

You have to do like this instead:

create function Func()
returns @T table(ColName int)
as
begin
  declare @Var int
  set @Var = 10
  insert into @T(ColName) values (@Var)
  return
end

Convert number of minutes into hours & minutes using PHP

You can achieve this with DateTime extension, which will also work for number of minutes that is larger than one day (>= 1440):

$minutes = 250;
$zero    = new DateTime('@0');
$offset  = new DateTime('@' . $minutes * 60);
$diff    = $zero->diff($offset);
echo $diff->format('%a Days, %h Hours, %i Minutes');

demo

nodeJS - How to create and read session with express

I forgot to tell a bug when i use I use req.session.email = req.param('email'), the server error says cannot sett property email of undefined.

The reason of this error is a wrong order of app.use. You must configure express in this order:

app.use(express.cookieParser());
app.use(express.session({ secret: sessionVal }));
app.use(app.route);

Git push requires username and password

You need to perform two steps -

  1. git remote remove origin
  2. git remote add origin [email protected]:NuggetAI/nugget.git

Notice the Git URL is a SSH URL and not an HTTPS URL... Which you can select from here:

Enter image description here

JIRA JQL searching by date - is there a way of getting Today() (Date) instead of Now() (DateTime)

We're using Jira 6.2 and I use this query:

updatedDate > startOfDay(-1d) AND updatedDate < endOfDay(-1)

to return all of the issues that were updated from the previous day. You can combine with whichever queries you want to return the appropriate issues for the previous day.

Matplotlib legends in subplot

This should work:

ax1.plot(xtr, color='r', label='HHZ 1')
ax1.legend(loc="upper right")
ax2.plot(xtr, color='r', label='HHN')
ax2.legend(loc="upper right")
ax3.plot(xtr, color='r', label='HHE')
ax3.legend(loc="upper right")

Parser Error: '_Default' is not allowed here because it does not extend class 'System.Web.UI.Page' & MasterType declaration

Remember.. inherits is case sensitive for C# (not so for vb.net)

Found that out the hard way.

Using FolderBrowserDialog in WPF application

You need to add a reference to System.Windows.Forms.dll, then use the System.Windows.Forms.FolderBrowserDialog class.

Adding using WinForms = System.Windows.Forms; will be helpful.

The value violated the integrity constraints for the column

It usually happens when Allow Nulls option is unchecked.

Solution:

  1. Look at the name of the column for this error/warning.
  2. Go to SSMS and find the table
  3. Allow Null for that Column
  4. Save the table
  5. Rerun the SSIS

Try these steps. It worked for me.

See this link

how to set background image in submit button?

Typically one would use one (or more) image tags, maybe in combination with setting div background images in css to act as the submit button. The actual submit would be done in javascript on the click event.

A tutorial on the subject.

Twitter Bootstrap Datepicker within modal window

Try to change z-index value for .modal and .modal-backdrop less than .datepicker z-index value.

How to know Laravel version and where is it defined?

You can also check with composer:

composer show laravel/framework

Android Completely transparent Status Bar?

I found fiddling with styles.xml and activity to be too cumbersome hence created a common utility method which has below options set

Java

Window window = getWindow();
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
window.setStatusBarColor(Color.TRANSPARENT);

Kotlin DSL

activity.window.apply {
    clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
    addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
    decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
    statusBarColor = Color.TRANSPARENT
}

And that's all it took to achieve transparent status bar. Hope this helps.

Temporary table in SQL server causing ' There is already an object named' error

In Azure Data warehouse also this occurs sometimes, because temporary tables created for a user session.. I got the same issue fixed by reconnecting the database,

webpack command not working

Installing webpack with -g option installs webpack in a folder in

C:\Users\<.profileusername.>\AppData\Roaming\npm\node_modules

same with webpack-cli and webpack-dev-server

Outside the global node_modules a link is created for webpack to be run from commandline

C:\Users\<.profileusername.>\AppData\Roaming\npm

to make this work locally, I did the following

  1. renamed the webpack folder in global node_modules to _old
  2. installed webpack locally within project
  3. edited the command link webpack.cmd and pointed the webpack.js to look into my local node_modules folder within my application

Problem with this approach is you'd have to maintain links for each project you have. Theres no other way since you are using the command line editor to run webpack command when installing with a -g option.

So if you had proj1, proj2 and proj3 all with their local node_modules and local webpack installed( not using -g when installing), then you'd have to create non-generic link names instead of just webpack.

example here would be to create webpack_proj1.cmd, webpack_proj2.cmd and webpack_proj3.cmd and in each cmd follow point 2 and 3 above

PS: dont forget to update your package.json with these changes or else you'll get errors as it won't find webpack command

Error: org.testng.TestNGException: Cannot find class in classpath: EmpClass

Let me share what worked for me:

  1. When we do "mvn clean" - we are cleaning old compiled classes please lgo to ocation "your project directroy -> target " you will find this folder is getting cleaned because that's where MVN places it's compiled artifacts

  2. Since it's already a MAVEN project then go to your project folder and open in command prompt. And issue "mvn clean" and then "mvn test" -> "mvn test" command will place all the compiled files under proper folders and then you can run your tests through TestNG or MAVEN itself.

  3. Make sure you set up "M2_HOME" or "MAVEN_HOME" to your env path , sometime "MAVEN_HOME" doesn't work so add "M2_HOME" as well (google it for this set up)

Above suggestions worked for me so I wanted to share, good luck

Installing jdk8 on ubuntu- "unable to locate package" update doesn't fix

Ubuntu defaults to the OpenJDK packages. If you want to install Oracle's JDK, then you need to visit their download page, and grab the package from there.

Once you've installed the Oracle JDK, you also need to update the following (system defaults will point to OpenJDK):

export JAVA_HOME=/my/path/to/oracle/jdk
export PATH=$JAVA_HOME/bin:$PATH

If you want the Oracle JDK to be the default for your system, you will need to remove the OpenJDK packages, and update your profile environment variables.

Authentication plugin 'caching_sha2_password' is not supported

Please install below command using command prompt.

pip install mysql-connector-python

enter image description here

How can I display a JavaScript object?

It will not work in a browser and you might only need this in case you want to get valid JS representation for your object and not a JSON. It just runs node inline evaluation

var execSync = require('child_process').execSync

const objectToSource = (obj) =>
  execSync('node -e \'console.log(JSON.parse(`' + JSON.stringify(obj) + '`))\'', { encoding: 'utf8' })

console.log(objectToSource({ a: 1 }))

What does href expression <a href="javascript:;"></a> do?

It is a way of making a link do absolutely nothing when clicked (unless Javascript events are bound to it).

It is a way of running Javascript instead of following a link:

<a href="Javascript: doStuff();">link</a>

When there isn't actually javascript to run (like your example) it does nothing.

Append Char To String in C?

If Linux is your concern, the easiest way to append two strings:

char * append(char * string1, char * string2)
{
    char * result = NULL;
    asprintf(&result, "%s%s", string1, string2);
    return result;
}

This won't work with MS Visual C.

Note: you have to free() the memory returned by asprintf()

PostgreSQL: Drop PostgreSQL database through command line

When it says users are connected, what does the query "select * from pg_stat_activity;" say? Are the other users besides yourself now connected? If so, you might have to edit your pg_hba.conf file to reject connections from other users, or shut down whatever app is accessing the pg database to be able to drop it. I have this problem on occasion in production. Set pg_hba.conf to have a two lines like this:

local   all         all                               ident
host    all         all         127.0.0.1/32          reject

and tell pgsql to reload or restart (i.e. either sudo /etc/init.d/postgresql reload or pg_ctl reload) and now the only way to connect to your machine is via local sockets. I'm assuming you're on linux. If not this may need to be tweaked to something other than local / ident on that first line, to something like host ... yourusername.

Now you should be able to do:

psql postgres
drop database mydatabase;

C# : Converting Base Class to Child Class

You can copy value of Parent Class to a Child class. For instance, you could use reflection if that is the case.