问:
How to get location name without showing map on screen?
I want location name in textfield without showing map on screen. I have implemented map by using google map API. And it is showing me the location on map.All i want is to save location in a Textfield without showing map.  </p>

答:
```<code>            Geocoder geocoder = new Geocoder(this, Locale.getDefault());
            List<Address> addresses = geocoder.getFromLocation(lat, lng, 1);
            String cityName = addresses.get(0).getAddressLine(0);
            String stateName = addresses.get(0).getAddressLine(1);
            String countryName = addresses.get(0).getAddressLine(2);
</code>```

you can make use of Geocoder class . Pass the necessary latitude and longitude to getFromLocation() method and this method will return the address of the location as a List ,from the list you can get necessary details as shown above

Body:
            Geocoder geocoder = new Geocoder(this, Locale.getDefault());
            List<Address> addresses = geocoder.getFromLocation(lat, lng, 1);
            String cityName = addresses.get(0).getAddressLine(0);
            String stateName = addresses.get(0).getAddressLine(1);
            String countryName = addresses.get(0).getAddressLine(2);

you can make use of Geocoder class . Pass the necessary latitude and longitude to getFromLocation() method and this method will return the address of the location as a List ,from the list you can get necessary details as shown above


来源: stackexchange

问:
iOS in-app subscriptions - do not show the iTunes Apple-ID dialog
When implementing subscriptions checking (iOS, in-app), each time a subscription is checked by the app in background, this dialog appears to the user:

It appears at each app start.
How to get rid of it? Is it possible not to show it?
I repeat: this is about subscriptions CHECKING, not actually byuing.

答: Usually this happens when you test in sandbox mode. But in production if user is already logged in , this won't pop up.</p>

ContentLicense: CC BY-SA 3.0


问:
Initialize multiple databases in Spring
I'm using AbstractRoutingDatasource to route between databases in runtime. In real condition on the informix database everything works just fine.

For tests I created a spring profile to use in memory H2 databases.
After running the spring app whith the test profile I checked the local databases using the h2 console. No schema was created.

I tried using schema.sql in recources and hibernates:

```<code>generate-ddl: true
hibernate:
  ddl-auto: create-drop
</code>```

hibernate throws

```<code>java.lang.IllegalStateException: Cannot determine target DataSource for lookup key [null]
</code>```

As I understand hibernate ist trying to generate only the "routed" datasource. Since no DatabaseContextHolder is set (null) this fails.

So both ways fail.

Is there a way to initialize all databases with (the same) schema?

I list my configuration below.

bootstrap.yml:

```<code>spring:
  profiles: acceptanceTest
  config:
    name: standalone
  cloud:
    config:
      enabled: false
      discovery:
        enabled: false
  jpa:
    database-platform: org.hibernate.dialect.H2Dialect
    generate-ddl: true
    hibernate:
      ddl-auto: create-drop
    properties:
      hibernate:
        show_sql: false
        use_sql_comments: false
        format_sql: false
  h2:
    console:
      enabled: true
      path: /h2
datasource:
  mc:
    driver-class-name: 'org.h2.Driver'
    url: 'jdbc:h2:mem:test-mc-db;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE'
    username: sa
    password: ''
    platform: h2
    initialize: true
    type: com.zaxxer.hikari.HikariDataSource
    hikari:
      maximum-pool-size: 10
      minimum-idle: 0
      idle-timeout: 60000
      pool-name: MarkHikariPool
  cw:
    driver-class-name: 'org.h2.Driver'
    url: 'jdbc:h2:mem:test-cw-db'
    username: sa
    password: ''
    type: com.zaxxer.hikari.HikariDataSource
    hikari:
      maximum-pool-size: 10
      minimum-idle: 0
      idle-timeout: 60000
      pool-name: MarkHikariPool
</code>```

MainApp.java:

```<code>@ComponentScan({ "de.md.mark" })
@EnableDiscoveryClient
@SpringBootApplication(
    exclude =
        {
            DataSourceAutoConfiguration.class,
            DataSourceTransactionManagerAutoConfiguration.class,
            HibernateJpaAutoConfiguration.class
        }
)
public class MainApp
{
    public static void main(String[] args)
    {
</code>```

DataSourceConfiguration.java:

```<code>@Configuration
@EnableJpaRepositories(
    basePackageClasses = { MarkTypeRepository.class, MarkRepository.class }, entityManagerFactoryRef = "markEntityManager",
    transactionManagerRef = "markTransactionManager"
)
@EnableTransactionManagement
public class DataSourceConfiguration
{
    @Autowired(required = false)
    private PersistenceUnitManager persistenceUnitManager;

    @Bean
    @ConfigurationProperties("app.jpa")
    @Primary
    public JpaProperties jpaProperties()
    {
        return new JpaProperties();
    }

    @Bean
    @ConfigurationProperties(prefix = "datasource.mc")
    public DataSource mcDataSource()
    {
        return DataSourceBuilder.create().build();
    }

    @Bean
    @ConfigurationProperties(prefix = "datasource.cw")
    public DataSource cwDataSource()
    {
        return DataSourceBuilder.create().build();
    }

    @Bean
    @Primary
    public DataSource dataSource()
    {
        DataSourceRouter router = new DataSourceRouter();

        final HashMap<Object, Object> map = new HashMap<>(DatabaseEnvironment.values().length);
        map.put(DatabaseEnvironment.MC, mcDataSource());
        map.put(DatabaseEnvironment.CW, cwDataSource());
        router.setTargetDataSources(map);
        return router;
    }

    @Bean
    @Primary
    public LocalContainerEntityManagerFactoryBean markEntityManager(final JpaProperties jpaProperties)
    {
        EntityManagerFactoryBuilder builder = createEntityManagerFactoryBuilder(jpaProperties);

        return builder.dataSource(dataSource()).packages(MarkTypeEntity.class).persistenceUnit("markEntityManager").build();
    }

    @Bean
    @Primary
    public JpaTransactionManager markTransactionManager(@Qualifier("markEntityManager") final EntityManagerFactory factory)
    {
        return new JpaTransactionManager(factory);
    }

    private EntityManagerFactoryBuilder createEntityManagerFactoryBuilder(JpaProperties jpaProperties)
    {
        JpaVendorAdapter jpaVendorAdapter = createJpaVendorAdapter(jpaProperties);
        return new EntityManagerFactoryBuilder(jpaVendorAdapter, jpaProperties.getProperties(), this.persistenceUnitManager);
    }

    private JpaVendorAdapter createJpaVendorAdapter(JpaProperties jpaProperties)
    {
        AbstractJpaVendorAdapter adapter = new HibernateJpaVendorAdapter();
        adapter.setShowSql(jpaProperties.isShowSql());
        adapter.setDatabase(jpaProperties.getDatabase());
        adapter.setDatabasePlatform(jpaProperties.getDatabasePlatform());
        adapter.setGenerateDdl(jpaProperties.isGenerateDdl());
        return adapter;
    }
}
</code>```

答:
After a lot research in the last two days I found a solution to initialize all datasources.
I created a method to create and initialize the local H2 databases using the SchemaExport.class of hibernate.
Since I only need the local db's for testing, I call the method for each DatabaseEnvirement in a @Before cucumber method.

```<code>public void createDatabase(DatabaseEnvironment environment)
throws Exception
{
    // load hibernate configuration from hibernate.cfg.xml in classpath
    Configuration configuration = new Configuration().configure();
    MetadataSources metadata =
    new MetadataSources(new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build());

    ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(true);
    scanner.addIncludeFilter(new AnnotationTypeFilter(Entity.class));

    for (BeanDefinition def : scanner.findCandidateComponents(MarkEntity.class.getPackage().getName()))
    {
        metadata.addAnnotatedClass(Class.forName(def.getBeanClassName()));
    }

    Connection connection = DriverManager.getConnection("jdbc:h2:mem:test-" + environment.name().toLowerCase(), "sa", "");

    SchemaExport export = new SchemaExport((MetadataImplementor) metadata.buildMetadata(), connection);
    export.create(true, true);
}

@Before
public void beforeTest()
    throws Exception
{
    // initialise databases
    for (DatabaseEnvironment env : DatabaseEnvironment.values())
    {
        createDatabase(env);
    }
}
</code>```

and this is how my hibernate.cfg.xml looks like:

```<code><?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
    <session-factory>

        <property name="dialect">org.hibernate.dialect.H2Dialect</property>

        <property name="show_sql">true</property>

        <property name="hbm2ddl.auto">create-drop</property>

    </session-factory>
</hibernate-configuration>
</code>```

Title: Initialize multiple databases in Spring

Body:
I'm using AbstractRoutingDatasource to route between databases in runtime. In real condition on the informix database everything works just fine.

For tests I created a spring profile to use in memory H2 databases.
After running the spring app whith the test profile I checked the local databases using the h2 console. No schema was created.

I tried using schema.sql in recources and hibernates:

generate-ddl: true
hibernate:
  ddl-auto: create-drop

hibernate throws

java.lang.IllegalStateException: Cannot determine target DataSource for lookup key [null]

As I understand hibernate ist trying to generate only the "routed" datasource. Since no DatabaseContextHolder is set (null) this fails.

So both ways fail.

Is there a way to initialize all databases with (the same) schema?

I list my configuration below.

bootstrap.yml:

spring:
  profiles: acceptanceTest
  config:
    name: standalone
  cloud:
    config:
      enabled: false
      discovery:
        enabled: false
  jpa:
    database-platform: org.hibernate.dialect.H2Dialect
    generate-ddl: true
    hibernate:
      ddl-auto: create-drop
    properties:
      hibernate:
        show_sql: false
        use_sql_comments: false
        format_sql: false
  h2:
    console:
      enabled: true
      path: /h2
datasource:
  mc:
    driver-class-name: 'org.h2.Driver'
    url: 'jdbc:h2:mem:test-mc-db;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE'
    username: sa
    password: ''
    platform: h2
    initialize: true
    type: com.zaxxer.hikari.HikariDataSource
    hikari:
      maximum-pool-size: 10
      minimum-idle: 0
      idle-timeout: 60000
      pool-name: MarkHikariPool
  cw:
    driver-class-name: 'org.h2.Driver'
    url: 'jdbc:h2:mem:test-cw-db'
    username: sa
    password: ''
    type: com.zaxxer.hikari.HikariDataSource
    hikari:
      maximum-pool-size: 10
      minimum-idle: 0
      idle-timeout: 60000
      pool-name: MarkHikariPool

MainApp.java:

