text:
Q: hibernate multitenancy implementation issue with injectservices Think I am very close  and if this works it should help a lot of people :)
was following this very useful link on SO : Manage Connection Pooling in multi-tenant web app with Spring, Hibernate and C3P0
My problem is that in my class that implements - MultiTenantConnectionProvider
I am not getting a handle to the javax.sql.Datasource
Here is my full code:
springs application context:
<bean id="testService" class="com.mkyong.common.service.TestServiceImpl" lazy-init="true">
    <property name="testDao" ref="testDao" />
</bean>

<bean id="testDao" class="com.mkyong.common.dao.TestDaoImpl" lazy-init="true">
    <!-- Injecting Standard Session Factory -->
    <property name="sessionFactory" ref="sessionFactoryWorking" />
</bean>

<!-- this seems to work -->
<jee:jndi-lookup id="dataSource" jndi-name="MYSQLDS"/>

<!-- SessionFactories -->
<!-- Standard Session Factory -->
<bean id="sessionFactoryWorking" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
    <property name="configLocation" value="classpath:local.JADE.PIT.hibernate.cfg.xml" />
    <property name="dataSource" ref="dataSource" />
</bean>

<bean id="transactionManagerWorking" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
    <property name="autodetectDataSource" value="false" />
    <property name="sessionFactory" ref="sessionFactoryWorking" />
</bean>

In the file local.JADE.PIT.hibernate.cfg.xml
<hibernate-configuration>
<session-factory>
    <property name="show_sql">true</property>
    <property name="multiTenancy">SCHEMA</property>
    <property name="multi_tenant_connection_provider">com.mkyong.common.provider.MySQLMultiTenantConnectionProviderImpl</property>
    &globalpit;
</session-factory>

Here is my MySQLMultiTenantConnectionProviderImpl
package com.mkyong.common.provider;

import org.hibernate.engine.jdbc.connections.spi.MultiTenantConnectionProvider;
import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider;
import org.hibernate.service.UnknownUnwrapTypeException;
import org.hibernate.service.spi.ServiceRegistryAwareService;
import org.hibernate.service.spi.ServiceRegistryImplementor;
import org.hibernate.engine.config.spi.ConfigurationService;
import org.hibernate.cfg.Environment;

import java.util.Map;
import java.sql.Connection;
import java.sql.SQLException;
import javax.sql.DataSource;

public class MySQLMultiTenantConnectionProviderImpl implements  MultiTenantConnectionProvider,ServiceRegistryAwareService{

private DataSource lazyDatasource;;

@Override
public void injectServices(ServiceRegistryImplementor serviceRegistry) {
    Map lSettings = serviceRegistry.getService(ConfigurationService.class).getSettings();
    System.out.println(" satish ********************** " + Environment.DATASOURCE );
    System.out.println(" satish ********************** " + lSettings.get( Environment.DATASOURCE ) );
    lazyDatasource = (DataSource) lSettings.get( Environment.DATASOURCE );
}

@Override
public boolean supportsAggressiveRelease() {
    System.out.println("<<<<<<< satish supportsAggressiveRelease >>>>>>>>>");
    /** this method must be overriden **/
    return false;
}

@Override
public void releaseConnection(String tenantIdentifier, Connection connection){
    /** this method must be overriden **/
    System.out.println("<<<<<<< satish releaseConnection 1 >>>>>>>>>");
    try {
        this.releaseAnyConnection(connection);
    }catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

@Override
public void releaseAnyConnection(Connection connection) throws SQLException {
    System.out.println("<<<<<<< satish releaseAnyConnection 2 >>>>>>>>>");
    /** this method must be overriden **/
    connection.close();
}

 @Override
 public Connection getConnection(String tenantIdentifier) throws SQLException {
    System.out.println("<<<<<<< satish getConnection 1 >>>>>>>>>");
    final Connection connection = getAnyConnection();
    System.out.println("<<<<<<< satish getConnection 2 >>>>>>>>>");
    try {
       /** this is the place where we can change our schema based on identifier **/
       connection.createStatement().execute("USE " + tenantIdentifier );
    }catch (SQLException e) {
       e.printStackTrace();
       throw new HibernateException("Could not alter JDBC connection to specified schema [" + tenantIdentifier + "]", e);
    }
    return connection;
 }

 @Override
 public Connection getAnyConnection() throws SQLException {
/** this method is getting called first **/
System.out.println("<<<<<<< satish getAnyConnection >>>>>>>>>");
return lazyDatasource.getConnection();
}

@SuppressWarnings("unchecked")
@Override
public <T> T unwrap(Class<T> unwrapType) {
    if ( isUnwrappableAs( unwrapType ) ) {
        return (T) this;
    }else {
        throw new UnknownUnwrapTypeException( unwrapType );
    }

}
@Override
public boolean isUnwrappableAs(Class unwrapType) {
 return ConnectionProvider.class.equals( unwrapType ) ||  MultiTenantConnectionProvider.class.equals( unwrapType ) || MySQLMultiTenantConnectionProviderImpl.class.isAssignableFrom( unwrapType );
}
}

Here is my DAO:
public class TestDaoImpl{

/** schema choice which comes from UI / http - which is outside the scope of this example **/
private String schema = null;

/** this is the injected way which works **/
private SessionFactory sessionFactory;

public final void setSessionFactory(SessionFactory sessionFactory) {
    this.sessionFactory = sessionFactory;
}

public void setSchema(String schema) {
            this.schema = schema;
}

public Session getCurrentSession() {
    Session session = null;
    try {
        **/** this is where we are getting a connection based on client / tenant **/**
        session = getSessionFactory().withOptions().tenantIdentifier(schema).openSession();
    } catch (HibernateException e) {
        e.printStackTrace();
        System.out.println("<<<<<< inside exception while getting session from sf >>>>>");
        session = getSessionFactory().openSession();
    }

    return session;
}
@SuppressWarnings("unchecked")
public List<Person> list() {
    Session session = getCurrentSession();
    List<Person> personList = session.createQuery("from Person").list();
    session.close();
    return personList;
}

}
So what is happening is that the method - injectServices - it is getting invoked
However the Datasource is null at the following line:
lSettings.get( Environment.DATASOURCE )
If I set the datasource name in my cfg.xml file -
MYSQLDS
Then I do get the returned value as 'MYSQLDS' - but it is a String - so it then fails while trying to cast to a javax.sql.DataSource
A few more notes:
It is extremely extremely important to read Hibernate docs word by word  - they are poor in giving examples - but the documentation takes on a completely new and enhanced meaning - if you read it carefully :) - http://docs.jboss.org/hibernate/orm/4.1/devguide/en-US/html/ch16.html
NOTE - my datasource is a weblogic jndi provided datasource
Thanks
EDIT 1 Dec 29 2014 11:35 AM IST
As stated by M Deinum - the issue was that I had not wired my datasource
Now it is indeed working - updated code above - so that this should work and help others too !
Restating the order of execution of steps:
In our UI layer we are aware of which client is accessing the application
We pass this client / tenant information to the DAO layer
The DAO is injected with the SessionFactory which is configured in Spring
In the DAO - we get session based on tenant - getCurrentSession()
This is very important to get tenant based conenction
session = getSessionFactory().withOptions().tenantIdentifier(schema).openSession();
Now once we have the session we make the call:
List<Person> personList = session.createQuery("from Person").list();

