Programs & Examples On #Accounts

How to implement a simple scenario the OO way

The Chapter object should have reference to the book it came from so I would suggest something like chapter.getBook().getTitle();

Your database table structure should have a books table and a chapters table with columns like:

books

  • id
  • book specific info
  • etc

chapters

  • id
  • book_id
  • chapter specific info
  • etc

Then to reduce the number of queries use a join table in your search query.

Implement specialization in ER diagram

So I assume your permissions table has a foreign key reference to admin_accounts table. If so because of referential integrity you will only be able to add permissions for account ids exsiting in the admin accounts table. Which also means that you wont be able to enter a user_account_id [assuming there are no duplicates!]

Subtracting 1 day from a timestamp date

Use the INTERVAL type to it. E.g:

--yesterday
SELECT NOW() - INTERVAL '1 DAY';

--Unrelated to the question, but PostgreSQL also supports some shortcuts:
SELECT 'yesterday'::TIMESTAMP, 'tomorrow'::TIMESTAMP, 'allballs'::TIME;

Then you can do the following on your query:

SELECT 
    org_id,
    count(accounts) AS COUNT,
    ((date_at) - INTERVAL '1 DAY') AS dateat
FROM 
    sourcetable
WHERE 
    date_at <= now() - INTERVAL '130 DAYS'
GROUP BY 
    org_id,
    dateat;


TIPS

Tip 1

You can append multiple operands. E.g.: how to get last day of current month?

SELECT date_trunc('MONTH', CURRENT_DATE) + INTERVAL '1 MONTH - 1 DAY';

Tip 2

You can also create an interval using make_interval function, useful when you need to create it at runtime (not using literals):

SELECT make_interval(days => 10 + 2);
SELECT make_interval(days => 1, hours => 2);
SELECT make_interval(0, 1, 0, 5, 0, 0, 0.0);


More info:

Date/Time Functions and Operators

datatype-datetime (Especial values).

Django - Reverse for '' not found. '' is not a valid view function or pattern name

Add store name to template like {% url 'app_name:url_name' %}

App_name = store

In urls.py, path('search', views.searched, name="searched"),

<form action="{% url 'store:searched' %}" method="POST">

How to send authorization header with axios

Install the cors middleware. We were trying to solve it with our own code, but all attempts failed miserably.

This made it work:

cors = require('cors')
app.use(cors());

Original link

How to create roles in ASP.NET Core and assign them to users?

The following code will work ISA.

    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, 
        IServiceProvider serviceProvider)
    {
        loggerFactory.AddConsole(Configuration.GetSection("Logging"));
        loggerFactory.AddDebug();

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseDatabaseErrorPage();
            app.UseBrowserLink();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
        }

        app.UseStaticFiles();

        app.UseIdentity();

        // Add external authentication middleware below. To configure them please see https://go.microsoft.com/fwlink/?LinkID=532715

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });

        CreateRolesAndAdminUser(serviceProvider);
    }

    private static void CreateRolesAndAdminUser(IServiceProvider serviceProvider)
    {
        const string adminRoleName = "Administrator";
        string[] roleNames = { adminRoleName, "Manager", "Member" };

        foreach (string roleName in roleNames)
        {
            CreateRole(serviceProvider, roleName);
        }

        // Get these value from "appsettings.json" file.
        string adminUserEmail = "[email protected]";
        string adminPwd = "_AStrongP1@ssword!";
        AddUserToRole(serviceProvider, adminUserEmail, adminPwd, adminRoleName);
    }

    /// <summary>
    /// Create a role if not exists.
    /// </summary>
    /// <param name="serviceProvider">Service Provider</param>
    /// <param name="roleName">Role Name</param>
    private static void CreateRole(IServiceProvider serviceProvider, string roleName)
    {
        var roleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole>>();

        Task<bool> roleExists = roleManager.RoleExistsAsync(roleName);
        roleExists.Wait();

        if (!roleExists.Result)
        {
            Task<IdentityResult> roleResult = roleManager.CreateAsync(new IdentityRole(roleName));
            roleResult.Wait();
        }
    }

    /// <summary>
    /// Add user to a role if the user exists, otherwise, create the user and adds him to the role.
    /// </summary>
    /// <param name="serviceProvider">Service Provider</param>
    /// <param name="userEmail">User Email</param>
    /// <param name="userPwd">User Password. Used to create the user if not exists.</param>
    /// <param name="roleName">Role Name</param>
    private static void AddUserToRole(IServiceProvider serviceProvider, string userEmail, 
        string userPwd, string roleName)
    {
        var userManager = serviceProvider.GetRequiredService<UserManager<ApplicationUser>>();

        Task<ApplicationUser> checkAppUser = userManager.FindByEmailAsync(userEmail);
        checkAppUser.Wait();

        ApplicationUser appUser = checkAppUser.Result;

        if (checkAppUser.Result == null)
        {
            ApplicationUser newAppUser = new ApplicationUser
            {
                Email = userEmail,
                UserName = userEmail
            };

            Task<IdentityResult> taskCreateAppUser = userManager.CreateAsync(newAppUser, userPwd);
            taskCreateAppUser.Wait();

            if (taskCreateAppUser.Result.Succeeded)
            {
                appUser = newAppUser;
            }
        }

        Task<IdentityResult> newUserRole = userManager.AddToRoleAsync(appUser, roleName);
        newUserRole.Wait();
    }

How to use Apple's new .p8 certificate for APNs in firebase console

When you upload your p8 file in Firebase, in the box that reads App ID Prefix(required) , you should enter your team ID. You can get it from https://developer.apple.com/account/#/membership and copy/paste the Team ID as shown below.

enter image description here

Firebase cloud messaging notification not received by device

You need to Follow Below Manifest Code (must have Service in manifest)

 <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="soapusingretrofitvolley.firebase">
        <uses-permission android:name="android.permission.INTERNET"/>
        <application
            android:allowBackup="true"
            android:icon="@mipmap/ic_launcher"
            android:label="@string/app_name"
            android:supportsRtl="true"
            android:theme="@style/AppTheme">
            <activity android:name=".MainActivity">
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />

                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>

            <service
                android:name=".MyFirebaseMessagingService">
                <intent-filter>
                    <action android:name="com.google.firebase.MESSAGING_EVENT"/>
                </intent-filter>
            </service>

            <service
                android:name=".MyFirebaseInstanceIDService">
                <intent-filter>
                    <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
                </intent-filter>
            </service>
        </application>

    </manifest>

Facebook login message: "URL Blocked: This redirect failed because the redirect URI is not whitelisted in the app’s Client OAuth Settings."

For my Node Application,

"facebook": {
        "clientID" : "##############",
        "clientSecret": "####################",
        "callbackURL": "/auth/facebook/callback/"
    }

put callback Url relative

My OAuth redirect URIs as follows

enter image description here

Make Sure "/" at the end of Facebook auth redirect URI

These setups worked for me.

How to reset the state of a Redux store?

I've created a component to give Redux the ability of resetting state, you just need to use this component to enhance your store and dispatch a specific action.type to trigger reset. The thought of implementation is same as what @Dan Abramov said.

Github: https://github.com/wwayne/redux-reset

Can't push image to Amazon ECR - fails with "no basic auth credentials"

Update

Since AWS CLI version 2 - aws ecr get-login is deprecated and the correct method is aws ecr get-login-password.

Therefore the correct and updated answer is the following: docker login -u AWS -p $(aws ecr get-login-password --region us-east-1) xxxxxxxx.dkr.ecr.us-east-1.amazonaws.com

Xcode 7 error: "Missing iOS Distribution signing identity for ..."

I removed old AppleWWDRCA, downloaded and installed AppleWWDRCA, but problem remained. I also, checked my distribution and development certificates from Keychain Access, and see below error;

"This certificate has an invalid issuer."

Then,

  1. I revoked both development and distribution certificates on member center.
  2. Re-created CSR file and add development and distribution certificates from zero, downloaded them, and installed.

This fixed certificate problem.

Since old certificates revoked, existing provisioning profiles become invalid. To fix this;

  1. On member center, opened provisioning profiles.
  2. Opened profile detail by clicking "Edit", checked certificate from the list, and clicked "Generate" button.
  3. Downloaded and installed both development and distribution profiles.

I hope this helps.

Neither user 10102 nor current process has android.permission.READ_PHONE_STATE

Are you running Android M? If so, this is because it's not enough to declare permissions in the manifest. For some permissions, you have to explicitly ask user in the runtime: http://developer.android.com/training/permissions/requesting.html

How to define partitioning of DataFrame?

I was able to do this using RDD. But I don't know if this is an acceptable solution for you. Once you have the DF available as an RDD, you can apply repartitionAndSortWithinPartitions to perform custom repartitioning of data.

Here is a sample I used:

class DatePartitioner(partitions: Int) extends Partitioner {

  override def getPartition(key: Any): Int = {
    val start_time: Long = key.asInstanceOf[Long]
    Objects.hash(Array(start_time)) % partitions
  }

  override def numPartitions: Int = partitions
}

myRDD
  .repartitionAndSortWithinPartitions(new DatePartitioner(24))
  .map { v => v._2 }
  .toDF()
  .write.mode(SaveMode.Overwrite)

java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to com.testing.models.Account

Solve problem with two method parse common

  1. Whith type is an object
public <T> T jsonToObject(String json, Class<T> type) {
        T target = null;
        try {
            target = objectMapper.readValue(json, type);
        } catch (Jsenter code hereonProcessingException e) {
            e.printStackTrace();
        }
    
        return target;
    }
  1. With type is collection wrap object
public <T> T jsonToObject(String json, TypeReference<T> type) {
    T target = null;
    try {
        target = objectMapper.readValue(json, type);
    } catch (JsonProcessingException e) {
        e.printStackTrace();
    }
    return target;
}

How does the Spring @ResponseBody annotation work?

First of all, the annotation doesn't annotate List. It annotates the method, just as RequestMapping does. Your code is equivalent to

@RequestMapping(value="/orders", method=RequestMethod.GET)
@ResponseBody
public List<Account> accountSummary() {
    return accountManager.getAllAccounts();
}

Now what the annotation means is that the returned value of the method will constitute the body of the HTTP response. Of course, an HTTP response can't contain Java objects. So this list of accounts is transformed to a format suitable for REST applications, typically JSON or XML.

The choice of the format depends on the installed message converters, on the values of the produces attribute of the @RequestMapping annotation, and on the content type that the client accepts (that is available in the HTTP request headers). For example, if the request says it accepts XML, but not JSON, and there is a message converter installed that can transform the list to XML, then XML will be returned.

EntityType 'IdentityUserLogin' has no key defined. Define the key for this EntityType

In my case I had inherited from the IdentityDbContext correctly (with my own custom types and key defined) but had inadvertantly removed the call to the base class's OnModelCreating:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder); // I had removed this
    /// Rest of on model creating here.
}

Which then fixed up my missing indexes from the identity classes and I could then generate migrations and enable migrations appropriately.

Laravel Update Query

$update = \DB::table('student') ->where('id', $data['id']) ->limit(1) ->update( [ 'name' => $data['name'], 'address' => $data['address'], 'email' => $data['email'], 'contactno' => $data['contactno'] ]); 

INSTALL_FAILED_DUPLICATE_PERMISSION... C2D_MESSAGE

In my case I received following error

Installation error: INSTALL_FAILED_DUPLICATE_PERMISSION perm=com.map.permission.MAPS_RECEIVE pkg=com.abc.Firstapp

When I was trying to install the app which have package name com.abc.Secondapp. Here point was that app with package name com.abc.Firstapp was already installed in my application.

I resolved this error by uninstalling the application with package name com.abc.Firstapp and then installing the application with package name com.abc.Secondapp

I hope this will help someone while testing.

How can I verify if an AD account is locked?

Here's another one:

PS> Search-ADAccount -Locked | Select Name, LockedOut, LastLogonDate

Name                                       LockedOut LastLogonDate
----                                       --------- -------------
Yxxxxxxx                                        True 14/11/2014 10:19:20
Bxxxxxxx                                        True 18/11/2014 08:38:34
Administrator                                   True 03/11/2014 20:32:05

Other parameters worth mentioning:

Search-ADAccount -AccountExpired
Search-ADAccount -AccountDisabled
Search-ADAccount -AccountInactive

Get-Help Search-ADAccount -ShowWindow

SMTPAuthenticationError when sending mail using gmail and python

Your code looks correct. Try logging in through your browser and if you are able to access your account come back and try your code again. Just make sure that you have typed your username and password correct

EDIT: Google blocks sign-in attempts from apps which do not use modern security standards (mentioned on their support page). You can however, turn on/off this safety feature by going to the link below:

Go to this link and select Turn On
https://www.google.com/settings/security/lesssecureapps

'NOT NULL constraint failed' after adding to models.py

if the zipcode field is not a required field then add null=True and blank=True, then run makemigrations and migrate command to successfully reflect the changes in the database.

Django 1.7 - "No migrations to apply" when run migrate after makemigrations

Maybe your model not linked when migration process is ongoing. Try to import it in file urls.py from models import your_file

Adding asterisk to required fields in Bootstrap 3

Assuming this is what the HTML looks like

<div class="form-group required">
   <label class="col-md-2 control-label">E-mail</label>
   <div class="col-md-4"><input class="form-control" id="id_email" name="email" placeholder="E-mail" required="required" title="" type="email" /></div>
</div>

To display an asterisk on the right of the label:

.form-group.required .control-label:after { 
    color: #d00;
    content: "*";
    position: absolute;
    margin-left: 8px;
    top:7px;
}

Or to the left of the label:

.form-group.required .control-label:before{
   color: red;
   content: "*";
   position: absolute;
   margin-left: -15px;
}

To make a nice big red asterisks you can add these lines:

font-family: 'Glyphicons Halflings';
font-weight: normal;
font-size: 14px;

Or if you are using Font Awesome add these lines (and change the content line):

font-family: 'FontAwesome';
font-weight: normal;
font-size: 14px;
content: "\f069";

535-5.7.8 Username and Password not accepted

In my case removing 2 factor authentication solves my problem.

"The underlying connection was closed: An unexpected error occurred on a send." With SSL Certificate

We had this issue whereby a website that was accessing our API was getting the “The underlying connection was closed: An unexpected error occurred on a send.” message.

Their code was a mix of .NET 3.x and 2.2, which as I understand it means they are using TLS 1.0.

The answer below can help you diagnose the issue by enabling TLS 1.0, SSL 2 and SSL3, but to be very clear, you do not want to do that long-term as all three of those protocols are regarded as insecure and should no longer be used:

To get our IIS to respond to their API calls we had to add registry settings on the IIS's server to explicitly enable versions of TLS - NOTE: You have to restart the Windows server (not just the IIS service) after making these changes:

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS
1.0\Client] "DisabledByDefault"=dword:00000000 "Enabled"=dword:00000001

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS
1.0\Server] "DisabledByDefault"=dword:00000000 "Enabled"=dword:00000001

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS
1.1\Client] "DisabledByDefault"=dword:00000000 "Enabled"=dword:00000001

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS
1.1\Server] "DisabledByDefault"=dword:00000000 "Enabled"=dword:00000001

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS
1.2\Client] "DisabledByDefault"=dword:00000000 "Enabled"=dword:00000001

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS
1.2\Server] "DisabledByDefault"=dword:00000000 "Enabled"=dword:00000001

If that doesn't do it, you could also experiment with adding the entry for SSL 2.0:

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\SSL 2.0\Client]
"DisabledByDefault"=dword:00000000
"Enabled"=dword:00000001

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\SSL 2.0\Server]
"DisabledByDefault"=dword:00000000
"Enabled"=dword:00000001

To be clear, this is not a nice solution, and the right solution is to get the caller to use TLS 1.2, but the above can help diagnose that this is the issue.

You can speed adding those reg entries up with this powershell script:

$ProtocolList       = @("SSL 2.0","SSL 3.0","TLS 1.0", "TLS 1.1", "TLS 1.2")
$ProtocolSubKeyList = @("Client", "Server")
$DisabledByDefault = "DisabledByDefault"
$Enabled = "Enabled"
$registryPath = "HKLM:\\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\"

foreach($Protocol in $ProtocolList)
{
    Write-Host " In 1st For loop"
        foreach($key in $ProtocolSubKeyList)
        {         
            $currentRegPath = $registryPath + $Protocol + "\" + $key
            Write-Host " Current Registry Path $currentRegPath"
            if(!(Test-Path $currentRegPath))
            {
                Write-Host "creating the registry"
                    New-Item -Path $currentRegPath -Force | out-Null             
            }
            Write-Host "Adding protocol"
                New-ItemProperty -Path $currentRegPath -Name $DisabledByDefault -Value "0" -PropertyType DWORD -Force | Out-Null
                New-ItemProperty -Path $currentRegPath -Name $Enabled -Value "1" -PropertyType DWORD -Force | Out-Null    
    }
}
 
Exit 0

That's a modified version of the script from the Microsoft help page for Set up TLS for VMM. This basics.net article was the page that originally gave me the idea to look at these settings.

Google OAUTH: The redirect URI in the request did not match a registered redirect URI

I was able to get mine working using the following Client Credentials:

Authorized JavaScript origins

http://localhost

Authorized redirect URIs

http://localhost:8090/oauth2callback

Note: I used port 8090 instead of 8080, but that doesn't matter as long as your python script uses the same port as your client_secret.json file.

Reference: Python Quickstart

Conditionally formatting if multiple cells are blank (no numerics throughout spreadsheet )

enter image description here

How about just > Format only cells that contain - in the drop down box select Blanks

How does Facebook disable the browser's integrated Developer Tools?

This is not a security measure for weak code to be left unattended. Always get a permanent solution to weak code and secure your websites properly before implementing this strategy

The best tool by far according to my knowledge would be to add multiple javascript files that simply changes the integrity of the page back to normal by refreshing or replacing content. Disabling this developer tool would not be the greatest idea since bypassing is always in question since the code is part of the browser and not a server rendering, thus it could be cracked.

Should you have js file one checking for <element> changes on important elements and js file two and js file three checking that this file exists per period you will have full integrity restore on the page within the period.

Lets take an example of the 4 files and show you what I mean.

index.html

   <!DOCTYPE html>
   <html>
   <head id="mainhead">
   <script src="ks.js" id="ksjs"></script>
   <script src="mainfile.js" id="mainjs"></script>
   <link rel="stylesheet" href="style.css" id="style">
   <meta id="meta1" name="description" content="Proper mitigation against script kiddies via Javascript" >
   </head>
   <body>
   <h1 id="heading" name="dontdel" value="2">Delete this from console and it will refresh. If you change the name attribute in this it will also refresh. This is mitigating an attack on attribute change via console to exploit vulnerabilities. You can even try and change the value attribute from 2 to anything you like. If This script says it is 2 it should be 2 or it will refresh. </h1>
   <h3>Deleting this wont refresh the page due to it having no integrity check on it</h3>

   <p>You can also add this type of error checking on meta tags and add one script out of the head tag to check for changes in the head tag. You can add many js files to ensure an attacker cannot delete all in the second it takes to refresh. Be creative and make this your own as your website needs it. 
   </p>

   <p>This is not the end of it since we can still enter any tag to load anything from everywhere (Dependent on headers etc) but we want to prevent the important ones like an override in meta tags that load headers. The console is designed to edit html but that could add potential html that is dangerous. You should not be able to enter any meta tags into this document unless it is as specified by the ks.js file as permissable. <br>This is not only possible with meta tags but you can do this for important tags like input and script. This is not a replacement for headers!!! Add your headers aswell and protect them with this method.</p>
   </body>
   <script src="ps.js" id="psjs"></script>
   </html>

mainfile.js

   setInterval(function() {
   // check for existence of other scripts. This part will go in all other files to check for this file aswell. 
   var ksExists = document.getElementById("ksjs"); 
   if(ksExists) {
   }else{ location.reload();};

   var psExists = document.getElementById("psjs");
   if(psExists) {
   }else{ location.reload();};

   var styleExists = document.getElementById("style");
   if(styleExists) {
   }else{ location.reload();};


   }, 1 * 1000); // 1 * 1000 milsec

ps.js

   /*This script checks if mainjs exists as an element. If main js is not existent as an id in the html file reload!You can add this to all js files to ensure that your page integrity is perfect every second. If the page integrity is bad it reloads the page automatically and the process is restarted. This will blind an attacker as he has one second to disable every javascript file in your system which is impossible.

   */

   setInterval(function() {
   // check for existence of other scripts. This part will go in all other files to check for this file aswell. 
   var mainExists = document.getElementById("mainjs"); 
   if(mainExists) {
   }else{ location.reload();};

   //check that heading with id exists and name tag is dontdel.
   var headingExists = document.getElementById("heading"); 
   if(headingExists) {
   }else{ location.reload();};
   var integrityHeading = headingExists.getAttribute('name');
   if(integrityHeading == 'dontdel') {
   }else{ location.reload();};
   var integrity2Heading = headingExists.getAttribute('value');
   if(integrity2Heading == '2') {
   }else{ location.reload();};
   //check that all meta tags stay there
   var meta1Exists = document.getElementById("meta1"); 
   if(meta1Exists) {
   }else{ location.reload();};

   var headExists = document.getElementById("mainhead"); 
   if(headExists) {
   }else{ location.reload();};

   }, 1 * 1000); // 1 * 1000 milsec

ks.js

   /*This script checks if mainjs exists as an element. If main js is not existent as an id in the html file reload! You can add this to all js files to ensure that your page integrity is perfect every second. If the page integrity is bad it reloads the page automatically and the process is restarted. This will blind an attacker as he has one second to disable every javascript file in your system which is impossible.

   */

   setInterval(function() {
   // check for existence of other scripts. This part will go in all other files to check for this file aswell. 
   var mainExists = document.getElementById("mainjs"); 
   if(mainExists) {
   }else{ location.reload();};
   //Check meta tag 1 for content changes. meta1 will always be 0. This you do for each meta on the page to ensure content credibility. No one will change a meta and get away with it. Addition of a meta in spot 10, say a meta after the id="meta10" should also be covered as below.
   var x = document.getElementsByTagName("meta")[0];
   var p = x.getAttribute("name");
   var s = x.getAttribute("content");
   if (p != 'description') {
   location.reload();
   }
   if ( s != 'Proper mitigation against script kiddies via Javascript') {
   location.reload();
   }
   // This will prevent a meta tag after this meta tag @ id="meta1". This prevents new meta tags from being added to your pages. This can be used for scripts or any tag you feel is needed to do integrity check on like inputs and scripts. (Yet again. It is not a replacement for headers to be added. Add your headers aswell!)
   var lastMeta = document.getElementsByTagName("meta")[1];
   if (lastMeta) {
   location.reload();
   }
   }, 1 * 1000); // 1 * 1000 milsec

style.css

Now this is just to show it works on all files and tags aswell

   #heading {
   background-color:red;
   }

If you put all these files together and build the example you will see the function of this measure. This will prevent some unforseen injections should you implement it correctly on all important elements in your index file especially when working with PHP.

Why I chose reload instead of change back to normal value per attribute is the fact that some attackers could have another part of the website already configured and ready and it lessens code amount. The reload will remove all the attacker's hard work and he will probably go play somewhere easier.

Another note: This could become a lot of code so keep it clean and make sure to add definitions to where they belong to make edits easy in future. Also set the seconds to your preferred amount as 1 second intervals on large pages could have drastic effects on older computers your visitors might be using

Test credit card numbers for use with PayPal sandbox

In case anyone else comes across this in a search for an answer...

The test numbers listed in various places no longer work in the Sandbox. PayPal have the same checks in place now so that a card cannot be linked to more than one account.

Go here and get a number generated. Use any expiry date and CVV

https://ppmts.custhelp.com/app/answers/detail/a_id/750/

It's worked every time for me so far...

MVC 5 Access Claims Identity User Data

This is an alternative if you don't want to use claims all the time. Take a look at this tutorial by Ben Foster.

public class AppUser : ClaimsPrincipal
{
    public AppUser(ClaimsPrincipal principal)
        : base(principal)
    {
    }

    public string Name
    {
        get
        {
            return this.FindFirst(ClaimTypes.Name).Value;
        } 
    }

}

Then you can add a base controller.

public abstract class AppController : Controller
{       
    public AppUser CurrentUser
    {
        get
        {
            return new AppUser(this.User as ClaimsPrincipal);
        }
    }
}

In you controller, you would do:

public class HomeController : AppController
{
    public ActionResult Index()
    {
        ViewBag.Name = CurrentUser.Name;
        return View();
    }
}

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

What worked for me was to activate the option for less secure apps (I am using VB.NET)

Public Shared Sub enviaDB(ByRef body As String, ByRef file_location As String)
        Dim mail As New MailMessage()
        Dim SmtpServer As New SmtpClient("smtp.gmail.com")
        mail.From = New MailAddress("[email protected]")
        mail.[To].Add("[email protected]")
        mail.Subject = "subject"
        mail.Body = body
        Dim attachment As System.Net.Mail.Attachment
        attachment = New System.Net.Mail.Attachment(file_location)
        mail.Attachments.Add(attachment)
        SmtpServer.Port = 587
        SmtpServer.Credentials = New System.Net.NetworkCredential("user", "password")
        SmtpServer.EnableSsl = True
        SmtpServer.Send(mail)
    End Sub

So log in to your account and then go to google.com/settings/security/lesssecureapps

Refused to display in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN'

I was having the same issue implementing in Angular 9. These are the two steps I did:

  1. Change your YouTube URL from https://youtube.com/your_code to https://youtube.com/embed/your_code.

  2. And then pass the URL through DomSanitizer of Angular.

    import { Component, OnInit } from "@angular/core";
    import { DomSanitizer } from '@angular/platform-browser';
    
    @Component({
      selector: "app-help",
      templateUrl: "./help.component.html",
      styleUrls: ["./help.component.scss"],
    })
    export class HelpComponent implements OnInit {
    
      youtubeVideoLink: any = 'https://youtube.com/embed/your_code'
    
      constructor(public sanitizer: DomSanitizer) {
        this.sanitizer = sanitizer;   
      }
    
      ngOnInit(): void {}
    
      getLink(){
        return this.sanitizer.bypassSecurityTrustResourceUrl(this.youtubeVideoLink);
      }
    
    }
    
    <iframe width="420" height="315" [src]="getLink()" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>
    

How to install Google Play Services in a Genymotion VM (with no drag and drop support)?

  1. Download ARM Translation v1.1 and flash it by dragging and dropping over the emulator. Then reboot the emulator.
  2. Go to Open GApps, select x86 architecture, Android version of your emulator and variant (nano is enough, other applications can be installed from Play Store) and download zip archive. Drag and drop this archive to the emulator and flash it. Reboot the emulator.

Import Excel Spreadsheet Data to an EXISTING sql table?

You can use import data with wizard and there you can choose destination table.

Run the wizard. In selecting source tables and views window you see two parts. Source and Destination.

Click on the field under Destination part to open the drop down and select you destination table and edit its mappings if needed.

EDIT

Merely typing the name of the table does not work. It appears that the name of the table must include the schema (dbo) and possibly brackets. Note the dropdown on the right hand side of the text field.

enter image description here

__init__() got an unexpected keyword argument 'user'

LivingRoom.objects.create() calls LivingRoom.__init__() - as you might have noticed if you had read the traceback - passing it the same arguments. To make a long story short, a Django models.Model subclass's initializer is best left alone, or should accept *args and **kwargs matching the model's meta fields. The correct way to provide default values for fields is in the field constructor using the default keyword as explained in the FineManual.

Nodemailer with Gmail and NodeJS

See nodemailer's official guide to connecting Gmail:

https://community.nodemailer.com/using-gmail/

-

It works for me after doing this:

  1. Enable less secure apps - https://www.google.com/settings/security/lesssecureapps
  2. Disable Captcha temporarily so you can connect the new device/server - https://accounts.google.com/b/0/displayunlockcaptcha

Python: No acceptable C compiler found in $PATH when installing python

On Arch Linux run the following:

sudo pacman -S base-devel

Java 8: Lambda-Streams, Filter by Method with Exception

If you don't mind using 3rd party libraries, AOL's cyclops-react lib, disclosure::I am a contributor, has a ExceptionSoftener class that can help here.

 s.filter(softenPredicate(a->a.isActive()));

Wait on the Database Engine recovery handle failed. Check the SQL server error log for potential causes

Below worked for me:

When you come to Server Configuration Screen, Change the Account Name of Database Engine Service to NT AUTHORITY\NETWORK SERVICE and continue installation and it will successfully install all components without any error. - See more at: https://superpctricks.com/sql-install-error-database-engine-recovery-handle-failed/

Difference between Role and GrantedAuthority in Spring Security

Like others have mentioned, I think of roles as containers for more granular permissions.

Although I found the Hierarchy Role implementation to be lacking fine control of these granular permission.
So I created a library to manage the relationships and inject the permissions as granted authorities in the security context.

I may have a set of permissions in the app, something like CREATE, READ, UPDATE, DELETE, that are then associated with the user's Role.

Or more specific permissions like READ_POST, READ_PUBLISHED_POST, CREATE_POST, PUBLISH_POST

These permissions are relatively static, but the relationship of roles to them may be dynamic.

Example -

@Autowired 
RolePermissionsRepository repository;

public void setup(){
  String roleName = "ROLE_ADMIN";
  List<String> permissions = new ArrayList<String>();
  permissions.add("CREATE");
  permissions.add("READ");
  permissions.add("UPDATE");
  permissions.add("DELETE");
  repository.save(new RolePermissions(roleName, permissions));
}

You may create APIs to manage the relationship of these permissions to a role.

I don't want to copy/paste another answer, so here's the link to a more complete explanation on SO.
https://stackoverflow.com/a/60251931/1308685

To re-use my implementation, I created a repo. Please feel free to contribute!
https://github.com/savantly-net/spring-role-permissions

How can I switch my signed in user in Visual Studio 2013?

I faced this issue Many time from different scenarios

one of them when I tryed Connecting to team foundation server for different Logged User

enter image description here

so the solution is easy Just Click Switch User

hope this help you