@ComponentScan({ "de.md.mark" })
@EnableDiscoveryClient
@SpringBootApplication(
    exclude =
        {
            DataSourceAutoConfiguration.class,
            DataSourceTransactionManagerAutoConfiguration.class,
            HibernateJpaAutoConfiguration.class
        }
)
public class MainApp
{
    public static void main(String[] args)
    {

DataSourceConfiguration.java:

@Configuration
@EnableJpaRepositories(
    basePackageClasses = { MarkTypeRepository.class, MarkRepository.class }, entityManagerFactoryRef = "markEntityManager",
    transactionManagerRef = "markTransactionManager"
)
@EnableTransactionManagement
public class DataSourceConfiguration
{
    @Autowired(required = false)
    private PersistenceUnitManager persistenceUnitManager;

    @Bean
    @ConfigurationProperties("app.jpa")
    @Primary
    public JpaProperties jpaProperties()
    {
        return new JpaProperties();
    }

    @Bean
    @ConfigurationProperties(prefix = "datasource.mc")
    public DataSource mcDataSource()
    {
        return DataSourceBuilder.create().build();
    }

    @Bean
    @ConfigurationProperties(prefix = "datasource.cw")
    public DataSource cwDataSource()
    {
        return DataSourceBuilder.create().build();
    }

    @Bean
    @Primary
    public DataSource dataSource()
    {
        DataSourceRouter router = new DataSourceRouter();

        final HashMap<Object, Object> map = new HashMap<>(DatabaseEnvironment.values().length);
        map.put(DatabaseEnvironment.MC, mcDataSource());
        map.put(DatabaseEnvironment.CW, cwDataSource());
        router.setTargetDataSources(map);
        return router;
    }

    @Bean
    @Primary
    public LocalContainerEntityManagerFactoryBean markEntityManager(final JpaProperties jpaProperties)
    {
        EntityManagerFactoryBuilder builder = createEntityManagerFactoryBuilder(jpaProperties);

        return builder.dataSource(dataSource()).packages(MarkTypeEntity.class).persistenceUnit("markEntityManager").build();
    }

    @Bean
    @Primary
    public JpaTransactionManager markTransactionManager(@Qualifier("markEntityManager") final EntityManagerFactory factory)
    {
        return new JpaTransactionManager(factory);
    }

    private EntityManagerFactoryBuilder createEntityManagerFactoryBuilder(JpaProperties jpaProperties)
    {
        JpaVendorAdapter jpaVendorAdapter = createJpaVendorAdapter(jpaProperties);
        return new EntityManagerFactoryBuilder(jpaVendorAdapter, jpaProperties.getProperties(), this.persistenceUnitManager);
    }

    private JpaVendorAdapter createJpaVendorAdapter(JpaProperties jpaProperties)
    {
        AbstractJpaVendorAdapter adapter = new HibernateJpaVendorAdapter();
        adapter.setShowSql(jpaProperties.isShowSql());
        adapter.setDatabase(jpaProperties.getDatabase());
        adapter.setDatabasePlatform(jpaProperties.getDatabasePlatform());
        adapter.setGenerateDdl(jpaProperties.isGenerateDdl());
        return adapter;
    }
}

Body:
After a lot research in the last two days I found a solution to initialize all datasources.
I created a method to create and initialize the local H2 databases using the SchemaExport.class of hibernate.
Since I only need the local db's for testing, I call the method for each DatabaseEnvirement in a @Before cucumber method.

public void createDatabase(DatabaseEnvironment environment)
throws Exception
{
    // load hibernate configuration from hibernate.cfg.xml in classpath
    Configuration configuration = new Configuration().configure();
    MetadataSources metadata =
    new MetadataSources(new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build());

    ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(true);
    scanner.addIncludeFilter(new AnnotationTypeFilter(Entity.class));

    for (BeanDefinition def : scanner.findCandidateComponents(MarkEntity.class.getPackage().getName()))
    {
        metadata.addAnnotatedClass(Class.forName(def.getBeanClassName()));
    }

    Connection connection = DriverManager.getConnection("jdbc:h2:mem:test-" + environment.name().toLowerCase(), "sa", "");

    SchemaExport export = new SchemaExport((MetadataImplementor) metadata.buildMetadata(), connection);
    export.create(true, true);
}

@Before
public void beforeTest()
    throws Exception
{
    // initialise databases
    for (DatabaseEnvironment env : DatabaseEnvironment.values())
    {
        createDatabase(env);
    }
}

and this is how my hibernate.cfg.xml looks like:

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
    <session-factory>

        <property name="dialect">org.hibernate.dialect.H2Dialect</property>

        <property name="show_sql">true</property>

        <property name="hbm2ddl.auto">create-drop</property>

    </session-factory>
</hibernate-configuration>


问:
How to convert epoch seconds to normal time in perl?
I have a string of epoch seconds "1510652305" which when i convert to normal time on unix command line using

```<code>`date -d @1510652305`
</code>```

i get
Tue Nov 14 15:08:25 IST 2017

But when i tried it in perl using something like this

```<code>use POSIX qw(strftime);
use Time::Local;
use Time::localtime;

$kickoff_time=1510652305;
$kickoff_time=ctime($kickoff_time);
</code>```

i get

Thu Jan  1 05:30:00 1970

How can i achieve the result i am getting in linux in perl?

Thanks!!

答:
I would recommend using Time::Piece for this job - it's core in perl.

```<code>#!/usr/bin/env perl

use strict;
use warnings;
use Time::Piece;

my $t = localtime ( 1510652305 );

print $t;
</code>```

It'll print default format, or you can use formatted using strftime.

Body:
I have a string of epoch seconds "1510652305" which when i convert to normal time on unix command line using

`date -d @1510652305`

i get
Tue Nov 14 15:08:25 IST 2017

But when i tried it in perl using something like this

use POSIX qw(strftime);
use Time::Local;
use Time::localtime;

$kickoff_time=1510652305;
$kickoff_time=ctime($kickoff_time);

i get

Thu Jan  1 05:30:00 1970

How can i achieve the result i am getting in linux in perl?

Thanks!!

Body:
I would recommend using Time::Piece for this job - it's core in perl.

#!/usr/bin/env perl

use strict;
use warnings;
use Time::Piece;

my $t = localtime ( 1510652305 );

print $t;

It'll print default format, or you can use formatted using strftime.


问:
List of References in Google App Engine for Python
In Google App Engine, there is such a thing as a ListProperty that allows you to hold a list (array) of items. You may also specify the type of the item being held, for instance string, integer, or whatever.

Google App Engine also allows you to have a ReferenceProperty. A ReferenceProperty "contains" a reference to another Google App Engine Model entity. If you access a ReferenceProperty, it will automatically retrieve the actual entity that the reference points to. This is convenient, as it beats getting the key, and then getting the entity for said key.

However, I do not see any such thing as a ListReferenceProperty (or ReferenceListProperty). I would like to hold a list of references to other entities, that would automatically be resolved when I attempt to access elements within the list. The closest I can get it seems is to hold a list of db.Key objects. I can use these keys to then manually retrieve their associated entities from the server.

Is there any good solution to this? Basically, I would like the ability to have a collection of (auto-dereferencing) references to other entities. I can almost get there by having a collection of keys to other entities, but I would like it to "know" that these are key items, and that it could dereference them as a service to me.

Thank you

答:
Step one:

Use db.ListProperty(db.Key) to create the relationship.  You want the ListProp to be on the Entity that will have the fewer references in the Many to Many relationship.  This will also give you a back reference.  So:

```<code>class Spam
  prop1 = db.String
  eggs = db.List

class Eggs
  prop1 = db.string
  @property
  def spams(self):
    return Spam.all().filter('eggs', self.key())
</code>```

This provides a References both ways.

Step two:

Create a utlility method that derefrences properties.

```<code>def prefetch_refprops(entities, *props):
    """Dereference Reference Properties to reduce Gets.  See:
    http://blog.notdot.net/2010/01/ReferenceProperty-prefetching-in-App-Engine
    """
    fields = [(entity, prop) for entity in entities for prop in props]
    ref_keys = [prop.get_value_for_datastore(x) for x, prop in fields]
    ref_entities = dict((x.key(), x) for x in db.get(set(ref_keys)))
    for (entity, prop), ref_key in zip(fields, ref_keys):
        prop.__set__(entity, ref_entities[ref_key])
    return entities
</code>```

Usage would be:

```<code>derefrenced_spams = prefetch_refprops(Spams, models.Spam.eggs)
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Step one:

Use db.ListProperty(db.Key) to create the relationship.  You want the ListProp to be on the Entity that will have the fewer references in the Many to Many relationship.  This will also give you a back reference.  So:

class Spam
  prop1 = db.String
  eggs = db.List

class Eggs
  prop1 = db.string
  @property
  def spams(self):
    return Spam.all().filter('eggs', self.key())

This provides a References both ways.

Step two:

Create a utlility method that derefrences properties.

def prefetch_refprops(entities, *props):
    """Dereference Reference Properties to reduce Gets.  See:
    http://blog.notdot.net/2010/01/ReferenceProperty-prefetching-in-App-Engine
    """
    fields = [(entity, prop) for entity in entities for prop in props]
    ref_keys = [prop.get_value_for_datastore(x) for x, prop in fields]
    ref_entities = dict((x.key(), x) for x in db.get(set(ref_keys)))
    for (entity, prop), ref_key in zip(fields, ref_keys):
        prop.__set__(entity, ref_entities[ref_key])
    return entities

Usage would be:

derefrenced_spams = prefetch_refprops(Spams, models.Spam.eggs)


问:
FCM + Swift 3 - Notifications not appearing
I know you've stumbled across this question before; several times in fact. But I have followed EVERY suggestion provided to me here, here, and even here.

(Written in Swift 3, running on Xcode 8.1)

Yes, my PUSH NOTIFICATIONS in Capabilities are on. And even my Background Modes Remote Capabilities is on - I've tried toggling the FirebaseAppDelegateProxy On and Off, checked the certificates (why, yes, it is pointing to the correct App bundle), moved the

```<code>application.registerForRemoteNotifications()
</code>```

Cried, consumed copious amounts of sugar, prayed to God and then what ever other related deities I could think of, and still - naught.

It could just be a screaming need for a second set of eyes, but any ideas?

```<code>import UIKit
import UserNotifications

import Firebase
import FirebaseMessaging

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?
    let gcmMessageIDKey = "gcm.message_id"

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        FIRApp.configure()
        // Override point for customization after application launch.

        // Override point for customization after application launch.
        // [START register_for_notifications]
        if #available(iOS 10.0, *) {
            let authOptions : UNAuthorizationOptions = [.alert, .badge, .sound]
            UNUserNotificationCenter.current().requestAuthorization(
                options: authOptions,
                completionHandler: {_,_ in })

            // For iOS 10 display notification (sent via APNS)
            UNUserNotificationCenter.current().delegate = self
            // For iOS 10 data message (sent via FCM)
            FIRMessaging.messaging().remoteMessageDelegate = self

        } else {
            let settings: UIUserNotificationSettings =
                UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
            application.registerUserNotificationSettings(settings)
        }