At this time the below method of the class MySQLMultiTenantConnectionProviderImpl gets invoked
public Connection getConnection(String tenantIdentifier) throws SQLException {

This is the place where the mojo happens / we are expected to write - and you change the schema
In my case I am using MySQL so the syntax would vary depending on the database being used:
connection.createStatement().execute("USE " + tenantIdentifier );

Thats it - this approach of multitenancy ( separate schema ) now works
One more note - I did not use - CurrentTenantIdentifierResolver
From Hibernate Documentation: ( I did not understand the first paragraph below - but the second paragraph seemed to indicate that this class is not necessary if specifying tenant identifier from SessionFactory ) - which is what I am doing so I did not define the class - CurrentTenantIdentifierResolver

There are 2 situations where CurrentTenantIdentifierResolver is used:

The first situation is when the application is using the
org.hibernate.context.spi.CurrentSessionContext feature in conjunction with multi-tenancy.
In the case of the current-session feature, Hibernate will need to open a session if it cannot
find an existing one in scope. However, when a session is opened in a multi-tenant environment
the tenant identifier has to be specified. This is where the CurrentTenantIdentifierResolver
comes into play; Hibernate will consult the implementation you provide to determine the tenant
identifier to use when opening the session. In this case, it is required that a
CurrentTenantIdentifierResolver be supplied.

The other situation is when you do not want to have to explicitly specify the tenant  identifier
all the time as we saw in Example 16.1, "Specifying tenant identifier from SessionFactory".
If a CurrentTenantIdentifierResolver has been specified, Hibernate will use it to determine
the default tenant identifier to use when opening the session.

Once again a big thanks to M Deinum for nudging me in this direction and helping out
Thanks

A: <jee:jndi-lookup id="dataSource" jndi-name="MYSQLDS"/>

<bean id="sessionFactoryWorking" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
    <property name="configLocation" value="classpath:local.JADE.PIT.hibernate.cfg.xml" />
</bean>

In the configuration above the DataSource is looked up and well that is it. It isn't used it just sits around. You want to connect it to your LocalSessionFactoryBean by injecting it into the dataSource property.
<bean id="sessionFactoryWorking" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
    <property name="configLocation" value="classpath:local.JADE.PIT.hibernate.cfg.xml" />
    <property name="dataSource" ref="dataSource" />
</bean>

With this configuration the datasource is wired and will be available.
Another thing in your hibernate configuration file the connection.* properties are useless due to the injected datasource.


text:
Q: List all defined functions name by user in V8 From 3 hours, I search for make a Javascript function who return the list of  reachable/created functions by an user.
Unfortunately, I don't find anything....
You know how to do this on google V8 Javascript engine ?
PS: Sorry for my english, I'm french student :D

A: There is no programmatical way of scraping a list of current functions or variables.
You would in the least need to know where these functions lived - e.g. on a particular namespace.
var fn = {};
fn.someFunc = function(){}
fn.someProp = 'foo';
fn.someOtherFunc = function(){}

//get all funcs
for (var i in fn) if (typeof fn[i] == 'function') alert('found a function');

A: Please note that by default the functions which are not declared as a method of an object are considered as a method of window object.
So, using something like the code below you can list all functions of window object.
You can inspect the output and add better filters to improve isFunction function which I steal here.
<script type="text/javascript">

        function myTest() //function to be detected
        {
            return true;
        }

        function isFunction(functionToCheck)
        {
            var getType = {};
            return functionToCheck && getType.toString.call(functionToCheck) == '[object Function]';
        }

        for( var it in window )
        {
            if(isFunction(window[it]))
                console.log(it+":"+window[it]);
        }

    </script>

A: Maybe I can help you. This call go top to down in every object, starting with global context. the first function return the global object that is where are our free-scope objects . And we do a recursion over each object search for functions or anything you want.
var global = (function(){return this;})();

(function(ctx){
  for(var i in ctx) {
   // put your function check here.
   // System.out.println(i + ' ' + typeof ctx[i]);
   if(ctx[i] instanceof Object) {
     arguments.callee(ctx[i]); }
  }
})(global);

run code on the fly

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to properly use fire and forget without affecting performance? I have asked this question, but couldn't get much response and the ones I get did not solve my problem. So here I'm trying to ask again in a different way.
I have a project that process product feed files into my system. For one certain feed file whole process is taking around 40-50 minutes. Now I have created a WebJob to process images from the feed and I'm sending picture urls from my first project to WebJob by creating storage client. When I have that to my project, it increased the processing time significantly, so I tried using it with Task.Run to use Fire and Forget approach, but still even with that overall process time is around 2 hours now.
Here is how I call my method that creates storage queue.
if (insertImages)
{
    #pragma warning disable 4014
    Task.Run(async () => { await new QueueUtility().CreateQueueMessage(picture); }).ConfigureAwait(false);
    #pragma warning restore 4014
}

And here is my code to create queue message
public async Task CreateQueueMessage(Picture picture)
    {
            Utility.Log log = new Utility.Log();
            await AddQueueMessage(picture.url);

    }

public async Task AddQueueMessage(string queueMessage)
    {
        ServicePointManager.UseNagleAlgorithm = false;

        CloudStorageAccount storageAccount = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("ImagekWebJobStorage"));

        // Create the queue client.
        CloudQueueClient queueClient = storageAccount.CreateCloudQueueClient();

        // Retrieve a reference to a container.
        CloudQueue queue = queueClient.GetQueueReference("imagequeue");

        // Create a message and add it to the queue.
        CloudQueueMessage message = new CloudQueueMessage(queueMessage);
        queue.AddMessage(message);

    }

I don't understand why my processing time doubled up and can't find a way to work around that either. Any ideas that would help me resolve this would be really helpful.
EDIT:
Turning QueueUtility into static class and methods into static methods seemed to help. Not sure how or why though.

A: Creating a new CloudStorageAccount, CloudQueueClient, and CloudQueue for every message sent is very inefficient.
You should create these once and reuse them to send each message.
For more guidance on optimizing the performance of applications that use Azure Storage, see:
Microsoft Azure Storage Performance and Scalability Checklist
https://azure.microsoft.com/en-us/documentation/articles/storage-performance-checklist/


text:
Q: get multiple table with same columns data i have three table with same value of columns. example: say i have three table "table1", "table2", "table3" and each columns has "id", "title", "description", "category", "date", "thumbnail", "admin". now i'm trying to get all data from those three table. but there is a think, i want to check with if statement. if table1 not match with id, check table2. if table2 not match with id, check table3 and at last show the data. please check my below code, i'm trying to get data from those three table:
<?php
            include('config/database.php');
            $id=$_GET['single'];
            $query=mysqli_query($conn,"select * from table1, table2, table3 where id='$id'  ");
            while($row=mysqli_fetch_array($query)){
            $title=$row['title'];
            $date=$row['date'];
            $admin=$row['admin'];
            $thumbnail=$row['thumbnail'];
            $description=$row['description'];
            $category=$row['category'];
         }
          ?>

please help me to get all data from those three table with if statement
it will be better to understand if you post an answer. thank you in advance.

A: Use a UNION of 3 queries.
$sql = "
    SELECT * FROM (
        SELECT 1 AS tnum, * FROM table1 WHERE id = ?
        UNION ALL
        SELECT 2 AS tnum, * FROM table2 WHERE id = ?
        UNION ALL
        SELECT 3 AS tnum, * FROM table3 WHERE id = ?
    ) AS x
    ORDER BY tnum
    LIMIT 1";
$stmt = $conn->prepare($sql);
$stmt->bind_param('iii', $id, $id, $id);
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_assoc();
if ($row) {
    $title = $row['title']
    $date=$row['date'];
    $admin=$row['admin'];
    $thumbnail=$row['thumbnail'];
    $description=$row['description'];
    $category=$row['category'];
}

Adding the tnum column to the result orders them so the table1 data is preferred, then table2, finally table3.


text:
Q: Import Excel data to OS X Calendar I'm trying to find a way to import data from an Excel file into OS X Calendar app, but I can only find articles related to iCal, which I am guessing is the iOS App.
Basically we need to import a list of birth dates into the Mac OS Calendar app, through a file exported from Excel (maybe a CSV file?) How do I do this?

A: iCal is just the old name for what is currently Apple's main "Calendar" application (referenced here). They are exactly the same thing, Apple just rebranded iCal a few years ago.
That being said, there is a relatively easy (albeit lengthy) way to go about putting an Excel file into the Calendar app. Essentially you have to export the Excel document as a CSV, and then change it into an .ics format in order to get it to work. Instead of trying to repeat what I have found, here is the original article (updated as of 2013) which says it much better than I can in this small space.


text:
Q: IE9 ignoring *some* media queries in same stylesheet I have a responsive site located here: http://wnmu.edu
Everything seems to be working just fine in all other modern browsers except IE9.
It seems like only certain @media queries are being recognize, even though they are in the same stylesheet. Take a look at this screenshot:

The menu "About WNMU, Current Students..." is visible, which is originally hidden in less than 480px screens. However, the hamburger menu is still visible. My css code seems pretty simple:
@media only screen and (min-width: 784px){
    .banner #responsive_menu_toggles {
        display: none;
    }
}

I have capability mode off.
Thank you.

A: It looks like this question was asked once before, here.
Media query not working in IE9

Just in case anyone is crawling SO for an answer to this, the above
  two answers aren't solving the core problem which is answered here -
  CSS media query not working in IE 9
Basically inline CSS3 media queries DO work in IE9 but you have to
  disable Compatibilty mode -
<meta http-equiv="X-UA-Compatible" content="IE=9">

The above meta tag needs to be placed before any other meta tags otherwise IE9 will default to compatibility mode on and will subsequently not work.

If you are curious I found this by searching google for ie9 @media css issues

A: Wow. Just figured it out. I guess IE9 has a "4094 rule" limit. So I broke apart the css file, and everything is good! I'll definitely see why I have so many rules.
Sigh of relief.


text:
Q: Ruby on Rails: How to validate data using Rspec or cucumber I am querying data from HotDeal model in Homepage01 which is present in ProductDetailController like this
def Homepage01
    @hotdetail=HotDeal.where("department_id=?",1).limit(15).offset(0)
end

I need to test or validate the data using Rspec. How can i validate data or any mysql error in RSpec or cucumber framework.?

A: Create a hotdeal factory using factory girl with department_id 1.
Inside your product_detail_controller_spec.rb (which should rather be plural btw, i.e. product_details for your controller and your spec) write:
require 'spec_helper'

describe ClientsController do
  describe "GET Homepage01" do
    it "assigns the right records" do
      FactoryGirl.create(:hot_deal)
      hotdetail = HotDeal.where("department_id=?",1).limit(15).offset(0)
      get "Homepage01"
      assigns(:hotdetail).should eq(hotdetail)
    end
  end
end

This will make sure that your query works 1) technically and 2) as expected.


text:
Q: How can I check how many bytes a reference requires? From C# 5.0 in a Nutshell: The Definitive Reference in page 22;

Reference types require separate allocations of memory for the
  reference and object. The object consumes as many bytes as its fields,
  plus additional administrative overhead. The precise overhead is
  intrinsically private to the implementation of the .NET runtime, but
  at minimum the overhead is eight bytes, used to store a key to the
  object's type, as well as temporary information such as its lock state
  for multithreading and a flag to indicate whether it has been fixed
  from movement by the garbage collector. Each reference to an object
  requires an extra four or eight bytes, depending on whether the .NET
  runtime is running on a 32- or 64-bit platform.

I'm not quite sure I understand this bold part completely. It says on 32-bit platforms a reference requires four bytes, on 64-bit platforms it requires eight bytes.
So, let's say we have
string s = "Soner";

How can I check how many bytes this s reference requires?

A: You can use Environment.Is64BitProcess. If it is, every reference will be 8 bytes. If it's not, every reference will be 4 bytes. The type of the reference, and the contents of the object it refers to, are irrelevant.
EDIT: As noted in a now-deleted answer, IntPtr.Size is even simpler.
EDIT: As noted in comments, although currently all references in a CLR are the same size, it's just possible that at some point it will go down a similar path to Hotspot, which uses "compressed oops" in many cases to store references as 32-bit values even in a 64-bit process (without limiting the memory available).

A: If you really want to calculate the size of a reference, using this Reference.Size should work:
using System;
using System.Reflection.Emit;

public static class Reference
{
    public static readonly int Size = new Func<int>(delegate()
    {
        var method = new DynamicMethod(string.Empty, typeof(int), null);
        var gen = method.GetILGenerator();
        gen.Emit(OpCodes.Sizeof, typeof(object));
        gen.Emit(OpCodes.Conv_I4);
        gen.Emit(OpCodes.Ret);
        return ((Func<int>)method.CreateDelegate(typeof(Func<int>)))();
    })();
}