Is there a way since (iOS 7's release) to get the UDID without using iTunes on a PC/Mac?

If any of your users are running linux they can use this from a terminal:

lsusb -v 2> /dev/null | grep -e "Apple Inc" -A 2

This gets the all the information for your connected usb devices and prints lines with "Apple Inc" including the next 2 lines.

The result looks like this:

iManufacturer           1 Apple Inc.
iProduct                2 iPad
iSerial                 3 7ddf32e17a6ac5ce04a8ecbf782ca509...

This has worked for me on iOS5 -> iOS7, I haven’t tried on any iOS4 devices though.

IMO this is faster then any Win/Mac/Browser solution I have found and requires no "software" installation.

Find provisioning profile in Xcode 5

You can use "iPhone Configuration Utility" to manage provisioning profiles.

How to check if a variable is NULL, then set it with a MySQL stored procedure?

@last_run_time is a 9.4. User-Defined Variables and last_run_time datetime one 13.6.4.1. Local Variable DECLARE Syntax, are different variables.

Try: SELECT last_run_time;

UPDATE

Example:

/* CODE FOR DEMONSTRATION PURPOSES */
DELIMITER $$

CREATE PROCEDURE `sp_test`()
BEGIN
    DECLARE current_procedure_name CHAR(60) DEFAULT 'accounts_general';
    DECLARE last_run_time DATETIME DEFAULT NULL;
    DECLARE current_run_time DATETIME DEFAULT NOW();

    -- Define the last run time
    SET last_run_time := (SELECT MAX(runtime) FROM dynamo.runtimes WHERE procedure_name = current_procedure_name);

    -- if there is no last run time found then use yesterday as starting point
    IF(last_run_time IS NULL) THEN
        SET last_run_time := DATE_SUB(NOW(), INTERVAL 1 DAY);
    END IF;

    SELECT last_run_time;

    -- Insert variables in table2
    INSERT INTO table2 (col0, col1, col2) VALUES (current_procedure_name, last_run_time, current_run_time);
END$$

DELIMITER ;

Parsing Json rest api response in C#

Create a C# class that maps to your Json and use Newsoft JsonConvert to Deserialise it.

For example:

public Class MyResponse
{
    public Meta Meta { get; set; }
    public Response Response { get; set; }
}

How to get current user, and how to use User class in MVC5?

I feel your pain, I'm trying to do the same thing. In my case I just want to clear the user.

I've created a base controller class that all my controllers inherit from. In it I override OnAuthentication and set the filterContext.HttpContext.User to null

That's the best I've managed to far...

public abstract class ApplicationController : Controller   
{
    ...
    protected override void OnAuthentication(AuthenticationContext filterContext)
    {
        base.OnAuthentication(filterContext); 

        if ( ... )
        {
            // You may find that modifying the 
            // filterContext.HttpContext.User 
            // here works as desired. 
            // In my case I just set it to null
            filterContext.HttpContext.User = null;
        }
    }
    ...
}

Why I get 411 Length required error?

Google search

2nd result

System.Net.WebException: The remote server returned an error: (411) Length Required.

This is a pretty common issue that comes up when trying to make call a REST based API method through POST. Luckily, there is a simple fix for this one.

This is the code I was using to call the Windows Azure Management API. This particular API call requires the request method to be set as POST, however there is no information that needs to be sent to the server.

var request = (HttpWebRequest) HttpWebRequest.Create(requestUri);
request.Headers.Add("x-ms-version", "2012-08-01"); request.Method =
"POST"; request.ContentType = "application/xml";

To fix this error, add an explicit content length to your request before making the API call.

request.ContentLength = 0;

How do you install Google frameworks (Play, Accounts, etc.) on a Genymotion virtual device?

If anyone got an error while signing in to Google and this message appear:

Couldn't Sign In
can't establish a reliable connection to the server...

then try to sign in from the browser - in YouTube, Gmail, Google sites, etc.

This helped me. After signing in in the browser I was able to sign in the Google Play app...

SQL Server Creating a temp table for this query

DECLARE #MyTempTable TABLE (SiteName varchar(50), BillingMonth varchar(10), Consumption float)

INSERT INTO #MyTempTable (SiteName, BillingMonth, Consumption)
SELECT  tblMEP_Sites.Name AS SiteName, convert(varchar(10),BillingMonth ,101) AS BillingMonth, SUM(Consumption) AS Consumption
FROM tblMEP_Projects.......  --your joining statements

Here, # - use this to create table inside tempdb
@ - use this to create table as variable.

invalid_client in google oauth2

Steps that worked for me:

  1. Delete credentials that are not working for you
  2. Create new credentials with some NAME
  3. Fill in the same NAME on your OAuth consent screen
  4. Fill in the e-mail address on the OAuth consent screen

The name should be exactly the same.

cURL not working (Error #77) for SSL connections on CentOS for non-root users

Windows users, add this to PHP.ini:

curl.cainfo = "C:/cacert.pem";

Path needs to be changed to your own and you can download cacert.pem from a google search

(yes I know its a CentOS question)

Google drive limit number of download

Sure Google has a limit of downloads so that you don't abuse the system. These are the limits if you are using Gmail:

The following limits apply for Google Apps for Business or Education editions. Limits for domains during trial are lower. These limits may change without notice in order to protect Google’s infrastructure.

Bandwidth limits

Limit                          Per hour            Per day
Download via web client        750 MB              1250 MB
Upload via web client          300 MB              500 MB
POP and IMAP bandwidth limits

Limit                Per day
Download via IMAP    2500 MB
Download via POP     1250 MB
Upload via IMAP      500 MB

check out this link

How to use a ViewBag to create a dropdownlist?

Try:

In the controller:

ViewBag.Accounts= new SelectList(db.Accounts, "AccountId", "AccountName");

In the View:

@Html.DropDownList("AccountId", (IEnumerable<SelectListItem>)ViewBag.Accounts, null, new { @class ="form-control" })

or you can replace the "null" with whatever you want display as default selector, i.e. "Select Account".

How to execute my SQL query in CodeIgniter

    $sql="Select * from my_table where 1";    
    $query = $this->db->query($SQL);
    return $query->result_array();

Twitter Bootstrap Use collapse.js on table cells [Almost Done]

If you're using Angular's ng-repeat to populate the table hackel's jquery snippet will not work by placing it in the document load event. You'll need to run the snippet after angular has finished rendering the table.

To trigger an event after ng-repeat has rendered try this directive:

var app = angular.module('myapp', [])
.directive('onFinishRender', function ($timeout) {
return {
    restrict: 'A',
    link: function (scope, element, attr) {
        if (scope.$last === true) {
            $timeout(function () {
                scope.$emit('ngRepeatFinished');
            });
        }
    }
}
});

Complete example in angular: http://jsfiddle.net/ADukg/6880/

I got the directive from here: Use AngularJS just for routing purposes

Powershell Active Directory - Limiting my get-aduser search to a specific OU [and sub OUs]

If I understand you correctly, you need to use -SearchBase:

Get-ADUser -SearchBase "OU=Accounts,OU=RootOU,DC=ChildDomain,DC=RootDomain,DC=com" -Filter *

Note that Get-ADUser defaults to using

 -SearchScope Subtree

so you don't need to specify it. It's this that gives you all sub-OUs (and sub-sub-OUs, etc.).

Java double.MAX_VALUE?

Resurrecting the dead here, but just in case someone stumbles against this like myself. I know where to get the maximum value of a double, the (more) interesting part was to how did they get to that number.

double has 64 bits. The first one is reserved for the sign.

Next 11 represent the exponent (that is 1023 biased). It's just another way to represent the positive/negative values. If there are 11 bits then the max value is 1023.

Then there are 52 bits that hold the mantissa.

This is easily computed like this for example:

public static void main(String[] args) {

    String test = Strings.repeat("1", 52);

    double first = 0.5;
    double result = 0.0;
    for (char c : test.toCharArray()) {
        result += first;
        first = first / 2;
    }

    System.out.println(result); // close approximation of 1
    System.out.println(Math.pow(2, 1023) * (1 + result));
    System.out.println(Double.MAX_VALUE);

} 

You can also prove this in reverse order :

    String max = "0" + Long.toBinaryString(Double.doubleToLongBits(Double.MAX_VALUE));

    String sign = max.substring(0, 1);
    String exponent = max.substring(1, 12); // 11111111110
    String mantissa = max.substring(12, 64);

    System.out.println(sign); // 0 - positive
    System.out.println(exponent); // 2046 - 1023 = 1023
    System.out.println(mantissa); // 0.99999...8

Error Code 1292 - Truncated incorrect DOUBLE value - Mysql

Had this issue with ES6 and TypeORM while trying to pass .where("order.id IN (:orders)", { orders }), where orders was a comma separated string of numbers. When I converted to a template literal, the problem was resolved.

.where(`order.id IN (${orders})`);

How to get column values in one comma separated value

I think it will be easy to you. I am using group_concat which concatenate diffent values with separator as we have defined

select ID,User, GROUP_CONCAT(Distinct Department order  by Department asc 

separator ', ') as Department from Table_Name   group by ID

How can I populate a select dropdown list from a JSON feed with AngularJS?

In my Angular Bootstrap dropdowns I initialize the JSON Array (vm.zoneDropdown) with ng-init (you can also have ng-init inside the directive template) and I pass the Array in a custom src attribute

<custom-dropdown control-id="zone" label="Zona" model="vm.form.zone" src="vm.zoneDropdown"
                         ng-init="vm.getZoneDropdownSrc()" is-required="true" form="farmaciaForm" css-class="custom-dropdown col-md-3"></custom-dropdown>

Inside the controller:

vm.zoneDropdown = [];
vm.getZoneDropdownSrc = function () {
    vm.zoneDropdown = $customService.getZone();
}

And inside the customDropdown directive template(note that this is only one part of the bootstrap dropdown):

<ul class="uib-dropdown-menu" role="menu" aria-labelledby="btn-append-to-body">
    <li role="menuitem" ng-repeat="dropdownItem in vm.src" ng-click="vm.setValue(dropdownItem)">
        <a ng-click="vm.preventDefault($event)" href="##">{{dropdownItem.text}}</a>
    </li>
</ul>

How do I left align these Bootstrap form items?

Just my two cents. If you are using Bootstrap 3 then I would just add an extra style into your own site's stylesheet which controls the text-left style of the control-label.

If you were to add text-left to the label, by default there is another style which overrides this .form-horizontal .control-label. So if you add:

.form-horizontal .control-label.text-left{
    text-align: left;
}

Then the built in text-left style is applied to the label correctly.

Can a relative sitemap url be used in a robots.txt?

Google crawlers are not smart enough, they can't crawl relative URLs, that's why it's always recommended to use absolute URL's for better crawlability and indexability.

Therefore, you can not use this variation

> sitemap: /sitemap.xml

Recommended syntax is

Sitemap: https://www.yourdomain.com/sitemap.xml

Note:

  • Don't forgot to capitalise the first letter in "sitemap"
  • Don't forgot to put space after "Sitemap:"

Is there a command to list all Unix group names?

If you want all groups known to the system, I would recommend using getent group instead of parsing /etc/group:

getent group

The reason is that on networked systems, groups may not only read from /etc/group file, but also obtained through LDAP or Yellow Pages (the list of known groups comes from the local group file plus groups received via LDAP or YP in these cases).

If you want just the group names you can use:

getent group | cut -d: -f1

SCRIPT438: Object doesn't support property or method IE

This is a common problem in web applications which employ JavaScript namespacing. When this is the case, the problem 99.9% of the time is IE's inability to bind methods within the current namespace to the "this" keyword.

For example, if I have the JS namespace "StackOverflow" with the method "isAwesome". Normally, if you are within the "StackOverflow" namespace you can invoke the "isAwesome" method with the following syntax:

this.isAwesome();

Chrome, Firefox and Opera will happily accept this syntax. IE on the other hand, will not. Thus, the safest bet when using JS namespacing is to always prefix with the actual namespace. A la:

StackOverflow.isAwesome();

Python: json.loads returns items prefixing with 'u'

The u prefix means that those strings are unicode rather than 8-bit strings. The best way to not show the u prefix is to switch to Python 3, where strings are unicode by default. If that's not an option, the str constructor will convert from unicode to 8-bit, so simply loop recursively over the result and convert unicode to str. However, it is probably best just to leave the strings as unicode.

MySQL - Cannot add or update a child row: a foreign key constraint fails

I've faced this issue and the solution was making sure that all the data from the child field are matching the parent field

for example, you want to add foreign key inside (attendance) table to the column (employeeName)

where the parent is (employees) table, (employeeName) column

all the data in attendance.employeeName must be matching employee.employeeName

MySQL - Trigger for updating same table after insert

This is how I update a row in the same table on insert

activationCode and email are rows in the table USER. On insert I don't specify a value for activationCode, it will be created on the fly by MySQL.

Change username with your MySQL username and db_name with your db name.

CREATE DEFINER=`username`@`localhost` 
       TRIGGER `db_name`.`user_BEFORE_INSERT` 
       BEFORE INSERT ON `user` 
       FOR EACH ROW
         BEGIN
            SET new.activationCode = MD5(new.email);
         END

Error TF30063: You are not authorized to access ... \DefaultCollection

Make sure that Windows Authentication hasn't been disabled for the Website / Application within IIS.

I'm not sure HOW this happened, but I did uninstall Hyper-V today to be able to install VMWare Player and then re-install Hyper-V

Reenabling this allowed everything to work again.

enter image description here

SQL Server returns error "Login failed for user 'NT AUTHORITY\ANONYMOUS LOGON'." in Windows application

If your issue is with linked servers, you need to look at a few things.

First, your users need to have delegation enabled and if the only thing that's changed, it'l likely they do. Otherwise you can uncheck the "Account is sensitive and cannot be delegated" checkbox is the user properties in AD.

Second, your service account(s) must be trusted for delegation. Since you recently changed your service account I suspect this is the culprit. (http://technet.microsoft.com/en-us/library/cc739474(v=ws.10).aspx)

You mentioned that you might have some SPN issues, so be sure to set the SPN for both endpoints, otherwise you will not be able to see the delegation tab in AD. Also make sure you're in advanced view in "Active Directory Users and Computers."

If you still do not see the delegation tab, even after correcting your SPN, make sure your domain not in 2000 mode. If it is, you can "raise domain function level."

At this point, you can now mark the account as trusted for delegation:

In the details pane, right-click the user you want to be trusted for delegation, and click Properties.

Click the Delegation tab, select the Account is trusted for delegation check box, and then click OK.

Finally you will also need to set all the machines as trusted for delegation.

Once you've done this, reconnect to your sql server and test your liked servers. They should work.

Using JsonConvert.DeserializeObject to deserialize Json to a C# POCO class

Along the lines of the accepted answer, if you have a JSON text sample you can plug it in to this converter, select your options and generate the C# code.

If you don't know the type at runtime, this topic looks like it would fit.

dynamically deserialize json into any object passed in. c#

Using % for host when creating a MySQL user

As @nos pointed out in the comments of the currently accepted answer to this question, the accepted answer is incorrect.

Yes, there IS a difference between using % and localhost for the user account host when connecting via a socket connect instead of a standard TCP/IP connect.

A host value of % does not include localhost for sockets and thus must be specified if you want to connect using that method.

Rails - passing parameters in link_to

link_to "+ Service", controller_action_path(:account_id => acct.id)

If it is still not working check the path:

$ rake routes

Best practice to return errors in ASP.NET Web API

For me I usually send back an HttpResponseException and set the status code accordingly depending on the exception thrown and if the exception is fatal or not will determine whether I send back the HttpResponseException immediately.

At the end of the day it's an API sending back responses and not views, so I think it's fine to send back a message with the exception and status code to the consumer. I currently haven't needed to accumulate errors and send them back as most exceptions are usually due to incorrect parameters or calls etc.

An example in my app is that sometimes the client will ask for data, but there isn't any data available so I throw a custom NoDataAvailableException and let it bubble to the Web API app, where then in my custom filter which captures it sending back a relevant message along with the correct status code.

I am not 100% sure on what's the best practice for this, but this is working for me currently so that's what I'm doing.

Update:

Since I answered this question a few blog posts have been written on the topic:

https://weblogs.asp.net/fredriknormen/asp-net-web-api-exception-handling

(this one has some new features in the nightly builds) https://docs.microsoft.com/archive/blogs/youssefm/error-handling-in-asp-net-webapi

Update 2

Update to our error handling process, we have two cases:

  1. For general errors like not found, or invalid parameters being passed to an action we return a HttpResponseException to stop processing immediately. Additionally for model errors in our actions we will hand the model state dictionary to the Request.CreateErrorResponse extension and wrap it in a HttpResponseException. Adding the model state dictionary results in a list of the model errors sent in the response body.

  2. For errors that occur in higher layers, server errors, we let the exception bubble to the Web API app, here we have a global exception filter which looks at the exception, logs it with ELMAH and tries to make sense of it setting the correct HTTP status code and a relevant friendly error message as the body again in a HttpResponseException. For exceptions that we aren't expecting the client will receive the default 500 internal server error, but a generic message due to security reasons.

Update 3

Recently, after picking up Web API 2, for sending back general errors we now use the IHttpActionResult interface, specifically the built in classes for in the System.Web.Http.Results namespace such as NotFound, BadRequest when they fit, if they don't we extend them, for example a NotFound result with a response message:

public class NotFoundWithMessageResult : IHttpActionResult
{
    private string message;

    public NotFoundWithMessageResult(string message)
    {
        this.message = message;
    }

    public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
    {
        var response = new HttpResponseMessage(HttpStatusCode.NotFound);
        response.Content = new StringContent(message);
        return Task.FromResult(response);
    }
}

How to remove and clear all localStorage data

If you want to remove/clean all the values from local storage than use

localStorage.clear();

And if you want to remove the specific item from local storage than use the following code

localStorage.removeItem(key);

Troubleshooting "Warning: session_start(): Cannot send session cache limiter - headers already sent"

You will find I have added the session_start() at the very top of the page. I have also removed the session_start() call later in the page. This page should work fine.

<?php
session_start();
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link href="style.css" rel="stylesheet" type="text/css" />
<title>Welcome</title>


<script type="text/javascript" src="jquery.js"></script>
    <script type="text/javascript">
$(document).ready(function () { 

    $('#nav li').hover(
        function () {
            //show its submenu
            $('ul', this).slideDown(100);

        }, 
        function () {
            //hide its submenu
            $('ul', this).slideUp(100);         
        }
    );

});
    </script>

</head>

<body>
<table width="100%" border="0" cellspacing="0" cellpadding="0">
  <tr>
    <td class="header">&nbsp;</td>
  </tr>
  <tr>
    <td class="menu"><table align="center" cellpadding="0" cellspacing="0" width="80%">
    <tr>
    <td>

    <ul id="nav">
    <li><a href="#">Catalog</a>
    <ul><li><a href="#">Products</a></li>
        <li><a href="#">Bulk Upload</a></li>
        </ul>
        <div class="clear"></div>
        </li>


    <li><a href="#">Purchase  </a>

    </li>
    <li><a href="#">Customer Service</a>
    <ul>
        <li><a href="#">Contact Us</a></li>
        <li><a href="#">CS Panel</a></li>

    </ul>           
        <div class="clear"></div>
    </li>
    <li><a href="#">All Reports</a></li>
    <li><a href="#">Configuration</a>
    <ul> <li><a href="#">Look and Feel </a></li>
         <li><a href="#">Business Details</a></li>
         <li><a href="#">CS Details</a></li>
         <li><a href="#">Emaqil Template</a></li>
         <li><a href="#">Domain and Analytics</a></li>
         <li><a href="#">Courier</a></li>
         </ul>
    <div class="clear"></div>
    </li>
    <li><a href="#">Accounts</a>
    <ul><li><a href="#">Ledgers</a></li>
        <li><a href="#">Account Details</a></li>
        </ul>
         <div class="clear"></div></li>

</ul></td></tr></table></td>
  </tr>
  <tr>
    <td valign="top"><table width="80%" border="0" align="center" cellpadding="0" cellspacing="0">
      <tr>
        <td valign="top"><table width="100%" border="0" cellspacing="0" cellpadding="2">
          <tr>
            <td width="22%" height="327" valign="top"><table width="100%" border="0" cellspacing="0" cellpadding="2">
              <tr>
                <td>&nbsp;</td>
                </tr>
              <tr>
                <td height="45"><strong>-&gt; Products</strong></td>
                </tr>
              <tr>
                <td height="61"><strong>-&gt; Categories</strong></td>
                </tr>
              <tr>
                <td height="48"><strong>-&gt; Sub Categories</strong></td>
                </tr>
            </table></td>
            <td width="78%" valign="top"><table width="100%" border="0" cellpadding="0" cellspacing="0">
              <tr>
                <td>&nbsp;</td>
                </tr>
              <tr>
                <td>
                  <table width="90%" border="0" cellspacing="0" cellpadding="0">
                    <tr>
                      <td width="26%">&nbsp;</td>
                      <td width="74%"><h2>Manage Categories</h2></td>
                    </tr>
                  </table></td>
                </tr>
              <tr>
                <td height="30">&nbsp;

                </td>
                </tr>
              <tr>
                <td>


</td>
                </tr>

                <tr>
                <td>
                <table width="49%" align="center" cellpadding="0" cellspacing="0">
                <tr><td>




<?php


                if (isset($_SESSION['error']))

                {

                    echo "<span id=\"error\"><p>" . $_SESSION['error'] . "</p></span>";

                    unset($_SESSION['error']);

                }

                ?>

                <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" enctype="multipart/form-data">

                <p>
                 <label class="style4">Category Name</label>

                   &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <input type="text" name="categoryname" /><br /><br />

                    <label class="style4">Category Image</label>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

                    <input type="file" name="image" /><br />

                    <input type="hidden" name="MAX_FILE_SIZE" value="100000" />

                   <br />
<br />
 <input type="submit" id="submit" value="UPLOAD" />

                </p>

                </form>




                             <?php


require("includes/conn.php");


function is_valid_type($file)

{

    $valid_types = array("image/jpg", "image/jpeg", "image/bmp", "image/gif", "image/png");



    if (in_array($file['type'], $valid_types))

        return 1;

    return 0;
}

function showContents($array)

{

    echo "<pre>";

    print_r($array);

    echo "</pre>";
}


$TARGET_PATH = "images/category";

$cname = $_POST['categoryname'];

$image = $_FILES['image'];

$cname = mysql_real_escape_string($cname);

$image['name'] = mysql_real_escape_string($image['name']);

$TARGET_PATH .= $image['name'];

if ( $cname == "" || $image['name'] == "" )

{

    $_SESSION['error'] = "All fields are required";

    header("Location: managecategories.php");

    exit;

}

if (!is_valid_type($image))

{

    $_SESSION['error'] = "You must upload a jpeg, gif, or bmp";

    header("Location: managecategories.php");

    exit;

}




if (file_exists($TARGET_PATH))

{

    $_SESSION['error'] = "A file with that name already exists";

    header("Location: managecategories.php");

    exit;

}


if (move_uploaded_file($image['tmp_name'], $TARGET_PATH))

{



    $sql = "insert into Categories (CategoryName, FileName) values ('$cname', '" . $image['name'] . "')";

    $result = mysql_query($sql) or die ("Could not insert data into DB: " . mysql_error());

  header("Location: mangaecategories.php");

    exit;

}

else

{





    $_SESSION['error'] = "Could not upload file.  Check read/write persmissions on the directory";

    header("Location: mangagecategories.php");

    exit;

}

?> 

Is there any JSON Web Token (JWT) example in C#?

Here is the list of classes and functions:

open System
open System.Collections.Generic
open System.Linq
open System.Threading.Tasks
open Microsoft.AspNetCore.Mvc
open Microsoft.Extensions.Logging
open Microsoft.AspNetCore.Authorization
open Microsoft.AspNetCore.Authentication
open Microsoft.AspNetCore.Authentication.JwtBearer
open Microsoft.IdentityModel.Tokens
open System.IdentityModel.Tokens
open System.IdentityModel.Tokens.Jwt
open Microsoft.IdentityModel.JsonWebTokens
open System.Text
open Newtonsoft.Json
open System.Security.Claims
    let theKey = "VerySecretKeyVerySecretKeyVerySecretKey"
    let securityKey = SymmetricSecurityKey(Encoding.UTF8.GetBytes(theKey))
    let credentials = SigningCredentials(securityKey, SecurityAlgorithms.RsaSsaPssSha256)
    let expires = DateTime.UtcNow.AddMinutes(123.0) |> Nullable
    let token = JwtSecurityToken(
                    "lahoda-pro-issuer", 
                    "lahoda-pro-audience",
                    claims = null,
                    expires =  expires,
                    signingCredentials = credentials
        )

    let tokenString = JwtSecurityTokenHandler().WriteToken(token)

How to transfer paid android apps from one google account to another google account

It's totally feasible now. Google now allow you to transfer Android apps between accounts. Please take a look at this link: https://support.google.com/googleplay/android-developer/checklist/3294213?hl=en

Update Query with INNER JOIN between tables in 2 different databases on 1 server

Should look like this:

UPDATE DHE.dbo.tblAccounts
   SET DHE.dbo.tblAccounts.ControllingSalesRep = 
       DHE_Import.dbo.tblSalesRepsAccountsLink.SalesRepCode
  from DHE.dbo.tblAccounts 
     INNER JOIN DHE_Import.dbo.tblSalesRepsAccountsLink 
        ON DHE.dbo.tblAccounts.AccountCode =
           DHE_Import.tblSalesRepsAccountsLink.AccountCode 

Update table is repeated in FROM clause.

How to refresh token with Google API client?

FYI: The 3.0 Google Analytics API will automatically refresh the access token if you have a refresh token when it expires so your script never needs refreshToken.

(See the Sign function in auth/apiOAuth2.php)

Understanding the Linux oom-killer's logs

This webpage have an explanation and a solution.

The solution is:

To fix this problem the behavior of the kernel has to be changed, so it will no longer overcommit the memory for application requests. Finally I have included those mentioned values into the /etc/sysctl.conf file, so they get automatically applied on start-up:

vm.overcommit_memory = 2

vm.overcommit_ratio = 80

What is the http-header "X-XSS-Protection"?

You can see in this List of useful HTTP headers.

X-XSS-Protection: This header enables the Cross-site scripting (XSS) filter built into most recent web browsers. It's usually enabled by default anyway, so the role of this header is to re-enable the filter for this particular website if it was disabled by the user. This header is supported in IE 8+, and in Chrome (not sure which versions). The anti-XSS filter was added in Chrome 4. Its unknown if that version honored this header.

Get refresh token google api

Found out by adding this to your url parameters

approval_prompt=force

Update:

Use access_type=offline&prompt=consent instead.

approval_prompt=force no longer works https://github.com/googleapis/oauth2client/issues/453

Accessing session from TWIG template

Setup twig

$twig = new Twig_Environment(...);    
$twig->addGlobal('session', $_SESSION);

Then within your template access session values for example

$_SESSION['username'] in php file Will be equivalent to {{ session.username }} in your twig template

Set variable value to array of strings

declare  @tab table(FirstName  varchar(100))
insert into @tab   values('John'),('Sarah'),('George')

SELECT * 
FROM @tab
WHERE 'John' in (FirstName)

Eclipse - "Workspace in use or cannot be created, chose a different one."

Running eclipse in Administrator Mode fixed it for me. You can do this by [Right Click] -> Run as Administrator on the eclipse.exe from your install dir.

I was on a working environment with win7 machine having restrictive permission. I also did remove the .lock and .log files but that did not help. It can be a combination of all as well that made it work.

Java SSLException: hostname in certificate didn't match

Updating the java version from 1.8.0_40 to 1.8.0_181 resolved the issue.

javax.mail.AuthenticationFailedException: failed to connect, no password specified?

See the 9 line of your code,it may be an error; it should be:

mail.smtp.user 

not

mail.stmp.user;

URL Encode a string in jQuery for an AJAX request

try this one

var query = "{% url accounts.views.instasearch  %}?q=" + $('#tags').val().replace(/ /g, '+');

SELECT where row value contains string MySQL

SELECT * FROM Accounts WHERE Username LIKE '%$query%'

but it's not suggested. use PDO

Access-Control-Allow-Origin error sending a jQuery Post to Google API's

There is a little hack with php. And it works not only with Google, but with any website you don't control and can't add Access-Control-Allow-Origin *

We need to create PHP-file (ex. getContentFromUrl.php) on our webserver and make a little trick.

PHP

<?php

$ext_url = $_POST['ext_url'];

echo file_get_contents($ext_url);

?>

JS

$.ajax({
    method: 'POST',
    url: 'getContentFromUrl.php', // link to your PHP file
    data: {
        // url where our server will send request which can't be done by AJAX
        'ext_url': 'https://stackoverflow.com/questions/6114436/access-control-allow-origin-error-sending-a-jquery-post-to-google-apis'
    },
    success: function(data) {
        // we can find any data on external url, cause we've got all page
        var $h1 = $(data).find('h1').html();

        $('h1').val($h1);
    },
    error:function() {
        console.log('Error');
    }
});

How it works:

  1. Your browser with the help of JS will send request to your server
  2. Your server will send request to any other server and get reply from another server (any website)
  3. Your server will send this reply to your JS

And we can make events onClick, put this event on some button. Hope this will help!

how to read a text file using scanner in Java?

This should help you..:

import java.io.*;
import static java.lang.System.*;
/**
* Write a description of class InRead here.
* 
* @author (your name) 
* @version (a version number or a date)
*/
public class InRead
{
public InRead(String Recipe)
{
    find(Recipe);
}
public void find(String Name){
    String newRecipe= Name+".txt";
    try{
        FileReader fr= new FileReader(newRecipe);
        BufferedReader br= new BufferedReader(fr);

        String str;


    while ((str=br.readLine()) != null){
            out.println(str + "\n");
        }
        br.close();

    }catch (IOException e){
        out.println("File Not Found!");
    }
}

}

There is already an open DataReader associated with this Command which must be closed first

use the syntax .ToList() to convert object read from db to list to avoid being re-read again.Hope this would work for it. Thanks.

What are all the user accounts for IIS/ASP.NET and how do they differ?

This is a very good question and sadly many developers don't ask enough questions about IIS/ASP.NET security in the context of being a web developer and setting up IIS. So here goes....

To cover the identities listed:

IIS_IUSRS:

This is analogous to the old IIS6 IIS_WPG group. It's a built-in group with it's security configured such that any member of this group can act as an application pool identity.

IUSR:

This account is analogous to the old IUSR_<MACHINE_NAME> local account that was the default anonymous user for IIS5 and IIS6 websites (i.e. the one configured via the Directory Security tab of a site's properties).

For more information about IIS_IUSRS and IUSR see:

Understanding Built-In User and Group Accounts in IIS 7

DefaultAppPool:

If an application pool is configured to run using the Application Pool Identity feature then a "synthesised" account called IIS AppPool\<pool name> will be created on the fly to used as the pool identity. In this case there will be a synthesised account called IIS AppPool\DefaultAppPool created for the life time of the pool. If you delete the pool then this account will no longer exist. When applying permissions to files and folders these must be added using IIS AppPool\<pool name>. You also won't see these pool accounts in your computers User Manager. See the following for more information:

Application Pool Identities

ASP.NET v4.0: -

This will be the Application Pool Identity for the ASP.NET v4.0 Application Pool. See DefaultAppPool above.

NETWORK SERVICE: -

The NETWORK SERVICE account is a built-in identity introduced on Windows 2003. NETWORK SERVICE is a low privileged account under which you can run your application pools and websites. A website running in a Windows 2003 pool can still impersonate the site's anonymous account (IUSR_ or whatever you configured as the anonymous identity).

In ASP.NET prior to Windows 2008 you could have ASP.NET execute requests under the Application Pool account (usually NETWORK SERVICE). Alternatively you could configure ASP.NET to impersonate the site's anonymous account via the <identity impersonate="true" /> setting in web.config file locally (if that setting is locked then it would need to be done by an admin in the machine.config file).

Setting <identity impersonate="true"> is common in shared hosting environments where shared application pools are used (in conjunction with partial trust settings to prevent unwinding of the impersonated account).

In IIS7.x/ASP.NET impersonation control is now configured via the Authentication configuration feature of a site. So you can configure to run as the pool identity, IUSR or a specific custom anonymous account.

LOCAL SERVICE:

The LOCAL SERVICE account is a built-in account used by the service control manager. It has a minimum set of privileges on the local computer. It has a fairly limited scope of use:

LocalService Account

LOCAL SYSTEM:

You didn't ask about this one but I'm adding for completeness. This is a local built-in account. It has fairly extensive privileges and trust. You should never configure a website or application pool to run under this identity.

LocalSystem Account

In Practice:

In practice the preferred approach to securing a website (if the site gets its own application pool - which is the default for a new site in IIS7's MMC) is to run under Application Pool Identity. This means setting the site's Identity in its Application Pool's Advanced Settings to Application Pool Identity:

enter image description here

In the website you should then configure the Authentication feature:

enter image description here

Right click and edit the Anonymous Authentication entry:

enter image description here

Ensure that "Application pool identity" is selected:

enter image description here

When you come to apply file and folder permissions you grant the Application Pool identity whatever rights are required. For example if you are granting the application pool identity for the ASP.NET v4.0 pool permissions then you can either do this via Explorer:

enter image description here

Click the "Check Names" button:

enter image description here

Or you can do this using the ICACLS.EXE utility:

icacls c:\wwwroot\mysite /grant "IIS AppPool\ASP.NET v4.0":(CI)(OI)(M)

...or...if you site's application pool is called BobsCatPicBlogthen:

icacls c:\wwwroot\mysite /grant "IIS AppPool\BobsCatPicBlog":(CI)(OI)(M)

I hope this helps clear things up.

Update:

I just bumped into this excellent answer from 2009 which contains a bunch of useful information, well worth a read:

The difference between the 'Local System' account and the 'Network Service' account?

Receiving login prompt using integrated windows authentication

In my case the authorization settings were not set up properly.

I had to

  1. open the .NET Authorization Rules in IIS Manager

    open the .NET Authorization Rules in IIS Manager
  2. and remove the Deny Rule

    remove the Deny Rule

How to send/receive SOAP request and response using C#?

The urls are different.

  • http://localhost/AccountSvc/DataInquiry.asmx

vs.

  • /acctinqsvc/portfolioinquiry.asmx

Resolve this issue first, as if the web server cannot resolve the URL you are attempting to POST to, you won't even begin to process the actions described by your request.

You should only need to create the WebRequest to the ASMX root URL, ie: http://localhost/AccountSvc/DataInquiry.asmx, and specify the desired method/operation in the SOAPAction header.

The SOAPAction header values are different.

  • http://localhost/AccountSvc/DataInquiry.asmx/ + methodName

vs.

  • http://tempuri.org/GetMyName

You should be able to determine the correct SOAPAction by going to the correct ASMX URL and appending ?wsdl

There should be a <soap:operation> tag underneath the <wsdl:operation> tag that matches the operation you are attempting to execute, which appears to be GetMyName.

There is no XML declaration in the request body that includes your SOAP XML.

You specify text/xml in the ContentType of your HttpRequest and no charset. Perhaps these default to us-ascii, but there's no telling if you aren't specifying them!

The SoapUI created XML includes an XML declaration that specifies an encoding of utf-8, which also matches the Content-Type provided to the HTTP request which is: text/xml; charset=utf-8

Hope that helps!

How to change the decimal separator of DecimalFormat from comma to dot/point?

You can change the separator either by setting a locale or using the DecimalFormatSymbols.

If you want the grouping separator to be a point, you can use an european locale:

NumberFormat nf = NumberFormat.getNumberInstance(Locale.GERMAN);
DecimalFormat df = (DecimalFormat)nf;

Alternatively you can use the DecimalFormatSymbols class to change the symbols that appear in the formatted numbers produced by the format method. These symbols include the decimal separator, the grouping separator, the minus sign, and the percent sign, among others:

DecimalFormatSymbols otherSymbols = new DecimalFormatSymbols(currentLocale);
otherSymbols.setDecimalSeparator(',');
otherSymbols.setGroupingSeparator('.'); 
DecimalFormat df = new DecimalFormat(formatString, otherSymbols);

currentLocale can be obtained from Locale.getDefault() i.e.:

Locale currentLocale = Locale.getDefault();

IE8 crashes when loading website - res://ieframe.dll/acr_error.htm

Forcefully set the IE compatibility mode to IE7 or IE9 in the header section of your master page For example

<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7">

Django - after login, redirect user to his custom page --> mysite.com/username

A simpler approach relies on redirection from the page LOGIN_REDIRECT_URL. The key thing to realize is that the user information is automatically included in the request.

Suppose:

LOGIN_REDIRECT_URL = '/profiles/home'

and you have configured a urlpattern:

(r'^profiles/home', home),

Then, all you need to write for the view home() is:

from django.http import HttpResponseRedirect
from django.urls import reverse
from django.contrib.auth.decorators import login_required

@login_required
def home(request):
    return HttpResponseRedirect(
               reverse(NAME_OF_PROFILE_VIEW, 
                       args=[request.user.username]))

where NAME_OF_PROFILE_VIEW is the name of the callback that you are using. With django-profiles, NAME_OF_PROFILE_VIEW can be 'profiles_profile_detail'.

Asp.Net MVC with Drop Down List, and SelectListItem Assistance

You have a view model to which your view is strongly typed => use strongly typed helpers:

<%= Html.DropDownListFor(
    x => x.SelectedAccountId, 
    new SelectList(Model.Accounts, "Value", "Text")
) %>

Also notice that I use a SelectList for the second argument.

And in your controller action you were returning the view model passed as argument and not the one you constructed inside the action which had the Accounts property correctly setup so this could be problematic. I've cleaned it a bit:

public ActionResult AccountTransaction()
{
    var accounts = Services.AccountServices.GetAccounts(false);
    var viewModel = new AccountTransactionView
    {
        Accounts = accounts.Select(a => new SelectListItem
        {
            Text = a.Description,
            Value = a.AccountId.ToString()
        })
    };
    return View(viewModel);
}

Check if a value exists in ArrayList

Just use ArrayList.contains(desiredElement). For example, if you're looking for the conta1 account from your example, you could use something like:

if (lista.contains(conta1)) {
    System.out.println("Account found");
} else {
    System.out.println("Account not found");
}

Edit: Note that in order for this to work, you will need to properly override the equals() and hashCode() methods. If you are using Eclipse IDE, then you can have these methods generated by first opening the source file for your CurrentAccount object and the selecting Source > Generate hashCode() and equals()...

Pass variables to Ruby script via command line

Unfortunately, Ruby does not support such passing mechanism as e.g. AWK:

> awk -v a=1 'BEGIN {print a}'
> 1

It means you cannot pass named values into your script directly.

Using cmd options may help:

> ruby script.rb val_0 val_1 val_2

# script.rb
puts ARGV[0] # => val_0
puts ARGV[1] # => val_1
puts ARGV[2] # => val_2

Ruby stores all cmd arguments in the ARGV array, the scriptname itself can be captured using the $PROGRAM_NAME variable.

The obvious disadvantage is that you depend on the order of values.

If you need only Boolean switches use the option -s of the Ruby interpreter:

> ruby -s -e 'puts "So do I!" if $agreed' -- -agreed
> So do I!

Please note the -- switch, otherwise Ruby will complain about a nonexistent option -agreed, so pass it as a switch to your cmd invokation. You don't need it in the following case:

> ruby -s script_with_switches.rb -agreed
> So do I!

The disadvantage is that you mess with global variables and have only logical true/false values.

You can access values from environment variables:

> FIRST_NAME='Andy Warhol' ruby -e 'puts ENV["FIRST_NAME"]'
> Andy Warhol

Drawbacks are present here to, you have to set all the variables before the script invocation (only for your ruby process) or to export them (shells like BASH):

> export FIRST_NAME='Andy Warhol'
> ruby -e 'puts ENV["FIRST_NAME"]'

In the latter case, your data will be readable for everybody in the same shell session and for all subprocesses, which can be a serious security implication.

And at least you can implement an option parser using getoptlong and optparse.

Happy hacking!

Multiple github accounts on the same computer?

Use HTTPS:

change remote url to https:

git remote set-url origin https://[email protected]/USERNAME/PROJECTNAME.git

and you are good to go:

git push

To ensure that the commits appear as performed by USERNAME, one can setup the user.name and user.email for this project, too:

git config user.name USERNAME
git config user.email [email protected]

Multiple GitHub Accounts & SSH Config

Follow these steps to fix this it looks too long but trust me it won't take more than 5 minutes:

Step-1: Create two ssh key pairs:

ssh-keygen -t rsa -C "[email protected]"

Step-2: It will create two ssh keys here:

~/.ssh/id_rsa_account1
~/.ssh/id_rsa_account2

Step-3: Now we need to add these keys:

ssh-add ~/.ssh/id_rsa_account2
ssh-add ~/.ssh/id_rsa_account1
  • You can see the added keys list by using this command: ssh-add -l
  • You can remove old cached keys by this command: ssh-add -D

Step-4: Modify the ssh config

cd ~/.ssh/
touch config

subl -a config or code config or nano config

Step-5: Add this to config file:

#Github account1
Host github.com-account1
    HostName github.com
    User account1
    IdentityFile ~/.ssh/id_rsa_account1

#Github account2
Host github.com-account2
    HostName github.com
    User account2
    IdentityFile ~/.ssh/id_rsa_account2

Step-6: Update your .git/config file:

Step-6.1: Navigate to account1's project and update host:

[remote "origin"]
        url = [email protected]:account1/gfs.git

If you are invited by some other user in their git Repository. Then you need to update the host like this:

[remote "origin"]
            url = [email protected]:invitedByUserName/gfs.git

Step-6.2: Navigate to account2's project and update host:

[remote "origin"]
        url = [email protected]:account2/gfs.git

Step-7: Update user name and email for each repository separately if required this is not an amendatory step:

Navigate to account1 project and run these:

git config user.name "account1"
git config user.email "[email protected]" 

Navigate to account2 project and run these:

git config user.name "account2"
git config user.email "[email protected]" 

`IF` statement with 3 possible answers each based on 3 different ranges

This is what I did:

Very simply put:

=IF(C7>100,"Profit",IF(C7=100,"Quota Met","Loss"))

The first IF Statement, if true will input Profit, and if false will lead on to the next IF statement and so forth :)

I only have basic formula knowledge but it's working so I will accept I am right!

Invalid length for a Base-64 char array

My initial guess without knowing the data would be that the UserNameToVerify is not a multiple of 4 in length. Check out the FromBase64String on msdn.

// Ok
byte[] b1 = Convert.FromBase64String("CoolDude");
// Exception
byte[] b2 = Convert.FromBase64String("MyMan");

How do I list all tables in all databases in SQL Server in a single result set?

I realize this is a very old thread, but it was very helpful when I had to put together some system documentation for several different servers that were hosting different versions of Sql Server. I ended up creating 4 stored procedures which I am posting here for the benefit of the community. We use Dynamics NAV so the two stored procedures with NAV in the name split the Nav company out of the table name. Enjoy...

4 of 4 - ListServerDatabaseNavTables - for Dynamics NAV

USE [YourDatabase]
GO

SET QUOTED_IDENTIFIER ON
GO

ALTER proc [dbo].[ListServerDatabaseNavTables]
(
    @SearchDatabases varchar(max) = NULL,  
    @SearchSchema sysname = NULL,
    @SearchCompanies varchar(max) = NULL,
    @SearchTables varchar(max) = NULL,
    @ExcludeSystemDatabases bit = 1,
    @Sql varchar(max) OUTPUT
)
AS BEGIN

/**************************************************************************************************************************************
* Lists all of the database tables for a given server.
*   Parameters
*       SearchDatabases - Comma delimited list of database names for which to search - converted into series of Like statements
*                         Defaults to null  
*       SearchSchema - Schema name for which to search
*                      Defaults to null 
*       SearchCompanies - Comma delimited list of company names for which to search - converted into series of Like statements
*                         Defaults to null  
*       SearchTables - Comma delimited list of table names for which to search - converted into series of Like statements
*                      Defaults to null 
*       ExcludeSystemDatabases - 1 to exclude system databases, otherwise 0
*                          Defaults to 1
*       Sql - Output - the stored proc generated sql
*
*   Adapted from answer by KM answered May 21 '10 at 13:33
*   From: How do I list all tables in all databases in SQL Server in a single result set?
*   Link: https://stackoverflow.com/questions/2875768/how-do-i-list-all-tables-in-all-databases-in-sql-server-in-a-single-result-set
*
**************************************************************************************************************************************/

    SET NOCOUNT ON

    DECLARE @l_CompoundLikeStatement varchar(max) = ''
    DECLARE @l_TableName sysname
    DECLARE @l_CompanyName sysname
    DECLARE @l_DatabaseName sysname

    DECLARE @l_Index int

    DECLARE @l_UseAndText bit = 0

    DECLARE @AllTables table (ServerName sysname, DbName sysname, SchemaName sysname, CompanyName sysname, TableName sysname, NavTableName sysname)

    SET @Sql = 
        'select @@ServerName as ''ServerName'', ''?'' as ''DbName'', s.name as ''SchemaName'', ' + char(13) +
        '       case when charindex(''$'', t.name) = 0 then '''' else left(t.name, charindex(''$'', t.name) - 1) end as ''CompanyName'', ' + char(13) +
        '       case when charindex(''$'', t.name) = 0 then t.name else substring(t.name, charindex(''$'', t.name) + 1, 1000) end as ''TableName'', ' + char(13) +
        '       t.name as ''NavTableName'' ' + char(13) +
        'from [?].sys.tables t inner join ' + char(13) + 
        '     sys.schemas s on t.schema_id = s.schema_id '

    -- Comma delimited list of database names for which to search
    IF @SearchDatabases IS NOT NULL BEGIN
        SET @l_CompoundLikeStatement = char(13) + 'where (' + char(13)
        WHILE LEN(LTRIM(RTRIM(@SearchDatabases))) > 0 BEGIN
            SET @l_Index = CHARINDEX(',', @SearchDatabases)
            IF @l_Index = 0 BEGIN
                SET @l_DatabaseName = LTRIM(RTRIM(@SearchDatabases))
            END ELSE BEGIN
                SET @l_DatabaseName = LTRIM(RTRIM(LEFT(@SearchDatabases, @l_Index - 1)))
            END

            SET @SearchDatabases = LTRIM(RTRIM(REPLACE(LTRIM(RTRIM(REPLACE(@SearchDatabases, @l_DatabaseName, ''))), ',', '')))
            SET @l_CompoundLikeStatement = @l_CompoundLikeStatement + char(13) + ' ''?'' like ''' + @l_DatabaseName + '%'' COLLATE Latin1_General_CI_AS or '
        END

        -- Trim trailing Or and add closing right parenthesis )
        SET @l_CompoundLikeStatement = LTRIM(RTRIM(@l_CompoundLikeStatement))
        SET @l_CompoundLikeStatement = LEFT(@l_CompoundLikeStatement, LEN(@l_CompoundLikeStatement) - 2) + ')'

        SET @Sql = @Sql + char(13) +
            @l_CompoundLikeStatement

        SET @l_UseAndText = 1
    END

    -- Search schema
    IF @SearchSchema IS NOT NULL BEGIN
        SET @Sql = @Sql + char(13)
        SET @Sql = @Sql + CASE WHEN @l_UseAndText = 1 THEN '  and ' ELSE 'where ' END +
            's.name LIKE ''' + @SearchSchema + ''' COLLATE Latin1_General_CI_AS'
        SET @l_UseAndText = 1
    END

    -- Comma delimited list of company names for which to search
    IF @SearchCompanies IS NOT NULL BEGIN
        SET @l_CompoundLikeStatement = char(13) + CASE WHEN @l_UseAndText = 1 THEN '  and (' ELSE 'where (' END + char(13) 
        WHILE LEN(LTRIM(RTRIM(@SearchCompanies))) > 0 BEGIN
            SET @l_Index = CHARINDEX(',', @SearchCompanies)
            IF @l_Index = 0 BEGIN
                SET @l_CompanyName = LTRIM(RTRIM(@SearchCompanies))
            END ELSE BEGIN
                SET @l_CompanyName = LTRIM(RTRIM(LEFT(@SearchCompanies, @l_Index - 1)))
            END

            SET @SearchCompanies = LTRIM(RTRIM(REPLACE(LTRIM(RTRIM(REPLACE(@SearchCompanies, @l_CompanyName, ''))), ',', '')))
            SET @l_CompoundLikeStatement = @l_CompoundLikeStatement + char(13) + ' t.name like ''' + @l_CompanyName + '%'' COLLATE Latin1_General_CI_AS or '
        END

        -- Trim trailing Or and add closing right parenthesis )
        SET @l_CompoundLikeStatement = LTRIM(RTRIM(@l_CompoundLikeStatement))
        SET @l_CompoundLikeStatement = LEFT(@l_CompoundLikeStatement, LEN(@l_CompoundLikeStatement) - 2) + ' )'

        SET @Sql = @Sql + char(13) +
            @l_CompoundLikeStatement

        SET @l_UseAndText = 1
    END

    -- Comma delimited list of table names for which to search
    IF @SearchTables IS NOT NULL BEGIN
        SET @l_CompoundLikeStatement = char(13) + CASE WHEN @l_UseAndText = 1 THEN '  and (' ELSE 'where (' END + char(13) 
        WHILE LEN(LTRIM(RTRIM(@SearchTables))) > 0 BEGIN
            SET @l_Index = CHARINDEX(',', @SearchTables)
            IF @l_Index = 0 BEGIN
                SET @l_TableName = LTRIM(RTRIM(@SearchTables))
            END ELSE BEGIN
                SET @l_TableName = LTRIM(RTRIM(LEFT(@SearchTables, @l_Index - 1)))
            END

            SET @SearchTables = LTRIM(RTRIM(REPLACE(LTRIM(RTRIM(REPLACE(@SearchTables, @l_TableName, ''))), ',', '')))
            SET @l_CompoundLikeStatement = @l_CompoundLikeStatement + char(13) + ' t.name like ''$' + @l_TableName + ''' COLLATE Latin1_General_CI_AS or '
        END

        -- Trim trailing Or and add closing right parenthesis )
        SET @l_CompoundLikeStatement = LTRIM(RTRIM(@l_CompoundLikeStatement))
        SET @l_CompoundLikeStatement = LEFT(@l_CompoundLikeStatement, LEN(@l_CompoundLikeStatement) - 2) + ' )'

        SET @Sql = @Sql + char(13) +
            @l_CompoundLikeStatement

        SET @l_UseAndText = 1
    END

    IF @ExcludeSystemDatabases = 1 BEGIN
        SET @Sql = @Sql + char(13)
        SET @Sql = @Sql + case when @l_UseAndText = 1 THEN '  and ' ELSE 'where ' END +
            '''?'' not in (''master'' COLLATE Latin1_General_CI_AS, ''model'' COLLATE Latin1_General_CI_AS, ''msdb'' COLLATE Latin1_General_CI_AS, ''tempdb'' COLLATE Latin1_General_CI_AS)' 
    END

/*  PRINT @Sql  */

    INSERT INTO @AllTables 
    EXEC sp_msforeachdb @Sql

    SELECT * FROM @AllTables ORDER BY DbName COLLATE Latin1_General_CI_AS, CompanyName COLLATE Latin1_General_CI_AS, TableName COLLATE Latin1_General_CI_AS
END

Deserializing JSON data to C# using JSON.NET

Use

var rootObject =  JsonConvert.DeserializeObject<RootObject>(string json);

Create your classes on JSON 2 C#


Json.NET documentation: Serializing and Deserializing JSON with Json.NET

Reading Xml with XmlReader in C#

For sub-objects, ReadSubtree() gives you an xml-reader limited to the sub-objects, but I really think that you are doing this the hard way. Unless you have very specific requirements for handling unusual / unpredicatable xml, use XmlSerializer (perhaps coupled with sgen.exe if you really want).

XmlReader is... tricky. Contrast to:

using System;
using System.Collections.Generic;
using System.Xml.Serialization;
public class ApplicationPool {
    private readonly List<Account> accounts = new List<Account>();
    public List<Account> Accounts {get{return accounts;}}
}
public class Account {
    public string NameOfKin {get;set;}
    private readonly List<Statement> statements = new List<Statement>();
    public List<Statement> StatementsAvailable {get{return statements;}}
}
public class Statement {}
static class Program {
    static void Main() {
        XmlSerializer ser = new XmlSerializer(typeof(ApplicationPool));
        ser.Serialize(Console.Out, new ApplicationPool {
            Accounts = { new Account { NameOfKin = "Fred",
                StatementsAvailable = { new Statement {}, new Statement {}}}}
        });
    }
}

How do a LDAP search/authenticate against this LDAP in Java

Another approach is using UnboundID. Its api is very readable and shorter

Create a Ldap Connection

public static LDAPConnection getConnection() throws LDAPException {
    // host, port, username and password
    return new LDAPConnection("com.example.local", 389, "[email protected]", "admin");
}

Get filter result

public static List<SearchResultEntry> getResults(LDAPConnection connection, String baseDN, String filter) throws LDAPSearchException {
    SearchResult searchResult;

    if (connection.isConnected()) {
        searchResult = connection.search(baseDN, SearchScope.ONE, filter);

        return searchResult.getSearchEntries();
    }

    return null;
}

Get all Oragnization Units and Containers

String baseDN = "DC=com,DC=example,DC=local";
String filter = "(&(|(objectClass=organizationalUnit)(objectClass=container)))";

LDAPConnection connection = getConnection();        
List<SearchResultEntry> results = getResults(connection, baseDN, filter);

Get a specific Organization Unit

String baseDN = "DC=com,DC=example,DC=local";
String dn = "CN=Users,DC=com,DC=example,DC=local";

String filterFormat = "(&(|(objectClass=organizationalUnit)(objectClass=container))(distinguishedName=%s))";
String filter = String.format(filterFormat, dn);

LDAPConnection connection =  getConnection();

List<SearchResultEntry> results = getResults(connection, baseDN, filter);

Get all users under an Organizational Unit

String baseDN = "CN=Users,DC=com,DC=example,DC=local";
String filter = "(&(objectClass=user)(!(objectCategory=computer)))";

LDAPConnection connection =  getConnection();       
List<SearchResultEntry> results = getResults(connection, baseDN, filter);

Get a specific user under an Organization Unit

String baseDN = "CN=Users,DC=com,DC=example,DC=local";
String userDN = "CN=abc,CN=Users,DC=com,DC=example,DC=local";

String filterFormat = "(&(objectClass=user)(distinguishedName=%s))";
String filter = String.format(filterFormat, userDN);

LDAPConnection connection =  getConnection();
List<SearchResultEntry> results = getResults(connection, baseDN, filter);

Display result

for (SearchResultEntry e : results) {
    System.out.println("name: " + e.getAttributeValue("name"));
}

How to automatically add user account AND password with a Bash script?

You could also use chpasswd:

echo username:new_password | chpasswd

so, you change password for user username to new_password.

Removing double quotes from variables in batch file creates problems with CMD environment

Spent a lot of time trying to do this in a simple way. After looking at FOR loop carefully, I realized I can do this with just one line of code:

FOR /F "delims=" %%I IN (%Quoted%) DO SET Unquoted=%%I

Example:

@ECHO OFF
SET Quoted="Test string"

FOR /F "delims=" %%I IN (%Quoted%) DO SET Unquoted=%%I

ECHO %Quoted%
ECHO %Unquoted%

Output:

"Test string"
Test string

Add IIS 7 AppPool Identities as SQL Server Logons

If you're going across machines, you either need to be using NETWORK SERVICE, LOCAL SYSTEM, a domain account, or a SQL 2008 R2 (if you have it) Managed Service Account (which is my preference if you had such an infrastructure). You can not use an account which is not visible to the Active Directory domain.

What is the best way to ensure only one instance of a Bash script is running?

I had the same problem, and came up with a template that uses lockfile, a pid file that holds the process id number, and a kill -0 $(cat $pid_file) check to make aborted scripts not stop the next run. This creates a foobar-$USERID folder in /tmp where the lockfile and pid file lives.

You can still call the script and do other things, as long as you keep those actions in alertRunningPS.

#!/bin/bash

user_id_num=$(id -u)
pid_file="/tmp/foobar-$user_id_num/foobar-$user_id_num.pid"
lock_file="/tmp/foobar-$user_id_num/running.lock"
ps_id=$$

function alertRunningPS () {
    local PID=$(cat "$pid_file" 2> /dev/null)
    echo "Lockfile present. ps id file: $PID"
    echo "Checking if process is actually running or something left over from crash..."
    if kill -0 $PID 2> /dev/null; then
        echo "Already running, exiting"
        exit 1
    else
        echo "Not running, removing lock and continuing"
        rm -f "$lock_file"
        lockfile -r 0 "$lock_file"
    fi
}

echo "Hello, checking some stuff before locking stuff"

# Lock further operations to one process
mkdir -p /tmp/foobar-$user_id_num
lockfile -r 0 "$lock_file" || alertRunningPS

# Do stuff here
echo -n $ps_id > "$pid_file"
echo "Running stuff in ONE ps"

sleep 30s

rm -f "$lock_file"
rm -f "$pid_file"
exit 0

MySQL connection not working: 2002 No such file or directory

The error 2002 means that MySQL can't connect to local database server through the socket file (e.g. /tmp/mysql.sock).

To find out where is your socket file, run:

mysql_config --socket

then double check that your application uses the right Unix socket file or connect through the TCP/IP port instead.

Then double check if your PHP has the right MySQL socket set-up:

php -i | grep mysql.default_socket

and make sure that file exists.

Test the socket:

mysql --socket=/var/mysql/mysql.sock

If the Unix socket is wrong or does not exist, you may symlink it, for example:

ln -vs /Applications/MAMP/tmp/mysql/mysql.sock /var/mysql/mysql.sock

or correct your configuration file (e.g. php.ini).

To test the PDO connection directly from PHP, you may run:

php -r "new PDO('mysql:host=localhost;port=3306;charset=utf8;dbname=dbname', 'root', 'root');"

Check also the configuration between Apache and CLI (command-line interface), as the configuration can be differ.

It might be that the server is running, but you are trying to connect using a TCP/IP port, named pipe, or Unix socket file different from the one on which the server is listening. To correct that you need to invoke a client program (e.g. specifying --port option) to indicate the proper port number, or the proper named pipe or Unix socket file (e.g. --socket option).

See: Troubleshooting Problems Connecting to MySQL


Other utils/commands which can help to track the problem:

  • mysql --socket=$(php -r 'echo ini_get("mysql.default_socket");')
  • netstat -ln | grep mysql
  • php -r "phpinfo();" | grep mysql
  • php -i | grep mysql
  • Use XDebug with xdebug.show_exception_trace=1 in your xdebug.ini
  • On OS X try sudo dtruss -fn mysqld, on Linux debug with strace
  • Check permissions on Unix socket: stat $(mysql_config --socket) and if you've enough free space (df -h).
  • Restart your MySQL.
  • Check net.core.somaxconn.

C# equivalent of C++ map<string,double>

Although System.Collections.Generic.Dictionary matches the tag "hashmap" and will work well in your example, it is not an exact equivalent of C++'s std::map - std::map is an ordered collection.

If ordering is important you should use SortedDictionary.

How to get a list of user accounts using the command line in MySQL?

MySQL stores the user information in its own database. The name of the database is MySQL. Inside that database, the user information is in a table, a dataset, named user. If you want to see what users are set up in the MySQL user table, run the following command:

SELECT User, Host FROM mysql.user;

+------------------+-----------+
| User             | Host      |
+------------------+-----------+
| root             | localhost |
| root             | demohost  |
| root             | 127.0.0.1 |
| debian-sys-maint | localhost |
|                  | %         |
+------------------+-----------+

Algorithm for Determining Tic Tac Toe Game Over

I developed an algorithm for this as part of a science project once.

You basically recursively divide the board into a bunch of overlapping 2x2 rects, testing the different possible combinations for winning on a 2x2 square.

It is slow, but it has the advantage of working on any sized board, with fairly linear memory requirements.

I wish I could find my implementation

Changing the action of a form with JavaScript/jQuery

You can actually just use

$("#form").attr("target", "NewAction");

As far as I know, this will NOT fail silently.

If the page is opening in a new target, you may need to make sure the URL is unique each time because Webkit (chrome/safari) will cache the fact you have visited that URL and won't perform the post.

For example

$("form").attr("action", "/Pages/GeneratePreview?" + new Date().getMilliseconds());

how to customize `show processlist` in mysql?

Another useful tool for this from the command line interface, is the pager command.

eg

pager grep -v Sleep | more; show full processlist;

Then you can page through the results.

You can also look for certain users, IPs or queries with grep or sed in this way.

The pager command is persistent per session.

Connect different Windows User in SQL Server Management Studio (2005 or later)

There are many places where someone might want to deploy this kind of scenario, but due to the way integrated authentication works, it is not possible.

As gbn mentioned, integrated authentication uses a special token that corresponds to your Windows identity. There are coding practices called "impersonation" (probably used by the Run As... command) that allow you to effectively perform an activity as another Windows user, but there is not really a way to arbitrarily act as a different user (à la Linux) in Windows applications aside from that.

If you really need to administer multiple servers across several domains, you might consider one of the following:

  1. Set up Domain Trust between your domains so that your account can access computers in the trusting domain
  2. Configure a SQL user (using mixed authentication) across all the servers you need to administer so that you can log in that way; obviously, this might introduce some security issues and create a maintenance nightmare if you have to change all the passwords at some point.

Hopefully this helps!

How do I change the JAVA_HOME for ant?

You could create your own script for running ant, e.g. named ant.sh like:

#!/bin/sh
JAVA_HOME=</path/to/jdk>; export JAVA_HOME
ant $@

and then run your script.

$ chmod 755 ant.sh
$./ant.sh clean compile

or whatever ant target you wish to run

The difference between the 'Local System' account and the 'Network Service' account?

Since there is so much confusion about functionality of standard service accounts, I'll try to give a quick run down.

First the actual accounts:

  • LocalService account (preferred)

    A limited service account that is very similar to Network Service and meant to run standard least-privileged services. However, unlike Network Service it accesses the network as an Anonymous user.

    • Name: NT AUTHORITY\LocalService
    • the account has no password (any password information you provide is ignored)
    • HKCU represents the LocalService user account
    • has minimal privileges on the local computer
    • presents anonymous credentials on the network
    • SID: S-1-5-19
    • has its own profile under the HKEY_USERS registry key (HKEY_USERS\S-1-5-19)

     

  • NetworkService account

    Limited service account that is meant to run standard privileged services. This account is far more limited than Local System (or even Administrator) but still has the right to access the network as the machine (see caveat above).

    • NT AUTHORITY\NetworkService
    • the account has no password (any password information you provide is ignored)
    • HKCU represents the NetworkService user account
    • has minimal privileges on the local computer
    • presents the computer's credentials (e.g. MANGO$) to remote servers
    • SID: S-1-5-20
    • has its own profile under the HKEY_USERS registry key (HKEY_USERS\S-1-5-20)
    • If trying to schedule a task using it, enter NETWORK SERVICE into the Select User or Group dialog

     

  • LocalSystem account (dangerous, don't use!)

    Completely trusted account, more so than the administrator account. There is nothing on a single box that this account cannot do, and it has the right to access the network as the machine (this requires Active Directory and granting the machine account permissions to something)

    • Name: .\LocalSystem (can also use LocalSystem or ComputerName\LocalSystem)
    • the account has no password (any password information you provide is ignored)
    • SID: S-1-5-18
    • does not have any profile of its own (HKCU represents the default user)
    • has extensive privileges on the local computer
    • presents the computer's credentials (e.g. MANGO$) to remote servers

     

Above when talking about accessing the network, this refers solely to SPNEGO (Negotiate), NTLM and Kerberos and not to any other authentication mechanism. For example, processing running as LocalService can still access the internet.

The general issue with running as a standard out of the box account is that if you modify any of the default permissions you're expanding the set of things everything running as that account can do. So if you grant DBO to a database, not only can your service running as Local Service or Network Service access that database but everything else running as those accounts can too. If every developer does this the computer will have a service account that has permissions to do practically anything (more specifically the superset of all of the different additional privileges granted to that account).

It is always preferable from a security perspective to run as your own service account that has precisely the permissions you need to do what your service does and nothing else. However, the cost of this approach is setting up your service account, and managing the password. It's a balancing act that each application needs to manage.

In your specific case, the issue that you are probably seeing is that the the DCOM or COM+ activation is limited to a given set of accounts. In Windows XP SP2, Windows Server 2003, and above the Activation permission was restricted significantly. You should use the Component Services MMC snapin to examine your specific COM object and see the activation permissions. If you're not accessing anything on the network as the machine account you should seriously consider using Local Service (not Local System which is basically the operating system).


In Windows Server 2003 you cannot run a scheduled task as

  • NT_AUTHORITY\LocalService (aka the Local Service account), or
  • NT AUTHORITY\NetworkService (aka the Network Service account).

That capability only was added with Task Scheduler 2.0, which only exists in Windows Vista/Windows Server 2008 and newer.

A service running as NetworkService presents the machine credentials on the network. This means that if your computer was called mango, it would present as the machine account MANGO$:

enter image description here

IIS7: Setup Integrated Windows Authentication like in IIS6

Two-stage authentication is not supported with IIS7 Integrated mode. Authentication is now modularized, so rather than IIS performing authentication followed by asp.net performing authentication, it all happens at the same time.

You can either:

  1. Change the app domain to be in IIS6 classic mode...
  2. Follow this example (old link) of how to fake two-stage authentication with IIS7 integrated mode.
  3. Use Helicon Ape and mod_auth to provide basic authentication

How do I use the built in password reset/change views with my own templates

You can do the following:

  1. add to your urlpatterns (r'^/accounts/password/reset/$', password_reset)
  2. put your template in '/templates/registration/password_reset_form.html'
  3. make your app come before 'django.contrib.auth' in INSTALLED_APPS

Explanation:

When the templates are loaded, they are searched in your INSTALLED_APPS variable in settings.py . The order is dictated by the definition's rank in INSTALLED_APPS, so since your app come before 'django.contrib.auth' your template were loaded (reference: https://docs.djangoproject.com/en/dev/ref/templates/api/#django.template.loaders.app_directories.Loader).

Motivation of approach:

  1. I want be more dry and don't repeat for any view(defined by django) the template name (they are already defined in django)
  2. I want a smallest url.py

How can I verify a Google authentication API access token?

function authenticate_google_OAuthtoken($user_id)
{
    $access_token   = google_get_user_token($user_id); // get existing token from DB
    $redirecturl    = $Google_Permissions->redirecturl;
    $client_id      = $Google_Permissions->client_id;
    $client_secret  = $Google_Permissions->client_secret;
    $redirect_uri   = $Google_Permissions->redirect_uri;
    $max_results    = $Google_Permissions->max_results;

    $url = 'https://www.googleapis.com/oauth2/v1/tokeninfo?access_token='.$access_token;
    $response_contacts  =  curl_get_responce_contents($url);
    $response   =   (json_decode($response_contacts));

    if(isset($response->issued_to))
    {
        return true;
    }
    else if(isset($response->error))
    {
        return false;
    }
}

How to validate domain credentials?

I`m using the following code to validate credentials. The method shown below will confirm if the credentials are correct and if not wether the password is expired or needs change.

I`ve been looking for something like this for ages... So i hope this helps someone!

using System;
using System.DirectoryServices;
using System.DirectoryServices.AccountManagement;
using System.Runtime.InteropServices;

namespace User
{
    public static class UserValidation
    {
        [DllImport("advapi32.dll", SetLastError = true)]
        static extern bool LogonUser(string principal, string authority, string password, LogonTypes logonType, LogonProviders logonProvider, out IntPtr token);
        [DllImport("kernel32.dll", SetLastError = true)]
        static extern bool CloseHandle(IntPtr handle);
        enum LogonProviders : uint
        {
            Default = 0, // default for platform (use this!)
            WinNT35,     // sends smoke signals to authority
            WinNT40,     // uses NTLM
            WinNT50      // negotiates Kerb or NTLM
        }
        enum LogonTypes : uint
        {
            Interactive = 2,
            Network = 3,
            Batch = 4,
            Service = 5,
            Unlock = 7,
            NetworkCleartext = 8,
            NewCredentials = 9
        }
        public  const int ERROR_PASSWORD_MUST_CHANGE = 1907;
        public  const int ERROR_LOGON_FAILURE = 1326;
        public  const int ERROR_ACCOUNT_RESTRICTION = 1327;
        public  const int ERROR_ACCOUNT_DISABLED = 1331;
        public  const int ERROR_INVALID_LOGON_HOURS = 1328;
        public  const int ERROR_NO_LOGON_SERVERS = 1311;
        public  const int ERROR_INVALID_WORKSTATION = 1329;
        public  const int ERROR_ACCOUNT_LOCKED_OUT = 1909;      //It gives this error if the account is locked, REGARDLESS OF WHETHER VALID CREDENTIALS WERE PROVIDED!!!
        public  const int ERROR_ACCOUNT_EXPIRED = 1793;
        public  const int ERROR_PASSWORD_EXPIRED = 1330;

        public static int CheckUserLogon(string username, string password, string domain_fqdn)
        {
            int errorCode = 0;
            using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, domain_fqdn, "ADMIN_USER", "PASSWORD"))
            {
                if (!pc.ValidateCredentials(username, password))
                {
                    IntPtr token = new IntPtr();
                    try
                    {
                        if (!LogonUser(username, domain_fqdn, password, LogonTypes.Network, LogonProviders.Default, out token))
                        {
                            errorCode = Marshal.GetLastWin32Error();
                        }
                    }
                    catch (Exception)
                    {
                        throw;
                    }
                    finally
                    {
                        CloseHandle(token);
                    }
                }
            }
            return errorCode;
        }
    }

How to create relationships in MySQL

create table departement(
    dep_id      int primary key auto_increment,
    dep_name    varchar(100) not null,
    dep_descriptin      text,
    dep_photo       varchar(100) not null,
    dep_video       varchar(300) not null
);

create table newsfeeds(
    news_id         int primary key auto_increment,
    news_title      varchar(200) not null,
    news_description    text,
    news_photo          varchar(300) ,
    news_date           varchar(30) not null,
    news_video          varchar(300),
    news_comment        varchar(200),
    news_departement    int foreign key(dep_id) references departement(dep_id)
);

Minimum rights required to run a windows service as a domain account

I do know that the account needs to have "Log on as a Service" privileges. Other than that, I'm not sure. A quick reference to Log on as a Service can be found here, and there is a lot of information of specific privileges here.

How do you run CMD.exe under the Local System Account?

Found an answer here which seems to solve the problem by adding /k start to the binPath parameter. So that would give you:

sc create testsvc binpath= "cmd /K start" type= own type= interact

However, Ben said that didn't work for him and when I tried it on Windows Server 2008 it did create the cmd.exe process under local system, but it wasn't interactive (I couldn't see the window).

I don't think there is an easy way to do what you ask, but I'm wondering why you're doing it at all? Are you just trying to see what is happening when you run your service? Seems like you could just use logging to determine what is happening instead of having to run the exe as local system...

Using Rsync include and exclude options to include directory and file by pattern

The problem is that --exclude="*" says to exclude (for example) the 1260000000/ directory, so rsync never examines the contents of that directory, so never notices that the directory contains files that would have been matched by your --include.

I think the closest thing to what you want is this:

rsync -nrv --include="*/" --include="file_11*.jpg" --exclude="*" /Storage/uploads/ /website/uploads/

(which will include all directories, and all files matching file_11*.jpg, but no other files), or maybe this:

rsync -nrv --include="/[0-9][0-9][0-9]0000000/" --include="file_11*.jpg" --exclude="*" /Storage/uploads/ /website/uploads/

(same concept, but much pickier about the directories it will include).

How to forcefully set IE's Compatibility Mode off from the server-side?

For Node/Express developers you can use middleware and set this via server.

app.use(function(req, res, next) {
  res.setHeader('X-UA-Compatible', 'IE=edge');
  next();
});

Delete last char of string

string strgroupids = string.Empty;

groupIds.ForEach(g =>
{
    strgroupids = strgroupids + g.ToString() + ",";
});

strgroupids = strgroupids.Substring(0, strgroupids.Length - 1);

Note that the use of ForEach here is normally considered "wrong" (read for example http://blogs.msdn.com/b/ericlippert/archive/2009/05/18/foreach-vs-foreach.aspx)

Using some LINQ:

string strgroupids = groupIds.Aggregate(string.Empty, (p, q) => p + q + ',');
strgroupids = strgroupids.Substring(0, str1.Length - 1);

Without end-substringing:

string strgroupids = groupIds.Aggregate(string.Empty, (p, q) => (p != string.Empty ? p + "," + q : q.ToString()));

Rails: Address already in use - bind(2) (Errno::EADDRINUSE)

you can also try this trick:

ps aux | grep puma

sample output:

myname           77921   0.0  0.0  2433828   1972 s000  R+   11:17AM   0:00.00 grep puma
myname           67661   0.0  2.3  2680504 191204 s002  S+   11:00AM   0:18.38 puma 3.11.2 (tcp://localhost:3000) [my_proj]

then:

kill -9 67661

DISTINCT for only one column

When you use DISTINCT think of it as a distinct row, not column. It will return only rows where the columns do not match exactly the same.

SELECT DISTINCT ID, Email, ProductName, ProductModel
FROM Products

----------------------
1 | [email protected] | ProductName1 | ProductModel1
2 | [email protected] | ProductName1 | ProductModel1

The query would return both rows because the ID column is different. I'm assuming that the ID column is an IDENTITY column that is incrementing, if you want to return the last then I recommend something like this:

SELECT DISTINCT TOP 1 ID, Email, ProductName, ProductModel
FROM Products
ORDER BY ID DESC

The TOP 1 will return only the first record, by ordering it by the ID descending it will return the results with the last row first. This will give you the last record.

Why aren't variable-length arrays part of the C++ standard?

C99 allows VLA. And it puts some restrictions on how to declare VLA. For details, refer to 6.7.5.2 of the standard. C++ disallows VLA. But g++ allows it.

How can I check if a URL exists via PHP?

Here:

$file = 'http://www.example.com/somefile.jpg';
$file_headers = @get_headers($file);
if(!$file_headers || $file_headers[0] == 'HTTP/1.1 404 Not Found') {
    $exists = false;
}
else {
    $exists = true;
}

From here and right below the above post, there's a curl solution:

function url_exists($url) {
    return curl_init($url) !== false;
}

Accessing bash command line args $@ vs $*

$@ is same as $*, but each parameter is a quoted string, that is, the parameters are passed on intact, without interpretation or expansion. This means, among other things, that each parameter in the argument list is seen as a separate word.

Of course, "$@" should be quoted.

http://tldp.org/LDP/abs/html/internalvariables.html#ARGLIST

'gulp' is not recognized as an internal or external command

I had the same problem on windows 7. You must edit your path system variable manually.

Go to START -> edit the system environment variables -> Environment variables -> in system part find variables "Path" -> edit -> add new path after ";" to your file gulp.cmd directory some like ';C:\Users\YOURUSERNAME\AppData\Roaming\npm' -> click ok and close these windows -> restart your CLI -> enjoy

Join/Where with LINQ and Lambda

I find that if you're familiar with SQL syntax, using the LINQ query syntax is much clearer, more natural, and makes it easier to spot errors:

var id = 1;
var query =
   from post in database.Posts
   join meta in database.Post_Metas on post.ID equals meta.Post_ID
   where post.ID == id
   select new { Post = post, Meta = meta };

If you're really stuck on using lambdas though, your syntax is quite a bit off. Here's the same query, using the LINQ extension methods:

var id = 1;
var query = database.Posts    // your starting point - table in the "from" statement
   .Join(database.Post_Metas, // the source table of the inner join
      post => post.ID,        // Select the primary key (the first part of the "on" clause in an sql "join" statement)
      meta => meta.Post_ID,   // Select the foreign key (the second part of the "on" clause)
      (post, meta) => new { Post = post, Meta = meta }) // selection
   .Where(postAndMeta => postAndMeta.Post.ID == id);    // where statement

Hide strange unwanted Xcode logs

This solution has been working for me:

  1. Run the app in the simulator
  2. Open the system log (? + /)

This will dump out all of the debug data and also your NSLogs.

To filter just your NSLog statements:

  1. Prefix each with a symbol, for example: NSLog(@"^ Test Log")
  2. Filter the results using the search box on the top right, "^" in the case above

This is what you should get:

Screenshot of console

Start ssh-agent on login

Users of the fish shell can use this script to do the same thing.

# content has to be in .config/fish/config.fish
# if it does not exist, create the file
setenv SSH_ENV $HOME/.ssh/environment

function start_agent                                                                                                                                                                    
    echo "Initializing new SSH agent ..."
    ssh-agent -c | sed 's/^echo/#echo/' > $SSH_ENV
    echo "succeeded"
    chmod 600 $SSH_ENV 
    . $SSH_ENV > /dev/null
    ssh-add
end

function test_identities                                                                                                                                                                
    ssh-add -l | grep "The agent has no identities" > /dev/null
    if [ $status -eq 0 ]
        ssh-add
        if [ $status -eq 2 ]
            start_agent
        end
    end
end

if [ -n "$SSH_AGENT_PID" ] 
    ps -ef | grep $SSH_AGENT_PID | grep ssh-agent > /dev/null
    if [ $status -eq 0 ]
        test_identities
    end  
else
    if [ -f $SSH_ENV ]
        . $SSH_ENV > /dev/null
    end  
    ps -ef | grep $SSH_AGENT_PID | grep -v grep | grep ssh-agent > /dev/null
    if [ $status -eq 0 ]
        test_identities
    else 
        start_agent
    end  
end

Git: "Not currently on any branch." Is there an easy way to get back on a branch, while keeping the changes?

One way to end up in this situation is after doing a rebase from a remote branch. In this case, the new commits are pointed to by HEAD but master does not point to them -- it's pointing to wherever it was before you rebased the other branch.

You can make this commit your new master by doing:

git branch -f master HEAD
git checkout master

This forcibly updates master to point to HEAD (without putting you on master) then switches to master.

Detect if a jQuery UI dialog box is open

If you want to check if the dialog's open on a particular element you can do this:

if ($('#elem').closest('.ui-dialog').is(':visible')) { 
  // do something
}

Or if you just want to check if the element itself is visible you can do:

if ($('#elem').is(':visible')) { 
  // do something
}

Or...

if ($('#elem:visible').length) { 
  // do something
}

What's the best way to check if a file exists in C?

Use stat like this:

#include <sys/stat.h>   // stat
#include <stdbool.h>    // bool type

bool file_exists (char *filename) {
  struct stat   buffer;   
  return (stat (filename, &buffer) == 0);
}

and call it like this:

#include <stdio.h>      // printf

int main(int ac, char **av) {
    if (ac != 2)
        return 1;

    if (file_exists(av[1]))
        printf("%s exists\n", av[1]);
    else
        printf("%s does not exist\n", av[1]);

    return 0;
}

SQL, How to Concatenate results?

Small update on Marc we will have additional " , " at the end. i used stuff function to remove extra semicolon .

       SELECT STUFF((  SELECT ',' + ModuleValue AS ModuleValue
                           FROM ModuleValue WHERE ModuleID=@ModuleID
                      FOR XML PATH('') 
                     ), 1, 1, '' )

How to create a directory and give permission in single command

install -d -m 0777 /your/dir

should give you what you want. Be aware that every user has the right to write add and delete files in that directory.

Get query string parameters url values with jQuery / Javascript (querystring)

Why extend jQuery? What would be the benefit of extending jQuery vs just having a global function?

function qs(key) {
    key = key.replace(/[*+?^$.\[\]{}()|\\\/]/g, "\\$&"); // escape RegEx meta chars
    var match = location.search.match(new RegExp("[?&]"+key+"=([^&]+)(&|$)"));
    return match && decodeURIComponent(match[1].replace(/\+/g, " "));
}

http://jsfiddle.net/gilly3/sgxcL/

An alternative approach would be to parse the entire query string and store the values in an object for later use. This approach doesn't require a regular expression and extends the window.location object (but, could just as easily use a global variable):

location.queryString = {};
location.search.substr(1).split("&").forEach(function (pair) {
    if (pair === "") return;
    var parts = pair.split("=");
    location.queryString[parts[0]] = parts[1] &&
        decodeURIComponent(parts[1].replace(/\+/g, " "));
});

http://jsfiddle.net/gilly3/YnCeu/

This version also makes use of Array.forEach(), which is unavailable natively in IE7 and IE8. It can be added by using the implementation at MDN, or you can use jQuery's $.each() instead.

pyplot axes labels for subplots

# list loss and acc are your data
fig = plt.figure()
ax1 = fig.add_subplot(121)
ax2 = fig.add_subplot(122)

ax1.plot(iteration1, loss)
ax2.plot(iteration2, acc)

ax1.set_title('Training Loss')
ax2.set_title('Training Accuracy')

ax1.set_xlabel('Iteration')
ax1.set_ylabel('Loss')

ax2.set_xlabel('Iteration')
ax2.set_ylabel('Accuracy')

mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, boolean given

What happens in your code if $usertable is not a valid table or doesn't include a column PartNumber or part is not a number.

You must escape $partid and also read the document for mysql_fetch_assoc() because it can return a boolean

Catching errors in Angular HttpClient

You have some options, depending on your needs. If you want to handle errors on a per-request basis, add a catch to your request. If you want to add a global solution, use HttpInterceptor.

Open here the working demo plunker for the solutions below.

tl;dr

In the simplest case, you'll just need to add a .catch() or a .subscribe(), like:

import 'rxjs/add/operator/catch'; // don't forget this, or you'll get a runtime error
this.httpClient
      .get("data-url")
      .catch((err: HttpErrorResponse) => {
        // simple logging, but you can do a lot more, see below
        console.error('An error occurred:', err.error);
      });

// or
this.httpClient
      .get("data-url")
      .subscribe(
        data => console.log('success', data),
        error => console.log('oops', error)
      );

But there are more details to this, see below.


Method (local) solution: log error and return fallback response

If you need to handle errors in only one place, you can use catch and return a default value (or empty response) instead of failing completely. You also don't need the .map just to cast, you can use a generic function. Source: Angular.io - Getting Error Details.

So, a generic .get() method, would be like:

import { Injectable } from '@angular/core';
import { HttpClient, HttpErrorResponse } from "@angular/common/http";
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/of';
import 'rxjs/add/observable/empty';
import 'rxjs/add/operator/retry'; // don't forget the imports

@Injectable()
export class DataService {
    baseUrl = 'http://localhost';
    constructor(private httpClient: HttpClient) { }

    // notice the <T>, making the method generic
    get<T>(url, params): Observable<T> {
      return this.httpClient
          .get<T>(this.baseUrl + url, {params})
          .retry(3) // optionally add the retry
          .catch((err: HttpErrorResponse) => {

            if (err.error instanceof Error) {
              // A client-side or network error occurred. Handle it accordingly.
              console.error('An error occurred:', err.error.message);
            } else {
              // The backend returned an unsuccessful response code.
              // The response body may contain clues as to what went wrong,
              console.error(`Backend returned code ${err.status}, body was: ${err.error}`);
            }

            // ...optionally return a default fallback value so app can continue (pick one)
            // which could be a default value
            // return Observable.of<any>({my: "default value..."});
            // or simply an empty observable
            return Observable.empty<T>();
          });
     }
}

Handling the error will allow you app to continue even when the service at the URL is in bad condition.

This per-request solution is good mostly when you want to return a specific default response to each method. But if you only care about error displaying (or have a global default response), the better solution is to use an interceptor, as described below.

Run the working demo plunker here.


Advanced usage: Intercepting all requests or responses

Once again, Angular.io guide shows:

A major feature of @angular/common/http is interception, the ability to declare interceptors which sit in between your application and the backend. When your application makes a request, interceptors transform it before sending it to the server, and the interceptors can transform the response on its way back before your application sees it. This is useful for everything from authentication to logging.

Which, of course, can be used to handle errors in a very simple way (demo plunker here):

import { Injectable } from '@angular/core';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpResponse,
         HttpErrorResponse } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/of';
import 'rxjs/add/observable/empty';
import 'rxjs/add/operator/retry'; // don't forget the imports

@Injectable()
export class HttpErrorInterceptor implements HttpInterceptor {
  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(request)
      .catch((err: HttpErrorResponse) => {

        if (err.error instanceof Error) {
          // A client-side or network error occurred. Handle it accordingly.
          console.error('An error occurred:', err.error.message);
        } else {
          // The backend returned an unsuccessful response code.
          // The response body may contain clues as to what went wrong,
          console.error(`Backend returned code ${err.status}, body was: ${err.error}`);
        }

        // ...optionally return a default fallback value so app can continue (pick one)
        // which could be a default value (which has to be a HttpResponse here)
        // return Observable.of(new HttpResponse({body: [{name: "Default value..."}]}));
        // or simply an empty observable
        return Observable.empty<HttpEvent<any>>();
      });
  }
}

Providing your interceptor: Simply declaring the HttpErrorInterceptor above doesn't cause your app to use it. You need to wire it up in your app module by providing it as an interceptor, as follows:

import { NgModule } from '@angular/core';
import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { HttpErrorInterceptor } from './path/http-error.interceptor';

@NgModule({
  ...
  providers: [{
    provide: HTTP_INTERCEPTORS,
    useClass: HttpErrorInterceptor,
    multi: true,
  }],
  ...
})
export class AppModule {}

Note: If you have both an error interceptor and some local error handling, naturally, it is likely that no local error handling will ever be triggered, since the error will always be handled by the interceptor before it reaches the local error handling.

Run the working demo plunker here.

Redis connection to 127.0.0.1:6379 failed - connect ECONNREFUSED

For me I had this issue on Ubuntu 18.x, but my problem was that my redis-server was running on 127.0.0.1 but I found out I needed to run it on my IP address xxx.xx.xx.xx

I went into my Ubuntu machine and did the following.

cd /etc/redis/

sudo vim redis.conf

Then I edited this part.

################################## NETWORK #####################################

# By default, if no "bind" configuration directive is specified, Redis listens
# for connections from all the network interfaces available on the server.
# It is possible to listen to just one or multiple selected interfaces using
# the "bind" configuration directive, followed by one or more IP addresses.
#
# Examples:
#
# bind 192.168.1.100 10.0.0.1
# bind 127.0.0.1 ::1
#
# ~~~ WARNING ~~~ If the computer running Redis is directly exposed to the
# internet, binding to all the interfaces is dangerous and will expose the
# instance to everybody on the internet. So by default we uncomment the
# following bind directive, that will force Redis to listen only into
# the IPv4 loopback interface address (this means Redis will be able to
# accept connections only from clients running into the same computer it
# is running).le to listen to just one or multiple selected interfaces using
#
# IF YOU ARE SURE YOU WANT YOUR INSTANCE TO LISTEN TO ALL THE INTERFACES
# JUST COMMENT THE FOLLOWING LINE.
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# bind 127.0.0.1 ::1 10.0.0.1
bind 127.0.0.1 ::1 # <<-------- change this to what your iP address is something like (bind 192.168.2.2)

Save that, and then restart redis-server.

sudo service redis-server restart or simply run redis-server

How do you redirect HTTPS to HTTP?

If none of the above solutions work for you (they did not for me) here is what worked on my server:

RewriteCond %{HTTPS} =on
RewriteRule ^(.*)$ http://%{HTTP_HOST}/$1 [L,R=301]

PHP: How to use array_filter() to filter array keys?

array filter function from php:

array_filter ( $array, $callback_function, $flag )

$array - It is the input array

$callback_function - The callback function to use, If the callback function returns true, the current value from array is returned into the result array.

$flag - It is optional parameter, it will determine what arguments are sent to callback function. If this parameter empty then callback function will take array values as argument. If you want to send array key as argument then use $flag as ARRAY_FILTER_USE_KEY. If you want to send both keys and values you should use $flag as ARRAY_FILTER_USE_BOTH .

For Example : Consider simple array

$array = array("a"=>1, "b"=>2, "c"=>3, "d"=>4, "e"=>5);

If you want to filter array based on the array key, We need to use ARRAY_FILTER_USE_KEY as third parameter of array function array_filter.

$get_key_res = array_filter($array,"get_key",ARRAY_FILTER_USE_KEY );

If you want to filter array based on the array key and array value, We need to use ARRAY_FILTER_USE_BOTH as third parameter of array function array_filter.

$get_both = array_filter($array,"get_both",ARRAY_FILTER_USE_BOTH );

Sample Callback functions:

 function get_key($key)
 {
    if($key == 'a')
    {
        return true;
    } else {
        return false;
    }
}
function get_both($val,$key)
{
    if($key == 'a' && $val == 1)
    {
        return true;
    }   else {
        return false;
    }
}

It will output

Output of $get_key is :Array ( [a] => 1 ) 
Output of $get_both is :Array ( [a] => 1 ) 

IntelliJ - Convert a Java project/module into a Maven project/module

The easiest way is to add the project as a Maven project directly. To do this, in the project explorer on the left, right-click on the POM file for the project, towards the bottom of the context menu, you will see an option called 'Add as Maven Project', click it. This will automatically convert the project to a Maven project

How to write to a file, using the logging Python module?

http://docs.python.org/library/logging.handlers.html#filehandler

The FileHandler class, located in the core logging package, sends logging output to a disk file.

How to set text color in submit button?

Use this CSS:

color: red;

that's all.

Converting String to Double in Android

  kw=(EditText)findViewById(R.id.kw);
    btn=(Button)findViewById(R.id.btn);
    cost=(TextView )findViewById(R.id.cost);


            btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) { cst =  Double.valueOf(kw.getText().toString());
            cst = cst*0.551;
            cost.setText(cst.toString());
        }
    });