        application.registerForRemoteNotifications()

        // Add observer for InstanceID token refresh callback.
        NotificationCenter.default.addObserver(self,
                                                         selector: #selector(self.tokenRefreshNotification),
                                                         name: NSNotification.Name.firInstanceIDTokenRefresh,
                                                         object: nil)

        return true
    }

    func tokenRefreshNotification(_ notification: Notification) {
        if let refreshedToken = FIRInstanceID.instanceID().token() {
            print("InstanceID token: \(refreshedToken)")
        }

        // Connect to FCM since connection may have failed when attempted before having a token.
        connectToFcm()
    }

    // [START connect_to_fcm]
    func connectToFcm() {
        FIRMessaging.messaging().connect { (error) in
            if error != nil {
                print("Unable to connect with FCM. \(error)")
            } else {
                print("Connected to FCM.")
            }
        }
    }
    // [END connect_to_fcm]

    func applicationWillResignActive(_ application: UIApplication) {
        // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
        // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
    }

    func applicationDidEnterBackground(_ application: UIApplication) {
        // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
        // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    }

    func applicationWillEnterForeground(_ application: UIApplication) {
        // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
    }

    func applicationDidBecomeActive(_ application: UIApplication) {
        // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    }

    func applicationWillTerminate(_ application: UIApplication) {
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    }

    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
        // If you are receiving a notification message while your app is in the background,
        // this callback will not be fired till the user taps on the notification launching the application.
        // TODO: Handle data of notification

        // Print message ID.
        if let messageID = userInfo[gcmMessageIDKey] {
            print("Message ID: \(messageID)")
        }

        // Print full message.
        print(userInfo)
    }

    private func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
//        let tokenChars = deviceToken.bytes
        var tokenString = ""

        for i in 0..<deviceToken.length {
            tokenString += String(format: "%02.2hhx", arguments: [[deviceToken.bytes as! CVarArg][i]])
        }

        FIRInstanceID.instanceID().setAPNSToken(deviceToken as Data, type: FIRInstanceIDAPNSTokenType.unknown)

        print("tokenString: \(tokenString)")
    }
}
</code>```

And here are the extensions...

```<code>import Foundation
import UserNotifications
import FirebaseMessaging

@available(iOS 10, *)
extension AppDelegate : UNUserNotificationCenterDelegate {

    // Receive displayed notifications for iOS 10 devices.

    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        let userInfo = notification.request.content.userInfo
        // Print message ID.
        print("Message ID: \(userInfo["gcm.message_id"]!)")

        // Print full message.
        print("%@", userInfo)

    }

}

extension AppDelegate : FIRMessagingDelegate {
    // Receive data message on iOS 10 devices.
    func applicationReceivedRemoteMessage(_ remoteMessage: FIRMessagingRemoteMessage) {
        print("%@", remoteMessage.appData)
    }
}
</code>```

Tokens are logging into the console, FCM is connected, Cloud Messaging is holding my certificates... the only possible hint I MAY have is that Firebase Console doesn't count the one device it is sending a message to as being 'Sent'.

But the console looks fine.

```<code>2016-12-15 00:07:05.344 voltuser[4199:2008900] WARNING: Firebase Analytics App Delegate Proxy is disabled. To log deep link campaigns manually, call the methods in FIRAnalytics+AppDelegate.h.
2016-12-15 00:07:05.349 voltuser[4199:2008900] Firebase automatic screen reporting is enabled. Call +[FIRAnalytics setScreenName:setScreenClass:] to set the screen name or override the default screen class name. To disable automatic screen reporting, set the flag FirebaseAutomaticScreenReportingEnabled to NO in the Info.plist
2016-12-15 00:07:05.447 voltuser[4199] <Debug> [Firebase/Core][I-COR000001] Configuring the default app.
2016-12-15 00:07:05.514: <FIRInstanceID/WARNING> Failed to fetch APNS token Error Domain=com.firebase.iid Code=1001 "(null)"
2016-12-15 00:07:05.520: <FIRMessaging/INFO> FIRMessaging library version 1.2.0
2016-12-15 00:07:05.549 voltuser[4199:] <FIRAnalytics/INFO> Firebase Analytics v.3600000 started
2016-12-15 00:07:05.549 voltuser[4199:] <FIRAnalytics/INFO> To enable debug logging set the following application argument: -FIRAnalyticsDebugEnabled (see this)
2016-12-15 00:07:05.605 voltuser[4199] <Debug> [Firebase/Core][I-COR000018] Already sending logs.
2016-12-15 00:07:05.679 voltuser[4199] <Debug> [Firebase/Core][I-COR000019] Clearcut post completed.
2016-12-15 00:07:05.782 voltuser[4199] <Debug> [Firebase/Core][I-COR000019] Clearcut post completed.
2016-12-15 00:07:05.824 voltuser[4199:] <FIRAnalytics/WARNING> The AdSupport Framework is not currently linked. Some features will not function properly. Learn more at here
2016-12-15 00:07:07.286 voltuser[4199:] <FIRAnalytics/INFO> Firebase Analytics enabled
InstanceID token: c_4iSvTQcHw:APA91bGjKnPoH9LysKl9CQxCJRJsfqwXBSUFAmgRp-KEWKjWqe2j4nt6Y5gx8us41rB6eLnRCOwRntnbr_N1fh_swz8j-GvvChSsV3gvG8dufVFLpagdtOxrxPSgLubQrfw-JqkA-4wV
Connected to FCM.
And the snapshot says Snap (mx7zr3y6XpSGZ4uB4PhZ8QRHIvt2) <null>
[AnyHashable("notification"): {
    body = "THIS IS SO PAINFUL";
    e = 1;
    title = "WHY WONT YOU WORK";
}, AnyHashable("from"): 99570566728, AnyHashable("collapse_key"): com.mishastone.voltuser]
</code>```

... but the message is logging just fine in my console. In fact, there are not outcrying errors at all!

sigh

My phone is not getting foreground, background or any sort of notification from the app - there's nothing. Zip. Zilch. Nada. Just the breaking sounds of my heart.

My iPhone is currently on 9.3.5. If that helps any.

Any help would be greatly appreciated - or suggestions for alternative push notification systems...

答: If you are sure about your code is perfect and still you are unable to receive FCM notifications then please update p12 certificate from Firebase console. You have to export only security key from Push certifcate and upload it . You will start receiving notifications.</p>

Body:
I know you've stumbled across this question before; several times in fact. But I have followed EVERY suggestion provided to me here, here, and even here.

(Written in Swift 3, running on Xcode 8.1)

Yes, my PUSH NOTIFICATIONS in Capabilities are on. And even my Background Modes Remote Capabilities is on - I've tried toggling the FirebaseAppDelegateProxy On and Off, checked the certificates (why, yes, it is pointing to the correct App bundle), moved the

application.registerForRemoteNotifications()

Cried, consumed copious amounts of sugar, prayed to God and then what ever other related deities I could think of, and still - naught.

It could just be a screaming need for a second set of eyes, but any ideas?

import UIKit
import UserNotifications

import Firebase
import FirebaseMessaging

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?
    let gcmMessageIDKey = "gcm.message_id"

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        FIRApp.configure()
        // Override point for customization after application launch.

        // Override point for customization after application launch.
        // [START register_for_notifications]
        if #available(iOS 10.0, *) {
            let authOptions : UNAuthorizationOptions = [.alert, .badge, .sound]
            UNUserNotificationCenter.current().requestAuthorization(
                options: authOptions,
                completionHandler: {_,_ in })

            // For iOS 10 display notification (sent via APNS)
            UNUserNotificationCenter.current().delegate = self
            // For iOS 10 data message (sent via FCM)
            FIRMessaging.messaging().remoteMessageDelegate = self

        } else {
            let settings: UIUserNotificationSettings =
                UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
            application.registerUserNotificationSettings(settings)
        }

        application.registerForRemoteNotifications()

        // Add observer for InstanceID token refresh callback.
        NotificationCenter.default.addObserver(self,
                                                         selector: #selector(self.tokenRefreshNotification),
                                                         name: NSNotification.Name.firInstanceIDTokenRefresh,
                                                         object: nil)

        return true
    }

    func tokenRefreshNotification(_ notification: Notification) {
        if let refreshedToken = FIRInstanceID.instanceID().token() {
            print("InstanceID token: \(refreshedToken)")
        }

        // Connect to FCM since connection may have failed when attempted before having a token.
        connectToFcm()
    }

    // [START connect_to_fcm]
    func connectToFcm() {
        FIRMessaging.messaging().connect { (error) in
            if error != nil {
                print("Unable to connect with FCM. \(error)")
            } else {
                print("Connected to FCM.")
            }
        }
    }
    // [END connect_to_fcm]

    func applicationWillResignActive(_ application: UIApplication) {
        // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
        // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
    }

    func applicationDidEnterBackground(_ application: UIApplication) {
        // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
        // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    }

    func applicationWillEnterForeground(_ application: UIApplication) {
        // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
    }

    func applicationDidBecomeActive(_ application: UIApplication) {
        // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    }

    func applicationWillTerminate(_ application: UIApplication) {
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    }

    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
        // If you are receiving a notification message while your app is in the background,
        // this callback will not be fired till the user taps on the notification launching the application.
        // TODO: Handle data of notification

        // Print message ID.
        if let messageID = userInfo[gcmMessageIDKey] {
            print("Message ID: \(messageID)")
        }

        // Print full message.
        print(userInfo)
    }

    private func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
//        let tokenChars = deviceToken.bytes
        var tokenString = ""

        for i in 0..<deviceToken.length {
            tokenString += String(format: "%02.2hhx", arguments: [[deviceToken.bytes as! CVarArg][i]])
        }

        FIRInstanceID.instanceID().setAPNSToken(deviceToken as Data, type: FIRInstanceIDAPNSTokenType.unknown)

        print("tokenString: \(tokenString)")
    }
}

And here are the extensions...

import Foundation
import UserNotifications
import FirebaseMessaging

@available(iOS 10, *)
extension AppDelegate : UNUserNotificationCenterDelegate {

    // Receive displayed notifications for iOS 10 devices.

    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        let userInfo = notification.request.content.userInfo
        // Print message ID.
        print("Message ID: \(userInfo["gcm.message_id"]!)")

        // Print full message.
        print("%@", userInfo)

    }

}

extension AppDelegate : FIRMessagingDelegate {
    // Receive data message on iOS 10 devices.
    func applicationReceivedRemoteMessage(_ remoteMessage: FIRMessagingRemoteMessage) {
        print("%@", remoteMessage.appData)
    }
}

Tokens are logging into the console, FCM is connected, Cloud Messaging is holding my certificates... the only possible hint I MAY have is that Firebase Console doesn't count the one device it is sending a message to as being 'Sent'.

But the console looks fine.

2016-12-15 00:07:05.344 voltuser[4199:2008900] WARNING: Firebase Analytics App Delegate Proxy is disabled. To log deep link campaigns manually, call the methods in FIRAnalytics+AppDelegate.h.
2016-12-15 00:07:05.349 voltuser[4199:2008900] Firebase automatic screen reporting is enabled. Call +[FIRAnalytics setScreenName:setScreenClass:] to set the screen name or override the default screen class name. To disable automatic screen reporting, set the flag FirebaseAutomaticScreenReportingEnabled to NO in the Info.plist
2016-12-15 00:07:05.447 voltuser[4199] <Debug> [Firebase/Core][I-COR000001] Configuring the default app.
2016-12-15 00:07:05.514: <FIRInstanceID/WARNING> Failed to fetch APNS token Error Domain=com.firebase.iid Code=1001 "(null)"
2016-12-15 00:07:05.520: <FIRMessaging/INFO> FIRMessaging library version 1.2.0
2016-12-15 00:07:05.549 voltuser[4199:] <FIRAnalytics/INFO> Firebase Analytics v.3600000 started
2016-12-15 00:07:05.549 voltuser[4199:] <FIRAnalytics/INFO> To enable debug logging set the following application argument: -FIRAnalyticsDebugEnabled (see this)
2016-12-15 00:07:05.605 voltuser[4199] <Debug> [Firebase/Core][I-COR000018] Already sending logs.
2016-12-15 00:07:05.679 voltuser[4199] <Debug> [Firebase/Core][I-COR000019] Clearcut post completed.
2016-12-15 00:07:05.782 voltuser[4199] <Debug> [Firebase/Core][I-COR000019] Clearcut post completed.
2016-12-15 00:07:05.824 voltuser[4199:] <FIRAnalytics/WARNING> The AdSupport Framework is not currently linked. Some features will not function properly. Learn more at here
2016-12-15 00:07:07.286 voltuser[4199:] <FIRAnalytics/INFO> Firebase Analytics enabled
InstanceID token: c_4iSvTQcHw:APA91bGjKnPoH9LysKl9CQxCJRJsfqwXBSUFAmgRp-KEWKjWqe2j4nt6Y5gx8us41rB6eLnRCOwRntnbr_N1fh_swz8j-GvvChSsV3gvG8dufVFLpagdtOxrxPSgLubQrfw-JqkA-4wV
Connected to FCM.
And the snapshot says Snap (mx7zr3y6XpSGZ4uB4PhZ8QRHIvt2) <null>
[AnyHashable("notification"): {
    body = "THIS IS SO PAINFUL";
    e = 1;
    title = "WHY WONT YOU WORK";
}, AnyHashable("from"): 99570566728, AnyHashable("collapse_key"): com.mishastone.voltuser]

... but the message is logging just fine in my console. In fact, there are not outcrying errors at all!

sigh

My phone is not getting foreground, background or any sort of notification from the app - there's nothing. Zip. Zilch. Nada. Just the breaking sounds of my heart.

My iPhone is currently on 9.3.5. If that helps any.

Any help would be greatly appreciated - or suggestions for alternative push notification systems...


问:
Install Dependencies again for new React Project
I was working on a React Project and I successfully completed it. Now I started working on another project. Do I need to install these dependencies again or how can I inject dependencies and start work on my new React Project? </p>

<p>Let me know if you need more explanation. </p>

答:
The dependencies might vary across your various projects. npm packages installed with global flag reside on the system. You will need to install the required dependencies for your new project.

Alernatively, if you are going to use the same dependencies again, just copy the contents of package.json from old project to package.json of new project and run

```npm install```

or

```yarn```

I hope this will help.

Body:
I was working on a React Project and I successfully completed it. Now I started working on another project. Do I need to install these dependencies again or how can I inject dependencies and start work on my new React Project?

Let me know if you need more explanation.

Body:
The dependencies might vary across your various projects. npm packages installed with global flag reside on the system. You will need to install the required dependencies for your new project.

Alernatively, if you are going to use the same dependencies again, just copy the contents of package.json from old project to package.json of new project and run

npm install

or

yarn

I hope this will help.


问:
MuleSoft: How to refer to file nested under resource folder
I am doing a Mulesoft project by Mule-Anypoint studio.

Recently I categorized my resource files (xml, csv, xsl..) into nested folders under "resources" folder. (ex: resources/FlowResources/flowA/resource-a.csv) and updated the components to corresponding path. Everything works fine but when deploying to CloudHub throws following error:

Your application has failed with exception com.mulesoft.mmc.agent.v3.dto.DeploymentException: Unable to load FlowResources/flowA/resource-a.csv. It works fine again if I move the files up front to resources folder.

Is it some kind of limitation when we deploy to CloudHub? Cannot locate file in nested resource folders?

答:
Try this.

Basically, you need to update your .classpath file.

inside .classpath

resource entry exists -  < classpathentry kind="src" path="src/main/resources"/" >

need toupdate or add new entry of it it  as path="src/main/resource/myfolder".


问:
How to create a column on a SQL table, based on values of another table
I currently have 2 SQL tables:  table1 and table2. table1 has 2 columns called id_a and column_a. table2 has 2 columns called id_b and column_b.

I would like to create a new_column in table1. The value of new_column should be 1 if the value of table1.id_a exists in table2.id_b. Otherwise, new_column should have the value of 0.

How do I do this? I'm using SQLite3 and table1 is significantly larger than table2.

答:
How about a simple IN?

```<code>SELECT *,
       id_a IN (SELECT id_b FROM table2) AS flag