But going with the other answers is probably a better idea.

A: To expand on Jon Skeet's answer, to get the number of possible bytes you should do this:
int bytesInRef = Environment.Is64BitProcess ? 8 : 4;

However, this is an implementation detail. Not only should you not worry about this, you should ignore this. Here's a good blog post on (another) implementation detail, but it's still applicable as it talks about implementation details and how you shouldn't trust them or depend on them. Here: The Stack Is An Implementation Detail


text:
Q: Where are shell functions stored on Linux? At first I was looking for the reason that which doesn't output anything after giving it certain programs as an argument, e.g. cd.
From what I've found here, the reason probably is that cd on my machine is a function, which is confirmed by running type cd.
TLDR: But as normal programs that which can locate thanks to $PATH variable are placed in one of those $PATH folders, where are functions or scripts like cd stored?
user@linuxmchine:~$ type cd
cd is a function
cd ()
{
    __zsh_like_cd cd "$@"
}

A: Shell functions are stored in the memory of the shell
(or, perhaps, in undocumented temporary files).
They don't exist in any usable way until the shell starts
(e.g., when you login to a CLI, or start a shell window such as xterm)
and they are defined (e.g., by reading .bashrc, .bash_profile, or something similar)
and they cease to exist when the shell terminates.

A: cd and other common commands like echo, type & alias are so called builtins .
Builtin commands are contained within the shell itself and different shells may have different built in commands.

A: User defined functions
Typically bash functions are permanently stored in a bash start-up script.

*

*System-wide start-up scripts: /etc/profile for login shells, and /etc/bashrc for interactive shells.

*User define start-up scripts: ~/.bash_profile for login shells, and ~/.bashrc for interactive shells.

*More information on interactive/login shells can be found in the bash man page in the INVOCATION section.

User defined shell functions are loaded dynamically in a hash (or lookup table) when bash starts.  From the bash source file variable.c the definition for the table is:
/* The list of shell functions that the user has created, or that came from
   the environment. */
HASH_TABLE *shell_functions = (HASH_TABLE *)NULL;

User defined functions can be listed with the bash declare command, other shells still use typeset. In bash declare has superceded the typeset command.
declare -f

The functions exist in memory for the lifetime of the bash shell.
Shell defined (builtin) functions
These are common functions such as echo, printf, cd and :.  They are compiled into a library which is linked into the bash executable. Building the definitions into the executable saves time compared to loading an external definition. Definitions for these functions (held in .def source files which are parsed into C source) are held in the builtins directory of bash source.
A useful aside: for information on a shell builtin command use help <command>.
e.g.
help                # list all builtins
help declare        # info and options for declare
help -m declare     # gives man style information for declare

A: The Super User question Finding the definition of a bash function
is closely related to this one.
User HairOfTheDog provided this answer (paraphrased):

The following commands will report the location (filename and line number)
  of a function's definition.  Assuming a function named foo,

# Turn on extended shell debugging
shopt -s extdebug

# Display the function's name, line number and fully qualified source file
declare -F foo

# Turn off extended shell debugging
shopt -u extdebug

For example, the output of these commands might be:

foo 32 /source/private/main/developer/cue.pub.sh

The above might work only in bash, and not in POSIX shells in general.
Thanks to Blue Raspberry for finding this!


text:
Q: Create a shortcut for application on Google Chrome for MacOSX Google Chrome on Windows comes with a very usefull feature allowing the user to Create application shortcuts from the settings menu: http://support.google.com/chrome/bin/answer.py?hl=en&answer=95710
Unfortunately there is not such feature on Google Chrome for MacOSX. Is there a trick to enable this feature? An hidden menu? Is it on the developpement list?

A: Applicationize
Applicationize is an open-source, free service I built that replicates the "Create Application Shortcuts" behavior on Mac by generating a Chrome Extension of your favorite website on-the-fly that opens in its own window with its own dock icon!
https://applicationize.me/
https://github.com/eladnava/applicationize

A: Here is a little more simpler method using createGcApp application.

In addition to giving it a much more familiar interface, it also fixes
  some of the bugs in the previous script such as those preventing
  spaces in application names. The usage of the new version of the tool
  should be pretty straight forward. Start by downloading the .dmg, and
  opening the image. Inside, you should find a readme file, a script
  called createGcApp, and the source folder. Double-clicking the script
  will prompt you with questions about name, url, and icon for the
  application shortcut (make sure it's a square if you include an icon).
  The resulting file will then be saved to the /Applications folder.
  Thanks so much to Mait for sharing this much easier version.

Screenshot for how it looks:

A: I found the solution:
http://lifehacker.com/5611711/create-application-shortcuts-in-google-chrome-for-mac-with-a-shell-script
Basically a script is creating a proper icon in the application with the 3 following parameters:

*

*Application name

*Application URL

*Logo path

It works almost like on Windows except that external link are open in a internal tab.


text: Q: Android Studio Instant Run makes HTTPS handshake fail I am using Android Studio 2.2.2 to develop my project.And I use HTTPS in my project to get data from server.But when I open the Instant Run options,the HTTPS fails and saying "https handshake fail".After I turn off Instant Run and reinstall my app,it turns out to be OK again.Does anyone ever got into similar situation?Or can someone tells me why Instant Run has some effect on HTTPS?


text:
Q: Sinatra and Grape API together? I've been reading around and I found this micro-framework called Grape for ruby. I am currently using Sinatra to handle the web interface but I would also like to implement Grape to handle the API aspect of the app. I can't find any helpful suggestions to this topic. The grape documentation says "Grape is a REST-like API micro-framework for Ruby. It's designed to run on Rack or complement existing web application frameworks such as Rails and Sinatra by providing a simple DSL to easily develop RESTful APIs." So it sounds like there should be an official way of combining both right? This app will also be run on Heroku.

A: The phrases you're looking for are:

*

*multiple rack apps

*rack middleware

*mapping urls rack sinatra

That kind of thing. Grape, Sinatra and Rails are all Rack apps. What this means is that you can build your Grape app, your Sinatra app, and your Rails app, and then you can use Rack to run them as they're all Rack compliant because they share an interface.
What this means in practice is you write the applications, and then you put them in a rackup file to run them. A short example using 2 Sinatra apps (but they could be any number of any kind of Rack apps) :
# app/frontend.rb
require 'sinatra/base'
# This is a rack app.
class Frontend < Sinatra::Base
  get "/"
    haml :index
  end
end

__END__

@@ layout
%html
  = yield

@@ index
%div.title This is the frontend.

# app/api.rb
# This is also a rack app.
class API < Sinatra::Base

  # when this is mapped below,
  # it will mean it gets called via "/api/"
  get "/" do
    "This is the API"
  end
end

# config.ru
require_relative "./app/frontend.rb"
require_relative "./app/api.rb"

# Here base URL's are mapped to rack apps.
run Rack::URLMap.new("/" => Frontend.new,
                     "/api" => Api.new)

If you wanted to add the Twitter API example from the Grape README:
# app/twitter_api.rb
module Twitter
  # more code follows

# config.ru
require_relative "./app/twitter_api.rb" # add this

# change this to:
run Rack::URLMap.new("/" => Frontend,
                     "/api" => API,
                     "/twitter" => Twitter::API)

Hopefully that's enough to get you started. There are plenty of examples once you know where to look. You can also run other apps inside a Sinatra app by using use (see http://www.sinatrarb.com/intro#Rack%20Middleware) and I see that Grape offers the mount keyword too. There are lots of ways available, which may be a bit confusing at first, but just try them out and see what they do and what you like best. A big part of it is preference, so don't be afraid to go with what feels right. Ruby is for the human more than the computer :)

Edit: A Sinatra app with a Grape app "inside"
class App < Sinatra::Base
  use Twitter::API
  # other stuff…
end

# config.ru
# instead of URLMap…
map "/" do
  run App
end

I believe it will be something like that.


text:
Q: primeng autocomplete functionality is not working I have added the AutoCompleteModule in app.module.ts file.
import { AutoCompleteModule } from 'primeng/autocomplete';

But autocomplete is not working as expected. I am getting below error:
Template parse errors:
Can't bind to 'ngModel' since it isn't a known property of 'p-autoComplete'.
1. If 'p-autoComplete' is an Angular component and it has 'ngModel' input, then verify that it is part of this module.
2. If 'p-autoComplete' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.

I am using primeng latest version.
I have tried adding autocomplete module in app.module.ts. After this I rebuild the application but still it is giving above error. Any help would be appreciated. Thanks

A: To make it work, you need to add FormsModule in app.module.ts file. Then it will work.
import { FormsModule  } from '@angular/forms';

A: use it like this:
<p-autoComplete  ... [(ngModel)]="WHATEVER" ...></p-autoComplete>

That's how you use ngModel with primeng components.


text:
Q: django-piston: how to get values of a many to many field? I have a model with ManyToManyField to another model. I would like to get all the info on a particular record (including the related info from other models) return by JSON.
How to get django-piston to display those values? I would be happy with just primary keys.
Or can you suggest another option ?

A: I may be wrong, but this should do it:
class PersonHandler(BaseHandler):
    model = Person
    fields = ('id', ('friends', ('id', 'name')), 'name')

    def read(self, request):
        return Person.objects.filter(...)

A: You need to define a classmethod on the handler that returns the many-to-many data, I don't believe Piston does this automatically.
class MyHandler(BaseHandler):
    model = MyModel
    fields = ('myfield', 'mymanytomanyfield')

    @classmethod
    def mymanytomanyfield(cls, myinstance):
        return myinstance.mymanytomanyfield.all()

A: My code:
Models:
class Tag(models.Model):
"""docstring for Tags"""
tag_name = models.CharField(max_length=20, blank=True)
create_time = models.DateTimeField(auto_now_add=True)

def __unicode__(self):
    return self.tag_name
class Author(models.Model):
"""docstring for Author"""
name = models.CharField(max_length=30)
email = models.EmailField(blank=True)
website = models.URLField(blank=True)

def __unicode__(self):
    return u'%s' % (self.name)