Detecting a long press with Android

I have a code which detects a click, a long click and movement. It is fairly a combination of the answer given above and the changes i made from peeping into every documentation page.

//Declare this flag globally
boolean goneFlag = false;

//Put this into the class
final Handler handler = new Handler(); 
    Runnable mLongPressed = new Runnable() { 
        public void run() { 
            goneFlag = true;
            //Code for long click
        }   
    };

//onTouch code
@Override
    public boolean onTouch(View v, MotionEvent event) {
        switch (event.getAction()) {    
        case MotionEvent.ACTION_DOWN:
            handler.postDelayed(mLongPressed, 1000);
            //This is where my code for movement is initialized to get original location.
            break;
        case MotionEvent.ACTION_UP:
            handler.removeCallbacks(mLongPressed);
            if(Math.abs(event.getRawX() - initialTouchX) <= 2 && !goneFlag) {
                //Code for single click
                return false;
            }
            break;
        case MotionEvent.ACTION_MOVE:
            handler.removeCallbacks(mLongPressed);
            //Code for movement here. This may include using a window manager to update the view
            break;
        }
        return true;
    }

I confirm it's working as I have used it in my own application.

How to Disable GUI Button in Java

Rather than using booleans, why not just set the button to false when its clicked, so you do that in your actionPerformed method. Its more efficient..