FROM table1;
</code>```

Body:
How about a simple IN?

SELECT *,
       id_a IN (SELECT id_b FROM table2) AS flag
FROM table1;


问:
Jupyter 5, Python 3.6, and Latex
I am wanting to use a Jupyter notebook to document my research results. Previously, I had used a notebook with Python 2.7 and Jupyter 4 without any problems. I have recently been trying to use Jupyter 5 and Python 3.6 courtesy of Anaconda. However, when I attempt to display a heatmap, I receive an error.

Edited with simple line graph
     # -- coding: utf-8 --
    %matplotlib inline

```<code>from future.builtins import *
from future.utils import (viewitems, viewkeys, viewvalues)

import sys
from os import (environ, path)
from collections import OrderedDict

# Numpy and related libraries
import numpy as np
import scipy
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from scipy import (linalg, stats)
from matplotlib import (cm, colors, ticker)
from mpl_toolkits import axes_grid1

from IPython.display import (display, )

# Display full list of DataFrame
pd.set_option("display.max_rows", None)
pd.set_option("display.max_columns", None)
pd.set_option("display.notebook_repr_html",True)

# Update parameters for matplotlib
params = {"text.usetex": True,
          "text.latex.unicode": True,
          "axes.unicode_minus": True,
         }
plt.rcParams.update(params)
pd.set_option("precision", 2)

# This sets reasonable defaults for font size for
# a figure that will go in a paper
sns.set_context("paper")

# Set the font to be serif, rather than sans
sns.set(font='serif')

# Make the background white, and specify the
# specific font family
sns.set_style("white",
              {
                  "font.family": "serif",
                  "font.serif": ["Times New Roman", "Palatino", "serif"],
                  "font.sans-serif": ["Arial", "Helvetica"],
                  "font.monospace": ["Courier New", "Courier"]
              })
sns.set_style("ticks")
models = ("calpha", "caside", "ncsc", "polar")

# Simple test case
data = np.random.random(10)
data = pd.Series(data=data, dtype=np.float)

fig, ax = plt.subplots()
data.plot(ax=ax, title="Linear randomness", kind="line", use_index=True)
ax.set_xlabel(r"Time (${\mu}$s)")
ax.set_ylabel("r.m.s.d. (Å)")
ax.xaxis.set_major_locator(ticker.MultipleLocator(0.1))
ax.xaxis.set_major_formatter(ticker.StrMethodFormatter("{x:.0f}"))
ax.yaxis.set_major_formatter(ticker.StrMethodFormatter("{x:.1f}"))
ax.grid()
fig.tight_layout()
</code>```

But, I receive the following error:

```<code>---------------------------------------------------------------------------
FileNotFoundError                         Traceback (most recent call last)
<ipython-input-5-727fbc0d285c> in <module>()
     10 ax.yaxis.set_major_formatter(ticker.StrMethodFormatter("{x:.1f}"))
     11 ax.grid()
---> 12 fig.tight_layout()

/opt/homebrew/anaconda3/envs/mda-dev/lib/python3.6/site-packages/matplotlib/figure.py in tight_layout(self, renderer, pad, h_pad, w_pad, rect)
   2005         kwargs = get_tight_layout_figure(
   2006             self, self.axes, subplotspec_list, renderer,
-> 2007             pad=pad, h_pad=h_pad, w_pad=w_pad, rect=rect)
   2008         self.subplots_adjust(**kwargs)
   2009

/opt/homebrew/anaconda3/envs/mda-dev/lib/python3.6/site-packages/matplotlib/tight_layout.py in get_tight_layout_figure(fig, axes_list, subplotspec_list, renderer, pad, h_pad, w_pad, rect)
    349                                      subplot_list=subplot_list,
    350                                      ax_bbox_list=ax_bbox_list,
--> 351                                      pad=pad, h_pad=h_pad, w_pad=w_pad)
    352
    353     if rect is not None:

/opt/homebrew/anaconda3/envs/mda-dev/lib/python3.6/site-packages/matplotlib/tight_layout.py in auto_adjust_subplotpars(fig, renderer, nrows_ncols, num1num2_list, subplot_list, ax_bbox_list, pad, h_pad, w_pad, rect)
    127             continue
    128