class Blog(models.Model):
"""docstring for Blogs"""
caption = models.CharField(max_length=50)
author = models.ForeignKey(Author)
tags = models.ManyToManyField(Tag, blank=True)
content = models.TextField()
publish_time = models.DateTimeField(auto_now_add=True)
update_time = models.DateTimeField(auto_now=True)

def __unicode__(self):
    return u'%s %s %s' % (self.caption, self.author, self.publish_time)

Handle:
class BlogAndTagsHandler(BaseHandler):
allowed_methods = ('GET',)
model = Blog
fields = ('id' 'caption', 'author',('tags',('id', 'tag_name')), 'content', 'publish_time', 'update_time')

def read(self, request, _id=None):
    """
    Returns a single post if `blogpost_id` is given,
    otherwise a subset.

    """
    base = Blog.objects

    if _id:
        return base.get(id=_id)
    else:
        return base.all() # Or base.filter(...)

Works petty good.


text:
Q: React Hooks - Update parent component without triggering infinite loop Say I have a parent component, which renders a child component, and all the child does is keep some state and trigger an onChange handler if its own state changes. See the code below, or the CodeSandbox.
CodeSandbox example
This code gets into an infinite loop and I want to get rid of this behaviour.
Possible solutions, but ones I don't prefer:
1: I could put all state in the parent component, and control the child with the parent, but that is not really what I want. In real life, my child component takes care of more than a simple counter, and I want to use it easily from the parent. There is complex behaviour inside of the child component and I want to communicate some simple changes to the parent. Or is this an absolute no-go in React? (to keep state in child and also trigger change on state update to parent) I would say it's not necessarily?
2: I could also trigger the onChange handler from within the handleInternalChange handler. Also, not what I want. In real life, my child component will update from several separate places in the component itself, so a state change is the most elegant thing to watch and trigger an onChange parent.
3: I could omit the onChange dependency in the useEffect dependency array. This is not recommended, React community refers to this explanation. Which I understand, only I feel that this situation would be an exception?** Also, I use CRA, which comes with great linters etc out of the box, and the linter complains about it if I remove the onChange handler from the dependencies, and I don't prefer to start brewing my own liner rules. For such a simple use case as mine, community-set linters should work fine.
What I think that happens
What I think happens, is that the parent gets updated, then re-renders the whole thing, and somehow, the onChange handler is 'changed' too. The function doesn't actually change, as far as I would say, but React thinks (or knows) it does, so it triggers the useEffect call again in the child component, and then the endless loop is born.
But, as far as I'm concerned, the onChange function doesn't change. So why is the useEffect call being triggered? And how can I prevent this?
import React, { useState, useEffect } from "react";

const Comp = ({ onChange }) => {
  const [internalState, setInternalState] = useState(0);
  const handleChange = () => {
    setInternalState(internalState + 1);
  };

  useEffect(() => {
    const result = internalState.toString();
    onChange(result);
  }, [internalState, onChange]);

  return (

      CLICK ME

{`INTERNAL NUM: ${internalState}`}

  );
};

export default function App() {
  const [state, setState] = useState("");
  const handleChange = () => setState(state + 1);
  return (

{`STATE: ${state}`}

      <Comp onChange={handleChange} />

  );
}

** After some though, in other cases, the onChange prop could of course be changed, simply by assigning a different function to the prop. So this rule is perfectly clear to me. Only (as said in last paragraph) why is it behaving like it changes in this scenario? Since my function does not change at all.

A: You should wrap the handleChange method with useCallback hooks, so that it will be created  once.
const handleChange = useCallback(() => setState(state + 1),[]);

The infinite loop happens because you have added onChange method as dependency for useEffect in the <Comp /> component.
useEffect takes array of dependencies and runs the effect if one of dependencies change.
Since you have added onchange handler as dependency, each time parent component re-renders, a new instance of handleChange method is created which is not equal to the previous handlechange method.
The component rendering flow will be like this:

*

*<App /> component creates handleChange method and passes it to the <Comp />

*Useffect in the <Comp /> will be called after initial rendering and from there <App /> component's handleChange method will be called.

*state changes in <App /> component and re-renders it. While re-rendering new instance of  handleChange is created and passed on onChange prop to <Comp /> component.

*Since the value at previous and new onChange prop is different, useEffect will fired which again will update parent component's state and this loop continues.

To prevent this, handleChange method should be wrapped with useCallback. The callback function passed to useCallback hook will be memoized so when the child component compares the old and new prop they remain equal.
{} === {}  // false
[] === []  // false
(() => {}) == (() => {})  //false


text:
Q: How far have you understood my lesson? As far as  I know  your  answer  is  correct..I think  this  statement is  correct.

How  far  have  you understood  my  lesson?

I am doubtful about  the  correctness of  the  sentence.But  how  far  means  to  what  extent. so  my  question seems  to  be  correct.

How  well have  you  understood my  lesson?

I think  The  above  is  a  correct  sentence.
If  how  far  have  you  understood  my lesson  is  wrong, what  is the  correct  alternative  for  the  question   besides  how  well have  you  understood?
Here  are two  links  which  show  the  usage  of  how  far.
https://www.collinsdictionary.com/dictionary/english/how-far
https://sentencedict.com/how%20far.html
Aftet  going  through  these  two links
I have  found  this sentence:

How  far  has  this  penetrated into  the  general public?

So  I  think:

How  far  have  you  understood  my  lesson    is   not  at all  wrong.

A: Understanding is not a matter of distance but of completeness. So alternatives you could use are:

How well have you understood my question.
How completely have you understood my question.
How much have you understood the information.

Note, for the last one we can't use "question" because much relates to the quantity of a substance not the completeness of it.
You could also say:

How far have you got in understanding my question

Here you are treating the process of understanding as a journey, and you are asking how far along the journey have traveled.


text:
Q: How to read parquet file compressed by .gz in databricks? My file is stored on an Azure's blob storage and it looks like 1627937153-1627937153-ab_test-20210604-0-0.parquet.gz. How can I read the data from this file in databricks using Python without downloading this file into databricks environment? I have multiple files of the same format in the same folder. Can anyone help me with this?

A: *

*

You may try
import pandas as pd
df = read_parquet("myFile.parquet.gzip")
display(df)

as referred in here by @bala
(or)
2.
From SO reference
 import io
df = pd.read_parquet(blob_to_read, engine='pyarrow')
display(df)

(Or)
3.
Try using gzip file to read from a zip file
import gzip
file = gzip.open("filename.parquet.gz", "rb")
df = file.read()
display(df)

*

You can also this article on zip-files-python taken from zip-files-python-notebook  which shows how to unzip files which has these steps  as below :
1.retrieve file
2.Unzip file
3.Move file to DBFS
And finally load file into data frame using
df = spark.read.format("parquet").option("inferSchema", "true").option("header","true").load("dbfs:/tmp/LoanStats3a. parquet ")
display(df)

*

If in case you use azure data lake gen2 ,check this
pyarrowfs-adlgen2 is an implementation of a pyarrow filesystem for Azure Data Lake Gen2. See >  Use pyarrow with Azure Data Lake gen2  .It allows you to use pyarrow and pandas to read parquet datasets directly from Azure without the need to copy files to local storage first.


text:
Q: Reading partitioned Parquet files to DataFame in Python (in memory) where a column type is array of array Context
I have partitioned Parquet files in S3. I want to read and concatenate them into a DataFrame so I can query and view the data (in memory). I did it so far, however one of the columns's data with the type (array<array< double >>) is converted to None. Other columns (such as str, array of int, etc) are converted correctly. I am not sure what I am missing in the process. I imagine the data is missed during this conversion, or the data is there and my querying method is wrong.
Steps I did so far
import s3fs
import fastparquet as fp
import pandas as pd

key = 'MyAWSKey'
secret = 'MyAWSSecret'
token = 'MyAWSToken'

s3_file_system = s3fs.S3FileSystem(secret= secret, token=token, key=key)
file_names = s3_file_system.glob(path='s3://.../*.snappy.parquet')

# <class 'fastparquet.api.ParquetFile'>
fp_api_parquetfile_obj = fp.ParquetFile(files, open_with= s3_file_system.open)

data = fp_api_parquetfile_obj.to_pandas()

Query Result
# column A type is array of array of doubles
print(pd.Series(data['A']).head(10))
# Prints 10 rows of None! [Incorrect]

# column B type is array of int
print(pd.Series(data['B']).head(10))
# Prints 10 rows of array of int values correctly

# column C type is string
print(pd.Series(data['C']).head(10))
# Prints 10 rows of str values correctly

Please note that the data (array of array of doubles) exist in the files, because I can query it using Athena.

A: I could not find any ways to get fastparquet reading the array of array column; instead I used a different library (pyarrow) and it works!
import s3fs
import pandas as pd
import pyarrow.parquet as pq

key = 'MyAWSKey'
secret = 'MyAWSSecret'
token = 'MyAWSToken'

s3_file_system = s3fs.S3FileSystem(secret= secret, token=token, key=key)
file_names = s3_file_system.glob(path='s3://.../*.snappy.parquet')

data_frames = [pq.ParquetDataset('s3://' + f, filesystem= s3_file_system).read_pandas().to_pandas() for f in files]

data = pd.concat(data_frames,ignore_index=True)

# column A type is array of array of doubles
print(pd.Series(data['A']).head(10))
# Prints 10 rows of array of arrays correctly


text:
Q: Aside is going down only in Chrome I have recently designed a responsive WP Theme for my blog and there only in Chrome, a aside is falling from header. I see, to stick it into header wrapper, I can add clearfix to header class=wrapper. That is clear but question is why it is coming down where it does not have much height.
I have tested in FF and IE and it is working there. In IE, it is working in IE10 and IE9. In IE8 many things are broken so please do not look there.
<aside> with top-bar-section is going down compared to the normal flow. The class top-bar-section was having display:inline-block and float:right and I made it to display:block. I saw that when I toggle in Chrome Dev tool with display:inline-block / float:right then problem was going away so i just took a chance with display:block as float makes div a block element!
Now, toggle in dev tool of chrome of Float:right is not helping but toggling of display:block help place it at right place.
With Toggling, I meant that un-selecting that property in dev tool and selecting again.