if (command.equals("w"))
{
    FileConverter fc = new FileConverter();
    btnConvertDocuments.setEnabled(false);
}

Remove empty space before cells in UITableView

In 2017, what is working for me is simply this one line

navigationController?.navigationBar.isTranslucent = false

I have no idea why that would even affect it. Perhaps someone could explain. But I'm pretty sure this is the answer most people would look for.

TokenMismatchException in VerifyCsrfToken.php Line 67

You should try this.

Add {{ csrf_field() }} just after your form opening tag like so.

<form method="POST" action="/your/{{ $action_id }}">
{{ csrf_field() }}    

RequiredIf Conditional Validation Attribute

I got it to work on ASP.NET MVC 5

I saw many people interested in and suffering from this code and i know it's really confusing and disrupting for the first time.

Notes

  • worked on MVC 5 on both server and client side :D
  • I didn't install "ExpressiveAnnotations" library at all.
  • I'm taking about the Original code from "@Dan Hunex", Find him above

Tips To Fix This Error

"The type System.Web.Mvc.RequiredAttributeAdapter must have a public constructor which accepts three parameters of types System.Web.Mvc.ModelMetadata, System.Web.Mvc.ControllerContext, and ExpressiveAnnotations.Attributes.RequiredIfAttribute Parameter name: adapterType"

Tip #1: make sure that you're inheriting from 'ValidationAttribute' not from 'RequiredAttribute'

 public class RequiredIfAttribute : ValidationAttribute, IClientValidatable { ...}

Tip #2: OR remove this entire line from 'Global.asax', It is not needed at all in the newer version of the code (after edit by @Dan_Hunex), and yes this line was a must in the old version ...

DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(RequiredIfAttribute), typeof(RequiredAttributeAdapter));

Tips To Get The Javascript Code Part Work

1- put the code in a new js file (ex:requiredIfValidator.js)

2- warp the code inside a $(document).ready(function(){........});

3- include our js file after including the JQuery validation libraries, So it look like this now :

@Scripts.Render("~/bundles/jqueryval")
<script src="~/Content/JS/requiredIfValidator.js"></script>

4- Edit the C# code

from

rule.ValidationParameters["dependentproperty"] = (context as ViewContext).ViewData.TemplateInfo.GetFullHtmlFieldId(PropertyName);

to

rule.ValidationParameters["dependentproperty"] = PropertyName;

and from

if (dependentValue.ToString() == DesiredValue.ToString())

to

if (dependentValue != null && dependentValue.ToString() == DesiredValue.ToString())

My Entire Code Up and Running

Global.asax

Nothing to add here, keep it clean

requiredIfValidator.js

create this file in ~/content or in ~/scripts folder

    $.validator.unobtrusive.adapters.add('requiredif', ['dependentproperty', 'desiredvalue'], function (options)
{
    options.rules['requiredif'] = options.params;
    options.messages['requiredif'] = options.message;
});


$(document).ready(function ()
{

    $.validator.addMethod('requiredif', function (value, element, parameters) {
        var desiredvalue = parameters.desiredvalue;
        desiredvalue = (desiredvalue == null ? '' : desiredvalue).toString();
        var controlType = $("input[id$='" + parameters.dependentproperty + "']").attr("type");
        var actualvalue = {}
        if (controlType == "checkbox" || controlType == "radio") {
            var control = $("input[id$='" + parameters.dependentproperty + "']:checked");
            actualvalue = control.val();
        } else {
            actualvalue = $("#" + parameters.dependentproperty).val();
        }
        if ($.trim(desiredvalue).toLowerCase() === $.trim(actualvalue).toLocaleLowerCase()) {
            var isValid = $.validator.methods.required.call(this, value, element, parameters);
            return isValid;
        }
        return true;
    });
});

_Layout.cshtml or the View

@Scripts.Render("~/bundles/jqueryval")
<script src="~/Content/JS/requiredIfValidator.js"></script>

RequiredIfAttribute.cs Class

create it some where in your project, For example in ~/models/customValidation/

    using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;

namespace Your_Project_Name.Models.CustomValidation
{
    public class RequiredIfAttribute : ValidationAttribute, IClientValidatable
    {
        private String PropertyName { get; set; }
        private Object DesiredValue { get; set; }
        private readonly RequiredAttribute _innerAttribute;

        public RequiredIfAttribute(String propertyName, Object desiredvalue)
        {
            PropertyName = propertyName;
            DesiredValue = desiredvalue;
            _innerAttribute = new RequiredAttribute();
        }

        protected override ValidationResult IsValid(object value, ValidationContext context)
        {
            var dependentValue = context.ObjectInstance.GetType().GetProperty(PropertyName).GetValue(context.ObjectInstance, null);

            if (dependentValue != null && dependentValue.ToString() == DesiredValue.ToString())
            {
                if (!_innerAttribute.IsValid(value))
                {
                    return new ValidationResult(FormatErrorMessage(context.DisplayName), new[] { context.MemberName });
                }
            }
            return ValidationResult.Success;
        }

        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            var rule = new ModelClientValidationRule
            {
                ErrorMessage = ErrorMessageString,
                ValidationType = "requiredif",
            };
            rule.ValidationParameters["dependentproperty"] = PropertyName;
            rule.ValidationParameters["desiredvalue"] = DesiredValue is bool ? DesiredValue.ToString().ToLower() : DesiredValue;

            yield return rule;
        }
    }
}

The Model

    using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
using Your_Project_Name.Models.CustomValidation;

namespace Your_Project_Name.Models.ViewModels
{

    public class CreateOpenActivity
    {
        public Nullable<int> ORG_BY_CD { get; set; }

        [RequiredIf("ORG_BY_CD", "5", ErrorMessage = "Coordinator ID is required")] // This means: IF 'ORG_BY_CD' is equal 5 (for the example)  > make 'COR_CI_ID_NUM' required and apply its all validation / data annotations
        [RegularExpression("[0-9]+", ErrorMessage = "Enter Numbers Only")]
        [MaxLength(9, ErrorMessage = "Enter a valid ID Number")]
        [MinLength(9, ErrorMessage = "Enter a valid ID Number")]
        public string COR_CI_ID_NUM { get; set; }
    }
}

The View

Nothing to note here actually ...

    @model Your_Project_Name.Models.ViewModels.CreateOpenActivity
@{
    ViewBag.Title = "Testing";
}

@using (Html.BeginForm()) 
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>CreateOpenActivity</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })

        <div class="form-group">
            @Html.LabelFor(model => model.ORG_BY_CD, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.ORG_BY_CD, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.ORG_BY_CD, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.COR_CI_ID_NUM, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.COR_CI_ID_NUM, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.COR_CI_ID_NUM, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </div>
    </div>
}

I may upload a project sample for this later ...

Hope this was helpful

Thank You

Insert an item into sorted list in Python

Hint 1: You might want to study the Python code in the bisect module.

Hint 2: Slicing can be used for list insertion:

>>> s = ['a', 'b', 'd', 'e']
>>> s[2:2] = ['c']
>>> s
['a', 'b', 'c', 'd', 'e']

What exactly does Perl's "bless" do?

Along with a number of good answers, what specifically distinguishes a bless-ed reference is that the SV for it picks up an additional FLAGS (OBJECT) and a STASH

perl -MDevel::Peek -wE'
    package Pack  { sub func { return { a=>1 } } }; 
    package Class { sub new  { return bless { A=>10 } } }; 
    $vp  = Pack::func(); print Dump $vp;   say"---"; 
    $obj = Class->new;   print Dump $obj'

Prints, with the same (and irrelevant for this) parts suppressed

SV = IV(0x12d5530) at 0x12d5540
  REFCNT = 1
  FLAGS = (ROK)
  RV = 0x12a5a68
  SV = PVHV(0x12ab980) at 0x12a5a68
    REFCNT = 1
    FLAGS = (SHAREKEYS)
    ...
      SV = IV(0x12a5ce0) at 0x12a5cf0
      REFCNT = 1
      FLAGS = (IOK,pIOK)
      IV = 1
---
SV = IV(0x12cb8b8) at 0x12cb8c8
  REFCNT = 1
  FLAGS = (PADMY,ROK)
  RV = 0x12c26b0
  SV = PVHV(0x12aba00) at 0x12c26b0
    REFCNT = 1
    FLAGS = (OBJECT,SHAREKEYS)
    STASH = 0x12d5300   "Class"
    ...
      SV = IV(0x12c26b8) at 0x12c26c8
      REFCNT = 1
      FLAGS = (IOK,pIOK)
      IV = 10

With that it's known that 1) it is an object 2) what package it belongs to, and this informs its use.

For example, when dereferencing on that variable is encountered ($obj->name), a sub with that name is sought in the package (or hierarchy), the object is passed as the first argument, etc.

How to edit a text file in my terminal

Open the file again using vi. and then press " i " or press insert key ,

For save and quit

  Enter Esc    

and write the following command

  :wq

without save and quit

  :q!

Error: Cannot pull with rebase: You have unstaged changes

Do git status, this will show you what files have changed. Since you stated that you don't want to keep the changes you can do git checkout -- <file name> or git reset --hard to get rid of the changes.

For the most part, git will tell you what to do about changes. For example, your error message said to git stash your changes. This would be if you wanted to keep them. After pulling, you would then do git stash pop and your changes would be reapplied.

git status also has how to get rid of changes depending on if the file is staged for commit or not.

How to set an image's width and height without stretching it?

you can try setting the padding instead of the height/width.

Error in Chrome only: XMLHttpRequest cannot load file URL No 'Access-Control-Allow-Origin' header is present on the requested resource

If your problem is like the following while using Google Chrome:

[XMLHttpRequest cannot load file. Received an invalid response. Origin 'null' is therefore not allowed access.]

Then create a batch file by following these steps:

Open notepad in Desktop.

  1. Just copy and paste the followings in your currently opened notepad file:

start "chrome" "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --allow-file-access-from-files exit

  1. Note: In the previous line, Replace the full absolute address with your location of chrome installation. [To find it...Right click your short cut of chrome.exe link or icon and Click on Properties and copy-paste the target link][Remember : start to files in one line, & exit in another line by pressing enter]
  2. Save the file as fileName.bat [Very important: .bat]
  3. If you want to change the file later then right-click on the .bat file and click on edit. After modifying, save the file.

This will do what? It will open Chrome.exe with file access. Now, from any location in your computer, browse your html files with Google Chrome. I hope this will solve the XMLHttpRequest problem.

Keep in mind : Just use the shortcut bat file to open Chrome when you require it. Tell me if it solves your problem. I had a similar problem and I solved it in this way. Thanks.

Can RDP clients launch remote applications and not desktops

RDP will not do that natively.

As other answers have said -- you'll need to do some scripting and make policy changes as a kludge to make it hard for RDP logins to run anything but the intended application.

However, as of 2008, Microsoft has released application virtualization technology via Terminal Services that will allow you to do this seamlessly.

spring autowiring with unique beans: Spring expected single matching bean but found 2

If I'm not mistaken, the default bean name of a bean declared with @Component is the name of its class its first letter in lower-case. This means that

@Component
public class SuggestionService {

declares a bean of type SuggestionService, and of name suggestionService. It's equivalent to

@Component("suggestionService")
public class SuggestionService {

or to

<bean id="suggestionService" .../>

You're redefining another bean of the same type, but with a different name, in the XML:

<bean id="SuggestionService" class="com.hp.it.km.search.web.suggestion.SuggestionService">
    ...
</bean>

So, either specify the name of the bean in the annotation to be SuggestionService, or use the ID suggestionService in the XML (don't forget to also modify the <ref> element, or to remove it, since it isn't needed). In this case, the XML definition will override the annotation definition.

Please initialize the log4j system properly warning

This work for me:

public static void main(String[] args) {

        Properties props = new Properties();
        props.load(new FileInputStream("src/log4j.properties"));
        PropertyConfigurator.configure(props);

Structs data type in php?

Closest you'd get to a struct is an object with all members public.

class MyStruct {
    public $foo;
    public $bar;
}

$obj = new MyStruct();
$obj->foo = 'Hello';
$obj->bar = 'World';

I'd say looking at the PHP Class Documentation would be worth it. If you need a one-off struct, use the StdObject as mentioned in alex's answer.

Export javascript data to CSV file without server interaction

Once I packed JS code doing that to a tiny library:

https://github.com/AlexLibs/client-side-csv-generator

The Code, Documentation and Demo/Playground are provided on Github.

Enjoy :)

Pull requests are welcome.

Why can't I have abstract static methods in C#?

The abstract methods are implicitly virtual. Abstract methods require an instance, but static methods do not have an instance. So, you can have a static method in an abstract class, it just cannot be static abstract (or abstract static).

What does 'git blame' do?

The git blame command is used to examine the contents of a file line by line and see when each line was last modified and who the author of the modifications was.

If there was a bug in code,use it to identify who cased it,then you can blame him. Git blame is get blame(d).

If you need to know history of one line code,use git log -S"code here", simpler than git blame.

git log vs git blame

How to add a new column to an existing sheet and name it?

Use insert method from range, for example

Sub InsertColumn()
        Columns("C:C").Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
        Range("C1").Value = "Loc"
End Sub

Get the value in an input text box

I think this function is missed here in previous answers:

.val( function(index, value) ) 

Determine Whether Two Date Ranges Overlap

The easiest way to do it in my opinion would be to compare if either EndDate1 is before StartDate2 and EndDate2 is before StartDate1.

That of course if you are considering intervals where StartDate is always before EndDate.

Maven: Failed to retrieve plugin descriptor error

In my case, it was not worknig even after passing the proxy credentails.

Mistake was - forgot to remove the comment line.

<!-- proxy
 | Specification for one proxy, to be used in connecting to the network.

<proxy>
  <id>optional</id>
  <active>true</active>
  <protocol>http</protocol>
  <username>345325</username>
  <password>dfgasdfg</password>
  <host>proxy.abc.com</host>
  <port>8080</port>
  <nonProxyHosts>proxy.abc.com</nonProxyHosts>
</proxy>
|-->    ----------REMOVE THIS LINE AND CLOSE It above <proxy> tag

Convert to Datetime MM/dd/yyyy HH:mm:ss in Sql Server

use

select convert(varchar(10),GETDATE(), 103) + 
       ' '+
       right(convert(varchar(32),GETDATE(),108),8) AS Date_Time

It will Produce:

Date_Time 30/03/2015 11:51:40

Export table from database to csv file

I wrote a small tool that does just that. Code is available on github.

To dump the results of one (or more) SQL queries to one (or more) CSV files:

java -jar sql_dumper.jar /path/sql/files/ /path/out/ user pass jdbcString

Cheers.

Necessary to add link tag for favicon.ico?

Please note that both the HTML5 specification of W3C and WhatWG standardize

<link rel="icon" href="/favicon.ico">

Note the value of the "rel" attribute!

The value shortcut icon for the rel attribute is a very old Internet Explorer specific extension and deprecated.

So please consider not using it any more and updating your files so they are standards compliant and are displayed correctly in all browsers.

You might also want to take a look at this great post: rel="shortcut icon" considered harmful

Search a string in a file and delete it from this file by Shell Script

Try the vim-way:

ex -s +"g/foo/d" -cwq file.txt

How to stop/terminate a python script from running?

  • To stop a python script just press Ctrl + C.
  • Inside a script with exit(), you can do it.
  • You can do it in an interactive script with just exit.
  • You can use pkill -f name-of-the-python-script.

How do I check if a number is positive or negative in C#?

The Math.Sign method is one way to go. It will return -1 for negative numbers, 1 for positive numbers, and 0 for values equal to zero (i.e. zero has no sign). Double and single precision variables will cause an exception (ArithmeticException) to be thrown if they equal NaN.

variable or field declared void

The thing is that, when you call a function you should not write the type of the function, that means you should call the funnction just like

initializeJSP(Experiment);

Can't install via pip because of egg_info error

I'll add this in here as my problem had something todo with my virtualenv:

I hadn't activated my virtual environment and was trying to install my requirements, this ultimately led to my install failing and throwing this error message.

So make sure you activate your virtualenv!

Select row with most recent date per user

Based in @TMS answer, I like it because there's no need for subqueries but I think ommiting the 'OR' part will be sufficient and much simpler to understand and read.

SELECT t1.*
FROM lms_attendance AS t1
LEFT JOIN lms_attendance AS t2
  ON t1.user = t2.user 
        AND t1.time < t2.time
WHERE t2.user IS NULL

if you are not interested in rows with null times you can filter them in the WHERE clause:

SELECT t1.*
FROM lms_attendance AS t1
LEFT JOIN lms_attendance AS t2
  ON t1.user = t2.user 
        AND t1.time < t2.time
WHERE t2.user IS NULL and t1.time IS NOT NULL

Angular - ng: command not found

*Windows only*

The clue is to arrange the entries in the path variable right.

As the NPM wiki tells us:

Because the installer puts C:\Program Files (x86)\nodejs before C:\Users<username>\AppData\Roaming\npm on your PATH, it will always use version of npm installed with node instead of the version of npm you installed using npm -g install npm@.

So your path variable will look something like:

C:\<path-to-node-installation>;%appdata%\npm;

Now you have to possibilities:

  1. Swap the two entries so it will look like
…;%appdata%\npm;C:\<path-to-node-installation>;…

This will load the npm version installed with npm (and not with node) and with it the installed Agnular CLI version.

  1. If you (for whatever reason) like to use the npm version bundled with node, add the direct path to your global Angualr CLI version. After this your path variable should look like this:
…;C:\Users\<username>\AppData\Roaming\npm\node_modules\@angular\cli;C:\<path-to-node-installation>;%appdata%\npm;…

or

    …;%appdata%\npm\node_modules\@angular\cli;C:\<path-to-node-installation>;%appdata%\npm;…  

for the short form.

This worked for me since a while now.

Download the Android SDK components for offline install

I know this topic is a bit old, but after struggling and waiting a lot to download, Ive changed my DNS settings to use google's one (4.4.4.4 and 8.8.8.8) and it worked!!

My connection is 30mbps from Brazil (Virtua), using isp's provider I was getting 80KB/s and after changing to google dns, I got 2MB/s average.

Commenting in a Bash script inside a multiline command

The trailing backslash must be the last character on the line for it to be interpreted as a continuation command. No comments or even whitespace are allowed after it.

You should be able to put comment lines in between your commands

# output MYSQLDUMP file
cat ${MYSQLDUMP} | \
# simplify the line
sed '/created_at/d' | \
# create some newlines
tr ",;" "\n" | \
# use some sed magic
sed -e 's/[asbi]:[0-9]*[:]*//g' -e '/^[{}]/d' -e 's/""//g' -e '/^"{/d' | \
# more magic
sed -n -e '/^"/p' -e '/^print_value$/,/^option_id$/p' | \
# even more magic
sed -e '/^option_id/d' -e '/^print_value/d' -e 's/^"\(.*\)"$/\1/' | \
tr "\n" "," | \
# I hate phone numbers in my output
sed -e 's/,\([0-9]*-[0-9]*-[0-9]*\)/\n\1/g' -e 's/,$//' | \ 
# one more sed call and then send it to the CSV file
sed -e 's/^/"/g' -e 's/$/"/g' -e 's/,/","/g' >> ${CSV}

How to count occurrences of a column value efficiently in SQL?

This should work:

SELECT age, count(age) 
  FROM Students 
 GROUP by age

If you need the id as well you could include the above as a sub query like so:

SELECT S.id, S.age, C.cnt
  FROM Students  S
       INNER JOIN (SELECT age, count(age) as cnt
                     FROM Students 
                    GROUP BY age) C ON S.age = C.age

Can anyone confirm that phpMyAdmin AllowNoPassword works with MySQL databases?

$cfg['Servers'][$i]['AllowNoPassword'] = TRUE;

yes the above answer is correct, but it's not secure, you can login root user directlyinto phpMyAdmin.

If you want to create new user with password and give grant permission, execute the below command in MySQL on terminal, Login into your server on terminal,

  # mysql