--> 129         tight_bbox_raw = union([ax.get_tightbbox(renderer) for ax in subplots
    130                                 if ax.get_visible()])
    131         tight_bbox = TransformedBbox(tight_bbox_raw,

/opt/homebrew/anaconda3/envs/mda-dev/lib/python3.6/site-packages/matplotlib/tight_layout.py in <listcomp>(.0)
    128
    129         tight_bbox_raw = union([ax.get_tightbbox(renderer) for ax in subplots
--> 130                                 if ax.get_visible()])
    131         tight_bbox = TransformedBbox(tight_bbox_raw,
    132                                      fig.transFigure.inverted())

/opt/homebrew/anaconda3/envs/mda-dev/lib/python3.6/site-packages/matplotlib/axes/_base.py in get_tightbbox(self, renderer, call_axes_locator)
   3952
   3953         if self.title.get_visible():
-> 3954             bb.append(self.title.get_window_extent(renderer))
   3955         if self._left_title.get_visible():
   3956             bb.append(self._left_title.get_window_extent(renderer))

/opt/homebrew/anaconda3/envs/mda-dev/lib/python3.6/site-packages/matplotlib/text.py in get_window_extent(self, renderer, dpi)
    968             raise RuntimeError('Cannot get window extent w/o renderer')
    969
--> 970         bbox, info, descent = self._get_layout(self._renderer)
    971         x, y = self.get_unitless_position()
    972         x, y = self.get_transform().transform_point((x, y))

/opt/homebrew/anaconda3/envs/mda-dev/lib/python3.6/site-packages/matplotlib/text.py in _get_layout(self, renderer)
    352         tmp, lp_h, lp_bl = renderer.get_text_width_height_descent('lp',
    353                                                          self._fontproperties,
--> 354                                                          ismath=False)
    355         offsety = (lp_h - lp_bl) * self._linespacing
    356

/opt/homebrew/anaconda3/envs/mda-dev/lib/python3.6/site-packages/matplotlib/backends/backend_agg.py in get_text_width_height_descent(self, s, prop, ismath)
    224             fontsize = prop.get_size_in_points()
    225             w, h, d = texmanager.get_text_width_height_descent(
--> 226                 s, fontsize, renderer=self)
    227             return w, h, d
    228

/opt/homebrew/anaconda3/envs/mda-dev/lib/python3.6/site-packages/matplotlib/texmanager.py in get_text_width_height_descent(self, tex, fontsize, renderer)
    602             dvifile = self.make_dvi(tex, fontsize)
    603             with dviread.Dvi(dvifile, 72 * dpi_fraction) as dvi:
--> 604                 page = next(iter(dvi))
    605             # A total height (including the descent) needs to be returned.
    606             return page.width, page.height + page.descent, page.descent

/opt/homebrew/anaconda3/envs/mda-dev/lib/python3.6/site-packages/matplotlib/dviread.py in __iter__(self)
    247         """
    248         while True:
--> 249             have_page = self._read()
    250             if have_page:
    251                 yield self._output()

/opt/homebrew/anaconda3/envs/mda-dev/lib/python3.6/site-packages/matplotlib/dviread.py in _read(self)
    308         while True:
    309             byte = ord(self.file.read(1)[0])
--> 310             self._dtable[byte](self, byte)
    311             if byte == 140:                         # end of page
    312                 return True

/opt/homebrew/anaconda3/envs/mda-dev/lib/python3.6/site-packages/matplotlib/dviread.py in wrapper(self, byte)
    164             if state is not None and self.state != state:
    165                 raise ValueError("state precondition failed")
--> 166             return method(self, *[f(self, byte-min) for f in get_args])
    167         if max is None:
    168             table[min] = wrapper

/opt/homebrew/anaconda3/envs/mda-dev/lib/python3.6/site-packages/matplotlib/dviread.py in _fnt_def(self, k, c, s, d, a, l)
    455     @dispatch(min=243, max=246, args=('olen1', 'u4', 'u4', 'u4', 'u1', 'u1'))
    456     def _fnt_def(self, k, c, s, d, a, l):
--> 457         self._fnt_def_real(k, c, s, d, a, l)
    458
    459     def _fnt_def_real(self, k, c, s, d, a, l):

/opt/homebrew/anaconda3/envs/mda-dev/lib/python3.6/site-packages/matplotlib/dviread.py in _fnt_def_real(self, k, c, s, d, a, l)
    460         n = self.file.read(a + l)
    461         fontname = n[-l:].decode('ascii')
--> 462         tfm = _tfmfile(fontname)
    463         if tfm is None:
    464             if six.PY2:

/opt/homebrew/anaconda3/envs/mda-dev/lib/python3.6/site-packages/matplotlib/dviread.py in _tfmfile(texname)
   1074
   1075 def _tfmfile(texname):
-> 1076     return _fontfile(texname, Tfm, '.tfm', _tfmcache)
   1077
   1078

/opt/homebrew/anaconda3/envs/mda-dev/lib/python3.6/site-packages/matplotlib/dviread.py in _fontfile(texname, class_, suffix, cache)
   1063         pass
   1064
-> 1065     filename = find_tex_file(texname + suffix)
   1066     if filename:
   1067         result = class_(filename)

/opt/homebrew/anaconda3/envs/mda-dev/lib/python3.6/site-packages/matplotlib/dviread.py in find_tex_file(filename, format)
   1043     # https://github.com/matplotlib/matplotlib/issues/633
   1044     pipe = subprocess.Popen(cmd, stdout=subprocess.PIPE,
-> 1045                             stderr=subprocess.PIPE)
   1046     result = pipe.communicate()[0].rstrip()
   1047     matplotlib.verbose.report('find_tex_file result: %s' % result,

/opt/homebrew/anaconda3/envs/mda-dev/lib/python3.6/subprocess.py in __init__(self, args, bufsize, executable, stdin, stdout, stderr, preexec_fn, close_fds, shell, cwd, env, universal_newlines, startupinfo, creationflags, restore_signals, start_new_session, pass_fds, encoding, errors)
    707                                 c2pread, c2pwrite,
    708                                 errread, errwrite,
--> 709                                 restore_signals, start_new_session)
    710         except:
    711             # Cleanup if the child failed starting.

/opt/homebrew/anaconda3/envs/mda-dev/lib/python3.6/subprocess.py in _execute_child(self, args, executable, preexec_fn, close_fds, pass_fds, cwd, env, startupinfo, creationflags, shell, p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite, restore_signals, start_new_session)
   1342                         if errno_num == errno.ENOENT:
   1343                             err_msg += ': ' + repr(err_filename)
-> 1344                     raise child_exception_type(errno_num, err_msg, err_filename)
   1345                 raise child_exception_type(err_msg)
   1346

FileNotFoundError: [Errno 2] No such file or directory: 'kpsewhich': 'kpsewhich'
</code>```

I understand that Latex is displayed using mathjax, but anaconda (and pip, for that matter), doesn't have it available for Python 3.6. I even tried this using a different kernel for Python 2.7 with no success. As noted above, I had previously been successful using an older version of Jupyter in Python 2.7.

Any help will be appreciated.

答:
So, after much searching and tinkering, the problem is with the following lines:

```<code># Update parameters for matplotlib
params = {"text.usetex": True,
          "text.latex.unicode": True,
          "axes.unicode_minus": True,
         }
plt.rcParams.update(params)
</code>```

Apparently, the above parameters are no longer needed in the latest version of Jupyter. Upon deleting these lines, my figure displayed properly with the appropriate Latex designations.

Title: Jupyter 5, Python 3.6, and Latex

Body:
I am wanting to use a Jupyter notebook to document my research results. Previously, I had used a notebook with Python 2.7 and Jupyter 4 without any problems. I have recently been trying to use Jupyter 5 and Python 3.6 courtesy of Anaconda. However, when I attempt to display a heatmap, I receive an error.

Edited with simple line graph
     # -- coding: utf-8 --
    %matplotlib inline

from future.builtins import *
from future.utils import (viewitems, viewkeys, viewvalues)

import sys
from os import (environ, path)
from collections import OrderedDict

# Numpy and related libraries
import numpy as np
import scipy
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from scipy import (linalg, stats)
from matplotlib import (cm, colors, ticker)
from mpl_toolkits import axes_grid1

from IPython.display import (display, )

# Display full list of DataFrame
pd.set_option("display.max_rows", None)
pd.set_option("display.max_columns", None)
pd.set_option("display.notebook_repr_html",True)

# Update parameters for matplotlib
params = {"text.usetex": True,
          "text.latex.unicode": True,
          "axes.unicode_minus": True,
         }
plt.rcParams.update(params)
pd.set_option("precision", 2)

# This sets reasonable defaults for font size for
# a figure that will go in a paper
sns.set_context("paper")

# Set the font to be serif, rather than sans
sns.set(font='serif')

# Make the background white, and specify the
# specific font family
sns.set_style("white",
              {
                  "font.family": "serif",
                  "font.serif": ["Times New Roman", "Palatino", "serif"],
                  "font.sans-serif": ["Arial", "Helvetica"],
                  "font.monospace": ["Courier New", "Courier"]
              })
sns.set_style("ticks")
models = ("calpha", "caside", "ncsc", "polar")

# Simple test case
data = np.random.random(10)
data = pd.Series(data=data, dtype=np.float)

fig, ax = plt.subplots()
data.plot(ax=ax, title="Linear randomness", kind="line", use_index=True)
ax.set_xlabel(r"Time (${\mu}$s)")
ax.set_ylabel("r.m.s.d. (Å)")
ax.xaxis.set_major_locator(ticker.MultipleLocator(0.1))
ax.xaxis.set_major_formatter(ticker.StrMethodFormatter("{x:.0f}"))
ax.yaxis.set_major_formatter(ticker.StrMethodFormatter("{x:.1f}"))
ax.grid()
fig.tight_layout()

But, I receive the following error:

---------------------------------------------------------------------------
FileNotFoundError                         Traceback (most recent call last)
<ipython-input-5-727fbc0d285c> in <module>()
     10 ax.yaxis.set_major_formatter(ticker.StrMethodFormatter("{x:.1f}"))
     11 ax.grid()
---> 12 fig.tight_layout()

/opt/homebrew/anaconda3/envs/mda-dev/lib/python3.6/site-packages/matplotlib/figure.py in tight_layout(self, renderer, pad, h_pad, w_pad, rect)
   2005         kwargs = get_tight_layout_figure(
   2006             self, self.axes, subplotspec_list, renderer,
-> 2007             pad=pad, h_pad=h_pad, w_pad=w_pad, rect=rect)
   2008         self.subplots_adjust(**kwargs)
   2009

/opt/homebrew/anaconda3/envs/mda-dev/lib/python3.6/site-packages/matplotlib/tight_layout.py in get_tight_layout_figure(fig, axes_list, subplotspec_list, renderer, pad, h_pad, w_pad, rect)
    349                                      subplot_list=subplot_list,
    350                                      ax_bbox_list=ax_bbox_list,
--> 351                                      pad=pad, h_pad=h_pad, w_pad=w_pad)
    352
    353     if rect is not None:

/opt/homebrew/anaconda3/envs/mda-dev/lib/python3.6/site-packages/matplotlib/tight_layout.py in auto_adjust_subplotpars(fig, renderer, nrows_ncols, num1num2_list, subplot_list, ax_bbox_list, pad, h_pad, w_pad, rect)
    127             continue
    128
--> 129         tight_bbox_raw = union([ax.get_tightbbox(renderer) for ax in subplots
    130                                 if ax.get_visible()])
    131         tight_bbox = TransformedBbox(tight_bbox_raw,

/opt/homebrew/anaconda3/envs/mda-dev/lib/python3.6/site-packages/matplotlib/tight_layout.py in <listcomp>(.0)
    128
    129         tight_bbox_raw = union([ax.get_tightbbox(renderer) for ax in subplots
--> 130                                 if ax.get_visible()])
    131         tight_bbox = TransformedBbox(tight_bbox_raw,
    132                                      fig.transFigure.inverted())

/opt/homebrew/anaconda3/envs/mda-dev/lib/python3.6/site-packages/matplotlib/axes/_base.py in get_tightbbox(self, renderer, call_axes_locator)
   3952
   3953         if self.title.get_visible():
-> 3954             bb.append(self.title.get_window_extent(renderer))
   3955         if self._left_title.get_visible():
   3956             bb.append(self._left_title.get_window_extent(renderer))

/opt/homebrew/anaconda3/envs/mda-dev/lib/python3.6/site-packages/matplotlib/text.py in get_window_extent(self, renderer, dpi)
    968             raise RuntimeError('Cannot get window extent w/o renderer')
    969
--> 970         bbox, info, descent = self._get_layout(self._renderer)
    971         x, y = self.get_unitless_position()
    972         x, y = self.get_transform().transform_point((x, y))

/opt/homebrew/anaconda3/envs/mda-dev/lib/python3.6/site-packages/matplotlib/text.py in _get_layout(self, renderer)
    352         tmp, lp_h, lp_bl = renderer.get_text_width_height_descent('lp',
    353                                                          self._fontproperties,
--> 354                                                          ismath=False)
    355         offsety = (lp_h - lp_bl) * self._linespacing
    356

/opt/homebrew/anaconda3/envs/mda-dev/lib/python3.6/site-packages/matplotlib/backends/backend_agg.py in get_text_width_height_descent(self, s, prop, ismath)
    224             fontsize = prop.get_size_in_points()
    225             w, h, d = texmanager.get_text_width_height_descent(
--> 226                 s, fontsize, renderer=self)
    227             return w, h, d
    228

/opt/homebrew/anaconda3/envs/mda-dev/lib/python3.6/site-packages/matplotlib/texmanager.py in get_text_width_height_descent(self, tex, fontsize, renderer)
    602             dvifile = self.make_dvi(tex, fontsize)
    603             with dviread.Dvi(dvifile, 72 * dpi_fraction) as dvi:
--> 604                 page = next(iter(dvi))
    605             # A total height (including the descent) needs to be returned.
    606             return page.width, page.height + page.descent, page.descent

/opt/homebrew/anaconda3/envs/mda-dev/lib/python3.6/site-packages/matplotlib/dviread.py in __iter__(self)
    247         """
    248         while True:
--> 249             have_page = self._read()
    250             if have_page:
    251                 yield self._output()

/opt/homebrew/anaconda3/envs/mda-dev/lib/python3.6/site-packages/matplotlib/dviread.py in _read(self)
    308         while True:
    309             byte = ord(self.file.read(1)[0])
--> 310             self._dtable[byte](self, byte)
    311             if byte == 140:                         # end of page
    312                 return True

/opt/homebrew/anaconda3/envs/mda-dev/lib/python3.6/site-packages/matplotlib/dviread.py in wrapper(self, byte)
    164             if state is not None and self.state != state:
    165                 raise ValueError("state precondition failed")
--> 166             return method(self, *[f(self, byte-min) for f in get_args])
    167         if max is None:
    168             table[min] = wrapper

/opt/homebrew/anaconda3/envs/mda-dev/lib/python3.6/site-packages/matplotlib/dviread.py in _fnt_def(self, k, c, s, d, a, l)
    455     @dispatch(min=243, max=246, args=('olen1', 'u4', 'u4', 'u4', 'u1', 'u1'))
    456     def _fnt_def(self, k, c, s, d, a, l):
--> 457         self._fnt_def_real(k, c, s, d, a, l)
    458
    459     def _fnt_def_real(self, k, c, s, d, a, l):

/opt/homebrew/anaconda3/envs/mda-dev/lib/python3.6/site-packages/matplotlib/dviread.py in _fnt_def_real(self, k, c, s, d, a, l)
    460         n = self.file.read(a + l)
    461         fontname = n[-l:].decode('ascii')
--> 462         tfm = _tfmfile(fontname)
    463         if tfm is None:
    464             if six.PY2:

/opt/homebrew/anaconda3/envs/mda-dev/lib/python3.6/site-packages/matplotlib/dviread.py in _tfmfile(texname)
   1074
   1075 def _tfmfile(texname):
-> 1076     return _fontfile(texname, Tfm, '.tfm', _tfmcache)
   1077
   1078

/opt/homebrew/anaconda3/envs/mda-dev/lib/python3.6/site-packages/matplotlib/dviread.py in _fontfile(texname, class_, suffix, cache)
   1063         pass
   1064
-> 1065     filename = find_tex_file(texname + suffix)
   1066     if filename:
   1067         result = class_(filename)

/opt/homebrew/anaconda3/envs/mda-dev/lib/python3.6/site-packages/matplotlib/dviread.py in find_tex_file(filename, format)
   1043     # https://github.com/matplotlib/matplotlib/issues/633
   1044     pipe = subprocess.Popen(cmd, stdout=subprocess.PIPE,
-> 1045                             stderr=subprocess.PIPE)
   1046     result = pipe.communicate()[0].rstrip()
   1047     matplotlib.verbose.report('find_tex_file result: %s' % result,

/opt/homebrew/anaconda3/envs/mda-dev/lib/python3.6/subprocess.py in __init__(self, args, bufsize, executable, stdin, stdout, stderr, preexec_fn, close_fds, shell, cwd, env, universal_newlines, startupinfo, creationflags, restore_signals, start_new_session, pass_fds, encoding, errors)
    707                                 c2pread, c2pwrite,
    708                                 errread, errwrite,
--> 709                                 restore_signals, start_new_session)
    710         except:
    711             # Cleanup if the child failed starting.

/opt/homebrew/anaconda3/envs/mda-dev/lib/python3.6/subprocess.py in _execute_child(self, args, executable, preexec_fn, close_fds, pass_fds, cwd, env, startupinfo, creationflags, shell, p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite, restore_signals, start_new_session)
   1342                         if errno_num == errno.ENOENT:
   1343                             err_msg += ': ' + repr(err_filename)
-> 1344                     raise child_exception_type(errno_num, err_msg, err_filename)
   1345                 raise child_exception_type(err_msg)
   1346

FileNotFoundError: [Errno 2] No such file or directory: 'kpsewhich': 'kpsewhich'

I understand that Latex is displayed using mathjax, but anaconda (and pip, for that matter), doesn't have it available for Python 3.6. I even tried this using a different kernel for Python 2.7 with no success. As noted above, I had previously been successful using an older version of Jupyter in Python 2.7.

Any help will be appreciated.

Body:
So, after much searching and tinkering, the problem is with the following lines:

# Update parameters for matplotlib
params = {"text.usetex": True,
          "text.latex.unicode": True,
          "axes.unicode_minus": True,
         }
plt.rcParams.update(params)

Apparently, the above parameters are no longer needed in the latest version of Jupyter. Upon deleting these lines, my figure displayed properly with the appropriate Latex designations.


问:
Cypress with SystemJS
I am attempting to create some basic tests to try out the new Cypress library. In my test I have cy.visit('http://mywebsite.com'); which is loading an AngularJS app that uses SystemJS.

If I understand Cypress correctly, I shouldn't have to do anything else and it will make sure the page is loaded before running anything else. However this doesn't seem to be working because the page is loaded, but SystemJS is still loading the modules.

How can I get Cypress to wait for all the SystemJS modules to load before running any more tests without using cy.wait(5000)?

EDIT

Thanks to Dwelle this is the solution that works for me. I wrap the initial System.import in a promise that gets resolved once the AngularJS app has been bootstrapped.

```<code>window.APP_READY = new Promise(function(resolve, reject) {
    System.import('app').then(function(app) {
        angular.element(document).ready(function() {
            angular.bootstrap(document, ['app']);
            resolve();
        });
    });
});
</code>```

And then in the test

```<code>cy.visit('http://mywebsite.com').its('APP_READY');
</code>```

答:
Not familiar with SystemJS or your app, but if we assume you're doing some asynchronous work on load, you can set up some global property which indicates whether the app is ready or not.

```<code>// your main.js
let _appReadyResolver;
window.APP_READY = new Promise( resolve => _appReadyResolver = resolve );

// do some async setup
setTimeout(() => {

    _appReadyResolver();
});
</code>```

Then, in your tests:

```<code>cy.visit("/")
    // by default will wait 4sec for APP_READY prop to exist on
    //  window object (unfortunately I don't know how to increase timeouts
    //  of `cy.its` command)
    // After that, it will wait indefinitely for your promise to resolve
    .its("APP_READY")
</code>```

That being said --- if you're not doing any async setup in your app, but the main.js is simply being loaded asynchronously and it can take longer than 4sec, then I'd do this:

```<code>// index.js
<script>
  SystemJS.import('/js/main.js');
  window.APP_READY = new Promise( resolve => {
    let interval = setInterval(() => {
        if ( window.MAIN_READY ) {
            resolve();
            clearTimeout(interval);
        };
  }, 100 );
</script>

// main.js
window.MAIN_READY = true;
</code>```

You'll want to strip the APP_READY logic from production build.

Title: Cypress with SystemJS

Body:
I am attempting to create some basic tests to try out the new Cypress library. In my test I have cy.visit('http://mywebsite.com'); which is loading an AngularJS app that uses SystemJS.

If I understand Cypress correctly, I shouldn't have to do anything else and it will make sure the page is loaded before running anything else. However this doesn't seem to be working because the page is loaded, but SystemJS is still loading the modules.

How can I get Cypress to wait for all the SystemJS modules to load before running any more tests without using cy.wait(5000)?

EDIT

Thanks to Dwelle this is the solution that works for me. I wrap the initial System.import in a promise that gets resolved once the AngularJS app has been bootstrapped.

window.APP_READY = new Promise(function(resolve, reject) {
    System.import('app').then(function(app) {
        angular.element(document).ready(function() {
            angular.bootstrap(document, ['app']);
            resolve();
        });
    });
});

And then in the test

cy.visit('http://mywebsite.com').its('APP_READY');

Body:
Not familiar with SystemJS or your app, but if we assume you're doing some asynchronous work on load, you can set up some global property which indicates whether the app is ready or not.

// your main.js
let _appReadyResolver;
window.APP_READY = new Promise( resolve => _appReadyResolver = resolve );

// do some async setup
setTimeout(() => {

    _appReadyResolver();
});

Then, in your tests:

cy.visit("/")
    // by default will wait 4sec for APP_READY prop to exist on
    //  window object (unfortunately I don't know how to increase timeouts
    //  of `cy.its` command)
    // After that, it will wait indefinitely for your promise to resolve
    .its("APP_READY")

That being said --- if you're not doing any async setup in your app, but the main.js is simply being loaded asynchronously and it can take longer than 4sec, then I'd do this:

// index.js
<script>
  SystemJS.import('/js/main.js');
  window.APP_READY = new Promise( resolve => {
    let interval = setInterval(() => {
        if ( window.MAIN_READY ) {
            resolve();
            clearTimeout(interval);
        };
  }, 100 );
</script>

// main.js
window.MAIN_READY = true;

You'll want to strip the APP_READY logic from production build.


问:
value not passing from javascript to c#
Asp.net

```<code>       <asp:HiddenField ID="hdnfldVariable" runat="server" />
</code>```

Javascript

```<code>function GetUserName() {
        var wshell = new ActiveXObject("WScript.Shell");
        var unamer = document.getElementById('hdnfldVariable');
        unamer.value = wshell.ExpandEnvironmentStrings("%USERNAME%");
    }
</code>```

c#

```<code>string username1 = hdnfldVariable.Value;
</code>```

username1 gets null value. Can anyone check if its correct way to do it?

答:
Explicitly retrieve through page request.</p>

```<code> string  username1 = Page.Request.Form["hdnfldVariable"].ToString();
</code>```

Title: value not passing from javascript to c#

Body:
Asp.net

       <asp:HiddenField ID="hdnfldVariable" runat="server" />

Javascript

function GetUserName() {
        var wshell = new ActiveXObject("WScript.Shell");
        var unamer = document.getElementById('hdnfldVariable');
        unamer.value = wshell.ExpandEnvironmentStrings("%USERNAME%");
    }

c#

string username1 = hdnfldVariable.Value;

username1 gets null value. Can anyone check if its correct way to do it?

Body:
Explicitly retrieve through page request.

 string  username1 = Page.Request.Form["hdnfldVariable"].ToString();


问:
How to write SQL query into code-igniter formate
How to write below SQL query in to code-igniter </p>

```<code>SELECT
    `pm`.`id`,
    `pm`.`region`,
    `pm`.`port_name`,
    `pm`.`country`,
    `tbl_port_annual_throughput`.`YEAR`,
    `tbl_port_annual_throughput`.`TOTAL_THROUGHPUT`,
    `tbl_port_annual_throughput`.`status`
    FROM (`tbl_port_annual_throughput`)
    JOIN `port_master` pm
      ON `pm`.`id` = `tbl_port_annual_throughput`.`PORT_ID`
    WHERE `pm`.`country` = "100@Kenya"
    AND (
        (`tbl_port_annual_throughput`.`YEAR` =  '2014' AND `tbl_port_annual_throughput`.`status` =  'Confirmed')
        OR (`tbl_port_annual_throughput`.`YEAR` =  '2015' AND `tbl_port_annual_throughput`.`status` =  'Confirmed')
        OR (`tbl_port_annual_throughput`.`YEAR` =  '2016' AND `tbl_port_annual_throughput`.`status` =  'Confirmed')
    )
</code>```

答:
if you really want your exact query you can do something like this</p>

```<code>$query = $this->db
    ->select('pm.id, pm.region, pm.port_name, tbl_port_annual_throughput.YEAR, tbl_port_annual_throughput.TOTAL_THROUGHPUT, tbl_port_annual_throughput.status')
    ->from('tbl_port_annual_throughput')
    ->join('port_master pm', 'pm.id = tbl_port_annual_throughput.PORT_ID')
    ->where('pm.country','100@Kenya')
    ->group_start()
        ->group_start()
            ->where('tbl_port_annual_throughput.YEAR','2014')
            ->where('tbl_port_annual_throughput.status','Confirmed')
        ->group_end()
        ->or_group_start()
            ->where('tbl_port_annual_throughput.YEAR','2015')
            ->where('tbl_port_annual_throughput.status','Confirmed')
        ->group_end()
        ->or_group_start()
            ->where('tbl_port_annual_throughput.YEAR','2016')
            ->where('tbl_port_annual_throughput.status','Confirmed')
        ->group_end()
    ->group_end()
    ->get();
</code>```

Body:
How to write below SQL query in to code-igniter

SELECT
    `pm`.`id`,
    `pm`.`region`,
    `pm`.`port_name`,
    `pm`.`country`,
    `tbl_port_annual_throughput`.`YEAR`,
    `tbl_port_annual_throughput`.`TOTAL_THROUGHPUT`,
    `tbl_port_annual_throughput`.`status`
    FROM (`tbl_port_annual_throughput`)
    JOIN `port_master` pm
      ON `pm`.`id` = `tbl_port_annual_throughput`.`PORT_ID`
    WHERE `pm`.`country` = "100@Kenya"
    AND (
        (`tbl_port_annual_throughput`.`YEAR` =  '2014' AND `tbl_port_annual_throughput`.`status` =  'Confirmed')
        OR (`tbl_port_annual_throughput`.`YEAR` =  '2015' AND `tbl_port_annual_throughput`.`status` =  'Confirmed')
        OR (`tbl_port_annual_throughput`.`YEAR` =  '2016' AND `tbl_port_annual_throughput`.`status` =  'Confirmed')
    )

Body:
if you really want your exact query you can do something like this

$query = $this->db
    ->select('pm.id, pm.region, pm.port_name, tbl_port_annual_throughput.YEAR, tbl_port_annual_throughput.TOTAL_THROUGHPUT, tbl_port_annual_throughput.status')
    ->from('tbl_port_annual_throughput')
    ->join('port_master pm', 'pm.id = tbl_port_annual_throughput.PORT_ID')
    ->where('pm.country','100@Kenya')
    ->group_start()
        ->group_start()
            ->where('tbl_port_annual_throughput.YEAR','2014')
            ->where('tbl_port_annual_throughput.status','Confirmed')
        ->group_end()
        ->or_group_start()
            ->where('tbl_port_annual_throughput.YEAR','2015')
            ->where('tbl_port_annual_throughput.status','Confirmed')
        ->group_end()
        ->or_group_start()
            ->where('tbl_port_annual_throughput.YEAR','2016')
            ->where('tbl_port_annual_throughput.status','Confirmed')
        ->group_end()
    ->group_end()
    ->get();


问:
How would one implement a variable sized cache object to reduce memory allocations in C++?
Before the performance people tear my head off: yes, I have done profiling before asking this :)

I'm once again looking at my one of a type container, and while I have a solution that works, the performance is poor because each type of item that's cached results in a separate allocation on the heap (which is of course expensive).

Based on static analysis of my program's input, I have figured out a way to know the total size required by all of the objects that might be put in my cache object that's getting passed around. Basically, I have a list of objects that may be constructed in a given cache object, so I know what the size of what I might have to cache is in advance, but not at compile time -- runtime only.

Basically, what I'd like to do is what boost::make_shared does -- gets a single memory block, and constructs the shared_ptr bits as well as the controlled object in the same memory block.

I don't have to worry about preserving copying behavior as the cache object is noncopyable and passed around by pointer by clients (it's usually stored in something like a ptr_vector or a std::auto_ptr).

I'm not familiar however with how exactly one would implement such a container however, namely how one follows alignment restrictions and such.

In pseudocode, what I'd like to do:

```<code>//I know a lot of what's in here is not portable -- I need to run only on x86
//and x64 machines. Yes, this couple of classes looks hacky, but I'd rather
//have one hacky class than a whole programfull :)

class CacheRegistrar
{
    //Blah blah
public:
    //Figures out what objects will be in the cache, etc
    const std::vector<std::size_t>& GetRequiredObjectSizes() const;
    //Other stuff...
    template <typename T>
    void RegisterCacheObject();
    template <typename T>
    std::size_t GetObjectIndex() const;
    // etc.
};

class CacheObject;

std::auto_ptr<CacheObject> CacheObjectFactory(const CacheRegistrar& registrar)
{
    //Pretend this is in a CPP file and therefore CacheObject is defined...
    const std::vector<size_t>& sizes(registrar.GetRequiredObjectSizes());
    std::size_t sumOfCache = std::accumulate(sizes.begin(), sizes.end());
    sumOfCache += sizeof(CacheObject);
    boost::scoped_array<char> buffer(new char[] sumOfCache);
    CacheObject *obj = new (reinterpret_cast<void *>(buffer.get())) CacheObject;
    buffer.release(); //PSEUDOCODE (boost::scoped_array has no release member);
    return std::auto_ptr<CacheObject>(obj); //Nothrow
}

class CacheObject
{
    CacheRegistrar *registrar; //Set by my constructor
public:
    template<typename T>
    T& Get()
    {
        char * startOfCache = reinterpret_cast<char *>(this) +
            sizeof(CacheObject);
        char * cacheItem = startOfCache + registrar->GetObjectIndex<T>();
        return *reinterpret_cast<T*>(cacheItem);
    }
};
</code>```

Is my general concept sound here? Is there are better way of accomplishing this?

答:
Check out the Loki small objects allocator.

Quick-googling that didn’t yield any direct human-oriented docs. There is DOxygen-generated documentation but not especially grokkable. However, the design and implementation is documented in Andrei Alexandrescu’s "Modern C++ Design".

If you just want efficient recycling for objects of a given class, then consider a simple free-list – possibly a free-list of raw storage chunks.

Cheers & hth.,

Body:
Before the performance people tear my head off: yes, I have done profiling before asking this :)