HTML markup group:

Online Example: Issue is not happening on Home page.
Update: I saw also, somewhere  is overflowing horizontally.


text:
Q: Using numerical variables as by group to get summary statistics I have data as follows:
library(data.table)
dat <- fread("total women young
              1       0      0
              1       1      1
              1       0      1
              2       1      1
              2       2      1
              2       2      1
              3       1      2
              3       2      3
              3       2      3
              4       4      2
              4       4      3
              4       3      3
              5       5      2
              5       2      3
              5       5      3
              10       4      2
              10       4      3
              20       5      3
             100      10     20")

I would like to create six categories for the variable tot_num:
1,2,3,4,5 and over 5.

I would like to count the observations per category total in  count.
sum_tot would simply be these multiplied. And womenand young are the average amount of women and young people in that group.
Desired output
            total count sum_tot_count women young
              1       3      3          0.33   0.66
              2       3      6          5/6    0.5
              3       3      9          5/9    8/9
              4       3      12         11/12  10/12
              5       3      15         12/15  8/15
              over 5  4      140        23/140 28/140

I am having some trouble figuring out where to start.
Could someone lead me on the right track?

A: Does this work:
library(dplyr)
dat %>% mutate(tot = if_else(total > 5, 'over 5', as.character(total))) %>%
      group_by(tot) %>% summarise(count = n(), sum_tot_count = sum(total), women = sum(women)/sum(total), young = sum(young)/sum(total))
# A tibble: 6 × 5
  tot    count sum_tot_count women young
  <chr>  <int>         <int> <dbl> <dbl>
1 1          3             3 0.333 0.667
2 2          3             6 0.833 0.5
3 3          3             9 0.556 0.889
4 4          3            12 0.917 0.667
5 5          3            15 0.8   0.533
6 over 5     4           140 0.164 0.2

A: With cut:
dat %>%
  group_by(cutGroup = cut(total, breaks = c(1:6, Inf), labels = c(1:5, "over 5"), include.lowest = TRUE, right = FALSE)) %>%
  summarise(count = n(),
            sum_tot_count = sum(total),
            women = sum(women) / sum(total),
            young = sum(young) / sum(total))

A: A data.table solution. The key is using cut(), as in other answers; after that, basic data.table syntax as in Use data.table to count and aggregate / summarize a column will get you the rest of the way:
dat[, cat := cut(total, breaks = 0.5 + c(0:5,Inf), labels = c(1:5, "over 5"))]
      .(count = n())]
dat[,.(count=.N,
       total = sum(total),
       women = sum(women)/sum(total),
       young = sum(young)/sum(total)),
    by = cat]


text:
Q: Is my 2010 MacBook Air 32 or 64 bit
Possible Duplicate:
Mac OS X: How can I tell if I'm in 64-bit mode?

How do I find out if my 2010 MacBook Air is 64 or 32 bit?
Trying to download Eclipse.

A: Goto Apple > About this Mac > More Info > "Select Software"
If "64-bit Kernel and Extensions" says Yes you are running 64bit if No 32bit.
If you want to change it see this artical http://support.apple.com/kb/ht3773
Regards