 mysql> GRANT ALL PRIVILEGES ON *.* TO  'user-name'@'%'  IDENTIFIED BY  'password'   REQUIRE NONE WITH GRANT OPTION MAX_QUERIES_PER_HOUR 0 MAX_CONNECTIONS_PER_HOUR 0 MAX_UPDATES_PER_HOUR 0 MAX_USER_CONNECTIONS 0;

Dynamically update values of a chartjs chart

Here is how to do it in the last version of ChartJs:

setInterval(function(){
    chart.data.datasets[0].data[5] = 80;
    chart.data.labels[5] = "Newly Added";
    chart.update();
}

Look at this clear video

or test it in jsfiddle

$.widget is not a function

Maybe placing the jquery.ui.widget.js as second after jquery.ui.core.js.

Convert HH:MM:SS string to seconds only in javascript

_x000D_
_x000D_
function parsehhmmsst(arg) {_x000D_
 var result = 0, arr = arg.split(':')_x000D_
 if (arr[0] < 12) {_x000D_
  result = arr[0] * 3600 // hours_x000D_
 }_x000D_
 result += arr[1] * 60 // minutes_x000D_
 result += parseInt(arr[2]) // seconds_x000D_
 if (arg.indexOf('P') > -1) {  // 8:00 PM > 8:00 AM_x000D_
  result += 43200_x000D_
 }_x000D_
 return result_x000D_
}_x000D_
$('body').append(parsehhmmsst('12:00:00 AM') + '<br>')_x000D_
$('body').append(parsehhmmsst('1:00:00 AM') + '<br>')_x000D_
$('body').append(parsehhmmsst('2:00:00 AM') + '<br>')_x000D_
$('body').append(parsehhmmsst('3:00:00 AM') + '<br>')_x000D_
$('body').append(parsehhmmsst('4:00:00 AM') + '<br>')_x000D_
$('body').append(parsehhmmsst('5:00:00 AM') + '<br>')_x000D_
$('body').append(parsehhmmsst('6:00:00 AM') + '<br>')_x000D_
$('body').append(parsehhmmsst('7:00:00 AM') + '<br>')_x000D_
$('body').append(parsehhmmsst('8:00:00 AM') + '<br>')_x000D_
$('body').append(parsehhmmsst('9:00:00 AM') + '<br>')_x000D_
$('body').append(parsehhmmsst('10:00:00 AM') + '<br>')_x000D_
$('body').append(parsehhmmsst('11:00:00 AM') + '<br>')_x000D_
$('body').append(parsehhmmsst('12:00:00 PM') + '<br>')_x000D_
$('body').append(parsehhmmsst('1:00:00 PM') + '<br>')_x000D_
$('body').append(parsehhmmsst('2:00:00 PM') + '<br>')_x000D_
$('body').append(parsehhmmsst('3:00:00 PM') + '<br>')_x000D_
$('body').append(parsehhmmsst('4:00:00 PM') + '<br>')_x000D_
$('body').append(parsehhmmsst('5:00:00 PM') + '<br>')_x000D_
$('body').append(parsehhmmsst('6:00:00 PM') + '<br>')_x000D_
$('body').append(parsehhmmsst('7:00:00 PM') + '<br>')_x000D_
$('body').append(parsehhmmsst('8:00:00 PM') + '<br>')_x000D_
$('body').append(parsehhmmsst('9:00:00 PM') + '<br>')_x000D_
$('body').append(parsehhmmsst('10:00:00 PM') + '<br>')_x000D_
$('body').append(parsehhmmsst('11:00:00 PM') + '<br>')
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

<div style display="none" > inside a table not working

simply change <div> to <tbody>

<table id="authenticationSetting" style="display: none">
  <tbody id="authenticationOuterIdentityBlock" style="display: none;">
    <tr>
      <td class="orionSummaryHeader">
        <orion:message key="policy.wifi.enterprise.authentication.outeridentitity" />:</td>
      <td class="orionSummaryColumn">
        <orion:textbox id="authenticationOuterIdentity" size="30" />
      </td>
    </tr>
  </tbody>
</table>

If statement with String comparison fails

You shouldn't do string comparisons with ==. That operator will only check to see if it is the same instance, not the same value. Use the .equals method to check for the same value.

Is there a link to the "latest" jQuery library on Google APIs?

Up until jQuery 1.11.1, you could use the following URLs to get the latest version of jQuery:

For example:

<script src="https://code.jquery.com/jquery-latest.min.js"></script>

However, since jQuery 1.11.1, both jQuery and Google stopped updating these URL's; they will forever be fixed at 1.11.1. There is no supported alternative URL to use. For an explanation of why this is the case, see this blog post; Don't use jquery-latest.js.

Both hosts support https as well as http, so change the protocol as you see fit (or use a protocol relative URI)

See also: https://developers.google.com/speed/libraries/devguide

How to use WPF Background Worker

  1. Add using
using System.ComponentModel;
  1. Declare Background Worker:
private readonly BackgroundWorker worker = new BackgroundWorker();
  1. Subscribe to events:
worker.DoWork += worker_DoWork;
worker.RunWorkerCompleted += worker_RunWorkerCompleted;
  1. Implement two methods:
private void worker_DoWork(object sender, DoWorkEventArgs e)
{
  // run all background tasks here
}

private void worker_RunWorkerCompleted(object sender, 
                                           RunWorkerCompletedEventArgs e)
{
  //update ui once worker complete his work
}
  1. Run worker async whenever your need.
worker.RunWorkerAsync();
  1. Track progress (optional, but often useful)

    a) subscribe to ProgressChanged event and use ReportProgress(Int32) in DoWork

    b) set worker.WorkerReportsProgress = true; (credits to @zagy)

Convert list to dictionary using linq and not worrying about duplicates

You can also use the ToLookup LINQ function, which you then can use almost interchangeably with a Dictionary.

_people = personList
    .ToLookup(e => e.FirstandLastName, StringComparer.OrdinalIgnoreCase);
_people.ToDictionary(kl => kl.Key, kl => kl.First()); // Potentially unnecessary

This will essentially do the GroupBy in LukeH's answer, but will give the hashing that a Dictionary provides. So, you probably don't need to convert it to a Dictionary, but just use the LINQ First function whenever you need to access the value for the key.

How do I plot only a table in Matplotlib?

Not sure if this is already answered, but if you want only a table in a figure window, then you can hide the axes:

fig, ax = plt.subplots()

# Hide axes
ax.xaxis.set_visible(False) 
ax.yaxis.set_visible(False)

# Table from Ed Smith answer
clust_data = np.random.random((10,3))
collabel=("col 1", "col 2", "col 3")
ax.table(cellText=clust_data,colLabels=collabel,loc='center')

Deleting all records in a database table

More recent answer in the case you want to delete every entries in every tables:

def reset
    Rails.application.eager_load!
    ActiveRecord::Base.descendants.each { |c| c.delete_all unless c == ActiveRecord::SchemaMigration  }
end

More information about the eager_load here.

After calling it, we can access to all of the descendants of ActiveRecord::Base and we can apply a delete_all on all the models.

Note that we make sure not to clear the SchemaMigration table.

How to place a JButton at a desired location in a JFrame using Java

I have figured it out lol. for the button do .setBounds(0, 0, 220, 30) The .setBounds layout is like this (int x, int y, int width, int height)

How can I get a resource content from a static context?

public Static Resources mResources;

 @Override
     public void onCreate()
     {
           mResources = getResources();
     }

PostgreSQL: How to change PostgreSQL user password?

For my case on Ubuntu 14.04 installed with postgres 10.3. I need to follow the following steps

  • su - postgres to switch user to postgres
  • psql to enter postgres shell
  • \password then enter your password
  • \q to quit the shell session
  • Then you switch back to root by executing exit and configure your pg_hba.conf (mine is at /etc/postgresql/10/main/pg_hba.conf) by making sure you have the following line

    local all postgres md5

  • Restart your postgres service by service postgresql restart
  • Now switch to postgres user and enter postgres shell again. It will prompt you with password.

Cannot open output file, permission denied

In my case - I found a process called

cb_console_runner

I stopped this process and things were ok again.

Need to find element in selenium by css

You can describe your css selection like cascading style sheet dows:

protected override void When()
{
   SUT.Browser.FindElements(By.CssSelector("#carousel > a.tiny.button"))
}

Merge 2 DataTables and store in a new one

DataTable dtAll = new DataTable();
DataTable dt= new DataTable();
foreach (int id in lst)
{
    dt.Merge(GetDataTableByID(id)); // Get Data Methode return DataTable
}
dtAll = dt;

Adding IN clause List to a JPA Query

You must convert to List as shown below:

    String[] valores = hierarquia.split(".");       
    List<String> lista =  Arrays.asList(valores);

    String jpqlQuery = "SELECT a " +
            "FROM AcessoScr a " +
            "WHERE a.scr IN :param ";

    Query query = getEntityManager().createQuery(jpqlQuery, AcessoScr.class);                   
    query.setParameter("param", lista);     
    List<AcessoScr> acessos = query.getResultList();

How do I check/uncheck all checkboxes with a button using jQuery?

Try This One:

HTML

<input type="checkbox" name="all" id="checkall" />

JavaScript

$('#checkall:checkbox').change(function () {
   if($(this).attr("checked")) $('input:checkbox').attr('checked','checked');
   else $('input:checkbox').removeAttr('checked');
});?

DEMO

Go doing a GET request and building the Querystring

Using NewRequest just to create an URL is an overkill. Use the net/url package:

package main

import (
    "fmt"
    "net/url"
)

func main() {
    base, err := url.Parse("http://www.example.com")
    if err != nil {
        return
    }

    // Path params
    base.Path += "this will get automatically encoded"

    // Query params
    params := url.Values{}
    params.Add("q", "this will get encoded as well")
    base.RawQuery = params.Encode() 

    fmt.Printf("Encoded URL is %q\n", base.String())
}

Playground: https://play.golang.org/p/YCTvdluws-r

How to draw a rounded Rectangle on HTML Canvas?

I needed to do the same thing and created a method to do it.

_x000D_
_x000D_
// Now you can just call
var ctx = document.getElementById("rounded-rect").getContext("2d");
// Draw using default border radius, 
// stroke it but no fill (function's default values)
roundRect(ctx, 5, 5, 50, 50);
// To change the color on the rectangle, just manipulate the context
ctx.strokeStyle = "rgb(255, 0, 0)";
ctx.fillStyle = "rgba(255, 255, 0, .5)";
roundRect(ctx, 100, 5, 100, 100, 20, true);
// Manipulate it again
ctx.strokeStyle = "#0f0";
ctx.fillStyle = "#ddd";
// Different radii for each corner, others default to 0
roundRect(ctx, 300, 5, 200, 100, {
  tl: 50,
  br: 25
}, true);

/**
 * Draws a rounded rectangle using the current state of the canvas.
 * If you omit the last three params, it will draw a rectangle
 * outline with a 5 pixel border radius
 * @param {CanvasRenderingContext2D} ctx
 * @param {Number} x The top left x coordinate
 * @param {Number} y The top left y coordinate
 * @param {Number} width The width of the rectangle
 * @param {Number} height The height of the rectangle
 * @param {Number} [radius = 5] The corner radius; It can also be an object 
 *                 to specify different radii for corners
 * @param {Number} [radius.tl = 0] Top left
 * @param {Number} [radius.tr = 0] Top right
 * @param {Number} [radius.br = 0] Bottom right
 * @param {Number} [radius.bl = 0] Bottom left
 * @param {Boolean} [fill = false] Whether to fill the rectangle.
 * @param {Boolean} [stroke = true] Whether to stroke the rectangle.
 */
function roundRect(ctx, x, y, width, height, radius, fill, stroke) {
  if (typeof stroke === 'undefined') {
    stroke = true;
  }
  if (typeof radius === 'undefined') {
    radius = 5;
  }
  if (typeof radius === 'number') {
    radius = {tl: radius, tr: radius, br: radius, bl: radius};
  } else {
    var defaultRadius = {tl: 0, tr: 0, br: 0, bl: 0};
    for (var side in defaultRadius) {
      radius[side] = radius[side] || defaultRadius[side];
    }
  }
  ctx.beginPath();
  ctx.moveTo(x + radius.tl, y);
  ctx.lineTo(x + width - radius.tr, y);
  ctx.quadraticCurveTo(x + width, y, x + width, y + radius.tr);
  ctx.lineTo(x + width, y + height - radius.br);
  ctx.quadraticCurveTo(x + width, y + height, x + width - radius.br, y + height);
  ctx.lineTo(x + radius.bl, y + height);
  ctx.quadraticCurveTo(x, y + height, x, y + height - radius.bl);
  ctx.lineTo(x, y + radius.tl);
  ctx.quadraticCurveTo(x, y, x + radius.tl, y);
  ctx.closePath();
  if (fill) {
    ctx.fill();
  }
  if (stroke) {
    ctx.stroke();
  }

}
_x000D_
<canvas id="rounded-rect" width="500" height="200">
  <!-- Insert fallback content here -->
</canvas>
_x000D_
_x000D_
_x000D_

VB.NET - Remove a characters from a String

Function RemoveCharacter(ByVal stringToCleanUp, ByVal characterToRemove)
  ' replace the target with nothing
  ' Replace() returns a new String and does not modify the current one
  Return stringToCleanUp.Replace(characterToRemove, "")
End Function

Here's more information about VB's Replace function

Why is my JavaScript function sometimes "not defined"?

This has probably been corrected, but... apparently firefox has a caching problem which is the cause of javascript functions not being recognized.. I really don't know the specifics, but if you clear your cache that will fix the problem (until your cache is full again... not a good solution).. I've been looking around to see if firefox has a real solution to this, but so far nothing... oh not all versions, I think it may be only in some 3.6.x versions, not sure...

RegEx match open tags except XHTML self-contained tags

It seems to me you're trying to match tags without a "/" at the end. Try this:

<([a-zA-Z][a-zA-Z0-9]*)[^>]*(?<!/)>

How to know installed Oracle Client is 32 bit or 64 bit?

On 64-bit system:

32-bit Driver: C:\Windows\SysWOW64\odbcad32.exe

64-bit Driver: C:\Windows\System32\odbcad32.exe

Go to Drivers Tab
Version is shown there as well.

Reloading the page gives wrong GET request with AngularJS HTML5 mode

As others have mentioned, you need to rewrite routes on the server and set <base href="/"/>.

For gulp-connect:

npm install connect-pushstate

var gulp = require('gulp'),
  connect = require('gulp-connect'),
  pushState = require('connect-pushstate/lib/pushstate').pushState;
...
connect.server({
  ...
  middleware: function (connect, options) {
    return [
      pushState()
    ];
  }
  ...
})
....

Javascript/jQuery: Set Values (Selection) in a multiple Select

var groups = ["Test", "Prof","Off"];

    $('#fruits option').filter(function() {
      return groups.indexOf($(this).text()) > -1; //Options text exists in array
    }).prop('selected', true); //Set selected

Using a dispatch_once singleton model in Swift

   func init() -> ClassA {
    struct Static {
        static var onceToken : dispatch_once_t = 0
        static var instance : ClassA? = nil
    }

    dispatch_once(&Static.onceToken) {
        Static.instance = ClassA()
    }

    return Static.instance!
}

Only allow specific characters in textbox

Intercept the KeyPressed event is in my opinion a good solid solution. Pay attention to trigger code characters (e.KeyChar lower then 32) if you use a RegExp.

But in this way is still possible to inject characters out of range whenever the user paste text from the clipboard. Unfortunately I did not found correct clipboard events to fix this.

So a waterproof solution is to intercept TextBox.TextChanged. Here is sometimes the original out of range character visible, for a short time. I recommend to implement both.

using System.Text.RegularExpressions;

private void Form1_Shown(object sender, EventArgs e)
{
    filterTextBoxContent(textBox1);
}


string pattern = @"[^0-9^+^\-^/^*^(^)]";

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
    if(e.KeyChar >= 32 && Regex.Match(e.KeyChar.ToString(), pattern).Success) { e.Handled = true; }
}

private void textBox1_TextChanged(object sender, EventArgs e)
{
    filterTextBoxContent(textBox1);
}

private bool filterTextBoxContent(TextBox textBox)
{
    string text = textBox.Text;

    MatchCollection matches = Regex.Matches(text, pattern);
    bool matched = false;

    int selectionStart = textBox.SelectionStart;
    int selectionLength = textBox.SelectionLength;

    int leftShift = 0;
    foreach (Match match in matches)
    {
        if (match.Success && match.Captures.Count > 0)
        {
            matched = true;
            Capture capture = match.Captures[0];

            int captureLength = capture.Length;
            int captureStart = capture.Index - leftShift;
            int captureEnd = captureStart + captureLength;

            int selectionEnd = selectionStart + selectionLength;

            text = text.Substring(0, captureStart) + text.Substring(captureEnd, text.Length - captureEnd);

            textBox.Text = text;

            int boundSelectionStart = selectionStart < captureStart ? -1 : (selectionStart < captureEnd ? 0 : 1);
            int boundSelectionEnd = selectionEnd < captureStart ? -1 : (selectionEnd < captureEnd ? 0 : 1);

            if (boundSelectionStart == -1)
            {
                if (boundSelectionEnd == 0)
                {
                    selectionLength -= selectionEnd - captureStart;
                }
                else if (boundSelectionEnd == 1)
                {
                    selectionLength -= captureLength;
                }
            }
            else if (boundSelectionStart == 0)
            {
                if (boundSelectionEnd == 0)
                {
                    selectionStart = captureStart;
                    selectionLength = 0;
                }
                else if (boundSelectionEnd == 1)
                {
                    selectionStart = captureStart;
                    selectionLength -= captureEnd - selectionStart;
                }
            }
            else if (boundSelectionStart == 1)
            {
                selectionStart -= captureLength;
            }

            leftShift++;
        }
    }

    textBox.SelectionStart = selectionStart;
    textBox.SelectionLength = selectionLength;

    return matched;
}

How do I convert a Python program to a runnable .exe Windows program?

If it is a simple py script refer here

Else for GUI :

$ pip3 install cx_Freeze

1) Create a setup.py file and put in the same directory as of the .py file you want to convert.

2)Copy paste the following lines in the setup.py and do change the "filename.py" into the filename you specified.

from cx_Freeze import setup, Executable
setup(
    name="GUI PROGRAM",
    version="0.1",
    description="MyEXE",
    executables=[Executable("filename.py", base="Win32GUI")],
    )

3) Run the setup.py "$python setup.py build"

4)A new directory will be there there called "build". Inside it you will get your .exe file to be ready to launced directly. (Make sure you copy paste the images files and other external files into the build directory)

jQuery AJAX Character Encoding

$str=iconv("windows-1250","UTF-8",$str);

what helped me on the eventually

GitHub: How to make a fork of public repository private?

GitHub now has an import option that lets you choose whatever you want your new imported repository public or private

Github Repository import

How to extract HTTP response body from a Python requests call?

Your code is correct. I tested:

r = requests.get("http://www.google.com")
print(r.content)

And it returned plenty of content. Check the url, try "http://www.google.com". Cheers!

How to iterate through an ArrayList of Objects of ArrayList of Objects?