I'm once again looking at my one of a type container, and while I have a solution that works, the performance is poor because each type of item that's cached results in a separate allocation on the heap (which is of course expensive).

Based on static analysis of my program's input, I have figured out a way to know the total size required by all of the objects that might be put in my cache object that's getting passed around. Basically, I have a list of objects that may be constructed in a given cache object, so I know what the size of what I might have to cache is in advance, but not at compile time -- runtime only.

Basically, what I'd like to do is what boost::make_shared does -- gets a single memory block, and constructs the shared_ptr bits as well as the controlled object in the same memory block.

I don't have to worry about preserving copying behavior as the cache object is noncopyable and passed around by pointer by clients (it's usually stored in something like a ptr_vector or a std::auto_ptr).

I'm not familiar however with how exactly one would implement such a container however, namely how one follows alignment restrictions and such.

In pseudocode, what I'd like to do:

//I know a lot of what's in here is not portable -- I need to run only on x86
//and x64 machines. Yes, this couple of classes looks hacky, but I'd rather
//have one hacky class than a whole programfull :)

class CacheRegistrar
{
    //Blah blah
public:
    //Figures out what objects will be in the cache, etc
    const std::vector<std::size_t>& GetRequiredObjectSizes() const;
    //Other stuff...
    template <typename T>
    void RegisterCacheObject();
    template <typename T>
    std::size_t GetObjectIndex() const;
    // etc.
};