A: It's 64-bit.  All of the MacBook Air versions use Core 2 Duo processors, which are 64-bit processors.  The kernel won't be running in 64-bit mode (as @Mathew's answer showed you how to find out), but that in no way limits you to 32-bit apps.  OS X can run each program in a different mode, and tries to run each program in the best possible mode -- many programs come with both 32- and 64-bit code included, and the OS will automatically pick the best one for your CPU.  If you run the Activity Monitor utility, it'll show you what programs are currently running (including invisible background programs), and its "Kind" column will show what mode they're running in -- I'll bet more than half are "Intel (64 bit)".


text:
Q: Communication with OBD-II using Windows Phone I have a problem with sending and receiving data from elm327 device.
I tried to connect to the device using channel 01 (on Bluetooth) but it doesn't matter what command I send, I just receive the string "AT+BRSF=24\r" as an answer.
I tried also to connect at channel 16 and there I receive a string "NO DATA"
somebody knows what is the problem?
thank you,
Arie

A: The AT+BRSF=24 response sounds like you're communicating with the wrong Bluetooth device (perhaps a headset?).
"NO DATA" sounds like an ELM327 response. What command are you sending? Try "ATZ\r" to start with.


text:
Q: Xamarin forms shell getting confused with Login screen not navigating to home content So the below is my xamrain forms shell I am having an issue when I am using my tab bar.
I have a login page so in my App.xaml.cs I have the folowing
    public App()
    {
         Syncfusion.Licensing.SyncfusionLicenseProvider
         .RegisterLicense("");//remove license for security
        DevExpress.XamarinForms.Editors.Initializer.Init();
        DevExpress.XamarinForms.DataGrid.Initializer.Init();

        InitializeComponent();

       MainPage = new NavigationPage(new LoginPage());
    }

As you see I am putting putting my main page to the login page however when I click my home button below when I am in my add pages the home page does not navigate back to the main screen.
<Shell xmlns="http://xamarin.com/schemas/2014/forms"
   xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
   xmlns:local="clr-namespace:THEHOCKEYLAB.Views"
   Title="THEHOCKEYLAB"
   x:Class="THEHOCKEYLAB.AppShell">

<!--
    The overall app visual hierarchy is defined here, along with navigation.

    https://learn.microsoft.com/xamarin/xamarin-forms/app-fundamentals/shell/
-->

<Shell.Resources>
    <ResourceDictionary>
        <Style x:Key="BaseStyle" TargetType="Element">
            <Setter Property="Shell.BackgroundColor" Value="{StaticResource Primary}" />
            <Setter Property="Shell.ForegroundColor" Value="White" />
            <Setter Property="Shell.TitleColor" Value="White" />
            <Setter Property="Shell.DisabledColor" Value="#B4FFFFFF" />
            <Setter Property="Shell.UnselectedColor" Value="#95FFFFFF" />
            <Setter Property="Shell.TabBarBackgroundColor" Value="{StaticResource Primary}" />
            <Setter Property="Shell.TabBarForegroundColor" Value="White"/>
            <Setter Property="Shell.TabBarUnselectedColor" Value="#95FFFFFF"/>
            <Setter Property="Shell.TabBarTitleColor" Value="White"/>
        </Style>
        <Style TargetType="TabBar" BasedOn="{StaticResource BaseStyle}" />
        <Style TargetType="FlyoutItem" BasedOn="{StaticResource BaseStyle}" />
    </ResourceDictionary>
</Shell.Resources>

<TabBar>
    <ShellContent Title="Menu" Icon="home.png"  ContentTemplate="{DataTemplate local:AdminMenuPage}" />
    <ShellContent Title="Settings" Icon="settings.png" ContentTemplate="{DataTemplate local:SettingsPage}" />
</TabBar>

<!--
    If you would like to navigate to this content you can do so by calling
    await Shell.Current.GoToAsync("//LoginPage");
-->
<TabBar>
    <ShellContent Route="LoginPage" ContentTemplate="{DataTemplate local:LoginPage}" />
</TabBar>

So for example here I have an issue
private async void btnAddStudent_Clicked(object sender, EventArgs e)
{
  await Shell.Current.GoToAsync("StudentsPage");
}

When I try to come back from this page clicking the  home nothing nappens can someone please explain to me as to why that is?

A: There are two ways to achieve this .

Include LoginPage into AppShell

*

*Set AppShell as MainPage in App.

*Place Two Tabbar in AppShell , and place LoginPage first than HomePage, and set  different Route for the two Tabbar.
<TabBar Route="Login">
  <ShellContent  ContentTemplate="{DataTemplate local:LoginPage}" />
</TabBar>

<TabBar Route="Home">
    <ShellContent Title="Menu" Icon="home.png"  ContentTemplate="{DataTemplate local:AdminMenuPage}" />
    <ShellContent Title="Settings" Icon="settings.png" ContentTemplate="{DataTemplate local:SettingsPage}" />
</TabBar>

*Call await Shell.Current.GoToAsync("//Home"); when login in , Call await Shell.Current.GoToAsync("//Login"); when login out .
Don't Include LoginPage into AppShell

*

*Set LoginPage as MainPage in App at first.

*Call MainPage = new AppShell(); When login in , Call MainPage = new LoginPage(); when login out .


text:
Q: CSS hover effect doesn't appear on adding background image I have added a css hover effect on the button which is inside the div main-container. Also inside it is a background div with a layer div inside of it. The problem is everytime, there is a background image the hover effect doesn't show but if I remove the background image, the effect is visible. How do I fix this? demo

.background {
    position: relative;
}

.background  img{
    max-width:100%;
 max-height:800px;
}

.layer {
    background-color: rgba(248, 247, 216, 0.7);
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
}
.btn {
 border: none;
 font-family: inherit;
 font-size: inherit;
 color: inherit;
 background: none;
 cursor: pointer;
 padding: 25px 80px;
 display: inline-block;
 margin: 15px 30px;
 text-transform: uppercase;
 letter-spacing: 1px;
 font-weight: 700;
 outline: none;
 position: relative;
 -webkit-transition: all 0.3s;
 -moz-transition: all 0.3s;
 transition: all 0.3s;
}

.btn:after {
 content: '';
 position: absolute;
 z-index: -1;
 -webkit-transition: all 0.3s;
 -moz-transition: all 0.3s;
 transition: all 0.3s;
}

.btn:before {
 speak: none;
 font-style: normal;
 font-weight: normal;
 font-variant: normal;
 text-transform: none;
 line-height: 1;
 position: relative;
 -webkit-font-smoothing: antialiased;
}

/* Button 1 */
.btn-1 {
 border: 3px solid #fff;
 color: #fff;
}

.btn-1f {
 overflow: hidden;
}

.btn-1f:after {
 width: 101%;
 height: 0;
 top: 50%;
 left: 50%;
 background: #000;
 opacity: 0;
 -webkit-transform: translateX(-50%) translateY(-50%);
 -moz-transform: translateX(-50%) translateY(-50%);
 -ms-transform: translateX(-50%) translateY(-50%);
 transform: translateX(-50%) translateY(-50%);
}

.btn-1f:hover,
.btn-1f:active {
 color: #0e83cd;
}

.btn-1f:hover:after {
 height: 75%;
 opacity: 1;
}

.btn-1f:active:after {
 height: 130%;
 opacity: 1;
}
.background {
    position: relative;
 width: inherit;
 height:inherit;
 background-image: url("http://www.wallpapereast.com/static/images/nature-wallpaper-desktop-308_ySxPe7m.jpg");
}
.main-container{
 width:100%;
 height:745px;
 position:relative;
}
.cities{position:absolute;bottom:0;}

<button class="btn btn-1 btn-1f">Bangalore</button>

A: I checked your code.
GIVE Z-index negative on background like below,
.background {
    background-image: url("http://www.wallpapereast.com/static/images/nature-wallpaper-desktop-308_ySxPe7m.jpg");
    height: inherit;
    position: relative;
    width: inherit;
    z-index: -1;
}

A: You may do this:
.btn{
    z-index: 99;
}
.btn:hover a{
    color: #efefef;
}

A: Give the button a z-index.
Eg : z-index: 999;


text:
Q: Imagick not using custom fonts when converting SVG to JPG with PHP I'm having an issue with custom fonts not rendering when attempting to convert an SVG to a JPG image.  I am using font-family="Lobster" defined for an SVG text element.
My server setup is as follows:

*

*CentOS 6.5 (32 bit)

*ImageMagick 6.5.4-7

*PHP 5.2.17

The PHP code I am testing with, but does not work.  I am attempting to use the custom font Lobster.
//Setup SVG to be read by Imagick.
$SVG = '<?xml version="1.0" encoding="utf-8"?>';
$SVG .= '<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">';
$SVG .= '<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="158px" height="92px" viewBox="0 0 158 92" enable-background="new 0 0 158 92" xml:space="preserve">';
$SVG .= '<text transform="matrix(1 0 0 1 32 58)" font-family="Lobster" font-style="normal" font-size="20px" font-weight="400">Lobster</text>';
$SVG .= '</svg>';

$image = new Imagick();

//Convert SVG to JPG
$image->readImageBlob($SVG);
$image->setImageFormat("jpeg");

//Save the thumbnail.
$save_path = '/home/username/lobster.jpg';
$image->writeImage($save_path);

echo '
';

Which produces the following image:

What I have tried:
I've created a type.xml file located at /home/username/.magick/type.xml with the Lobster font definition as shown here:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE typemap [
<!ELEMENT typemap (type)+>
<!ELEMENT type (#PCDATA)>
<!ELEMENT include (#PCDATA)>
<!ATTLIST type name CDATA #REQUIRED>
<!ATTLIST type fullname CDATA #IMPLIED>
<!ATTLIST type family CDATA #IMPLIED>
<!ATTLIST type foundry CDATA #IMPLIED>
<!ATTLIST type weight CDATA #IMPLIED>
<!ATTLIST type style CDATA #IMPLIED>
<!ATTLIST type stretch CDATA #IMPLIED>
<!ATTLIST type format CDATA #IMPLIED>
<!ATTLIST type metrics CDATA #IMPLIED>
<!ATTLIST type glyphs CDATA #REQUIRED>
<!ATTLIST type version CDATA #IMPLIED>
<!ATTLIST include file CDATA #REQUIRED>
]>
<typemap>

  <type
     format="ttf"
     name="Lobster"
     fullname="Lobster"
     family="Lobster"
     glyphs="/home/username/fonts/Lobster/Lobster.ttf"
     style="normal"
     stretch="normal"
     weight="400"
     />

</typemap>

I've included a direct include in the /usr/lib/ImageMagick-6.5.4/config/type.xml file like this:
<typemap>
   <include file="type-ghostscript.xml" />
   <include file="/home/username/.magick/type.xml" />
</typemap>

When outputting the fonts using the $image->queryfonts(); method, I can see the Lobster font defined in the list.  For example, this:
$image = new Imagick();
$fonts = $image->queryfonts();
foreach($fonts as $font) {
    echo $font . '
';
}

Returns this:
[...]
Hershey-Plain-Triplex-Regular
Hershey-Script-Complex-Regular
Hershey-Script-Simplex-Regular
Lobster
MeriendaOne
NewCenturySchlbk-Bold
NewCenturySchlbk-BoldItalic
NewCenturySchlbk-Italic
NewCenturySchlbk-Roman
[...etc]

Additionally, I believe ImageMagick is using it's own internal SVG renderer.   The shell command:
convert -list format | grep SVG

Returns:
MSVG  SVG       rw+   ImageMagick's own SVG internal renderer
SVG  SVG       rw+   Scalable Vector Graphics (RSVG 2.26.0)
SVGZ  SVG       rw+   Compressed Scalable Vector Graphics (RSVG 2.26.0)

Any ideas as to why this isn't working?

A: I was having the same problem converting SVG to PNG using Imagemagick but was unable to make it work using that approach. I was somehow able to get the result I need using docraptor:
 DocRaptor.createAndDownloadDoc("YOUR_API_KEY", {
    test: true, // test documents are free, but watermarked
    type: "pdf",
    document_content: document.getElementById('container_of_svg').innerHTML
  })

Just make sure to add the font declarations inside the container_of_svg element like below and make sure to add an absolute URL to your fonts:
@font-face {
    font-family: 'DaimlerCS-Demi';
    src: url("https://staging.xxx.com/xx/fonts/xx/FontCS-Demi.eot")
}
page {
      size: 21.16cm 15.87cm;
      padding: 1cm;
      margin:0;
      background: #E6E6E6;
}

Just check their document here: https://docraptor.com/documentation/jquery
Note: docraptor is not free but if your client can pay for it, I think its a solid option.

A: Please restart your webserver, or PHP-FPM instances.
Apparently the information about which fonts can be used in an SVG is cached by ImageMagick, even though the list returned by queryFonts() isn't cached.
Your code example didn't work for me until I restarted my php-fpm instance, and then it worked perfectly.


text:
Q: Downloading file from my project I have a controller with a method for downloading file. Without code, all I need is to go to this link:
http://localhost:1186/Content/MyFolder/file1.exe

and the file gets downloaded.
I tried to do this with code like this:
Response.Redirect(Server.MapPath("~\\Content\\MyFolder\\file1.exe"));

But the breakpoint passes through this line and nothing happens. I think the problem is I'm using Server.MapPath, but how else would I do this?

A: you can do something like this
create an action
public ActionResult RedirectToDownload()
{
    return View();
}

and then on the view with JavaScript on load redirect to your URL
$(document).ready(function() {
  window.navigate("~/Content/MyFolder/file1.exe");
});

you might also use this
public ActionResult Index()
{
    return Redirect("~/Content/MyFolder/file1.exe");
}


text:
Q: Deserializing with XmlSerializer List into Dictionary I am serializing data into xml by converting Dictionary into List.
The serialization is ok.
Is it possible to populate dictionary on deserialization? (right now I populate dictionary after deserialization completes and list is returned )
 [Serializable]
    public class Attribute
    {
        public string Key { get; set; }
        public int Value1 { get; set; }
        public int Value2 { get; set; }
        public int Value3 { get; set; }

        public Attribute() { }
        public Attribute(string key, int value1, int value2, int value3)
        {
            Key = key;
            Value1 = value1;
            Value2 = value2;
            Value3 = value3;
        }
    }

    [XmlRoot("Container")]
    public class TestObject
    {
        public TestObject() { }
        private Dictionary<string, Attribute> dictionary = new Dictionary<string, Attribute>();

        [XmlIgnore()]
        public Dictionary<string, Attribute> Dictionary
        {
            set { dictionary = value; }
            get { return dictionary; }
        }

        public string Str { get; set; }

        private List<Attribute> _attributes = new List<Attribute>();
        public List<Attribute> Attributes
        {
            get
            {
                if (Dictionary.Count>0)
                {

                    foreach (string key in Dictionary.Keys)
                    {
                        _attributes.Add(new Attribute(key, Dictionary[key].Value1,  Dictionary[key].Value2,    Dictionary[key].Value3));
                    }
                    return _attributes;
                }
            return _attributes;
            }
        }

    }

Code:
 TestObject TestObj = new TestObject();
 TestObj.Dictionary.Add("asdsad", new Attribute { Value1 = 232, Value2 = 12, Value3 = 89 });
 TestObj.Dictionary.Add("sdfer", new Attribute { Value1 = 10, Value2 = 7, Value3 = 857 });
 TestObj.Dictionary.Add("zxcdf", new Attribute { Value1 = 266, Value2 = 85, Value3 = 11 });

 TestObj.Str = "Test";

 XmlWriterSettings settings = new XmlWriterSettings();
 settings.OmitXmlDeclaration = true;
 settings.Indent = true;
 XmlSerializer serializer = new XmlSerializer(typeof(TestObject));

 using (XmlWriter writer = XmlWriter.Create(@"C:\test.xml", settings))
 {
      XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces();
      namespaces.Add(string.Empty, string.Empty);

      serializer.Serialize(writer, TestObj, namespaces);
 }

 TestObject newob;
 using (TextReader textReader = new StreamReader(@"C:\test.xml"))
 {
      newob = (TestObject)serializer.Deserialize(textReader);
     //repopulate dictionary from Attribute list
      foreach (Attribute atr in newob.Attributes)
      {
          //code
      }
 }

A: If the question is "can I convert a serialized list to a dictionary without writing code" then the answer is no.  There isn't much wrong with what you are doing now.
You could consider a dictionary that supports XML serialization so you don't have to convert it to a list first.  Here's one:
  public class XmlDictionary<T, V> : Dictionary<T, V>, IXmlSerializable {
    [XmlType("Entry")]
    public struct Entry {
      public Entry(T key, V value) : this() { Key = key; Value = value; }
      [XmlElement("Key")]
      public T Key { get; set; }
      [XmlElement("Value")]
      public V Value { get; set; }
    }

    System.Xml.Schema.XmlSchema IXmlSerializable.GetSchema() {
      return null;
    }

    void IXmlSerializable.ReadXml(System.Xml.XmlReader reader) {
      this.Clear();
      var serializer = new XmlSerializer(typeof(List<Entry>));
      reader.Read();
      var list = (List<Entry>)serializer.Deserialize(reader);
      foreach (var entry in list) this.Add(entry.Key, entry.Value);
      reader.ReadEndElement();
    }

    void IXmlSerializable.WriteXml(System.Xml.XmlWriter writer) {
      var list = new List<Entry>(this.Count);
      foreach (var entry in this) list.Add(new Entry(entry.Key, entry.Value));
      XmlSerializer serializer = new XmlSerializer(list.GetType());
      serializer.Serialize(writer, list);
    }
  }


text:
Q: An image with proper permissions and correctly linked disappeared from my site I'm building a website.
http://olympiandiamonds.worldwidejamie.com
As I was building the site and uploading files, the site logo suddenly stopped displaying. I don't get any errors in the console as if it's not finding the image or suggesting there might be a permission error.
The image just isn't displaying.
Here is my code:

                <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bottomNav">
                    Toggle navigation

                </button>

It's a pretty straightforward bootstrap site and any of the topics I've found are mentioning a path being wrong or the image not being uploaded to the server. I've checked both of those and I can't seem to solve why the image won't display.

A: Check at least following things

*

*You are using img/Olympian_Faceted.png as source. Is it same name on servers?

*Try renaming the file

*Try JPEG instead of PNG

Because, image is not showing if I open it in browser http://olympiandiamonds.worldwidejamie.com/img/Olympian_Faceted.png


text:
Q: Can't add LINQ to SQL Classes in project upgraded to 3.5 I just upgraded a project to 3.5 SP1
and trying to add a LINQ to SQL class item to the project and can't as it doesn't appear in the Add Item list.
Though if i create a new project in the same solution and try adding it the item (LINQ to SQL classes) is available and I can add it to the project.
What do i have to do to be able to add LINQ to SQL classes to my existing/upgraded project?

A: Right click the project, go to properties, and make sure you have the project set to target the correct version of the framework.
Edit To clarify, you can "upgrade" a project through Visual Studio but it can still be set to target an older version of .NET.


text:
Q: Create a loop to get 6 items from fullcalendar I am new to coldfusion and Mura and having a hard time to do the following: I was able to grab a single event from the fullcalendar. However, I am trying display underneath the calendar 6 events instead of 1. How and where would I add the cfloop to accomplish this? Here is the following code:

    <cffunction name="MultipleFeaturedEvents">
    <cfargument name="feedName" type="string" default="702771E7-155D-0201-11DF8865B175735F"/>
    <cfargument name="maxMonths" type="numeric" default="3" />
    <cfargument name="groupDailyEvents" default="true" />
    <cfscript>

        var rs = '';
        var subRS = '';
        var local = {};

        local.util = $.getCalendarUtility();
        local.rsItems = local.util.getCalendarItems(calendarid=arguments.feedName, start=Now(), end=DateAdd('m', val(4), Now()));

        var qoq = new Query();
        qoq.setDBType('query');
        qoq.setAttributes(rs=local.rsItems, maxRows=val(1));
        qoq.setSQL('
            SELECT *
            FROM rs
            ORDER BY displaystart ASC
        ');
        var qoqResult = qoq.execute().getResult();
        local.it = $.getBean('contentIterator').setQuery(qoqResult);

    </cfscript>
    <cfsavecontent variable="local.str">
        <cfoutput>

                <cfset local.item = local.it.next()>

Feature Event

                    #LSDateFormat(local.item.getValue('displayStart'), "mmm d, yyyy")#
                    <cfquery dbtype="query" name="subRS1">
                        select *
                        from rsItems
                        where rsItems.contentid = <cfqueryparam value="#local.item.getValue('contentid')#" />
                    </cfquery>
                    <cfif subRS1.recordcount gt 1>

                        <cfset enddate = ListLast(ValueList(subRS1.displaystop)) />
                        <cfif IsValid('date', enddate)>
                            - #LSDateFormat(enddate)#
                        </cfif>
                    </cfif>

                    #timeFormat(local.item.getValue('displayStart'), "h:mm tt")# - #timeFormat(local.item.getValue('displayStop'), "h:mm tt")#

                    #HTMLEditFormat(local.item.getMenuTitle())#

                        <cfif Len(local.item.getValue('summary'))>
                        #local.item.getValue('summary')#
                        </cfif>

        </cfoutput>
    </cfsavecontent>
    <cfreturn local.str />
</cffunction>

Any help would be appreciated.
Thanks
UPDATE
I have done the following to do the loop but it still is not working correctly. I am not sure what I am doing wrong but any help would be appreciated:
<cffunction name="MultipleFeaturedEvents">
    <cfargument name="feedName" type="string" default="702771E7-155D-0201-11DF8865B175735F"/>
    <cfargument name="maxMonths" type="numeric" default="3" />
    <cfargument name="groupDailyEvents" default="true" />
    <cfscript>

        var rs = '';
        var subRS = '';
        var local = {};

        local.util = $.getCalendarUtility();
        local.rsItems = local.util.getCalendarItems(calendarid=arguments.feedName, start=Now(), end=DateAdd('m', val(4), Now()));

        var qoq = new Query();
        qoq.setDBType('query');
        qoq.setAttributes(rs=local.rsItems, maxRows=val(1));
        qoq.setSQL('
            SELECT *
            FROM rs
            ORDER BY displaystart ASC
        ');
        var qoqResult = qoq.execute().getResult();
        local.it = $.getBean('contentIterator').setQuery(qoqResult);

    </cfscript>
    <cfsavecontent variable="local.str">
        <cfoutput>
        <cfset ctr= 1 />
            <cfloop condition="(local.it.hasNext()) AND (ctr LT 6)">
                <cfset local.item = local.it.next() />

Feature Event

                            #LSDateFormat(local.item.getValue('displayStart'), "mmm d, yyyy")#
                            <cfquery dbtype="query" name="subRS1">
                                select *
                                from rsItems
                                where rsItems.contentid = <cfqueryparam value="#local.item.getValue('contentid')#" />
                            </cfquery>
                            <cfif subRS1.recordcount gt 1>

                                <cfset enddate = ListLast(ValueList(subRS1.displaystop)) />
                                <cfif IsValid('date', enddate)>
                                    - #LSDateFormat(enddate)#
                                </cfif>
                            </cfif>

                            #timeFormat(local.item.getValue('displayStart'), "h:mm tt")# - #timeFormat(local.item.getValue('displayStop'), "h:mm tt")#

                            #HTMLEditFormat(local.item.getMenuTitle())#

                                <cfif Len(local.item.getValue('summary'))>
                                #local.item.getValue('summary')#
                                </cfif>

                <cfset ctr++ />
            </cfloop>
        </cfoutput>
    </cfsavecontent>
    <cfreturn local.str />
</cffunction>


text:
Q: mysql hostname with path "localhost:/some/path/ms.sock" Im connecting to mysql database with server defined as localhost:/some/path/ms.sock, can anyone explain how does this works? It surely is a path since localhost:/some/../some/path/ms.sock works as well, but when i run this exec from php
mysqldump -h localhost:/some/path/ms.sock -u xxx -pxxx xxx

it writes Error: 2005: Unknown MySQL server host 'localhost:/some/path/ms.sock' The PHP script is in the same directory. However this works fine:
new mysqli("localhost:/some/path/ms.sock", "xxx", "xxx", "xxx");

A: The /some/path/ms.sock refers to the Unix domain socket through wich PHP will connect to MySQL (this is one of the three connection protocols supported by MySQL, besides the usual TCP/IP).
This path must be provided to the mysql* clients with the --socket (or -S) option:
mysqldump -h localhost -S /some/path/ms.sock -u ...


text:
Q: Trouble with loading a "glb model" in three.js I'm trying to load a model into my scene. Unfortunately so far without success. I see an empty scene, not a model. When I insert a boxgeometry it can also be seen, so three.js works without any problems. I try to load a model from the example files "Stork.glb". I've reduced everything to the bare minimum. I can not see what it could be now. Do I have to integrate the GLTFLoader differently?
index.js
import Main from "./main";
new Main();

main.js
import * as THREE from "../lib/three/build/three.module.js";
import { OrbitControls } from '../lib/three/examples/jsm/controls/OrbitControls.js';
import { GLTFLoader } from '../lib/three/examples/jsm/loaders/GLTFLoader.js';

class Main {
    constructor(){
        this.init();
        this.animate();
    }

    init(){
        this.renderer = new THREE.WebGLRenderer( { antialias: true } );
        this.renderer.setPixelRatio( window.devicePixelRatio );
        this.renderer.shadowMap.enabled = true;
        this.renderer.shadowMap.type = THREE.PCFSoftShadowMap;
        this.renderer.autoClear = false;

        this.container = document.getElementById('container');
        this.renderer.setSize(this.container.clientWidth, this.container.clientHeight);
        this.container.appendChild( this.renderer.domElement );

        this.aspect = this.container.clientWidth / this.container.clientHeight;
        this.scene = new THREE.Scene();
        this.scene.background = new THREE.Color( 0x555555 );

        this.camera = new THREE.PerspectiveCamera( 45, this.aspect, .1, 10000 );
        this.camera.position.set(0, 0, 300);

        this.controls = new OrbitControls( this.camera, this.renderer.domElement );
        this.controls.enableZoom = true;
        this.controls.enabled = true;
        this.controls.target.set(0, 0, 0);

    //-------------------------------------------------------------------------------------------------

        var light = new THREE.AmbientLight(0xffffff);
        this.scene.add(light);

        const loader = new GLTFLoader();
        loader.load("models/Stork.glb", function(gltf){
            this.scene.add(gltf.scene);
        });

    }//end init

    animate(){
        requestAnimationFrame( this.animate.bind(this) );
        this.render();
    }//end animate

    render(){

        this.controls.update();
        this.camera.updateMatrixWorld();
        this.camera.updateProjectionMatrix();

        this.renderer.render(this.scene, this.camera);

    }//end render

}//end class

export default Main;

Folder layout:
mainfolder
|
|-index.html
|-webpack.config.js
|-package.json
|-build
|-src
|   |-index.js
|   |-main.js
|
|-lib
|   |-three
|
|-models
    |
  Stork.glb

webpack.config.js
const path = require('path');

module.exports = {
mode: 'development',
//devtool: "none",
//mode: 'production',
entry: './src/index.js',
output: {
path: path.resolve(__dirname, 'build'),
filename: 'bundle.js' },

//plugins: [new HtmlWebpackPlugin()],

    module: {
        rules: [
            {
                test: /\.(glb)$/i,
                use: [ { loader: 'file-loader', options: { outputPath: 'models/' } } ]

            },
        ],
    },

};//end module.exports

A: The problem was that i did not load the code with a localhost. I tryed to open it with a browser. If i use a localhost it works fine

A: Just a guess, but since you're within a class and using an es5 anonymous function, your this keyword may not be what you think it is. Maybe using the lexical nature of an arrow function will solve your problem?
        loader.load("models/Stork.glb", gltf => {
            this.scene.add(gltf.scene);
        });


text:
Q: using jquery, what is the easiest way to disable and enable a section of html input controls i have a bunch of form inputs (textboxex, radio buttons, checkboxes, etc)
there is a specific section of the form that i want to enable and disable.
i want a quick way when i click on a radio button (which is not part of the form) to disable all inputs in this specific section of a form. also on the selection of a different radio button (also not on the form in question) to enable that same section of the form input controls.
The one trick is that i dont fully have control over the id and classes of the actual inputs so i need something where i can put a parent div and have it find all items within that div
is there an easy way in jquery to enable or disable a section of input controls.

A: Use the :input selector which grabs all inputs, textareas, selects and buttons, providing a context to jQuery() will limit this to inputs inside a parent, then change the disabled attribute:
 $(':input', parent).attr('disabled', 'disabled');

Removing the disabled attribute will re-enable:
 $(':input', parent).removeAttr('disabled');

A: You can disable a div by adding the "disabled" attribute like this:
$('div.container').attr('disabled', 'disabled');

You can then re-enable it by removing the attribute:
$('.someElement').removeAttr('disabled');

In your case, add a click handler to your radio button or other control which uses the above lines of code to enable/disable the div element (and, by extension, all of its content), like this (for disabling):
$('#radio-button1').click(function() {
    $('div.container').attr('disabled', 'disabled');
});

A: $('#your_div_name').find('input').disable();
Needs this plugin.

A: The first way I can think of to do this is to insert/remove the word "disabled" into the inputs you want to manipulate.  You could do this with the appendTo() or html() functions selecting all inputs which match a certain id/class name.


text:
Q: converting an accumulated variable to timestep values in a netcdf file with CDO I have a netcdf-file with about 100 timesteps on a grid with one variable, which is accumulated over the timesteps. I am now interested in calculating the contribution of each timestep to the variable's value (i.e. the difference of consecutive timesteps).
Currently I use the following sequence:

*

*To extract every single timestep into a new file I use cdo seltimestep,$i ...,

*calculate each difference into a new file with cdo sub $i ${i-1} ...

*and merge those new files in the end with cdo mergetime ... into one single result file.

That seems to me to be very cumbersome and not ideal regarding to performance. Because of the amount of timesteps I cannot use a cdo pipeline and need to create many files in the meantime therefore.
Is there one better solution to convert an accumulated variable to timestep values with cdo (or something else like nco/ncl?)

A: If you want to use cdo, no need for all those loops and writing a lot of files, just use the function deltat:
cdo deltat in.nc diff.nc

Like the python solution, this will be orders of magnitude faster than the loops you were using, and has the advantage of being a command-line one-liner.
Alternatively, and much less concise, you can difference the two series if you know the length (I show this as this technique can be useful in other contexts):
# calculate number of steps in the file:
nstep=$(cdo -s ntime in.nc)

# do difference between steps 2:n and steps 1:(n-1)
cdo sub -seltimestep,2/$nstep in.nc -seltimestep,1/`expr $nstep - 1` in.nc diff.nc

Postscript on accumulated fields!
Note that the above solutions and BOTH the python solutions posted on this page produce an output that has one timestep less than the input, i.e. THEY THROW AWAY THE FIRST TIMESTEP.  In some cases, for example if you have a model flux field that is accumulated in the forecast, which seems to be the case, you don't want to discard the first timestep (as that is the accumulation from zero at the forecast start to the first step).  In that case you can extract that first step and insert it on at the "front" of the file like this:
cdo mergetime -seltimestep,1 in.nc diff.nc diff_with_step1.nc

You should also ensure you do this for the python solutions too.
you can pipe the whole thing as a oneliner (sometimes piping can lead to bus errors or seg faults, these can usually be remedied using the "-L" option to enforce sequential operations).
cdo mergetime -seltimestep,1 in.nc -deltat in.nc diff_with_step1.nc

try this if you get a seg fault
cdo -L mergetime -seltimestep,1 in.nc -deltat in.nc diff_with_step1.nc

and this to guard against rounding and accuracy issues, if you have packed data (i.e. type NC_SHORT):
cdo -L -b f32 mergetime -seltimestep,1 in.nc -deltat in.nc diff_with_step1.nc

A: numpy's diff computes the difference of consecutive entries.
I suspect you have a multi-dimension variable in your file, so here is a generic example of how to do it:
import netCDF4
import numpy as np

ncfile = netCDF4.Dataset('./myfile.nc', 'r')
var = ncfile.variables['variable'][:,:,:] # [time x lat x lon]

# Differences with a step of 1 along the 'time' axis (0)
var_diff = np.diff(var, n=1, axis=0)
ncfile.close()

# Write out the new variable to a new file
ntim, nlat, nlon = np.shape(var_diff)

ncfile_out = netCDF4.Dataset('./outfile.nc', 'w')
ncfile_out.createDimension('time', ntim)
ncfile_out.createDimension('lat', nlat)
ncfile_out.createDimension('lon', nlon)
var_out = ncfile_out.createVariable('variable', 'f4', ('time', 'lat', 'lon',))
var_out[:,:,:] = var_diff[:,:,:]
ncfile_out.close()

A: xarray is my tool of choice for this sort of thing:
import xarray as xr

# Open the netCDF file
ds = xr.open_dataset('./myfile.nc')

# Take the diff along the time dimension
ds['new_variable'] = ds['variable'].diff(dim='time')

# Write a new file
ds.to_netcdf('outfile.nc')


text:
Q: ERROR: Could not build wheels for pywinpty, which is required to install pyproject.toml-based I'm trying to upload my python flask app on azure app service. My app is running perfectly on local environment but on deploying it on azure web app its giving me this error.
note: This error originates from a subprocess, and is likely not a problem with pip.
ERROR: Failed building wheel for pywinpty
ERROR: Could not build wheels for pywinpty, which is required to install pyproject.toml-based projects
WARNING: There was an error checking the latest version of pip.
Error: Process completed with exit code 1.


text:
Q: "The SMTP host was not specified." - but it is specified? I'm slightly baffled here - I'm receiving the following error:

The SMTP host was not specified.

Even though my code appears to be correct (from what I can see).
I am able to do it manually by including all the details inside of the controller, e.g.
SmtpClient smtpClient = new SmtpClient("smtp.gmail.com");
smtpClient.Port = 587;
... etc

But I shouldn't have to do this, as I want to use the details inside mailSettings (Making it re-usable for various different controllers).
mailSettings in my Web.Config file:
<system.net>
   <mailSettings>
     <smtp from="example@gmail.com" deliveryMethod="Network" >
       <network host="smtp.gmail.com" defaultCredentials="true"
                port="587" enableSsl="true" userName="example@gmail.com"
                password="example"/>
     </smtp>
   </mailSettings>
</system.net>

My Controller action:
 [HttpPost]
 public ActionResult SubmitFeature(FormData formData)
 {
     SmtpClient smtpClient = new SmtpClient();

     MailMessage mail = new MailMessage();
     mail.To.Add(new MailAddress("example@gmail.com"));
     mail.Body = "Test";

     smtpClient.Send(mail);

     return View("Example");
 }

Is there anything I'm missing which may be causing this? I haven't messed around with any other settings in Web.Config, they are as is when setting up a new MVC5 project.

A: The solution was mentioned in the Chat, but never edited into the answer above.
Make sure that you make these settings in the web.config of the Root Level and not in the Views folder.

@Tommy: ...this looks like the web.config from your Views folder and not the web.config at the root of the application

A: In a clean MVC project, I am unable to replicate your issue.  Following the ScottGu blog post here, I was able to get a gmail sent email without issue (VS 2013, .NET 4.5.1, MVC 5).  Note the the <system.net> element is a top level element and not nested inside of AppSettings or <system.web>.
Important
There are a few web.config files in your solution, ensure that the mailSettings is inserted into the root level web.config (and not the one located in the Views folder)
Web.Config
<configuration>
  <system.net>
    <mailSettings>
      <smtp from="myEmail@gmail.com">
        <network host="smtp.gmail.com"
                 port="587"
                 enableSsl="true"
                 userName="myEmail@gmail.com"
                 password="SuperSecretPwd"
                 defaultCredentials="false" /> <!--This must be false on Gmail-->
      </smtp>
    </mailSettings>
  </system.net>
</configuration>

Controller
var smtpClient = new SmtpClient();
var msg = new MailMessage();
msg.To.Add("MyOtherAddress@yahoo.com");
msg.Subject = "Test";
msg.Body = "This is just a test email";
smtpClient.Send(msg);

It is unclear if some of the extra attributes you have included are causing issues (thought they shouldn't) such as delivery method.  Also, is there a setting for allowing SMTP access or is that just for IMAP/POP delivery?
If you can test and are successful in a clean project, then this would point to either a web.config transformation problem or some other setting(s) in your project overriding the web.config settings that you have in place.

A: If your code is right so,Turn on "Less secure app access" in your Gamil email account