int i = 0; // Counter used to determine when you're at the 3rd gun
for (Gun g : gunList) { // For each gun in your list
    System.out.println(g); // Print out the gun
    if (i == 2) { // If you're at the third gun
        ArrayList<Bullet> bullets = g.getBullet(); // Get the list of bullets in the gun
        for (Bullet b : bullets) { // Then print every bullet
            System.out.println(b);
        }
    i++; // Don't forget to increment your counter so you know you're at the next gun
}

Calculate difference between two dates (number of days)?

Assuming StartDate and EndDate are of type DateTime:

(EndDate - StartDate).TotalDays

Create mysql table directly from CSV file using the CSV Storage engine?

I'm recommended use MySQL Workbench where is import data. Workbench allows the user to create a new table from a file in CSV or JSON format. It handles table schema and data import in just a few clicks through the wizard.

In MySQL Workbench, use the context menu on table list and click Table Data Import Wizard.

MySQL Workbench image

More from the MySQL Workbench 6.5.1 Table Data Export and Import Wizard documentation. Download MySQL Workbench here.

WordPress query single post by slug

As wordpress api has changed, you can´t use get_posts with param 'post_name'. I´ve modified Maartens function a bit:

function get_post_id_by_slug( $slug, $post_type = "post" ) {
    $query = new WP_Query(
        array(
            'name'   => $slug,
            'post_type'   => $post_type,
            'numberposts' => 1,
            'fields'      => 'ids',
        ) );
    $posts = $query->get_posts();
    return array_shift( $posts );
}

Select DISTINCT individual columns in django?

One way to get the list of distinct column names from the database is to use distinct() in conjunction with values().

In your case you can do the following to get the names of distinct categories:

q = ProductOrder.objects.values('Category').distinct()
print q.query # See for yourself.

# The query would look something like
# SELECT DISTINCT "app_productorder"."category" FROM "app_productorder"

There are a couple of things to remember here. First, this will return a ValuesQuerySet which behaves differently from a QuerySet. When you access say, the first element of q (above) you'll get a dictionary, NOT an instance of ProductOrder.

Second, it would be a good idea to read the warning note in the docs about using distinct(). The above example will work but all combinations of distinct() and values() may not.

PS: it is a good idea to use lower case names for fields in a model. In your case this would mean rewriting your model as shown below:

class ProductOrder(models.Model):
    product  = models.CharField(max_length=20, primary_key=True)
    category = models.CharField(max_length=30)
    rank = models.IntegerField()

How to set size for local image using knitr for markdown?

Another option that worked for me is playing with the dpi option of knitr::include_graphics() like this:

```{r}
knitr::include_graphics("path/to/image.png", dpi = 100)
```

... which sure (unless you do the math) is trial and error compared to defining dimensions in the chunk, but maybe it will help somebody.

Can local storage ever be considered secure?

As an exploration of this topic, I have a presentation titled "Securing TodoMVC Using the Web Cryptography API" (video, code).

It uses the Web Cryptography API to store the todo list encrypted in localStorage by password protecting the application and using a password derived key for encryption. If you forget or lose the password, there is no recovery. (Disclaimer - it was a POC and not intended for production use.)

As the other answers state, this is still susceptible to XSS or malware installed on the client computer. However, any sensitive data would also be in memory when the data is stored on the server and the application is in use. I suggest that offline support may be the compelling use case.

In the end, encrypting localStorage probably only protects the data from attackers that have read only access to the system or its backups. It adds a small amount of defense in depth for OWASP Top 10 item A6-Sensitive Data Exposure, and allows you to answer "Is any of this data stored in clear text long term?" correctly.

JavaScript isset() equivalent

Reference to SOURCE

    module.exports = function isset () {
  //  discuss at: http://locutus.io/php/isset/
  // original by: Kevin van Zonneveld (http://kvz.io)
  // improved by: FremyCompany
  // improved by: Onno Marsman (https://twitter.com/onnomarsman)
  // improved by: Rafal Kukawski (http://blog.kukawski.pl)
  //   example 1: isset( undefined, true)
  //   returns 1: false
  //   example 2: isset( 'Kevin van Zonneveld' )
  //   returns 2: true

  var a = arguments
  var l = a.length
  var i = 0
  var undef

  if (l === 0) {
    throw new Error('Empty isset')
  }

  while (i !== l) {
    if (a[i] === undef || a[i] === null) {
      return false
    }
    i++
  }

  return true
}

phpjs.org is mostly retired in favor of locutus Here is the new link http://locutus.io/php/var/isset

Can I set text box to readonly when using Html.TextBoxFor?

   @Html.TextBoxFor(model => model.IdUsuario, new { @Value = "" + User.Identity.GetUserId() + "", @disabled = "true" })

@disabled = "true"

Work very well

Can we install Android OS on any Windows Phone and vice versa, and same with iPhone and vice versa?

Ok, For installing Android on Windows phone, I think you can..(But your window phone has required configuration to run Android) (For other I don't know If I will then surely post here)

Just go through these links,

Run Android on Your Windows Mobile Phone

full tutorial on how to put android on windows mobile touch pro 2

How to install Android on most Windows Mobile phones

Update:

For Windows 7 to Android device, this also possible, (You need to do some hack for this)

Just go through these links,

Install Windows Phone 7 Mango on HTC HD2 [How-To Guide]

HTC HD2: How To Install WP7 (Windows Phone 7) & MAGLDR 1.13 To NAND

Install windows phone 7 on android and iphones | Tips and Tricks

How to install Windows Phone 7 on HTC HD2? (Video)


To Install Android on your iOS Devices (This also possible...)

Look at How To Install Android on your iOS Devices

Android 2.2 Froyo running on Iphone

javax.faces.application.ViewExpiredException: View could not be restored

Please add this line in your web.xml It works for me

<context-param>
        <param-name>org.ajax4jsf.handleViewExpiredOnClient</param-name> 
        <param-value>true</param-value>     
    </context-param>

Deleting a pointer in C++

I believe you're not fully understanding how pointers work.
When you have a pointer pointing to some memory there are three different things you must understand:
- there is "what is pointed" by the pointer (the memory)
- this memory address
- not all pointers need to have their memory deleted: you only need to delete memory that was dynamically allocated (used new operator).

Imagine:

int *ptr = new int; 
// ptr has the address of the memory.
// at this point, the actual memory doesn't have anything.
*ptr = 8;
// you're assigning the integer 8 into that memory.
delete ptr;
// you are only deleting the memory.
// at this point the pointer still has the same memory address (as you could
//   notice from your 2nd test) but what inside that memory is gone!

When you did

ptr = NULL;
// you didn't delete the memory
// you're only saying that this pointer is now pointing to "nowhere".
// the memory that was pointed by this pointer is now lost.

C++ allows that you try to delete a pointer that points to null but it doesn't actually do anything, just doesn't give any error.

Find Item in ObservableCollection without using a loop

I'd suggest storing these in a Hashtable. You can then access an item in the collection using the key, it's a much more efficient lookup.

var myObjects = new Hashtable();
myObjects.Add(yourObject.Title, yourObject);
...
var myRetrievedObject = myObjects["TargetTitle"];

Proxy with express.js

I found a shorter and very straightforward solution which works seamlessly, and with authentication as well, using express-http-proxy:

const url = require('url');
const proxy = require('express-http-proxy');

// New hostname+path as specified by question:
const apiProxy = proxy('other_domain.com:3000/BLABLA', {
    proxyReqPathResolver: req => url.parse(req.baseUrl).path
});

And then simply:

app.use('/api/*', apiProxy);

Note: as mentioned by @MaxPRafferty, use req.originalUrl in place of baseUrl to preserve the querystring:

    forwardPath: req => url.parse(req.baseUrl).path

Update: As mentioned by Andrew (thank you!), there's a ready-made solution using the same principle:

npm i --save http-proxy-middleware

And then:

const proxy = require('http-proxy-middleware')
var apiProxy = proxy('/api', {target: 'http://www.example.org/api'});
app.use(apiProxy)

Documentation: http-proxy-middleware on Github

I know I'm late to join this party, but I hope this helps someone.

Test if a string contains a word in PHP?

If you wanna find just the word like 'are' in "How are you?" and not like 'are' in 'hare'

$word=" are ";
$str="How are you?";
if(strpos($word,$str) !== false){
echo 1;
 }

Inserting a Python datetime.datetime object into MySQL

when iserting into t-sql

this fails:

select CONVERT(datetime,'2019-09-13 09:04:35.823312',21)

this works:

select CONVERT(datetime,'2019-09-13 09:04:35.823',21)

easy way:

regexp = re.compile(r'\.(\d{6})')
def to_splunk_iso(dt):
    """Converts the datetime object to Splunk isoformat string."""
    # 6-digits string.
    microseconds = regexp.search(dt).group(1)
    return regexp.sub('.%d' % round(float(microseconds) / 1000), dt)

Java int to String - Integer.toString(i) vs new Integer(i).toString()

In terms of performance measurement, if you are considering the time performance then the Integer.toString(i); is expensive if you are calling less than 100 million times. Else if it is more than 100 million calls then the new Integer(10).toString() will perform better.

Below is the code through u can try to measure the performance,

public static void main(String args[]) {
            int MAX_ITERATION = 10000000;
        long starttime = System.currentTimeMillis();
        for (int i = 0; i < MAX_ITERATION; ++i) {
            String s = Integer.toString(10);
        }
        long endtime = System.currentTimeMillis();
        System.out.println("diff1: " + (endtime-starttime));

        starttime = System.currentTimeMillis();
        for (int i = 0; i < MAX_ITERATION; ++i) {
            String s1 = new Integer(10).toString();
        }
        endtime = System.currentTimeMillis();
        System.out.println("diff2: " + (endtime-starttime));
    }

In terms of memory, the

new Integer(i).toString();

will take more memory as it will create the object each time, so memory fragmentation will happen.

Simple URL GET/POST function in Python

I know you asked for GET and POST but I will provide CRUD since others may need this just in case: (this was tested in Python 3.7)

#!/usr/bin/env python3
import http.client
import json

print("\n GET example")
conn = http.client.HTTPSConnection("httpbin.org")
conn.request("GET", "/get")
response = conn.getresponse()
data = response.read().decode('utf-8')
print(response.status, response.reason)
print(data)


print("\n POST example")
conn = http.client.HTTPSConnection('httpbin.org')
headers = {'Content-type': 'application/json'}
post_body = {'text': 'testing post'}
json_data = json.dumps(post_body)
conn.request('POST', '/post', json_data, headers)
response = conn.getresponse()
print(response.read().decode())
print(response.status, response.reason)


print("\n PUT example ")
conn = http.client.HTTPSConnection('httpbin.org')
headers = {'Content-type': 'application/json'}
post_body ={'text': 'testing put'}
json_data = json.dumps(post_body)
conn.request('PUT', '/put', json_data, headers)
response = conn.getresponse()
print(response.read().decode(), response.reason)
print(response.status, response.reason)


print("\n delete example")
conn = http.client.HTTPSConnection('httpbin.org')
headers = {'Content-type': 'application/json'}
post_body ={'text': 'testing delete'}
json_data = json.dumps(post_body)
conn.request('DELETE', '/delete', json_data, headers)
response = conn.getresponse()
print(response.read().decode(), response.reason)
print(response.status, response.reason)

How to uninstall mini conda? python

If you are using windows, just search for miniconda and you'll find the folder. Go into the folder and you'll find a miniconda uninstall exe file. Run it.

php $_POST array empty upon form submission

In my case (php page on OVH mutualisé server) enctype="text/plain" does not work ($_POST and corresponding $_REQUEST is empty), the other examples below work. `

<form action="?" method="post">
<!-- in this case, my google chrome 45.0.2454.101 uses -->
<!--     Content-Type:application/x-www-form-urlencoded -->
    <input name="say" value="Hi">
    <button>Send my greetings</button>
</form>

<form action="?" method="post" enctype="application/x-www-form-urlencoded">
    <input name="say" value="Hi">
    <button>Send my application/x-www-form-urlencoded greetings</button>
</form>

<form action="?" method="post"  enctype="multipart/form-data">
    <input name="say" value="Hi">
    <button>Send my multipart/form-data greetings</button>
</form>

<form action="?" method="post" enctype="text/plain"><!-- not working -->
    <input name="say" value="Hi">
    <button>Send my text/plain greetings</button>
</form>

`

More here: method="post" enctype="text/plain" are not compatible?

Spring Hibernate - Could not obtain transaction-synchronized Session for current thread

In this class above @Repository just placed one more annotation @Transactional it will work. If it works reply back(Y/N):

@Repository
@Transactional
public class StudentDAOImpl implements StudentDAO

How does System.out.print() work?

Even though it look as if System.put.print...() take a variable number of arguments it doesn't. If you look closely, the string is simply concatenated and you can do the same with any string. The only thing that happens is, that the objects you are passing in, are implicitily converted to a string by java calling the toString() method.

If you try to do this it will fail:

int i = 0;
String s = i;
System.out.println(s);

Reason is, because here the implicit conversion is not done.

However if you change it to

int i = 0;
String s = "" + i;
System.out.println(s);

It works and this is what happens when using System.put.print...() as well.

If you want to implement a variable number of arguments in java to mimimc something like C printf you can declare it like this:

public void t(String s, String ... args)
{
    String val = args[1];
}

What happens here is that an array of Strings is passed in, with the length of the provided arguments. Here Java can do the type checking for you.

If you want truly a printf then you have to do it like this:

public void t(String s, Object ... args)
{
    String val = args[1].toString();
}

Then would you have to cast or interpret the arguments accordingly.

How to change default JRE for all Eclipse workspaces?

On windows I've tried different approaches - setting JAVA_HOME, JRE_HOME and extending the PATH to point to the desiered jre18 but nothing helped - disabling the JRE17 in the java control panel didn't helped either

What helped me out was to force eclipse to use the appropriate JRE in the eclipse.ini file e.g.

-vm C:\java\jdk1.8.0_111\jre\bin\javaw.exe

Measuring elapsed time with the Time module

For the best measure of elapsed time (since Python 3.3), use time.perf_counter().

Return the value (in fractional seconds) of a performance counter, i.e. a clock with the highest available resolution to measure a short duration. It does include time elapsed during sleep and is system-wide. The reference point of the returned value is undefined, so that only the difference between the results of consecutive calls is valid.

For measurements on the order of hours/days, you don't care about sub-second resolution so use time.monotonic() instead.

Return the value (in fractional seconds) of a monotonic clock, i.e. a clock that cannot go backwards. The clock is not affected by system clock updates. The reference point of the returned value is undefined, so that only the difference between the results of consecutive calls is valid.

In many implementations, these may actually be the same thing.

Before 3.3, you're stuck with time.clock().

On Unix, return the current processor time as a floating point number expressed in seconds. The precision, and in fact the very definition of the meaning of “processor time”, depends on that of the C function of the same name.

On Windows, this function returns wall-clock seconds elapsed since the first call to this function, as a floating point number, based on the Win32 function QueryPerformanceCounter(). The resolution is typically better than one microsecond.


Update for Python 3.7

New in Python 3.7 is PEP 564 -- Add new time functions with nanosecond resolution.

Use of these can further eliminate rounding and floating-point errors, especially if you're measuring very short periods, or your application (or Windows machine) is long-running.

Resolution starts breaking down on perf_counter() after around 100 days. So for example after a year of uptime, the shortest interval (greater than 0) it can measure will be bigger than when it started.


Update for Python 3.8

time.clock is now gone.

What does Html.HiddenFor do?

It creates a hidden input on the form for the field (from your model) that you pass it.

It is useful for fields in your Model/ViewModel that you need to persist on the page and have passed back when another call is made but shouldn't be seen by the user.

Consider the following ViewModel class:

public class ViewModel
{
    public string Value { get; set; }
    public int Id { get; set; }
}

Now you want the edit page to store the ID but have it not be seen:

<% using(Html.BeginForm() { %>
    <%= Html.HiddenFor(model.Id) %><br />
    <%= Html.TextBoxFor(model.Value) %>
<% } %>

This results in the equivalent of the following HTML:

<form name="form1">
    <input type="hidden" name="Id">2</input>
    <input type="text" name="Value" value="Some Text" />
</form>

"git rm --cached x" vs "git reset head --? x"?

Perhaps an example will help:

git rm --cached asd
git commit -m "the file asd is gone from the repository"

versus

git reset HEAD -- asd
git commit -m "the file asd remains in the repository"

Note that if you haven't changed anything else, the second commit won't actually do anything.

How do I convert hh:mm:ss.000 to milliseconds in Excel?

Here it is as a single formula:

=(RIGHT(D2,3))+(MID(D2,7,2)*1000)+(MID(D2,4,2)*60000)+(LEFT(D2,2)*3600000)

How to print a dictionary's key?

key_name = '...'
print "the key name is %s and its value is %s"%(key_name, mydic[key_name])

What is the difference between a field and a property?

IMO, Properties are just the "SetXXX()" "GetXXX()" functions/methods/interfaces pairs we used before, but they are more concise and elegant.

filename and line number of Python script

Thanks to mcandre, the answer is:

#python3
from inspect import currentframe, getframeinfo

frameinfo = getframeinfo(currentframe())

print(frameinfo.filename, frameinfo.lineno)

Git Symlinks in Windows

For those using CygWin on Vista, Win7, or above, the native git command can create "proper" symlinks that are recognized by Windows apps such as Android Studio. You just need to set the CYGWIN environment variable to include winsymlinks:native or winsymlinks:nativestrict as such:

export CYGWIN="$CYGWIN winsymlinks:native"

The downside to this (and a significant one at that) is that the CygWin shell has to be "Run as Administrator" in order for it to have the OS permissions required to create those kind of symlinks. Once they're created, though, no special permissions are required to use them. As long they aren't changed in the repository by another developer, git thereafter runs fine with normal user permissions.

Personally, I use this only for symlinks that are navigated by Windows apps (i.e. non-CygWin) because of this added difficulty.

For more information on this option, see this SO question: How to make symbolic link with cygwin in Windows 7

How to know if an object has an attribute in Python

Here's a very intuitive approach :

if 'property' in dir(a):
    a.property

Load HTML File Contents to Div [without the use of iframes]

Wow, from all the framework-promotional answers you'd think this was something JavaScript made incredibly difficult. It isn't really.

var xhr= new XMLHttpRequest();
xhr.open('GET', 'x.html', true);
xhr.onreadystatechange= function() {
    if (this.readyState!==4) return;
    if (this.status!==200) return; // or whatever error handling you want
    document.getElementById('y').innerHTML= this.responseText;
};
xhr.send();

If you need IE<8 compatibility, do this first to bring those browsers up to speed:

if (!window.XMLHttpRequest && 'ActiveXObject' in window) {
    window.XMLHttpRequest= function() {
        return new ActiveXObject('MSXML2.XMLHttp');
    };
}

Note that loading content into the page with scripts will make that content invisible to clients without JavaScript available, such as search engines. Use with care, and consider server-side includes if all you want is to put data in a common shared file.

How to get Database Name from Connection String using SqlConnectionStringBuilder

this gives you the Xact;

System.Data.SqlClient.SqlConnectionStringBuilder connBuilder = new System.Data.SqlClient.SqlConnectionStringBuilder();

connBuilder.ConnectionString = connectionString;

string server = connBuilder.DataSource;           //-> this gives you the Server name.
string database = connBuilder.InitialCatalog;     //-> this gives you the Db name.

Excel- compare two cell from different sheet, if true copy value from other cell

In your destination field you want to use VLOOKUP like so:

=VLOOKUP(Sheet1!A1:A100,Sheet2!A1:F100,6,FALSE)

VLOOKUP Arguments:

  1. The set fields you want to lookup.
  2. The table range you want to lookup up your value against. The first column of your defined table should be the column you want compared against your lookup field. The table range should also contain the value you want to display (Column F).
  3. This defines what field you want to display upon a match.
  4. FALSE tells VLOOKUP to do an exact match.

Can I make a <button> not submit a form?

Just use good old HTML:

<input type="button" value="Submit" />

Wrap it as the subject of a link, if you so desire:

<a href="http://somewhere.com"><input type="button" value="Submit" /></a>

Or if you decide you want javascript to provide some other functionality:

<input type="button" value="Cancel" onclick="javascript: someFunctionThatCouldIncludeRedirect();"/>

How can I avoid ResultSet is closed exception in Java?

The exception states that your result is closed. You should examine your code and look for all location where you issue a ResultSet.close() call. Also look for Statement.close() and Connection.close(). For sure, one of them gets called before rs.next() is called.

Best GUI designer for eclipse?

Here is a quite good but old comparison http://wiki.computerwoche.de/doku.php/programmierung/gui-builder_fuer_eclipse Window Builder Pro is now free at Google Web Toolkit

Difference between session affinity and sticky session?

This article clarifies the question for me and discusses other types of load balancer persistence.

Dave's Thoughts: Load balancer persistence (sticky sessions)

Maven Could not resolve dependencies, artifacts could not be resolved

Looks like you are missing some Maven repos. Ask for your friend's .m2/settings.xml, and you'll probably want to update the POM to include the repositories there.

--edit: after some quick googling, try adding this to your POM:

<repository>
    <id>com.springsource.repository.bundles.release</id>
    <name>SpringSource Enterprise Bundle Repository - SpringSource Bundle Releases</name>
    <url>http://repository.springsource.com/maven/bundles/release</url>
</repository>
<repository>
    <id>com.springsource.repository.bundles.external</id>
    <name>SpringSource Enterprise Bundle Repository - External Bundle Releases</name>
    <url>http://repository.springsource.com/maven/bundles/external</url>
</repository>

Head and tail in one line

Python 2, using lambda

>>> head, tail = (lambda lst: (lst[0], lst[1:]))([1, 1, 2, 3, 5, 8, 13, 21, 34, 55])
>>> head
1
>>> tail
[1, 2, 3, 5, 8, 13, 21, 34, 55]

You are trying to add a non-nullable field 'new_field' to userprofile without a default

If "website" can be empty than new_field should also be set to be empty.

Now if you want to add logic on save where if new_field is empty to grab the value from "website" all you need to do is override the save function for your Model like this:

class UserProfile(models.Model):
    user = models.OneToOneField(User)
    website = models.URLField(blank=True, default='DEFAULT VALUE')
    new_field = models.CharField(max_length=140, blank=True, default='DEFAULT VALUE')

    def save(self, *args, **kwargs):
        if not self.new_field:
            # Setting the value of new_field with website's value
            self.new_field = self.website

        # Saving the object with the default save() function
        super(UserProfile, self).save(*args, **kwargs)

Python, HTTPS GET with basic authentication

Use the power of Python and lean on one of the best libraries around: requests

import requests

r = requests.get('https://my.website.com/rest/path', auth=('myusername', 'mybasicpass'))
print(r.text)

Variable r (requests response) has a lot more parameters that you can use. Best thing is to pop into the interactive interpreter and play around with it, and/or read requests docs.

ubuntu@hostname:/home/ubuntu$ python3
Python 3.4.3 (default, Oct 14 2015, 20:28:29)
[GCC 4.8.4] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import requests
>>> r = requests.get('https://my.website.com/rest/path', auth=('myusername', 'mybasicpass'))
>>> dir(r)
['__attrs__', '__bool__', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getstate__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__nonzero__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setstate__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_content', '_content_consumed', 'apparent_encoding', 'close', 'connection', 'content', 'cookies', 'elapsed', 'encoding', 'headers', 'history', 'iter_content', 'iter_lines', 'json', 'links', 'ok', 'raise_for_status', 'raw', 'reason', 'request', 'status_code', 'text', 'url']
>>> r.content
b'{"battery_status":0,"margin_status":0,"timestamp_status":null,"req_status":0}'
>>> r.text
'{"battery_status":0,"margin_status":0,"timestamp_status":null,"req_status":0}'
>>> r.status_code
200
>>> r.headers
CaseInsensitiveDict({'x-powered-by': 'Express', 'content-length': '77', 'date': 'Fri, 20 May 2016 02:06:18 GMT', 'server': 'nginx/1.6.3', 'connection': 'keep-alive', 'content-type': 'application/json; charset=utf-8'})

Switch statement with returns -- code correctness

I would say remove them and define a default: branch.

setting the id attribute of an input element dynamically in IE: alternative for setAttribute method

The documentation says:

When you need to set attributes that are also mapped to a JavaScript dot-property (such as href, style, src or event-handlers), favour that mapping instead.

So, just change id, value assignment and you should be done.

Running MSBuild fails to read SDKToolsPath

I just had this error with a .sln file that was originally created in Visual Studio 2010 (and being built by Visual Studio 2010 and TFS 2010). I had modified the solution file to NOT build a project that was not supposed to be built in a particular configuration and visual studio changed the header of the solution file from:

Microsoft Visual Studio Solution File, Format Version 11.00
# Visual Studio 2010

To:

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 14
VisualStudioVersion = 14.0.24720.0
MinimumVisualStudioVersion = 10.0.40219.1

Setting it back to the original 2010 version fixed my problem. I guess backwards compatibility in Visual Studio has still not been perfected.

Is there an easy way to attach source in Eclipse?

  1. Put source files into a zip file (as it does for java source)
  2. Go to Project properties -> Libraries
  3. Select Source attachment and click 'Edit'
  4. On Source Attachment Configuration click 'Variable'
  5. On "Variable Selection" click 'New'
  6. Put a meaningful name and select the zip file created in step 1

What's the difference between KeyDown and KeyPress in .NET?

KEYUP will be captured only once, upon release of the key pressed, regardless of how long will the key be held down, so if you want to capture such press only once, KEYUP is the suitable event to capture.

How to build and fill pandas dataframe from for loop?

Try this using list comprehension:

import pandas as pd

df = pd.DataFrame(
    [p, p.team, p.passing_att, p.passer_rating()] for p in game.players.passing()
)

How exactly does __attribute__((constructor)) work?

This page provides great understanding about the constructor and destructor attribute implementation and the sections within within ELF that allow them to work. After digesting the information provided here, I compiled a bit of additional information and (borrowing the section example from Michael Ambrus above) created an example to illustrate the concepts and help my learning. Those results are provided below along with the example source.

As explained in this thread, the constructor and destructor attributes create entries in the .ctors and .dtors section of the object file. You can place references to functions in either section in one of three ways. (1) using either the section attribute; (2) constructor and destructor attributes or (3) with an inline-assembly call (as referenced the link in Ambrus' answer).

The use of constructor and destructor attributes allow you to additionally assign a priority to the constructor/destructor to control its order of execution before main() is called or after it returns. The lower the priority value given, the higher the execution priority (lower priorities execute before higher priorities before main() -- and subsequent to higher priorities after main() ). The priority values you give must be greater than100 as the compiler reserves priority values between 0-100 for implementation. Aconstructor or destructor specified with priority executes before a constructor or destructor specified without priority.

With the 'section' attribute or with inline-assembly, you can also place function references in the .init and .fini ELF code section that will execute before any constructor and after any destructor, respectively. Any functions called by the function reference placed in the .init section, will execute before the function reference itself (as usual).

I have tried to illustrate each of those in the example below:

#include <stdio.h>
#include <stdlib.h>

/*  test function utilizing attribute 'section' ".ctors"/".dtors"
    to create constuctors/destructors without assigned priority.
    (provided by Michael Ambrus in earlier answer)
*/

#define SECTION( S ) __attribute__ ((section ( S )))

void test (void) {
printf("\n\ttest() utilizing -- (.section .ctors/.dtors) w/o priority\n");
}

void (*funcptr1)(void) SECTION(".ctors") =test;
void (*funcptr2)(void) SECTION(".ctors") =test;
void (*funcptr3)(void) SECTION(".dtors") =test;

/*  functions constructX, destructX use attributes 'constructor' and
    'destructor' to create prioritized entries in the .ctors, .dtors
    ELF sections, respectively.

    NOTE: priorities 0-100 are reserved
*/
void construct1 () __attribute__ ((constructor (101)));
void construct2 () __attribute__ ((constructor (102)));
void destruct1 () __attribute__ ((destructor (101)));
void destruct2 () __attribute__ ((destructor (102)));

/*  init_some_function() - called by elf_init()
*/
int init_some_function () {
    printf ("\n  init_some_function() called by elf_init()\n");
    return 1;
}

/*  elf_init uses inline-assembly to place itself in the ELF .init section.
*/
int elf_init (void)
{
    __asm__ (".section .init \n call elf_init \n .section .text\n");

    if(!init_some_function ())
    {
        exit (1);
    }

    printf ("\n    elf_init() -- (.section .init)\n");

    return 1;
}

/*
    function definitions for constructX and destructX
*/
void construct1 () {
    printf ("\n      construct1() constructor -- (.section .ctors) priority 101\n");
}

void construct2 () {
    printf ("\n      construct2() constructor -- (.section .ctors) priority 102\n");
}

void destruct1 () {
    printf ("\n      destruct1() destructor -- (.section .dtors) priority 101\n\n");
}

void destruct2 () {
    printf ("\n      destruct2() destructor -- (.section .dtors) priority 102\n");
}

/* main makes no function call to any of the functions declared above
*/
int
main (int argc, char *argv[]) {

    printf ("\n\t  [ main body of program ]\n");

    return 0;
}

output:

init_some_function() called by elf_init()

    elf_init() -- (.section .init)

    construct1() constructor -- (.section .ctors) priority 101

    construct2() constructor -- (.section .ctors) priority 102

        test() utilizing -- (.section .ctors/.dtors) w/o priority

        test() utilizing -- (.section .ctors/.dtors) w/o priority

        [ main body of program ]

        test() utilizing -- (.section .ctors/.dtors) w/o priority

    destruct2() destructor -- (.section .dtors) priority 102

    destruct1() destructor -- (.section .dtors) priority 101

The example helped cement the constructor/destructor behavior, hopefully it will be useful to others as well.

How to Select Min and Max date values in Linq Query

dim mydate = from cv in mydata.t1s
  select cv.date1 asc

datetime mindata = mydate[0];

Running interactive commands in Paramiko

I had the same problem trying to make an interactive ssh session using ssh, a fork of Paramiko.

I dug around and found this article:

Updated link (last version before the link generated a 404): http://web.archive.org/web/20170912043432/http://jessenoller.com/2009/02/05/ssh-programming-with-paramiko-completely-different/

To continue your example you could do

ssh_stdin, ssh_stdout, ssh_stderr = ssh.exec_command("psql -U factory -d factory -f /tmp/data.sql")
ssh_stdin.write('password\n')
ssh_stdin.flush()
output = ssh_stdout.read()

The article goes more in depth, describing a fully interactive shell around exec_command. I found this a lot easier to use than the examples in the source.

Original link: http://jessenoller.com/2009/02/05/ssh-programming-with-paramiko-completely-different/

What is the correct way to do a CSS Wrapper?

The best way to do it depends on your specific use-case.

However, if we speak for the general best practices for implementing a CSS Wrapper, here is my proposal: introduce an additional <div> element with the following class:

/**
 * 1. Center the content. Yes, that's a bit opinionated.
 * 2. Use `max-width` instead `width`
 * 3. Add padding on the sides.
 */
.wrapper {
    margin-right: auto; /* 1 */
    margin-left:  auto; /* 1 */

    max-width: 960px; /* 2 */

    padding-right: 10px; /* 3 */
    padding-left:  10px; /* 3 */
}

... for those of you, who want to understand why, here are the 4 big reasons I see:

1. Use max-width instead width

In the answer currently accepted Aron says width. I disagree and I propose max-width instead.

Setting the width of a block-level element will prevent it from stretching out to the edges of its container. Therefore, the Wrapper element will take up the specified width. The problem occurs when the browser window is smaller than the width of the element. The browser then adds a horizontal scrollbar to the page.

Using max-width instead, in this situation, will improve the browser's handling of small windows. This is important when making a site usable on small devices. Here’s a good example showcasing the problem:

_x000D_
_x000D_
/**_x000D_
 * The problem with this one occurs_x000D_
 * when the browser window is smaller than 960px._x000D_
 * The browser then adds a horizontal scrollbar to the page._x000D_
 */_x000D_
.width {_x000D_
    width: 960px;_x000D_
    margin-left: auto;_x000D_
    margin-right: auto;_x000D_
    border: 3px solid #73AD21;_x000D_
}_x000D_
_x000D_
/**_x000D_
 * Using max-width instead, in this situation,_x000D_
 * will improve the browser's handling of small windows._x000D_
 * This is important when making a site usable on small devices._x000D_
 */_x000D_
.max-width {_x000D_
    max-width: 960px;_x000D_
    margin-left: auto;_x000D_
    margin-right: auto;_x000D_
    border: 3px solid #73AD21;_x000D_
}_x000D_
_x000D_
/**_x000D_
 * Credits for the tip: W3Schools_x000D_
 * https://www.w3schools.com/css/css_max-width.asp_x000D_
 */
_x000D_
<div class="width">This div element has width: 960px;</div>_x000D_
<br />_x000D_
_x000D_
<div class="max-width">This div element has max-width: 960px;</div>
_x000D_
_x000D_
_x000D_

So in terms of Responsiveness, is seems like max-width is the better choice!-


2. Add Padding on the Sides

I’ve seen a lot of developers still forget one edge case. Let’s say we have a Wrapper with max-width set to 980px. The edge case appears when the user’s device screen width is exactly 980px. The content then will exactly glue to the edges of the screen with not any breathing space left.

Generally, we’d want to have a bit of padding on the sides. That’s why if I need to implement a Wrapper with a total width of 980px, I’d do it like so:

.wrapper {
   max-width: 960px; /** 20px smaller, to fit the paddings on the sides */

   padding-right: 10px;
   padding-left:  10px;

   /** ... omitted for brevity */
}

Therefore, that’s why adding padding-left and padding-right to your Wrapper might be a good idea, especially on mobile.


3. Use a <div> Instead of a <section>

By definition, the Wrapper has no semantic meaning. It simply holds all visual elements and content on the page. It’s just a generic container. Therefore, in terms of semantics, <div> is the best choice.

One might wonder if maybe a <section> element could fit this purpose. However, here’s what the W3C spec says:

The element is not a generic container element. When an element is needed only for styling purposes or as a convenience for scripting, authors are encouraged to use the div element instead. A general rule is that the section element is appropriate only if the element's contents would be listed explicitly in the document's outline.

The <section> element carries it’s own semantics. It represents a thematic grouping of content. The theme of each section should be identified, typically by including a heading (h1-h6 element) as a child of the section element.

Examples of sections would be chapters, the various tabbed pages in a tabbed dialog box, or the numbered sections of a thesis. A Web site's home page could be split into sections for an introduction, news items, and contact information.

It might not seem very obvious at first sight, but yes! The plain old <div> fits best for a Wrapper!


4. Using the <body> Tag vs. Using an Additional <div>

Here's a related question. Yes, there are some instances where you could simply use the <body> element as a wrapper. However, I wouldn’t recommend you to do so, simply due to flexibility and resilience to changes.

Here's an use-case that illustrates a possible issue: Imagine if on a later stage of the project you need to enforce a footer to "stick" to the end of the document (bottom of the viewport when the document is short). Even if you can use the most modern way to do it - with Flexbox, I guess you need an additional Wrapper <div>.

I would conclude it is still best practice to have an additional <div> for implementing a CSS Wrapper. This way if spec requirements change later on you don't have to add the Wrapper later and deal with moving the styles around a lot. After all, we're only talking about 1 extra DOM element.

SQL RANK() versus ROW_NUMBER()

This article covers an interesting relationship between ROW_NUMBER() and DENSE_RANK() (the RANK() function is not treated specifically). When you need a generated ROW_NUMBER() on a SELECT DISTINCT statement, the ROW_NUMBER() will produce distinct values before they are removed by the DISTINCT keyword. E.g. this query

SELECT DISTINCT
  v, 
  ROW_NUMBER() OVER (ORDER BY v) row_number
FROM t
ORDER BY v, row_number

... might produce this result (DISTINCT has no effect):

+---+------------+
| V | ROW_NUMBER |
+---+------------+
| a |          1 |
| a |          2 |
| a |          3 |
| b |          4 |
| c |          5 |
| c |          6 |
| d |          7 |
| e |          8 |
+---+------------+

Whereas this query:

SELECT DISTINCT
  v, 
  DENSE_RANK() OVER (ORDER BY v) row_number
FROM t
ORDER BY v, row_number

... produces what you probably want in this case:

+---+------------+
| V | ROW_NUMBER |
+---+------------+
| a |          1 |
| b |          2 |
| c |          3 |
| d |          4 |
| e |          5 |
+---+------------+

Note that the ORDER BY clause of the DENSE_RANK() function will need all other columns from the SELECT DISTINCT clause to work properly.

The reason for this is that logically, window functions are calculated before DISTINCT is applied.

All three functions in comparison

Using PostgreSQL / Sybase / SQL standard syntax (WINDOW clause):

SELECT
  v,
  ROW_NUMBER() OVER (window) row_number,
  RANK()       OVER (window) rank,
  DENSE_RANK() OVER (window) dense_rank
FROM t
WINDOW window AS (ORDER BY v)
ORDER BY v

... you'll get:

+---+------------+------+------------+
| V | ROW_NUMBER | RANK | DENSE_RANK |
+---+------------+------+------------+
| a |          1 |    1 |          1 |
| a |          2 |    1 |          1 |
| a |          3 |    1 |          1 |
| b |          4 |    4 |          2 |
| c |          5 |    5 |          3 |
| c |          6 |    5 |          3 |
| d |          7 |    7 |          4 |
| e |          8 |    8 |          5 |
+---+------------+------+------------+

AttributeError: 'module' object has no attribute 'model'

It's called models.Model and not models.model (case sensitive). Fix your Poll model like this -

class Poll(models.Model):
    question = models.CharField(max_length=200) 
    pub_date = models.DateTimeField('date published')

How to compare files from two different branches?

If you want to make a diff against current branch you can ommit it and use:

git diff $BRANCH -- path/to/file

this way it will diff from current branch to the referenced branch ($BRANCH).

Javascript foreach loop on associative array object

This is very simple approach. The Advantage is you can get keys as well:

for (var key in array) {
    var value = array[key];
    console.log(key, value);
}

For ES6:

array.forEach(value => {
  console.log(value)
})  

For ES6: (If you want value, index and the array itself)

array.forEach((value, index, self) => {
  console.log(value, index, self)
})  

When to use dynamic vs. static libraries

A static library must be linked into the final executable; it becomes part of the executable and follows it wherever it goes. A dynamic library is loaded every time the executable is executed and remains separate from the executable as a DLL file.

You would use a DLL when you want to be able to change the functionality provided by the library without having to re-link the executable (just replace the DLL file, without having to replace the executable file).

You would use a static library whenever you don't have a reason to use a dynamic library.

Play an audio file using jQuery when a button is clicked

$("#myAudioElement")[0].play();

It doesn't work with $("#myAudioElement").play() like you would expect. The official reason is that incorporating it into jQuery would add a play() method to every single element, which would cause unnecessary overhead. So instead you have to refer to it by its position in the array of DOM elements that you're retrieving with $("#myAudioElement"), aka 0.

This quote is from a bug that was submitted about it, which was closed as "feature/wontfix":

To do that we'd need to add a jQuery method name for each DOM element method name. And of course that method would do nothing for non-media elements so it doesn't seem like it would be worth the extra bytes it would take.

Easily measure elapsed time

I needed to measure the execution time of individual functions within a library. I didn't want to have to wrap every call of every function with a time measuring function because its ugly and deepens the call stack. I also didn't want to put timer code at the top and bottom of every function because it makes a mess when the function can exit early or throw exceptions for example. So what I ended up doing was making a timer that uses its own lifetime to measure time.

In this way I can measure the wall-time a block of code took by just instantiating one of these objects at the beginning of the code block in question (function or any scope really) and then allowing the instances destructor to measure the time elapsed since construction when the instance goes out of scope. You can find the full example here but the struct is extremely simple:

template <typename clock_t = std::chrono::steady_clock>
struct scoped_timer {
  using duration_t = typename clock_t::duration;
  const std::function<void(const duration_t&)> callback;
  const std::chrono::time_point<clock_t> start;

  scoped_timer(const std::function<void(const duration_t&)>& finished_callback) :
      callback(finished_callback), start(clock_t::now()) { }
  scoped_timer(std::function<void(const duration_t&)>&& finished_callback) :
      callback(finished_callback), start(clock_t::now()) { }
  ~scoped_timer() { callback(clock_t::now() - start); }
};

The struct will call you back on the provided functor when it goes out of scope so you can do something with the timing information (print it or store it or whatever). If you need to do something even more complex you could even use std::bind with std::placeholders to callback functions with more arguments.

Here's a quick example of using it:

void test(bool should_throw) {
  scoped_timer<> t([](const scoped_timer<>::duration_t& elapsed) {
    auto e = std::chrono::duration_cast<std::chrono::duration<double, std::milli>>(elapsed).count();
    std::cout << "took " << e << "ms" << std::endl;
  });

  std::this_thread::sleep_for(std::chrono::seconds(1));

  if (should_throw)
    throw nullptr;

  std::this_thread::sleep_for(std::chrono::seconds(1));
}

If you want to be more deliberate, you can also use new and delete to explicitly start and stop the timer without relying on scoping to do it for you.

Using sudo with Python script

Please try module pexpect. Here is my code:

import pexpect
remove = pexpect.spawn('sudo dpkg --purge mytool.deb')
remove.logfile = open('log/expect-uninstall-deb.log', 'w')
remove.logfile.write('try to dpkg --purge mytool\n')
if remove.expect(['(?i)password.*']) == 0:
    # print "successfull"
    remove.sendline('mypassword')
    time.sleep(2)
    remove.expect(pexpect.EOF,5)
else:
    raise AssertionError("Fail to Uninstall deb package !")

How to get the nvidia driver version from the command line?

If you need to get that in a program with Python on a Linux system for reproducibility:

with open('/proc/driver/nvidia/version') as f:
    version = f.read().strip()
print(version)

gives:

NVRM version: NVIDIA UNIX x86_64 Kernel Module  384.90  Tue Sep 19 19:17:35 PDT 2017
GCC version:  gcc version 5.4.0 20160609 (Ubuntu 5.4.0-6ubuntu1~16.04.5) 

jQuery UI Datepicker - Multiple Date Selections

http://t1m0n.name/air-datepicker/docs/? I've have tried several method of multi datepicker but only this works

Resize Cross Domain Iframe Height

Minimum crossdomain set I've used for embedding fitted single iframe on a page.

On embedding page (containing iframe):

<iframe frameborder="0" id="sizetracker" src="http://www.hurtta.com/Services/SizeTracker/DE" width="100%"></iframe>
<script type="text/javascript">
  // Create browser compatible event handler.
  var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
  var eventer = window[eventMethod];
  var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";
  // Listen for a message from the iframe.
  eventer(messageEvent, function(e) {
    if (isNaN(e.data)) return;

    // replace #sizetracker with what ever what ever iframe id you need
    document.getElementById('sizetracker').style.height = e.data + 'px';

  }, false);
</script>

On embedded page (iframe):

<script type="text/javascript">
function sendHeight()
{
    if(parent.postMessage)
    {
        // replace #wrapper with element that contains 
        // actual page content
        var height= document.getElementById('wrapper').offsetHeight;
        parent.postMessage(height, '*');
    }
}

// Create browser compatible event handler.
var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
var eventer = window[eventMethod];
var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";

// Listen for a message from the iframe.
eventer(messageEvent, function(e) {

    if (isNaN(e.data)) return;

    sendHeight();

}, 
false);
</script>

Import CSV to SQLite

I am merging info from previous answers here with my own experience. The easiest is to add the comma-separated table headers directly to your csv file, followed by a new line, and then all your csv data.

If you are never doing sqlite stuff again (like me), this might save you a web search or two:

In the Sqlite shell enter:

$ sqlite3 yourfile.sqlite
sqlite>  .mode csv
sqlite>  .import test.csv yourtable
sqlite>  .exit

If you haven't got Sqlite installed on your Mac, run

$ brew install sqlite3

You may need to do one web search for how to install Homebrew.

Windows shell command to get the full path to the current directory?

Based on the follow up question (store the data in a variable) in the comments to the chdir post I'm betting he wants to store the current path to restore it after changeing directories.

The original user should look at "pushd", which changes directory and pushes the current one onto a stack that can be restored with a "popd". On any modern Windows cmd shell that is the way to go when making batch files.

If you really need to grab the current path then modern cmd shells also have a %CD% variable that you can easily stuff away in another variable for reference.

Difference between Running and Starting a Docker container

Explanation with an example:

Consider you have a game (iso) image in your computer.

When you run (mount your image as a virtual drive), a virtual drive is created with all the game contents in the virtual drive and the game installation file is automatically launched. [Running your docker image - creating a container and then starting it.]

But when you stop (similar to docker stop) it, the virtual drive still exists but stopping all the processes. [As the container exists till it is not deleted]

And when you do start (similar to docker start), from the virtual drive the games files start its execution. [starting the existing container]

In this example - The game image is your Docker image and virtual drive is your container.

What's the syntax for mod in java

Here is the representation of your pseudo-code in minimal Java code;

boolean isEven = a % 2 == 0;

I'll now break it down into its components. The modulus operator in Java is the percent character (%). Therefore taking an int % int returns another int. The double equals (==) operator is used to compare values, such as a pair of ints and returns a boolean. This is then assigned to the boolean variable 'isEven'. Based on operator precedence the modulus will be evaluated before the comparison.

Do Java arrays have a maximum size?

I tried to create a byte array like this

byte[] bytes = new byte[Integer.MAX_VALUE-x];
System.out.println(bytes.length);

With this run configuration:

-Xms4G -Xmx4G

And java version:

Openjdk version "1.8.0_141"

OpenJDK Runtime Environment (build 1.8.0_141-b16)

OpenJDK 64-Bit Server VM (build 25.141-b16, mixed mode)

It only works for x >= 2 which means the maximum size of an array is Integer.MAX_VALUE-2

Values above that give

Exception in thread "main" java.lang.OutOfMemoryError: Requested array size exceeds VM limit at Main.main(Main.java:6)

Check if an element has event listener on it. No jQuery

Nowadays (2016) in Chrome Dev Tools console, you can quickly execute this function below to show all event listeners that have been attached to an element.

getEventListeners(document.querySelector('your-element-selector'));

What is a 'multi-part identifier' and why can't it be bound?

You probably have a typo. For instance, if you have a table named Customer in a database named Sales, you could refer to it as Sales..Customer (although it is better to refer to it including the owner name (dbo is the default owner) like Sales.dbo.Customer.

If you typed Sales...Customer, you might have gotten the message you got.

Jquery sortable 'change' event element position

This works for me:

start: function(event, ui) {
        var start_pos = ui.item.index();
        ui.item.data('start_pos', start_pos);
    },
update: function (event, ui) {
        var start_pos = ui.item.data('start_pos');
        var end_pos = ui.item.index();
        //$('#sortable li').removeClass('highlights');
    }

Remove substring from the string

If you only have one occurrence of the target string you can use:

str[target] = ''

or

str.sub(target, '')

If you have multiple occurrences of target use:

str.gsub(target, '')

For instance:

asdf = 'foo bar'
asdf['bar'] = ''
asdf #=> "foo "

asdf = 'foo bar'
asdf.sub('bar', '') #=> "foo "
asdf = asdf + asdf #=> "foo barfoo bar"
asdf.gsub('bar', '') #=> "foo foo "

If you need to do in-place substitutions use the "!" versions of gsub! and sub!.

Logging framework incompatibility

Just to help those in a similar situation to myself...

This can be caused when a dependent library has accidentally bundled an old version of slf4j. In my case, it was tika-0.8. See https://issues.apache.org/jira/browse/TIKA-556

The workaround is exclude the component and then manually depends on the correct, or patched version.

EG.

<dependency>
    <groupId>org.apache.tika</groupId>
    <artifactId>tika-parsers</artifactId>
    <version>0.8</version>
    <exclusions>
        <exclusion>
            <!-- NOTE: Version 4.2 has bundled slf4j -->
            <groupId>edu.ucar</groupId>
            <artifactId>netcdf</artifactId>
        </exclusion>
    </exclusions>
</dependency>
<dependency>
    <!-- Patched version 4.2-min does not bundle slf4j -->
    <groupId>edu.ucar</groupId>
    <artifactId>netcdf</artifactId>
    <version>4.2-min</version>
</dependency>

Can't bind to 'formGroup' since it isn't a known property of 'form'

You can get this error message even if you have already imported FormsModule and ReactiveFormsModule. I moved a component (that uses the [formGroup] directive) from one project to another, but failed to add the component to the declarations array in the new module. That resulted in the Can't bind to 'formGroup' since it isn't a known property of 'form' error message.

Convert String to Carbon

Why not try using the following:

$dateTimeString = $aDateString." ".$aTimeString;
$dueDateTime = Carbon::createFromFormat('Y-m-d H:i:s', $dateTimeString, 'Europe/London');   

How can I convert ArrayList<Object> to ArrayList<String>?

Using Java 8 lambda:

ArrayList<Object> obj = new ArrayList<>();
obj.add(1);
obj.add("Java");
obj.add(3.14);

ArrayList<String> list = new ArrayList<>();
obj.forEach((xx) -> list.add(String.valueOf(xx)));

MySQL "Group By" and "Order By"

I struggled with both these approaches for more complex queries than those shown, because the subquery approach was horribly ineficient no matter what indexes I put on, and because I couldn't get the outer self-join through Hibernate

The best (and easiest) way to do this is to group by something which is constructed to contain a concatenation of the fields you require and then to pull them out using expressions in the SELECT clause. If you need to do a MAX() make sure that the field you want to MAX() over is always at the most significant end of the concatenated entity.

The key to understanding this is that the query can only make sense if these other fields are invariant for any entity which satisfies the Max(), so in terms of the sort the other pieces of the concatenation can be ignored. It explains how to do this at the very bottom of this link. http://dev.mysql.com/doc/refman/5.0/en/group-by-hidden-columns.html

If you can get am insert/update event (like a trigger) to pre-compute the concatenation of the fields you can index it and the query will be as fast as if the group by was over just the field you actually wanted to MAX(). You can even use it to get the maximum of multiple fields. I use it to do queries against multi-dimensional trees expresssed as nested sets.

Apply CSS to jQuery Dialog Buttons

Why not just inspect the generated markup, note the class on the button of choice and style it yourself?

Online SQL Query Syntax Checker

A lot of people, including me, use sqlfiddle.com to test SQL.

How to make the 'cut' command treat same sequental delimiters as one?

As you comment in your question, awk is really the way to go. To use cut is possible together with tr -s to squeeze spaces, as kev's answer shows.

Let me however go through all the possible combinations for future readers. Explanations are at the Test section.

tr | cut

tr -s ' ' < file | cut -d' ' -f4

awk

awk '{print $4}' file

bash

while read -r _ _ _ myfield _
do
   echo "forth field: $myfield"
done < file

sed

sed -r 's/^([^ ]*[ ]*){3}([^ ]*).*/\2/' file

Tests

Given this file, let's test the commands:

$ cat a
this   is    line     1 more text
this      is line    2     more text
this    is line 3     more text
this is   line 4            more    text

tr | cut

$ cut -d' ' -f4 a
is
                        # it does not show what we want!


$ tr -s ' ' < a | cut -d' ' -f4
1
2                       # this makes it!
3
4
$

awk

$ awk '{print $4}' a
1
2
3
4

bash

This reads the fields sequentially. By using _ we indicate that this is a throwaway variable as a "junk variable" to ignore these fields. This way, we store $myfield as the 4th field in the file, no matter the spaces in between them.

$ while read -r _ _ _ a _; do echo "4th field: $a"; done < a
4th field: 1
4th field: 2
4th field: 3
4th field: 4

sed

This catches three groups of spaces and no spaces with ([^ ]*[ ]*){3}. Then, it catches whatever coming until a space as the 4th field, that it is finally printed with \1.

$ sed -r 's/^([^ ]*[ ]*){3}([^ ]*).*/\2/' a
1
2
3
4

Output an Image in PHP

$file = '../image.jpg';
$type = 'image/jpeg';
header('Content-Type:'.$type);
header('Content-Length: ' . filesize($file));
readfile($file);

Set up Python simpleHTTPserver on Windows

From Stack Overflow question What is the Python 3 equivalent of "python -m SimpleHTTPServer":

The following works for me:

python -m http.server [<portNo>]

Because I am using Python 3 the module SimpleHTTPServer has been replaced by http.server, at least in Windows.

How to work with complex numbers in C?

To extract the real part of a complex-valued expression z, use the notation as __real__ z. Similarly, use __imag__ attribute on the z to extract the imaginary part.

For example;

__complex__ float z;
float r;
float i;
r = __real__ z;
i = __imag__ z;

r is the real part of the complex number "z" i is the imaginary part of the complex number "z"

Split string using a newline delimiter with Python

Here you go:

>>> data = """a,b,c
d,e,f
g,h,i
j,k,l"""
>>> data.split()  # split automatically splits through \n and space
['a,b,c', 'd,e,f', 'g,h,i', 'j,k,l']
>>> 

Using SSH keys inside docker container

A concise overview of the challenges of SSH inside Docker containers is detailed here. For connecting to trusted remotes from within a container without leaking secrets there are a few ways:

Beyond these there's also the possibility of using a key-store running in a separate docker container accessible at runtime when using Compose. The drawback here is additional complexity due to the machinery required to create and manage a keystore such as Vault by HashiCorp.

For SSH key use in a stand-alone Docker container see the methods linked above and consider the drawbacks of each depending on your specific needs. If, however, you're running inside Compose and want to share a key to an app at runtime (reflecting practicalities of the OP) try this:

  • Create a docker-compose.env file and add it to your .gitignore file.
  • Update your docker-compose.yml and add env_file for service requiring the key.
  • Access public key from environment at application runtime, e.g. process.node.DEPLOYER_RSA_PUBKEY in the case of a Node.js application.

The above approach is ideal for development and testing and, while it could satisfy production requirements, in production you're better off using one of the other methods identified above.

Additional resources:

How to setup Tomcat server in Netbeans?

I had same issue. No need to re install.

In Netbeans 6.0 , Find RunTime -> Servers - > Add server -> select Tomcat install 'root' directory

In Netbeans 7.x -> Tools -> Servers-> Add server -> select Tomcat install 'root' directory

Here is in Netbeans Wiki.

http://wiki.netbeans.org/AddExternalTomcat

Boxplot in R showing the mean

I also think chart.Boxplot is the best option, it gives you the position of the mean but if you have a matrix with returns all you need is one line of code to get all the boxplots in one graph.

Here is a small ETF portfolio example.

library(zoo)
library(PerformanceAnalytics)
library(tseries)
library(xts)

VTI.prices = get.hist.quote(instrument = "VTI", start= "2007-03-01", end="2013-03-01",
                        quote = c("AdjClose"),provider = "yahoo",origin ="1970-01-01", 
                        compression = "m", retclass = c("zoo"))

VEU.prices = get.hist.quote(instrument = "VEU", start= "2007-03-01", end="2013-03-01",
                        quote = c("AdjClose"),provider = "yahoo",origin ="1970-01-01", 
                        compression = "m", retclass = c("zoo"))

VWO.prices = get.hist.quote(instrument = "VWO", start= "2007-03-01", end="2013-03-01",
                        quote = c("AdjClose"),provider = "yahoo",origin ="1970-01-01", 
                        compression = "m", retclass = c("zoo"))


VNQ.prices = get.hist.quote(instrument = "VNQ", start= "2007-03-01", end="2013-03-01",
                       quote = c("AdjClose"),provider = "yahoo",origin ="1970-01-01", 
                       compression = "m", retclass = c("zoo"))

TLT.prices = get.hist.quote(instrument = "TLT", start= "2007-03-01", end="2013-03-01",
                        quote = c("AdjClose"),provider = "yahoo",origin ="1970-01-01", 
                        compression = "m", retclass = c("zoo"))

TIP.prices = get.hist.quote(instrument = "TIP", start= "2007-03-01", end="2013-03-01",
                         quote = c("AdjClose"),provider = "yahoo",origin ="1970-01-01", 
                         compression = "m", retclass = c("zoo"))

index(VTI.prices) = as.yearmon(index(VTI.prices))
index(VEU.prices) = as.yearmon(index(VEU.prices))
index(VWO.prices) = as.yearmon(index(VWO.prices))

index(VNQ.prices) = as.yearmon(index(VNQ.prices))
index(TLT.prices) = as.yearmon(index(TLT.prices))
index(TIP.prices) = as.yearmon(index(TIP.prices))

Prices.z=merge(VTI.prices, VEU.prices, VWO.prices, VNQ.prices, 
           TLT.prices, TIP.prices)

colnames(Prices.z) = c("VTI", "VEU", "VWO" , "VNQ", "TLT", "TIP")

returnscc.z = diff(log(Prices.z))

start(returnscc.z)
end(returnscc.z)
colnames(returnscc.z) 
head(returnscc.z)

Return Matrix

ret.mat = coredata(returnscc.z)
class(ret.mat)
colnames(ret.mat)
head(ret.mat)

Box Plot of Return Matrix

chart.Boxplot(returnscc.z, names=T, horizontal=TRUE, colorset="darkgreen", as.Tufte =F,
          mean.symbol = 20, median.symbol="|", main="Return Distributions Comparison",
          element.color = "darkgray", outlier.symbol = 20, 
          xlab="Continuously Compounded Returns", sort.ascending=F)

You can try changing the mean.symbol, and remove or change the median.symbol. Hope it helped. :)

How to run single test method with phpunit?

You Can try this i am able to run single Test cases

phpunit tests/{testfilename}

Eg:

phpunit tests/StackoverflowTest.php

If you want to run single Test cases in Laravel 5.5 Try

vendor/bin/phpunit tests/Feature/{testfilename} 

vendor/bin/phpunit tests/Unit/{testfilename} 

Eg:

vendor/bin/phpunit tests/Feature/ContactpageTest.php 

vendor/bin/phpunit tests/Unit/ContactpageTest.php

Why can I not create a wheel in python?

I also ran into this all of a sudden, after it had previously worked, and it was because I was inside a virtualenv, and wheel wasn’t installed in the virtualenv.

How to get Spinner value?

add setOnItemSelectedListener to spinner reference and get the data like that`

 mSizeSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> adapterView, View view, int position, long l) {
            selectedSize=adapterView.getItemAtPosition(position).toString();

Stack smashing detected

Please look at the following situation:

ab@cd-x:$ cat test_overflow.c 
#include <stdio.h>
#include <string.h>

int check_password(char *password){
    int flag = 0;
    char buffer[20];
    strcpy(buffer, password);

    if(strcmp(buffer, "mypass") == 0){
        flag = 1;
    }
    if(strcmp(buffer, "yourpass") == 0){
        flag = 1;
    }
    return flag;
}

int main(int argc, char *argv[]){
    if(argc >= 2){
        if(check_password(argv[1])){
            printf("%s", "Access granted\n");
        }else{
            printf("%s", "Access denied\n");
        }
    }else{
        printf("%s", "Please enter password!\n");
    }
}
ab@cd-x:$ gcc -g -fno-stack-protector test_overflow.c 
ab@cd-x:$ ./a.out mypass
Access granted
ab@cd-x:$ ./a.out yourpass
Access granted
ab@cd-x:$ ./a.out wepass
Access denied
ab@cd-x:$ ./a.out wepassssssssssssssssss
Access granted

ab@cd-x:$ gcc -g -fstack-protector test_overflow.c 
ab@cd-x:$ ./a.out wepass
Access denied
ab@cd-x:$ ./a.out mypass
Access granted
ab@cd-x:$ ./a.out yourpass
Access granted
ab@cd-x:$ ./a.out wepassssssssssssssssss
*** stack smashing detected ***: ./a.out terminated
======= Backtrace: =========
/lib/tls/i686/cmov/libc.so.6(__fortify_fail+0x48)[0xce0ed8]
/lib/tls/i686/cmov/libc.so.6(__fortify_fail+0x0)[0xce0e90]
./a.out[0x8048524]
./a.out[0x8048545]
/lib/tls/i686/cmov/libc.so.6(__libc_start_main+0xe6)[0xc16b56]
./a.out[0x8048411]
======= Memory map: ========
007d9000-007f5000 r-xp 00000000 08:06 5776       /lib/libgcc_s.so.1
007f5000-007f6000 r--p 0001b000 08:06 5776       /lib/libgcc_s.so.1
007f6000-007f7000 rw-p 0001c000 08:06 5776       /lib/libgcc_s.so.1
0090a000-0090b000 r-xp 00000000 00:00 0          [vdso]
00c00000-00d3e000 r-xp 00000000 08:06 1183       /lib/tls/i686/cmov/libc-2.10.1.so
00d3e000-00d3f000 ---p 0013e000 08:06 1183       /lib/tls/i686/cmov/libc-2.10.1.so
00d3f000-00d41000 r--p 0013e000 08:06 1183       /lib/tls/i686/cmov/libc-2.10.1.so
00d41000-00d42000 rw-p 00140000 08:06 1183       /lib/tls/i686/cmov/libc-2.10.1.so
00d42000-00d45000 rw-p 00000000 00:00 0 
00e0c000-00e27000 r-xp 00000000 08:06 4213       /lib/ld-2.10.1.so
00e27000-00e28000 r--p 0001a000 08:06 4213       /lib/ld-2.10.1.so
00e28000-00e29000 rw-p 0001b000 08:06 4213       /lib/ld-2.10.1.so
08048000-08049000 r-xp 00000000 08:05 1056811    /dos/hacking/test/a.out
08049000-0804a000 r--p 00000000 08:05 1056811    /dos/hacking/test/a.out
0804a000-0804b000 rw-p 00001000 08:05 1056811    /dos/hacking/test/a.out
08675000-08696000 rw-p 00000000 00:00 0          [heap]
b76fe000-b76ff000 rw-p 00000000 00:00 0 
b7717000-b7719000 rw-p 00000000 00:00 0 
bfc1c000-bfc31000 rw-p 00000000 00:00 0          [stack]
Aborted
ab@cd-x:$ 

When I disabled the stack smashing protector no errors were detected, which should have happened when I used "./a.out wepassssssssssssssssss"

So to answer your question above, the message "** stack smashing detected : xxx" was displayed because your stack smashing protector was active and found that there is stack overflow in your program.

Just find out where that occurs, and fix it.

How do I check in SQLite whether a table exists?

You can write the following query to check the table existance.

SELECT name FROM sqlite_master WHERE name='table_name'

Here 'table_name' is your table name what you created. For example

 CREATE TABLE IF NOT EXISTS country(country_id INTEGER PRIMARY KEY AUTOINCREMENT, country_code TEXT, country_name TEXT)"

and check

  SELECT name FROM sqlite_master WHERE name='country'

How can I use getSystemService in a non-activity class (LocationManager)?

For some non-activity classes, like Worker, you're already given a Context object in the public constructor.

Worker(Context context, WorkerParameters workerParams)

You can just use that, e.g., save it to a private Context variable in the class (say, mContext), and then, for example

mContext.getSystenService(Context.ACTIVITY_SERVICE)

How to download a folder from github?

You have to download the whole project with either "Clone to desktop" button that will use native github program or "Download as zip".

And then search that folder in downloaded project.

Rails: select unique values from a column

Some answers don't take into account the OP wants a array of values

Other answers don't work well if your Model has thousands of records

That said, I think a good answer is:

    Model.uniq.select(:ratings).map(&:ratings)
    => "SELECT DISTINCT ratings FROM `models` " 

Because, first you generate a array of Model (with diminished size because of the select), then you extract the only attribute those selected models have (ratings)

how to install Lex and Yacc in Ubuntu?

Use the synaptic packet manager in order to install yacc / lex. If you are feeling more comfortable doing this on the console just do:

sudo apt-get install bison flex

There are some very nice articles on the net on how to get started with those tools. I found the article from CodeProject to be quite good and helpful (see here). But you should just try and search for "introduction to lex", there are plenty of good articles showing up.

How to return history of validation loss in Keras

It's been solved.

The losses only save to the History over the epochs. I was running iterations instead of using the Keras built in epochs option.

so instead of doing 4 iterations I now have

model.fit(......, nb_epoch = 4)

Now it returns the loss for each epoch run:

print(hist.history)
{'loss': [1.4358016599558268, 1.399221191623641, 1.381293383180471, h1.3758836857303727]}

How to downgrade Xcode to previous version?

I'm assuming you are having at least OSX 10.7, so go ahead into the applications folder (Click on Finder icon > On the Sidebar, you'll find "Applications", click on it ), delete the "Xcode" icon. That will remove Xcode from your system completely. Restart your mac.

Now go to https://developer.apple.com/download/more/ and download an older version of Xcode, as needed and install. You need an Apple ID to login to that portal.

Android: Rotate image in imageview by an angle

Matrix matrix = new Matrix();
imageView.setScaleType(ImageView.ScaleType.MATRIX); //required
matrix.postRotate((float) 20, imageView.getDrawable().getBounds().width()/2, imageView.getDrawable().getBounds().height()/2);
imageView.setImageMatrix(matrix);

how to use?

public class MainActivity extends AppCompatActivity {
   int view = R.layout.activity_main;
   TextView textChanger;
   ImageView imageView;
   @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(view);
      textChanger = findViewById(R.id.textChanger);
      imageView=findViewById(R.id.imageView);
      textChanger.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            roateImage(imageView);
         }
      });
   }
   private void roateImage(ImageView imageView) {
      Matrix matrix = new Matrix();
      imageView.setScaleType(ImageView.ScaleType.MATRIX); //required
      matrix.postRotate((float) 20, imageView.getDrawable().getBounds().width()/2,    imageView.getDrawable().getBounds().height()/2);
      imageView.setImageMatrix(matrix);
   }
}

bootstrap datepicker change date event doesnt fire up when manually editing dates or clearing date

This should make it work in both cases

function onDateChange() {
   // Do something here
}

$('#dpd1').bind('changeDate', onDateChange);
$('#dpd1').bind('input', onDateChange);

Removing elements with Array.map in JavaScript

You must note however that the Array.filter is not supported in all browser so, you must to prototyped:

//This prototype is provided by the Mozilla foundation and
//is distributed under the MIT license.
//http://www.ibiblio.org/pub/Linux/LICENSES/mit.license

if (!Array.prototype.filter)
{
    Array.prototype.filter = function(fun /*, thisp*/)
    {
        var len = this.length;

        if (typeof fun != "function")
            throw new TypeError();

        var res = new Array();
        var thisp = arguments[1];

        for (var i = 0; i < len; i++)
        {
            if (i in this)
            {
                var val = this[i]; // in case fun mutates this

                if (fun.call(thisp, val, i, this))
                   res.push(val);
            }
        }

        return res;
    };
}

And doing so, you can prototype any method you may need.