class CacheObject;

std::auto_ptr<CacheObject> CacheObjectFactory(const CacheRegistrar& registrar)
{
    //Pretend this is in a CPP file and therefore CacheObject is defined...
    const std::vector<size_t>& sizes(registrar.GetRequiredObjectSizes());
    std::size_t sumOfCache = std::accumulate(sizes.begin(), sizes.end());
    sumOfCache += sizeof(CacheObject);
    boost::scoped_array<char> buffer(new char[] sumOfCache);
    CacheObject *obj = new (reinterpret_cast<void *>(buffer.get())) CacheObject;
    buffer.release(); //PSEUDOCODE (boost::scoped_array has no release member);
    return std::auto_ptr<CacheObject>(obj); //Nothrow
}

class CacheObject
{
    CacheRegistrar *registrar; //Set by my constructor
public:
    template<typename T>
    T& Get()
    {
        char * startOfCache = reinterpret_cast<char *>(this) +
            sizeof(CacheObject);
        char * cacheItem = startOfCache + registrar->GetObjectIndex<T>();
        return *reinterpret_cast<T*>(cacheItem);
    }
};

Is my general concept sound here? Is there are better way of accomplishing this?


问:
Laravel stuck cache keeps displaying what's not there
So I'm creating a web application and got stuck trying to fix this error

"Use of undefined constant images - assumed 'images' (View: /Users/ernest/Diplomska/bazar/resources/views/pages/welcome.blade.php)"

I used Chrome and Safari to see if the problem was in browser cache. Then I stopped, updated and restarted Valet. After that failed I cleared composer cache and updated it and still nothing. I also tried rebooting the system just in case to no avail.

My current code:

```<code>    <!-- First row -->
    <div class="row" style="text-align: center;">
      <div class="col-sm-2 offset-sm-1">
        <a href="#">
          <img src="{{ url('/public/images/literature.jpeg') }}">
          <p>Literature</p>
        </a>
      </div>
      <div class="col-sm-2 offset-sm-2">
        <a href="#">
          <img src="{{ url('/public/images/music.jpeg') }}">
          <p>Music</p>
         </a>
       </div>
       <div class="col-sm-2 offset-sm-2">
          <a href="#" id="categoryId">
            <img src="{{ url('/public/images/graphics.jpeg') }}">
            <p>Graphics</p>
          </a>
        </div>
      </div>
</code>```

What browser thinks my code is (displayed in error on any browser):

```<code>    1       <!-- Choose category -->
    2       <div class="container" style="padding-top: 70px; padding-bottom: 70px; border-bottom: 1px solid #d6dbe0;">
    3          <h1 style="text-align: center; color: #a7a7a7; padding-bottom: 40px;">Choose category</h1>
    4          <div style="margin: auto;">
    5
    6             <!-- First row -->
    7             <div class="row" style="text-align: center;">
    8               <div class="col-sm-2 offset-sm-1">
    9                 <a href="#">
    10                  <img src="<?php echo e(asset(images/literature.jpeg)); ?>">
    11                  <p>Literature</p>
    12                </a>
    13              </div>
    14              <div class="col-sm-2 offset-sm-2">
    15                <a href="#">
    16                  <img src="public/music.jpeg">
    17                  <p>Music</p>
    18                </a>
    19              </div>
    20              </a>
    21              <div class="col-sm-2 offset-sm-2">
    22                <a href="#" id="categoryId">
</code>```

So my question is how do I tell browser to recheck the written code because it keeps insisting on asset() which is no longer there.

答:
Laravel/Blade uses cache to speed up display of pages. To clear all cached views use

php artisan view:clear

from your command line.

Body:
So I'm creating a web application and got stuck trying to fix this error

"Use of undefined constant images - assumed 'images' (View: /Users/ernest/Diplomska/bazar/resources/views/pages/welcome.blade.php)"

I used Chrome and Safari to see if the problem was in browser cache. Then I stopped, updated and restarted Valet. After that failed I cleared composer cache and updated it and still nothing. I also tried rebooting the system just in case to no avail.

My current code:

Literature

Music

Graphics

What browser thinks my code is (displayed in error on any browser):

    1
    2

    3
Choose category

    4

    5
    6
    7

    8

    9
    10                  <img src="<?php echo e(asset(images/literature.jpeg)); ?>">
    11
Literature

    12
    13

    14

    15
    16
    17
Music

    18
    19

    20
    21

    22

So my question is how do I tell browser to recheck the written code because it keeps insisting on asset() which is no longer there.


问:
Constructor can not be instantiated Slick Scala
I was trying to convert a query from SQL into Scala code with Slick, but I have got a compiler error in filter clause: constructor cannot be instantiated to expected type.

My code in Slick:

```<code>val subquery = (for {
      pit <- PassInTripTable.table
      t <- TripTable.table if pit.tripNoFk === t.tripNo
    } yield (pit, t))
        .map{ case (pit, t) => ( pit, Case.If(t.townFrom <= t.townTo).Then(t.townFrom ++ t.townTo).Else(t.townFrom ++ t.townTo) )}
          .groupBy(_._1.idPsgFk)
            .filter{ case ((pit, count), group) => ( group.map(_._2).countDistinct === 1)}
                .map(_._1)
    val query = PassengerTable.table.filter(_.idPsg in subquery).map(_.name)
    db.run(query.result)
</code>```

The query in SQL itself:

```<code>select name from passenger
        where id_psg in
        (
          select id_psg from trip t,pass_in_trip pit
          where t.trip_no=pit.trip_no
          group by id_psg
          having count(distinct case when town_from<=town_to then town_from+town_to else town_to+town_from end)=1
        )
</code>```

I would be very grateful if someone helped me to find an error.

答:
From looking at your code, it looks like the type you are matching on is not supposed to be "((pit, count), group)".

groupBy in Slick only returns a collection of Tuple2s.

http://slick.lightbend.com/doc/3.0.0/queries.html

So, the filter might look something like...

```<code>.filter{ case (pit, count) => ( count.map(_._2).countDistinct === 1)}
</code>```

Body:
I was trying to convert a query from SQL into Scala code with Slick, but I have got a compiler error in filter clause: constructor cannot be instantiated to expected type.

My code in Slick:

val subquery = (for {
      pit <- PassInTripTable.table
      t <- TripTable.table if pit.tripNoFk === t.tripNo
    } yield (pit, t))
        .map{ case (pit, t) => ( pit, Case.If(t.townFrom <= t.townTo).Then(t.townFrom ++ t.townTo).Else(t.townFrom ++ t.townTo) )}
          .groupBy(_._1.idPsgFk)
            .filter{ case ((pit, count), group) => ( group.map(_._2).countDistinct === 1)}
                .map(_._1)
    val query = PassengerTable.table.filter(_.idPsg in subquery).map(_.name)
    db.run(query.result)

The query in SQL itself:

select name from passenger
        where id_psg in
        (
          select id_psg from trip t,pass_in_trip pit
          where t.trip_no=pit.trip_no
          group by id_psg
          having count(distinct case when town_from<=town_to then town_from+town_to else town_to+town_from end)=1
        )

I would be very grateful if someone helped me to find an error.

Body:
From looking at your code, it looks like the type you are matching on is not supposed to be "((pit, count), group)".

groupBy in Slick only returns a collection of Tuple2s.

http://slick.lightbend.com/doc/3.0.0/queries.html

So, the filter might look something like...

.filter{ case (pit, count) => ( count.map(_._2).countDistinct === 1)}


问:
Changing nodes in XSLT based on context
I have one XSL file that I wanna include or use in two different contexts. In one of the contexts I want to use 'fo:block' but in the other context I want to use 'div class="Block"'.

Is there someway to change all my 'fo:block' in my XSL to 'div class="Block"' or vice versa based on the context, maybe with the use of parameters?

答:
Its a simple condition:

```<code><xsl:variable name="outputformat" select="'html'"/>
<xsl:choose>
    <xsl:when test="$outputformat = 'html'">
        <div class="Block">
            <!-- your html code -->
        </div>
    </xsl:when>
    <xsl:otherwise>
        <fo:block>
           <!-- your normal code -->
        </fo:block>
    </xsl:otherwise>
</xsl:choose>
</code>```

Alternatively you can make a second xsl document and copy every node except the

```<code><fo:block/>
</code>```

which you should change to

```<code><div class="block"/>
</code>```

This would look like:

```<code><xsl:template match="@*|node()">
    <xsl:choose>
        <xsl:when test="local-name() = 'block'">
            <xsl:element name="div">
                <xsl:attribute name="class" select="'Block'"/>
                <xsl:apply-templates select="@*"/>
                <xsl:apply-templates/>
            </xsl:element>
        </xsl:when>
        <xsl:otherwise>
            <xsl:copy>
                <xsl:apply-templates select="@*|node()"/>
            </xsl:copy>
        </xsl:otherwise>
    </xsl:choose>
</xsl:template>
</code>```

Title: Changing nodes in XSLT based on context

Body:
Its a simple condition:

<xsl:variable name="outputformat" select="'html'"/>
<xsl:choose>
    <xsl:when test="$outputformat = 'html'">
        <div class="Block">
            <!-- your html code -->
        </div>
    </xsl:when>
    <xsl:otherwise>
        <fo:block>
           <!-- your normal code -->
        </fo:block>
    </xsl:otherwise>
</xsl:choose>

Alternatively you can make a second xsl document and copy every node except the

<fo:block/>

which you should change to

<div class="block"/>

This would look like:

<xsl:template match="@*|node()">
    <xsl:choose>
        <xsl:when test="local-name() = 'block'">
            <xsl:element name="div">
                <xsl:attribute name="class" select="'Block'"/>
                <xsl:apply-templates select="@*"/>
                <xsl:apply-templates/>
            </xsl:element>
        </xsl:when>
        <xsl:otherwise>
            <xsl:copy>
                <xsl:apply-templates select="@*|node()"/>
            </xsl:copy>
        </xsl:otherwise>
    </xsl:choose>
</xsl:template>

ContentLicense: CC BY-SA 4.0