问:
Unknown host in Java RMI
I'm working on a Java RMI distribuited system and I have 2 VMs running ubuntu on my local machine (ubuntu- (master) IP = 192.168.101.131 and ubuntu- (slave) IP = 92.168.101.137). Can I run my bankServer.jar on both VMs (within a tomcat). The ubuntu- (master) database automatically replicates on ubuntu- (slave). So far so good. Server mentions (in portuguese) that is running in the default port 1099.

```<code>Cubuntu@ubuntu:/var/www/html/classes$ java -cp ./code/:jar/serverBanco.jar -
Dja.rmi.server.codebase=file:jar/computeInterfaces.jar -
Djava.rmi.server.hostname=192.168.101.131 -
Djava.security.policy=file:jar/all.policy bank.BankServer
Default RMI Port = 1099
Servidor iniciado...
</code>```

Now when running the client on my local machine my program first ping the host to see if he is online and, if ok, binds to it the registry like so:

```<code>InetAddress inet = null;
     InetAddress inet2 = null;
     String rmi_adress;
        //ping
        inet = InetAddress.getByAddress(new byte[] { (byte) 192, (byte) 168, 101, (byte) 137 });
        System.out.println("Enviando Ping Request para host: " + inet);
        System.out.println(inet.isReachable(5000) ? "Resposta: Host online" : "Resposta: Host offline");

        inet2 = InetAddress.getByAddress(new byte[] { (byte) 192, (byte) 168, 101, (byte) 131 });
        System.out.println("Enviando Ping Request para host: " + inet2);
        System.out.println(inet2.isReachable(5000) ? "Resposta: Host online" : "Resposta: Host offline");

        try {
            registry = LocateRegistry.getRegistry("rmi://127.0.0.1/BankServer");
            if (inet.isReachable(5000)) {
                rmi_adress = "rmi://192.168.101.137/BankServer";
                registry = LocateRegistry.getRegistry(rmi_adress);
                System.out.println("RMI Port set to " + rmi_adress);
                bank = (OperationsInterface) registry.lookup(rmi_adress);
            }else {
                rmi_adress =  "rmi://192.168.101.131/BankServer";
                registry = LocateRegistry.getRegistry(rmi_adress);
                System.out.println("RMI Port set to " + rmi_adress);
                bank = (OperationsInterface) registry.lookup(rmi_adress);
            }
</code>```

But when running the client it can not recognize the host. This is the exception I'm getting:

```<code>Enviando Ping Request para host: /192.168.101.137
Resposta: Host online
Enviando Ping Request para host: /192.168.101.131
Resposta: Host online
RMI Port set to rmi://192.168.101.137/BankServer
Exception in thread "main" java.rmi.UnknownHostException: Unknown host:
rmi://192.168.101.137/BankServer; nested exception is:
    Java.net.UnknownHostException: rmi://192.168.101.137/BankServer
    at sun.rmi.transport.tcp.TCPEndpoint.newSocket(TCPEndpoint.java:616)
    at
sun.rmi.transport.tcp.TCPChannel.createConnection(TCPChannel.java:216)
    at sun.rmi.transport.tcp.TCPChannel.newConnection(TCPChannel.java:202)
    at sun.rmi.server.UnicastRef.newCall(UnicastRef.java:342)
    at sun.rmi.registry.RegistryImpl_Stub.lookup(Unknown Source)
    at atm.ATM.main(ATM.java:52)
Caused by: java.net.UnknownHostException: rmi://192.168.101.137/BankServer
    at
java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:184)
    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
    at java.net.Socket.connect(Socket.java:589)
    at java.net.Socket.connect(Socket.java:538)
    at java.net.Socket.<init>(Socket.java:434)
    at java.net.Socket.<init>(Socket.java:211)
    at...
</code>```

Now what could be happening here? Any help is appreciated.

答: The argument to LocateRegistry.getRegistry() is a hostname, not an RMI URL. See the Javadoc.

Title: Unknown host in Java RMI

Body:
I'm working on a Java RMI distribuited system and I have 2 VMs running ubuntu on my local machine (ubuntu- (master) IP = 192.168.101.131 and ubuntu- (slave) IP = 92.168.101.137). Can I run my bankServer.jar on both VMs (within a tomcat). The ubuntu- (master) database automatically replicates on ubuntu- (slave). So far so good. Server mentions (in portuguese) that is running in the default port 1099.

Cubuntu@ubuntu:/var/www/html/classes$ java -cp ./code/:jar/serverBanco.jar -
Dja.rmi.server.codebase=file:jar/computeInterfaces.jar -
Djava.rmi.server.hostname=192.168.101.131 -
Djava.security.policy=file:jar/all.policy bank.BankServer
Default RMI Port = 1099
Servidor iniciado...

Now when running the client on my local machine my program first ping the host to see if he is online and, if ok, binds to it the registry like so:

InetAddress inet = null;
     InetAddress inet2 = null;
     String rmi_adress;
        //ping
        inet = InetAddress.getByAddress(new byte[] { (byte) 192, (byte) 168, 101, (byte) 137 });
        System.out.println("Enviando Ping Request para host: " + inet);
        System.out.println(inet.isReachable(5000) ? "Resposta: Host online" : "Resposta: Host offline");

        inet2 = InetAddress.getByAddress(new byte[] { (byte) 192, (byte) 168, 101, (byte) 131 });
        System.out.println("Enviando Ping Request para host: " + inet2);
        System.out.println(inet2.isReachable(5000) ? "Resposta: Host online" : "Resposta: Host offline");

        try {
            registry = LocateRegistry.getRegistry("rmi://127.0.0.1/BankServer");
            if (inet.isReachable(5000)) {
                rmi_adress = "rmi://192.168.101.137/BankServer";
                registry = LocateRegistry.getRegistry(rmi_adress);
                System.out.println("RMI Port set to " + rmi_adress);
                bank = (OperationsInterface) registry.lookup(rmi_adress);
            }else {
                rmi_adress =  "rmi://192.168.101.131/BankServer";
                registry = LocateRegistry.getRegistry(rmi_adress);
                System.out.println("RMI Port set to " + rmi_adress);
                bank = (OperationsInterface) registry.lookup(rmi_adress);
            }

But when running the client it can not recognize the host. This is the exception I'm getting:

Enviando Ping Request para host: /192.168.101.137
Resposta: Host online
Enviando Ping Request para host: /192.168.101.131
Resposta: Host online
RMI Port set to rmi://192.168.101.137/BankServer
Exception in thread "main" java.rmi.UnknownHostException: Unknown host:
rmi://192.168.101.137/BankServer; nested exception is:
    Java.net.UnknownHostException: rmi://192.168.101.137/BankServer
    at sun.rmi.transport.tcp.TCPEndpoint.newSocket(TCPEndpoint.java:616)
    at
sun.rmi.transport.tcp.TCPChannel.createConnection(TCPChannel.java:216)
    at sun.rmi.transport.tcp.TCPChannel.newConnection(TCPChannel.java:202)
    at sun.rmi.server.UnicastRef.newCall(UnicastRef.java:342)
    at sun.rmi.registry.RegistryImpl_Stub.lookup(Unknown Source)
    at atm.ATM.main(ATM.java:52)
Caused by: java.net.UnknownHostException: rmi://192.168.101.137/BankServer
    at
java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:184)
    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
    at java.net.Socket.connect(Socket.java:589)
    at java.net.Socket.connect(Socket.java:538)
    at java.net.Socket.<init>(Socket.java:434)
    at java.net.Socket.<init>(Socket.java:211)
    at...

Now what could be happening here? Any help is appreciated.


来源: stackexchange

问:
Pandas dataframe get index and header when in multiple columns
I have a dataframe which looks like this:

```<code>d = {'id': ['Mc','Web','G','M','F'], 'Person1':['x','x','x',None,None],'Person2':['x',None,'x','x',None], 'Person3':['x',None, None,None, None]}

df = pd.DataFrame(d)
df.set_index('id', inplace=True)

    Person1 Person2 Person3
id
Mc        x       x       x
Web       x    None    None
G         x       x    None
M      None       x    None
F      None    None    None
</code>```

How can I get the id-value and column header if an id appears with more than one person?. For example, the above data frame should give the following dictionary:

{'Mc':[Person1, Person2, Person3], 'G':[Person1, Person2]}

Any help would be very much appreciated.

答:
Use  a mask i.e </p>

```<code>ndf = df.where(df.isnull(),df.apply(lambda x : x.index,1))
temp = ndf[ndf.notnull().sum(1)>=2]
</code>```

```
   Person1  Person2  Person3
id
Mc  Person1  Person2  Person3
G   Person1  Person2     None
```

<p>For a dictionary we can use </p>

```<code>di = { key: value[pd.notnull(value)].tolist() for key,value in zip(temp.index,temp.values)}

{'G': ['Person1', 'Person2'], 'Mc': ['Person1', 'Person2', 'Person3']}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a dataframe which looks like this:

d = {'id': ['Mc','Web','G','M','F'], 'Person1':['x','x','x',None,None],'Person2':['x',None,'x','x',None], 'Person3':['x',None, None,None, None]}

df = pd.DataFrame(d)
df.set_index('id', inplace=True)

    Person1 Person2 Person3
id
Mc        x       x       x
Web       x    None    None
G         x       x    None
M      None       x    None
F      None    None    None

How can I get the id-value and column header if an id appears with more than one person?. For example, the above data frame should give the following dictionary:

{'Mc':[Person1, Person2, Person3], 'G':[Person1, Person2]}

Any help would be very much appreciated.

Body:
Use  a mask i.e

ndf = df.where(df.isnull(),df.apply(lambda x : x.index,1))
temp = ndf[ndf.notnull().sum(1)>=2]

   Person1  Person2  Person3
id
Mc  Person1  Person2  Person3
G   Person1  Person2     None

For a dictionary we can use

di = { key: value[pd.notnull(value)].tolist() for key,value in zip(temp.index,temp.values)}

{'G': ['Person1', 'Person2'], 'Mc': ['Person1', 'Person2', 'Person3']}


问:
split one column from import into 2 column in database
i have a file i need to import that has a column with the settings A, S and B in them,

i would like to split this column and and all the A's go into a column but be reset to a 1 and the rest to go into another column and changed to a 1.

is this possible in derived columns?

答:
The answer is to create two derived columns using an If statement

([Product Type Code] == "A" ? "1" : "0")

and invert the outcome for the other derived column.

ContentLicense: CC BY-SA 2.5


问:
How can I load Child entities dynamically in Entity Framework 6
I have a Provider class and an Article one. Article has a int ProviderId{get;set} and a public virtual Provider Provider {get;set;} properties.

I know about Lazy loading and why I can't access the Provider property in Article outside the context but I have a generic method that returns the next T like this:

```<code>public static T Next<T>(T currentElement) where T : class, IModel {
    T data;

    if (currentElement.Id >= GetLastId<T>())
        return currentElement;

    using (DatabaseEntities context = new DatabaseEntities()) {
        data = context.Set<T>().Single(el => el.Id == currentElement.Id + 1);
    }

    return data;
}
</code>```

But I can't retrieve Child entities like Provider in Articles Class. How can I include all entities? Should I update the method and make one per entity?

I read about Eager loading and Explicit loading but I don't know how can I implement these in my method.

Note:

Not all my entities have entity children and I have more methods like Previous<T>(), First<T>() or Last<T>() that do the work you expect.

答:
So you have a one-to-many relation between Provider and Article: Every Provider has zero or more Articles, and every Article belongs to exactly one Provider.

If you have configured this one-to-many relationship correctly in Entity Framework, a Provider should have a reference to its many Articles:

```<code>public virtual ICollection<Article> Articles{get; set;}
</code>```

Furthermore you have a function Next, that takes as input an object of class T, which is a class that implements IModel. Next returns the next element from the DbSet of Ts, assuming you have a proper definition for the next element.

Apparently you want to adapt function Next such that you can use this function to get the next Provider with all its Articles.

More generic: if T is a type that has properly designed one-to-many relationships in it, and you have an object of type T, you want the T with the first Id higher than the Id of the current T, inclusive all its ICollections.

I've divided this into sever smaller functions:

A function that, given a type T returns all properties that implement ICollection

A function that, given a DbSet returns all elements of the DbSet inclusive all its ICollections

Given those two, and functions like OrderBy and FirstOrDefault you will be able to get the first Provider with Id larger than current provider with all its Articles.

```<code>static class QueryableExtensions
{
    // returns true if PropertyInfo implements ICollection<...>
    public static bool ImplementsICollection(this PropertyInfo propertyInfo)
    {
         return propertyInfo.IsGenericType
             && propertyInfo.GetGenericTypeDefinition() == typeof(ICollection<>);
    }

    // returns all readable & writable PropertyInfos of type T that implement ICollection<...>
    public static IEnumerable<PropertyInfo> CollectionProperties<T>()
    {
        return typeof(T).GetProperties()
            .Where(prop => prop.CanRead
                && prop.CanWrite
                && prop.PropertyType.ImplementICollection();
    }

    // given an IQueryable<T>, adds the Include of all ICollection<...> T has
    public static IQueryable<T> IncludeICollection<T>(IQueryable<T> query)
    {
         var iCollectionProperties = CollectionProperties<T>();
         foreach (var collectionProperty in collectionProperties)
         {
              query = query.Include(prop.Name);
         }
         return query;
    }

    // given a IQueryable<T> and a T return the first T in the query with Id higher than T
    // for this we need to be sure every T has an IComparable property Id
    // so T should implement interface IId (see below)
    public T Next<T>(this IQueryable<T> query, T currentItem)
         where T : IId  // makes sure every T has aproperty Id
    {
         T nextElement = query
             // keep only those DbSet items that have larger Ids:
             .Where(item => currentItem.Id < item.Id)
             // sort in ascending Id:
             .OrderBy(item => item.Id
             // keep only the first element of this sorted collection:
             .FirstOrDefault();
        return T
    }
}
</code>```

I need to be sure that every T has an Id, otherwise you can't get the next Id. Probably you have this in your IModel interface:

```<code>public Interface IId
{
     public int Id {get;}
}
</code>```

After these functions your query will be like:

```<code>public static T Next<T>(T currentElement) where T : class, IModel, IId
{
    T data;
    if (currentElement.Id >= GetLastId<T>())
        return currentElement;

    using (DatabaseEntities context = new DatabaseEntities())
    {
        return context.Set<T>().Next(currentElement);
    }
 }
</code>```

Body:
I have a Provider class and an Article one. Article has a int ProviderId{get;set} and a public virtual Provider Provider {get;set;} properties.

I know about Lazy loading and why I can't access the Provider property in Article outside the context but I have a generic method that returns the next T like this:

public static T Next<T>(T currentElement) where T : class, IModel {
    T data;

    if (currentElement.Id >= GetLastId<T>())
        return currentElement;

    using (DatabaseEntities context = new DatabaseEntities()) {
        data = context.Set<T>().Single(el => el.Id == currentElement.Id + 1);
    }

    return data;
}

But I can't retrieve Child entities like Provider in Articles Class. How can I include all entities? Should I update the method and make one per entity?

I read about Eager loading and Explicit loading but I don't know how can I implement these in my method.

Note:

Not all my entities have entity children and I have more methods like Previous<T>(), First<T>() or Last<T>() that do the work you expect.

Body:
So you have a one-to-many relation between Provider and Article: Every Provider has zero or more Articles, and every Article belongs to exactly one Provider.

If you have configured this one-to-many relationship correctly in Entity Framework, a Provider should have a reference to its many Articles:

public virtual ICollection<Article> Articles{get; set;}

Furthermore you have a function Next, that takes as input an object of class T, which is a class that implements IModel. Next returns the next element from the DbSet of Ts, assuming you have a proper definition for the next element.

Apparently you want to adapt function Next such that you can use this function to get the next Provider with all its Articles.

More generic: if T is a type that has properly designed one-to-many relationships in it, and you have an object of type T, you want the T with the first Id higher than the Id of the current T, inclusive all its ICollections.

I've divided this into sever smaller functions:

A function that, given a type T returns all properties that implement ICollection

A function that, given a DbSet returns all elements of the DbSet inclusive all its ICollections

Given those two, and functions like OrderBy and FirstOrDefault you will be able to get the first Provider with Id larger than current provider with all its Articles.

static class QueryableExtensions
{
    // returns true if PropertyInfo implements ICollection<...>
    public static bool ImplementsICollection(this PropertyInfo propertyInfo)
    {
         return propertyInfo.IsGenericType
             && propertyInfo.GetGenericTypeDefinition() == typeof(ICollection<>);
    }

    // returns all readable & writable PropertyInfos of type T that implement ICollection<...>
    public static IEnumerable<PropertyInfo> CollectionProperties<T>()
    {
        return typeof(T).GetProperties()
            .Where(prop => prop.CanRead
                && prop.CanWrite
                && prop.PropertyType.ImplementICollection();
    }

    // given an IQueryable<T>, adds the Include of all ICollection<...> T has
    public static IQueryable<T> IncludeICollection<T>(IQueryable<T> query)
    {
         var iCollectionProperties = CollectionProperties<T>();
         foreach (var collectionProperty in collectionProperties)
         {
              query = query.Include(prop.Name);
         }
         return query;
    }

    // given a IQueryable<T> and a T return the first T in the query with Id higher than T
    // for this we need to be sure every T has an IComparable property Id
    // so T should implement interface IId (see below)
    public T Next<T>(this IQueryable<T> query, T currentItem)
         where T : IId  // makes sure every T has aproperty Id
    {
         T nextElement = query
             // keep only those DbSet items that have larger Ids:
             .Where(item => currentItem.Id < item.Id)
             // sort in ascending Id:
             .OrderBy(item => item.Id
             // keep only the first element of this sorted collection:
             .FirstOrDefault();
        return T
    }
}

I need to be sure that every T has an Id, otherwise you can't get the next Id. Probably you have this in your IModel interface:

public Interface IId
{
     public int Id {get;}
}

After these functions your query will be like:

public static T Next<T>(T currentElement) where T : class, IModel, IId
{
    T data;
    if (currentElement.Id >= GetLastId<T>())
        return currentElement;

    using (DatabaseEntities context = new DatabaseEntities())
    {
        return context.Set<T>().Next(currentElement);
    }
 }


问:
Encode nil value as null with JSONEncoder
I'm using Swift 4's JSONEncoder. I have a Codable struct with an optional property, and I'd like this property to show up as null value in the produced JSON data when the value is nil. However, JSONEncoder discards the property and does not add it to the JSON output. Is there a way to configure JSONEncoder so that it preserves the key and sets it to null in this case?

Example

The code snippet below produces {"number":1}, but I'd rather like it to give me {"string":null,"number":1}:

```<code>struct Foo: Codable {
  var string: String? = nil
  var number: Int = 1
}

let encoder = JSONEncoder()
let data = try! encoder.encode(Foo())
print(String(data: data, encoding: .utf8)!)
</code>```

答:
Yes, but you'll have to write your own encode(to:) implementation, you can't use the auto-generated one.

```<code>struct Foo: Codable {
    var string: String? = nil
    var number: Int = 1

    func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: CodingKeys.self)
        try container.encode(number, forKey: .number)
        try container.encode(string, forKey: .string)
    }
}
</code>```

Encoding an optional directly will encode a null, like you're looking for.

If this is an important use case for you, you may consider opening a defect at bugs.swift.org to ask for a new OptionalEncodingStrategy flag to be added on JSONEncoder to match the existing DateEncodingStrategy, etc. (See below why this is likely impossible to actually implement in Swift today, but getting into the tracking system is still useful as Swift evolves.)

Edit: To Paulo's questions below, this dispatches to the generic encode<T: Encodable> version because Optional conforms to Encodable. This is implemented in Codable.swift this way:

```<code>extension Optional : Encodable /* where Wrapped : Encodable */ {
    @_inlineable // FIXME(sil-serialize-all)
    public func encode(to encoder: Encoder) throws {
        assertTypeIsEncodable(Wrapped.self, in: type(of: self))

        var container = encoder.singleValueContainer()
        switch self {
        case .none: try container.encodeNil()
        case .some(let wrapped): try (wrapped as! Encodable).__encode(to: &container)
        }
    }
}
</code>```

This wraps the call to encodeNil, and I think letting stdlib handle Optionals as just another Encodable is better than treating them as a special case in our own encoder and calling encodeNil ourselves.

Another obvious question is why it works this way in the first place. Since Optional is Encodable, and the generated Encodable conformance encodes all the properties, why does "encode all the properties by hand" work differently? The answer is that the conformance generator includes a special case for Optionals:

```<code>// Now need to generate `try container.encode(x, forKey: .x)` for all
// existing properties. Optional properties get `encodeIfPresent`.
...

if (varType->getAnyNominal() == C.getOptionalDecl() ||
    varType->getAnyNominal() == C.getImplicitlyUnwrappedOptionalDecl()) {
  methodName = C.Id_encodeIfPresent;
}
</code>```

This means that changing this behavior would require changing the auto-generated conformance, not JSONEncoder (which also means it's probably really hard to make configurable in today's Swift....)

Body:
I'm using Swift 4's JSONEncoder. I have a Codable struct with an optional property, and I'd like this property to show up as null value in the produced JSON data when the value is nil. However, JSONEncoder discards the property and does not add it to the JSON output. Is there a way to configure JSONEncoder so that it preserves the key and sets it to null in this case?

Example

The code snippet below produces {"number":1}, but I'd rather like it to give me {"string":null,"number":1}:

struct Foo: Codable {
  var string: String? = nil
  var number: Int = 1
}

let encoder = JSONEncoder()
let data = try! encoder.encode(Foo())
print(String(data: data, encoding: .utf8)!)

Body:
Yes, but you'll have to write your own encode(to:) implementation, you can't use the auto-generated one.

struct Foo: Codable {
    var string: String? = nil
    var number: Int = 1

    func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: CodingKeys.self)
        try container.encode(number, forKey: .number)
        try container.encode(string, forKey: .string)
    }
}

Encoding an optional directly will encode a null, like you're looking for.

If this is an important use case for you, you may consider opening a defect at bugs.swift.org to ask for a new OptionalEncodingStrategy flag to be added on JSONEncoder to match the existing DateEncodingStrategy, etc. (See below why this is likely impossible to actually implement in Swift today, but getting into the tracking system is still useful as Swift evolves.)

Edit: To Paulo's questions below, this dispatches to the generic encode<T: Encodable> version because Optional conforms to Encodable. This is implemented in Codable.swift this way:

extension Optional : Encodable /* where Wrapped : Encodable */ {
    @_inlineable // FIXME(sil-serialize-all)
    public func encode(to encoder: Encoder) throws {
        assertTypeIsEncodable(Wrapped.self, in: type(of: self))

        var container = encoder.singleValueContainer()
        switch self {
        case .none: try container.encodeNil()
        case .some(let wrapped): try (wrapped as! Encodable).__encode(to: &container)
        }
    }
}

This wraps the call to encodeNil, and I think letting stdlib handle Optionals as just another Encodable is better than treating them as a special case in our own encoder and calling encodeNil ourselves.

Another obvious question is why it works this way in the first place. Since Optional is Encodable, and the generated Encodable conformance encodes all the properties, why does "encode all the properties by hand" work differently? The answer is that the conformance generator includes a special case for Optionals:

// Now need to generate `try container.encode(x, forKey: .x)` for all
// existing properties. Optional properties get `encodeIfPresent`.
...

if (varType->getAnyNominal() == C.getOptionalDecl() ||
    varType->getAnyNominal() == C.getImplicitlyUnwrappedOptionalDecl()) {
  methodName = C.Id_encodeIfPresent;
}

This means that changing this behavior would require changing the auto-generated conformance, not JSONEncoder (which also means it's probably really hard to make configurable in today's Swift....)

ContentLicense: CC BY-SA 4.0


问:
Tkinter canvas & scrollbar with grid
I have a canvas in a frame

```<code>photoFrame = Frame(centerFrame, width=250, height=190, bg="#EBEBEB")
photoFrame.grid(row=0, column=1, sticky="nsew")
photoCanvas = Canvas(photoFrame, bg="#EBEBEB")
photoCanvas.grid(row=0, column=0, sticky="nsew")
</code>```

and I try to put a scrollbar to my canvas with this

```<code>photoScroll = Scrollbar(photoFrame, orient=VERTICAL)
photoScroll.config(command=photoCanvas.yview)
photoCanvas.config(yscrollcommand=photoScroll.set)
photoScroll.grid(row=0, column=1, sticky="ns")
</code>```

The scrollbar appears but it's disabled. Can you help me please ?

Sorry for my bad english.

In a for loop I add lots of Image button with this code

```<code>element = Button(photoCanvas, image = listPhotos[i], borderwidth=0, height = 200, width = 200, bg="#EBEBEB")
element.grid(row=rowPhoto, column=columnPhoto, padx=5, pady=5, sticky="nsew")
</code>```

Finnally I have this

```<code>    root = Tk()
    photoFrame = Frame(root, width=250, height=190, bg="#EBEBEB")

    photoCanvas = Canvas(photoFrame, bg="#EBEBEB")
    photoCanvas.grid(row=0, column=0, sticky="nsew")

    for i in range(0, len(listPhotos), 1):
       element = Button(photoCanvas, image = listPhotos[i], borderwidth=0, height = 200, width = 200, bg="#EBEBEB")
       element.grid(row=rowPhoto, column=columnPhoto, padx=5, pady=5, sticky="nsew")

    photoScroll=Scrollbar(photoFrame,orient=VERTICAL)
    photoScroll.config(command=photoCanvas.yview)
    photoCanvas.config(yscrollcommand=photoScroll.set)
    photoScroll.grid(row=0, column=1, sticky="ns")
</code>```

in my app, the purple rectangle is the next frame and I need a vertical scrollbar

Say if you have some questions

答:
One way to scroll a group of widgets is to put them (with grid of pack) inside a frame and put this frame inside a canvas.

The two key elements (besides connecting the scrollbar to the canvas) for the scrolling to work are:

Use canvas.create_window(x, y, window=frame) to put the frame inside the canvas so that it is treated like a canvas item.

Update the canvas scrollregion each time the size of the frame changes (for instance after adding a new widget) with canvas.configure(scrollregion=canvas.bbox('all')).

Here is an adaptation of the code of the question Python Tkinter scrollbar for frame, but using the widgets name from the OP's question and grid instead of pack:

```<code>import tkinter as tk

def update_scrollregion(event):
    photoCanvas.configure(scrollregion=photoCanvas.bbox("all"))

root = tk.Tk()

photoFrame = tk.Frame(root, width=250, height=190, bg="#EBEBEB")
photoFrame.grid()
photoFrame.rowconfigure(0, weight=1)
photoFrame.columnconfigure(0, weight=1)

photoCanvas = tk.Canvas(photoFrame, bg="#EBEBEB")
photoCanvas.grid(row=0, column=0, sticky="nsew")

canvasFrame = tk.Frame(photoCanvas, bg="#EBEBEB")
photoCanvas.create_window(0, 0, window=canvasFrame, anchor='nw')

for i in range(10):
   element = tk.Button(canvasFrame, text='Button %i' % i, borderwidth=0, bg="#EBEBEB")
   element.grid(padx=5, pady=5, sticky="nsew")

photoScroll = tk.Scrollbar(photoFrame, orient=tk.VERTICAL)
photoScroll.config(command=photoCanvas.yview)
photoCanvas.config(yscrollcommand=photoScroll.set)
photoScroll.grid(row=0, column=1, sticky="ns")

canvasFrame.bind("<Configure>", update_scrollregion)

root.mainloop()
</code>```

Title: Tkinter canvas & scrollbar with grid

Body:
I have a canvas in a frame

photoFrame = Frame(centerFrame, width=250, height=190, bg="#EBEBEB")
photoFrame.grid(row=0, column=1, sticky="nsew")
photoCanvas = Canvas(photoFrame, bg="#EBEBEB")
photoCanvas.grid(row=0, column=0, sticky="nsew")

and I try to put a scrollbar to my canvas with this

photoScroll = Scrollbar(photoFrame, orient=VERTICAL)
photoScroll.config(command=photoCanvas.yview)
photoCanvas.config(yscrollcommand=photoScroll.set)
photoScroll.grid(row=0, column=1, sticky="ns")

The scrollbar appears but it's disabled. Can you help me please ?

Sorry for my bad english.

In a for loop I add lots of Image button with this code

element = Button(photoCanvas, image = listPhotos[i], borderwidth=0, height = 200, width = 200, bg="#EBEBEB")
element.grid(row=rowPhoto, column=columnPhoto, padx=5, pady=5, sticky="nsew")

Finnally I have this

    root = Tk()
    photoFrame = Frame(root, width=250, height=190, bg="#EBEBEB")

    photoCanvas = Canvas(photoFrame, bg="#EBEBEB")
    photoCanvas.grid(row=0, column=0, sticky="nsew")

    for i in range(0, len(listPhotos), 1):
       element = Button(photoCanvas, image = listPhotos[i], borderwidth=0, height = 200, width = 200, bg="#EBEBEB")
       element.grid(row=rowPhoto, column=columnPhoto, padx=5, pady=5, sticky="nsew")

    photoScroll=Scrollbar(photoFrame,orient=VERTICAL)
    photoScroll.config(command=photoCanvas.yview)
    photoCanvas.config(yscrollcommand=photoScroll.set)
    photoScroll.grid(row=0, column=1, sticky="ns")

in my app, the purple rectangle is the next frame and I need a vertical scrollbar

Say if you have some questions

Body:
One way to scroll a group of widgets is to put them (with grid of pack) inside a frame and put this frame inside a canvas.

The two key elements (besides connecting the scrollbar to the canvas) for the scrolling to work are:

Use canvas.create_window(x, y, window=frame) to put the frame inside the canvas so that it is treated like a canvas item.

Update the canvas scrollregion each time the size of the frame changes (for instance after adding a new widget) with canvas.configure(scrollregion=canvas.bbox('all')).

Here is an adaptation of the code of the question Python Tkinter scrollbar for frame, but using the widgets name from the OP's question and grid instead of pack:

import tkinter as tk

def update_scrollregion(event):
    photoCanvas.configure(scrollregion=photoCanvas.bbox("all"))

root = tk.Tk()

photoFrame = tk.Frame(root, width=250, height=190, bg="#EBEBEB")
photoFrame.grid()
photoFrame.rowconfigure(0, weight=1)
photoFrame.columnconfigure(0, weight=1)

photoCanvas = tk.Canvas(photoFrame, bg="#EBEBEB")
photoCanvas.grid(row=0, column=0, sticky="nsew")

canvasFrame = tk.Frame(photoCanvas, bg="#EBEBEB")
photoCanvas.create_window(0, 0, window=canvasFrame, anchor='nw')

for i in range(10):
   element = tk.Button(canvasFrame, text='Button %i' % i, borderwidth=0, bg="#EBEBEB")
   element.grid(padx=5, pady=5, sticky="nsew")

photoScroll = tk.Scrollbar(photoFrame, orient=tk.VERTICAL)
photoScroll.config(command=photoCanvas.yview)
photoCanvas.config(yscrollcommand=photoScroll.set)
photoScroll.grid(row=0, column=1, sticky="ns")

canvasFrame.bind("<Configure>", update_scrollregion)

root.mainloop()


问:
Failed to add API
I followed the instuctions on
https://github.com/igdb/api-android-java/blob/master/README.md
and got this error

Error:Execution failed for task ':app:preDebugAndroidTestBuild'.
  Conflict with dependency 'com.android.support.test:runner' in project ':app'. Resolved versions for app (0.5) and test app (1.0.1) differ. See https://d.android.com/r/tools/test-apk-dependency-conflicts.html for details.

build.gradle project

```<code>buildscript {

    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.0'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        google()
        jcenter()
        maven { url 'https://jitpack.io' }
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
</code>```

build.gradle app

```<code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    defaultConfig {
        applicationId "com.example.ofirv.gamesugest"
        minSdkVersion 21
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:26.1.0'
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
    compile 'com.github.igdb:api-android-java:master-SNAPSHOT'
}
</code>```

Thank you

答:
Replace this line     compile 'com.github.igdb:api-android-java:master-SNAPSHOT' by the code below : (It should work. I have tested it for you)

```<code>  implementation ('com.github.igdb:api-android-java:master-SNAPSHOT'){
        exclude module: 'runner'
    }
</code>```

Title: Failed to add API

Body:
I followed the instuctions on
https://github.com/igdb/api-android-java/blob/master/README.md
and got this error

Error:Execution failed for task ':app:preDebugAndroidTestBuild'.
  Conflict with dependency 'com.android.support.test:runner' in project ':app'. Resolved versions for app (0.5) and test app (1.0.1) differ. See https://d.android.com/r/tools/test-apk-dependency-conflicts.html for details.

build.gradle project

buildscript {

    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.0'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        google()
        jcenter()
        maven { url 'https://jitpack.io' }
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

build.gradle app

apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    defaultConfig {
        applicationId "com.example.ofirv.gamesugest"
        minSdkVersion 21
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:26.1.0'
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
    compile 'com.github.igdb:api-android-java:master-SNAPSHOT'
}

Thank you

Body:
Replace this line     compile 'com.github.igdb:api-android-java:master-SNAPSHOT' by the code below : (It should work. I have tested it for you)

  implementation ('com.github.igdb:api-android-java:master-SNAPSHOT'){
        exclude module: 'runner'
    }


问:
java.lang.NoClassDefFoundError: com/fasterxml/jackson/core/util/DefaultIndenter
I am newbie to spring framework. I am trying to work on Maven. I just want to open an index page when the project is run but was unable to do it

Error says java.lang.NoClassDefFoundError:com/fasterxml/jackson/core/util/DefaultIndenter
Error here

pom.xml of parent

```<code><dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>javax</groupId>
            <artifactId>javaee-web-api</artifactId>
            <version>7.0</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>4.3.12.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>4.3.12.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>6.0.6</version>
        </dependency>

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.9.2</version>
        </dependency>

        <dependency>
            <groupId>com.nishan</groupId>
            <artifactId>LifeStyle</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>
    </dependencies>
</dependencyManagement>
</code>```

web.xml of WebModule

```<code>    <?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
     version="3.1">

    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
</web-app>
</code>```

dispatcher-servlet.xml

```<code>    <?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:p="http://www.springframework.org/schema/p"

       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
          http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
          http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
">

    <context:component-scan base-package="com.nishan.webmodule"/>
    <mvc:annotation-driven/>
    <mvc:resources mapping="/static/**" location="/WEB-INF/assets"/>

    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"
    p:prefix="/WEB-INF/views/" p:suffix=".jsp"/>

</beans>
</code>```

servlet page to navigate to index page

```<code>   @Controller
@RequestMapping(value="/")
public class DefaultServlet {

    @RequestMapping(method=RequestMethod.GET)
    public String index() {
        return "index";
    }
}
</code>```

答:
As per documentation for the <dependencyManagement> element (emphasis mine):

"Default dependency information for projects that inherit fromthis one. The dependencies in this section are not immediately resolved. Instead, when a POM derived from this one declares a dependency described by a matching groupId and artifactId, the version and other values from this section are used for that dependency if they were not already specified."

In other words, you are probably lacking the proper <dependency> definition in the module POM.

Body:
I am newbie to spring framework. I am trying to work on Maven. I just want to open an index page when the project is run but was unable to do it

Error says java.lang.NoClassDefFoundError:com/fasterxml/jackson/core/util/DefaultIndenter
Error here

pom.xml of parent

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>javax</groupId>
            <artifactId>javaee-web-api</artifactId>
            <version>7.0</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>4.3.12.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>4.3.12.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>6.0.6</version>
        </dependency>

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.9.2</version>
        </dependency>

        <dependency>
            <groupId>com.nishan</groupId>
            <artifactId>LifeStyle</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>
    </dependencies>
</dependencyManagement>

web.xml of WebModule

    <?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
     version="3.1">

    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
</web-app>

dispatcher-servlet.xml

    <?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:p="http://www.springframework.org/schema/p"

       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
          http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
          http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
">

    <context:component-scan base-package="com.nishan.webmodule"/>
    <mvc:annotation-driven/>
    <mvc:resources mapping="/static/**" location="/WEB-INF/assets"/>

    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"
    p:prefix="/WEB-INF/views/" p:suffix=".jsp"/>

</beans>

servlet page to navigate to index page

   @Controller
@RequestMapping(value="/")
public class DefaultServlet {

    @RequestMapping(method=RequestMethod.GET)
    public String index() {
        return "index";
    }
}


问:
Compare only time from datetime in entity framework 6 with odp.net Oracle 12c
I am using entity framework 6 with oracle and Sql. Timespan datatype is not working with oracle. so i changed datatype to datetime. now i want to compare only time in datetime with Linq query. ex.

```<code>var db0010016 = _idb0010016Rep.GetAll().Where(e => e.ExecutionTime.TimeOfDay == viewmodel.ExecutionTime).FirstOrDefault();
</code>```

in above example e.ExecutionTime is datetime  and viewmodel.ExecutionTime is timespan. i am using timeofday function to convert it to timespan

above query failed to execute so i used DbFunctions.CreateTime() function

```<code>var db0010016 = _idb0010016Rep.FindBy(e => DbFunctions.CreateTime(e.ExecutionTime.Hour, e.ExecutionTime.Minute, e.ExecutionTime.Second) == exetime).FirstOrDefault();
</code>```

above ex exetime is timespan.still i am getting below error

```<code>{"Invalid parameter binding\r\nParameter name: ParameterName"}
</code>```

答:
Can you convert both oracle timespan and SQL datatime in string and then compare it. Like:</p>

```<code>var db0010016 = _idb0010016Rep.GetAll().Where(e => e.ExecutionTime.TimeOfDay.ToString() == viewmodel.ExecutionTime.ToString()).FirstOrDefault()
</code>```

Body:
I am using entity framework 6 with oracle and Sql. Timespan datatype is not working with oracle. so i changed datatype to datetime. now i want to compare only time in datetime with Linq query. ex.

var db0010016 = _idb0010016Rep.GetAll().Where(e => e.ExecutionTime.TimeOfDay == viewmodel.ExecutionTime).FirstOrDefault();

in above example e.ExecutionTime is datetime  and viewmodel.ExecutionTime is timespan. i am using timeofday function to convert it to timespan

above query failed to execute so i used DbFunctions.CreateTime() function

var db0010016 = _idb0010016Rep.FindBy(e => DbFunctions.CreateTime(e.ExecutionTime.Hour, e.ExecutionTime.Minute, e.ExecutionTime.Second) == exetime).FirstOrDefault();

above ex exetime is timespan.still i am getting below error

{"Invalid parameter binding\r\nParameter name: ParameterName"}

Body:
Can you convert both oracle timespan and SQL datatime in string and then compare it. Like:

var db0010016 = _idb0010016Rep.GetAll().Where(e => e.ExecutionTime.TimeOfDay.ToString() == viewmodel.ExecutionTime.ToString()).FirstOrDefault()


问:
Can NumPy take care that an array is (nonstrictly) increasing along one axis?
Is there a function in numpy to guarantee or rather fix an array such that it is (nonstrictly) increasing along one particular axis?
For example, I have the following 2D array:

```<code>X = array([[1, 2, 1, 4, 5],
           [0, 3, 1, 5, 4]])
</code>```

the output of np.foobar(X) should return

```<code>array([[1, 2, 2, 4, 5],
       [0, 3, 3, 5, 5]])
</code>```

Does foobar exist or do I need to do that manually by using something like np.diff and some smart indexing?

答:
Use np.maximum.accumulate for a running (accumulated) max value along that axis to ensure the strictly increasing criteria -

```<code>np.maximum.accumulate(X,axis=1)
</code>```

Sample run -

```<code>In [233]: X
Out[233]:
array([[1, 2, 1, 4, 5],
       [0, 3, 1, 5, 4]])

In [234]: np.maximum.accumulate(X,axis=1)
Out[234]:
array([[1, 2, 2, 4, 5],
       [0, 3, 3, 5, 5]])
</code>```

For memory efficiency, we can assign it back to the input for in-situ changes with its out argument.

Runtime tests

Case #1 : Array as input

```<code>In [254]: X = np.random.rand(1000,1000)

In [255]: %timeit np.maximum.accumulate(X,axis=1)
1000 loops, best of 3: 1.69 ms per loop

# @cᴏʟᴅsᴘᴇᴇᴅ's pandas soln using df.cummax
In [256]: %timeit pd.DataFrame(X).cummax(axis=1).values
100 loops, best of 3: 4.81 ms per loop
</code>```

Case #2 : Dataframe as input

```<code>In [257]: df = pd.DataFrame(np.random.rand(1000,1000))

In [258]: %timeit np.maximum.accumulate(df.values,axis=1)
1000 loops, best of 3: 1.68 ms per loop

# @cᴏʟᴅsᴘᴇᴇᴅ's pandas soln using df.cummax
In [259]: %timeit df.cummax(axis=1)
100 loops, best of 3: 4.68 ms per loop
</code>```

Body:
Is there a function in numpy to guarantee or rather fix an array such that it is (nonstrictly) increasing along one particular axis?
For example, I have the following 2D array:

X = array([[1, 2, 1, 4, 5],
           [0, 3, 1, 5, 4]])

the output of np.foobar(X) should return

array([[1, 2, 2, 4, 5],
       [0, 3, 3, 5, 5]])

Does foobar exist or do I need to do that manually by using something like np.diff and some smart indexing?

Body:
Use np.maximum.accumulate for a running (accumulated) max value along that axis to ensure the strictly increasing criteria -

np.maximum.accumulate(X,axis=1)

Sample run -

In [233]: X
Out[233]:
array([[1, 2, 1, 4, 5],
       [0, 3, 1, 5, 4]])

In [234]: np.maximum.accumulate(X,axis=1)
Out[234]:
array([[1, 2, 2, 4, 5],
       [0, 3, 3, 5, 5]])

For memory efficiency, we can assign it back to the input for in-situ changes with its out argument.

Runtime tests

Case #1 : Array as input

In [254]: X = np.random.rand(1000,1000)

In [255]: %timeit np.maximum.accumulate(X,axis=1)
1000 loops, best of 3: 1.69 ms per loop

# @cᴏʟᴅsᴘᴇᴇᴅ's pandas soln using df.cummax
In [256]: %timeit pd.DataFrame(X).cummax(axis=1).values
100 loops, best of 3: 4.81 ms per loop

Case #2 : Dataframe as input

In [257]: df = pd.DataFrame(np.random.rand(1000,1000))

In [258]: %timeit np.maximum.accumulate(df.values,axis=1)
1000 loops, best of 3: 1.68 ms per loop

# @cᴏʟᴅsᴘᴇᴇᴅ's pandas soln using df.cummax
In [259]: %timeit df.cummax(axis=1)
100 loops, best of 3: 4.68 ms per loop


问:
Excel connection manager failed with error code 0xC0202009
I have ssis packages made  in Microsoft vs2008, for generating  reports in excel formats. For excel connection manager version excel version used is 'Microsoft Excel 97-2003. Till day before yesterday it was working fine. But from  yesterday it was throwing error for excel version. But when I changed version to ' Microsoft Excel 2007'. It works fine.
-No update in excel
-No update in vs2008.
- running package using SQL server agent

Thanks in advance.

答: It looks like that one of the latest Windows Security updates broke the Excel/Jet driver. Workaround would be to uninstall one of the following (KB 4040685,KB 4041693, KB 4041687) and reboot the server</p>


问:
How to dynamically set content to TinyMCE editor
I'm trying to dynamically set the content to the TinyMCE editor, based on the selected option from the drop down menu.

```<code><app-tinymce [elementId]="'myEditor'" [content]="myContentVar"></app-tinymce>
</code>```

The variable myContentVar gets updated correctly every time the drop down menu selection is changed.

```<code>onSelectionChanged(selectedValue: string){
    this.myContentVar = selectedValue;
}
</code>```

But still, the TinyMCE editor always shows blank. {{myContentVar}} does show the correct value though.

Below is the configuration setup for TinyMCE.

```<code>tinymce.init({
      selector: '#' + this.elementId,
      plugins: ['link image code charmap preview anchor'],
      toolbar: 'undo redo |  formatselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent',

      setup: editor => {
        this.editor = editor;

        editor.on('change', () => {
          const content = editor.getContent();
          this.editorContent = content;
          this.onEditorContentChange.emit(content);
          this.onModelChange(content);
          this.onTouch(content);

          if (this._controlContainer) {
            if (this.formControlName) {
              this.control = this._controlContainer.control.get(this.formControlName);
              if (this.control) {
                this.control.setValue(new RichFieldTextModel(this.formControlName, this.elementId, this.editorContent));
              }
            }
          }
        });
      }
    });
</code>```

答:
The issue you are dealing with is that once TinyMCE is instantiated on the page it won't look back at the <textarea> to see if that has changed.

The "on change" code you have in your example is focused on placing the latest content from TinyMCE back into the underlying form field as things are changed in the editor.  Something like that is common when injecting TinyMCE in any of the modern frameworks like Vue, React, or Angular.  What does not happen based on your code is the reverse - updating TinyMCE when the form field changes.

What I would suggest is that use TinyMCE's APIs (specifically setContent()) to update the editor when the select list is changed.  Using that API will trigger your existing code to update the underlying form field after you perform the setContent().

If you only have one TinyMCE instance on the page you can use something like:

```<code>onSelectionChanged(selectedValue: string){
    //assumes selectedValue is the HTML you want to insert
    tinymce.activeEditor.setContent(selectedValue);
}
</code>```

Body:
I'm trying to dynamically set the content to the TinyMCE editor, based on the selected option from the drop down menu.

<app-tinymce [elementId]="'myEditor'" [content]="myContentVar"></app-tinymce>

The variable myContentVar gets updated correctly every time the drop down menu selection is changed.

onSelectionChanged(selectedValue: string){
    this.myContentVar = selectedValue;
}

But still, the TinyMCE editor always shows blank. {{myContentVar}} does show the correct value though.

Below is the configuration setup for TinyMCE.

tinymce.init({
      selector: '#' + this.elementId,
      plugins: ['link image code charmap preview anchor'],
      toolbar: 'undo redo |  formatselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent',

      setup: editor => {
        this.editor = editor;

        editor.on('change', () => {
          const content = editor.getContent();
          this.editorContent = content;
          this.onEditorContentChange.emit(content);
          this.onModelChange(content);
          this.onTouch(content);

          if (this._controlContainer) {
            if (this.formControlName) {
              this.control = this._controlContainer.control.get(this.formControlName);
              if (this.control) {
                this.control.setValue(new RichFieldTextModel(this.formControlName, this.elementId, this.editorContent));
              }
            }
          }
        });
      }
    });

Body:
The issue you are dealing with is that once TinyMCE is instantiated on the page it won't look back at the <textarea> to see if that has changed.

The "on change" code you have in your example is focused on placing the latest content from TinyMCE back into the underlying form field as things are changed in the editor.  Something like that is common when injecting TinyMCE in any of the modern frameworks like Vue, React, or Angular.  What does not happen based on your code is the reverse - updating TinyMCE when the form field changes.

What I would suggest is that use TinyMCE's APIs (specifically setContent()) to update the editor when the select list is changed.  Using that API will trigger your existing code to update the underlying form field after you perform the setContent().

If you only have one TinyMCE instance on the page you can use something like:

onSelectionChanged(selectedValue: string){
    //assumes selectedValue is the HTML you want to insert
    tinymce.activeEditor.setContent(selectedValue);
}


问:
for loop break after using gregexpr
I'm going back to R after a few months without practicing and I am kind of dumbfounded from what happens there

```<code>for (year in c('09', '08', '10', '11',
          '12', '13', '14', '15')){

  col <- paste("price_", year, sep="")
  print(col)

  mpt <- gregexpr("P\\.T.*(\\d|,|\\.)+", data[col], perl=TRUE)
  print('done')
  pt_matches = regmatches(data[col], mpt)
  print("matches")}
</code>```

It seems fairly easy and I expected to have this output:

```<code>"price_09"
"done"
"matches"
"price_08"
... # and so on
</code>```

However, R does not seem to execute even a full loop, I get only:

```<code>"price_09"
"done"
</code>```

And nothing else. I don't get an error message, as if assigning mpt acted as a 'break'. Do I miss something obvious ?

If I delete the mptassignment I get the print "matches" printed but it obviously crashes further down the road

答:
According to ?gregexpr, the text argument

```<code>gregexpr(pattern, text, ignore.case = FALSE, perl = FALSE,
     fixed = FALSE, useBytes = FALSE)
</code>```

takes a vector

text - a character vector where matches are sought, or an object which
  can be coerced by as.character to a character vector. Long vectors are
  supported.

Here, the data[col] is still a data.frame.  In order to convert it to vector, use the [[

Using a reproducible example,

```<code>d1 <- data.frame(v1 = c('pine', 'tree', 'chill'))
regmatches(d1['v1'], gregexpr('pi', d1['v1']))
#$v1
#character(0)

regmatches(d1[['v1']], gregexpr('pi', d1[['v1']]))
#[[1]]
#[1] "pi"

#[[2]]
#character(0)

#[[3]]
#character(0)
</code>```

Title: for loop break after using gregexpr

Body:
I'm going back to R after a few months without practicing and I am kind of dumbfounded from what happens there

for (year in c('09', '08', '10', '11',
          '12', '13', '14', '15')){

  col <- paste("price_", year, sep="")
  print(col)

  mpt <- gregexpr("P\\.T.*(\\d|,|\\.)+", data[col], perl=TRUE)
  print('done')
  pt_matches = regmatches(data[col], mpt)
  print("matches")}

It seems fairly easy and I expected to have this output:

"price_09"
"done"
"matches"
"price_08"
... # and so on

However, R does not seem to execute even a full loop, I get only:

"price_09"
"done"

And nothing else. I don't get an error message, as if assigning mpt acted as a 'break'. Do I miss something obvious ?

If I delete the mptassignment I get the print "matches" printed but it obviously crashes further down the road

Body:
According to ?gregexpr, the text argument

gregexpr(pattern, text, ignore.case = FALSE, perl = FALSE,
     fixed = FALSE, useBytes = FALSE)

takes a vector

text - a character vector where matches are sought, or an object which
  can be coerced by as.character to a character vector. Long vectors are
  supported.

Here, the data[col] is still a data.frame.  In order to convert it to vector, use the [[

Using a reproducible example,

d1 <- data.frame(v1 = c('pine', 'tree', 'chill'))
regmatches(d1['v1'], gregexpr('pi', d1['v1']))
#$v1
#character(0)

regmatches(d1[['v1']], gregexpr('pi', d1[['v1']]))
#[[1]]
#[1] "pi"

#[[2]]
#character(0)

#[[3]]
#character(0)


问:
SQL Server 2012 Server Name duplicated
I just setup SQL Server 2012 on a test server, and I can't figure out why my Server name is being duplicated.  Should be 'DEVSVR' not 'DEVSVR\DEVSVR'

I've tried renaming my server name w/ sp_dropserver and sp_addserver which looks to have worked when I run a query on sys.servers but @@SERVERNAME still shows up as 'DEVSVR\DEVSVR'

Since this is my first time having to install SQL Server, I'm thinking I might have missed something during installation.  Any insight on how I can rename this server without having to resort to uninstalling and re-installing SQL Server would be greatly appreciated.  Thanks in advance.

答:
Looks like I didn't have it set as my default instance.  I did the following...

Open SQL Server Configuration Manager

Click SQL Server Network Configuration

Click Protocols for INSTANCENAME you want to make available (i.e. SQLExpress)

Right-click TCP/IP and click Enabled

Right-click TCP/IP and go to Properties

Set TCP Port to 1433 in the IPAll Section. and Clear TCP Dynamic Ports

Go to SQL Server Services

Right-click your SQL Server (INSTANCENAME) and click Restart

Reference: SQL Server, convert a named instance to default instance?

Title: SQL Server 2012 Server Name duplicated


问:
How to show all tables/views in ER diagram with DbVisualizer
Is there a setting in DbVisualizer to display all tables in the "References" tab? I am using the free version (10.0) and when I click on a table with the References tab open I only see the direct relationships from this table. I'd like to see all tables in the schema.</p>

答: In the left-hand pane, double-click on the database name while having the References tab open to have all tables displayed.</p>


问:
Unmanaged method calls taking high CPU
I have an unmanaged method that when executed takes high CPU. Is it safe to say that unmanaged calls naturally take high CPU?

Following is the code:

```<code> public void ReadAt(long ulOffset, IntPtr pv, int cb, out UIntPtr pcbRead)
 {
        Marshal.Copy(buffer, 0, pv, bytesRead);
        pcbRead = new UIntPtr((uint)bytesRead);
        bytesRead = 0;

        if (streamClosed)
            buffer = null;
 }
</code>```

答:
No it's not safe to generalize this. Both managed and unmanaged methods take whatever CPU they need to execute their code.

When someone says unmanaged calls may be expensive they usually mean the overhead from switching between managed and unmanaged. This particular cost will only matter if you do unmanaged calls in tight loops like per-pixel processing on a large image.

Some of the overhead of unmanaged calls can be removed by proper attributes, in particular it is possible to move the security checks from per-call to assembly-load-time. This is of course already done for all unmanaged functions in the .NET framework.

The best guess (without more context) about why you are spending so much time in that function is that you are either (a) copying a very large array or (b) you are calling the method very often in a loop.

In the first case the overhead from switching between managed-unmanaged for Marshal.Copy is negligible, copying a large memory block will always saturate the CPU (ie. 100% usage of one core). There is nothing you can do except eliminating the copy operation completely (which may or may not be possible, depending on how you use the buffers).

If you are in the second case and the arrays are very small it may be worth switching to a purely managed loop. But don't do this without measuring, it's easy to guess wrong, and the unmanaged implementation of Marshal.Copy can pull more tricks than the managed JIT to make up for the overhead.

PS: You might want to read this - high CPU usage by itself is no bad thing, the computer is just trying to get things done as fast as possible. Managed or unmanaged does not matter, if your usage is below 100% (per core) it just means your computer got nothing to do.

Title: Unmanaged method calls taking high CPU

Body:
I have an unmanaged method that when executed takes high CPU. Is it safe to say that unmanaged calls naturally take high CPU?

Following is the code:

 public void ReadAt(long ulOffset, IntPtr pv, int cb, out UIntPtr pcbRead)
 {
        Marshal.Copy(buffer, 0, pv, bytesRead);
        pcbRead = new UIntPtr((uint)bytesRead);
        bytesRead = 0;

        if (streamClosed)
            buffer = null;
 }


问:
OpenModelica solver reaches maximal number of iteration but not able to find root
I am trying to simulate a 1D system of 3 sliding bodies as I have explained here:

and here is the code I have implemented:

```<code>model friction
  //constants
  parameter Real muk = 0.2;
  parameter Real mus = 0.3;
  parameter Real m1 = 1.0;
  parameter Real m2 = 2.0;
  parameter Real m3 = 3.0;
  parameter Real Fn12 = 3.0;
  parameter Real Fn23 = 2.0;
  parameter Real absTol = 0.1;
  //variables
  Real X1, X2, X3, V1, V2, V3, A1, A2, A3, F1, F2, F3, Ff12, Ff23, Fs12, Fs23;

initial equation
  X1 = 0;
  X2 = 0;
  X3 = 0;
  V1 = 0;
  V2 = 0;
  V3 = 0;
equation
  F1 = 2 * sin(5 * time);
  F2 = 2 * sin(7 * time);
  F3 = 3 * sin(11 * time);
  V1 = der(X1);
  V2 = der(X2);
  V3 = der(X3);
  A1 = der(V1);
  A2 = der(V2);
  A3 = der(V3);
  m1 * A1 = F1 - Ff12;
  m2 * A2 = F2 + Ff12 - Ff23;
  m3 * A3 = F3 + Ff23;
  Fs12 = (m2 * F1 - m1 * (F2-Ff23)) / (m1 + m2);
  Fs23 = (m3 * (F2 + Ff12) - m2 * F3) / (m2 + m3);

  if abs(V1 - V2) < absTol and abs(Fs12) < mus * Fn12 then
    Ff12 = Fs12;
  else
    Ff12 = muk * Fn12 * sign(V1 - V2);
  end if;

  if abs(V3 - V2) < absTol and abs(Fs23) < mus * Fn23 then
    Ff23 = Fs23;
  else
    Ff23 = muk * Fn23 * sign(V2 - V3);
  end if;

end friction;
</code>```

Wolfram SystemModeler is able to run the simulation till t=6sec, but the results are not what I expect as I have explained here. And when I use OpenModelica to solve the simulation I get the error below:

C:/Users/foo/AppData/Local/Temp/OpenModelica/OMEdit/friction.exe -port=64457 -logFormat=xmltcp -override=startTime=0,stopTime=10,stepSize=0.02,tolerance=1e-6,solver=dassl,outputFormat=mat,variableFilter=.* -r=friction_res.mat -jacobian=coloredNumerical -w -lv=LOG_STATS
  Warning: maximal number of iteration reached but no root found
  Warning: maximal number of iteration reached but no root found
  Error solving nonlinear system 42 at time 0.2
  Error solving nonlinear system 42 at time 0.2
  nonlinear system 42 fails: at t=0.2
  Solving non-linear system 42 failed at time=0.2.
  For more information please use -lv LOG_NLS.
  Simulation process failed. Exited with code -1.

I would appreciate if you could help me know what is the problem and how I can solve it?

答:
You are trying to write your own Friction model.

In Modelica the normal way is to use s-parameterization by e.g. inheriting from: Modelica.Mechanics.Translational.Interfaces.PartialFriction (or using an existing model doing that).

It's documentation is online at:
http://doc.modelica.org/help/Modelica_Mechanics_Rotational_UsersGuide.html#Modelica.Mechanics.Rotational.UsersGuide.ModelingOfFriction

Specifically you have Fs12 and Fs23 that are maximum friction force for adherence, which works if the are constant  - but here they depend on Ff12 and Ff23 - and they in turn depend on Fs12 and Fs23; which does not work.

Body:
I am trying to simulate a 1D system of 3 sliding bodies as I have explained here:

and here is the code I have implemented:

model friction
  //constants
  parameter Real muk = 0.2;
  parameter Real mus = 0.3;
  parameter Real m1 = 1.0;
  parameter Real m2 = 2.0;
  parameter Real m3 = 3.0;
  parameter Real Fn12 = 3.0;
  parameter Real Fn23 = 2.0;
  parameter Real absTol = 0.1;
  //variables
  Real X1, X2, X3, V1, V2, V3, A1, A2, A3, F1, F2, F3, Ff12, Ff23, Fs12, Fs23;

initial equation
  X1 = 0;
  X2 = 0;
  X3 = 0;
  V1 = 0;
  V2 = 0;
  V3 = 0;
equation
  F1 = 2 * sin(5 * time);
  F2 = 2 * sin(7 * time);
  F3 = 3 * sin(11 * time);
  V1 = der(X1);
  V2 = der(X2);
  V3 = der(X3);
  A1 = der(V1);
  A2 = der(V2);
  A3 = der(V3);
  m1 * A1 = F1 - Ff12;
  m2 * A2 = F2 + Ff12 - Ff23;
  m3 * A3 = F3 + Ff23;
  Fs12 = (m2 * F1 - m1 * (F2-Ff23)) / (m1 + m2);
  Fs23 = (m3 * (F2 + Ff12) - m2 * F3) / (m2 + m3);

  if abs(V1 - V2) < absTol and abs(Fs12) < mus * Fn12 then
    Ff12 = Fs12;
  else
    Ff12 = muk * Fn12 * sign(V1 - V2);
  end if;

  if abs(V3 - V2) < absTol and abs(Fs23) < mus * Fn23 then
    Ff23 = Fs23;
  else
    Ff23 = muk * Fn23 * sign(V2 - V3);
  end if;

end friction;

Wolfram SystemModeler is able to run the simulation till t=6sec, but the results are not what I expect as I have explained here. And when I use OpenModelica to solve the simulation I get the error below:

C:/Users/foo/AppData/Local/Temp/OpenModelica/OMEdit/friction.exe -port=64457 -logFormat=xmltcp -override=startTime=0,stopTime=10,stepSize=0.02,tolerance=1e-6,solver=dassl,outputFormat=mat,variableFilter=.* -r=friction_res.mat -jacobian=coloredNumerical -w -lv=LOG_STATS
  Warning: maximal number of iteration reached but no root found
  Warning: maximal number of iteration reached but no root found
  Error solving nonlinear system 42 at time 0.2
  Error solving nonlinear system 42 at time 0.2
  nonlinear system 42 fails: at t=0.2
  Solving non-linear system 42 failed at time=0.2.
  For more information please use -lv LOG_NLS.
  Simulation process failed. Exited with code -1.

I would appreciate if you could help me know what is the problem and how I can solve it?


问:
Selecting only numeric columns from a data frame
Suppose, you have a data.frame like this: </p>

```<code>x <- data.frame(v1=1:20,v2=1:20,v3=1:20,v4=letters[1:20])
</code>```

<p>How would you select only those columns in x that are numeric? </p>

答:
The library PCAmixdata has functon splitmix that splits quantitative(Numerical data) and qualitative (Categorical data) of a given dataframe "YourDataframe" as shown below: </p>

```<code>install.packages("PCAmixdata")
library(PCAmixdata)
split <- splitmix(YourDataframe)
X1 <- split$X.quanti(Gives numerical columns in the dataset)
X2 <- split$X.quali (Gives categorical columns in the dataset)
</code>```

Body:
Suppose, you have a data.frame like this:

x <- data.frame(v1=1:20,v2=1:20,v3=1:20,v4=letters[1:20])

How would you select only those columns in x that are numeric?

Body:
The library PCAmixdata has functon splitmix that splits quantitative(Numerical data) and qualitative (Categorical data) of a given dataframe "YourDataframe" as shown below:

install.packages("PCAmixdata")
library(PCAmixdata)
split <- splitmix(YourDataframe)
X1 <- split$X.quanti(Gives numerical columns in the dataset)
X2 <- split$X.quali (Gives categorical columns in the dataset)


问:
Create Objects of inner Component of Object of outer Component
Is it possible to do something like this:

```<code>import QtQuick 2.7
import QtQuick.Window 2.2

Window{
    id: root_
    visible: true
    width: 300
    height: 300

    Component {
        id:compouter

        Column{
            anchors.fill: parent

            Component {
                id: compinner

                Rectangle {
                    width:parent.width
                    height:parent.height/2
                }
            }
        }
    }

    Component.onCompleted: {

        var c = compouter.createObject(this)
        //var d = c.compinner.createObject(c, {"color": "green"})
        //var e = c.compinner.createObject(c, {"color": "red"})
    }
}
</code>```

That is, I want to create multiple Objects inside the outer object (after the outer object was created). However this isn't possible, as I get the error:
TypeError: Cannot call method 'createObject' of undefined

Is there any workaround for this? Is it maybe only possible to instantiate all inner objects during the instantiation of the outer object?

答:
Ok, I found a workaround through sending a signal to the outter object:

```<code>import QtQuick 2.7
import QtQuick.Window 2.2

Window{
    id: root_
    visible: true
    width: 300
    height: 300

    Component {
        id:compouter

        Column{
            anchors.fill: parent
            signal createRect(var color)

            onCreateRect: {

                compinner.createObject(this, {"color": color})
            }

            Component {
                id: compinner

                Rectangle {
                    width:parent.width
                    height:parent.height/2
               }
            }
        }
     }

    Component.onCompleted: {

        var c = compouter.createObject(this)
        c.createRect("green")
        c.createRect("red")
    }
</code>```

It's working, but maybe there is some more generic approach to this (see the accepted answer). As the poster suggested, calling a function would be semantically more clean than sending a signal

Body:
Is it possible to do something like this:

import QtQuick 2.7
import QtQuick.Window 2.2

Window{
    id: root_
    visible: true
    width: 300
    height: 300

    Component {
        id:compouter

        Column{
            anchors.fill: parent

            Component {
                id: compinner

                Rectangle {
                    width:parent.width
                    height:parent.height/2
                }
            }
        }
    }

    Component.onCompleted: {

        var c = compouter.createObject(this)
        //var d = c.compinner.createObject(c, {"color": "green"})
        //var e = c.compinner.createObject(c, {"color": "red"})
    }
}

That is, I want to create multiple Objects inside the outer object (after the outer object was created). However this isn't possible, as I get the error:
TypeError: Cannot call method 'createObject' of undefined

Is there any workaround for this? Is it maybe only possible to instantiate all inner objects during the instantiation of the outer object?

Body:
Ok, I found a workaround through sending a signal to the outter object:

import QtQuick 2.7
import QtQuick.Window 2.2

Window{
    id: root_
    visible: true
    width: 300
    height: 300

    Component {
        id:compouter

        Column{
            anchors.fill: parent
            signal createRect(var color)

            onCreateRect: {

                compinner.createObject(this, {"color": color})
            }

            Component {
                id: compinner

                Rectangle {
                    width:parent.width
                    height:parent.height/2
               }
            }
        }
     }

    Component.onCompleted: {

        var c = compouter.createObject(this)
        c.createRect("green")
        c.createRect("red")
    }

It's working, but maybe there is some more generic approach to this (see the accepted answer). As the poster suggested, calling a function would be semantically more clean than sending a signal


问:
Using buttons to "simulate" mouse-up, mouse-move, and mouse-down events
Hello

I'm currently working on a project that is very similar to the following codepen that I found a long while ago. It's essential a Tinder-like application;

https://codepen.io/suez/pen/MaeVBy

Within the codepen is the following JavaScript/jQuery:

```<code>function pullChange() {
    animating = true;
    deg = pullDeltaX / 10;
    $card.css("transform", "translateX("+ pullDeltaX +"px) rotate("+ deg +"deg)");

    var opacity = pullDeltaX / 100;
    var rejectOpacity = (opacity >= 0) ? 0 : Math.abs(opacity);
    var likeOpacity = (opacity <= 0) ? 0 : opacity;
    $cardReject.css("opacity", rejectOpacity);
    $cardLike.css("opacity", likeOpacity);
};

$(document).on("mousedown touchstart", ".demo__card:not(.inactive)", function(e) {
      if (animating) return;

      $card = $(this);
      $cardReject = $(".demo__card__choice.m--reject", $card);
      $cardLike = $(".demo__card__choice.m--like", $card);
      var startX = e.pageX || e.originalEvent.touches[0].pageX;

      $(document).on("mousemove touchmove", function(e) {
        var x = e.pageX || e.originalEvent.touches[0].pageX;
        pullDeltaX = (x - startX);
        if (!pullDeltaX) return;
        pullChange();
      });

      $(document).on("mouseup touchend", function() {
        $(document).off("mousemove touchmove mouseup touchend");
        if (!pullDeltaX) return; // prevents from rapid click events
        release();
      });
});
</code>```

What I'm looking to achieve is the implementation of two buttons to "simulate" the mouse dragging. So - if you play with the codepen - you'll see that it's possible to drag the cards left and right. A "like" or "dislike" decision is then made based upon how far left or right it was dragged. Also, if you drag a card too far or too little in one direction, the card will snap to a set point upon release.

I want to give the users an option to click a "Like" or 'Dislike" button instead of dragging. Hitting one of these buttons will then perform the same actions as if the card had been dragged.

Is this simple to do? Can anybody give me any guidance? I've spent a bit of time with this, and can't seem to get it to work, so any help would be greatly appreciated!

Let me know if you need more data or information.

Thanks!

答: Your question left out the important parts of the code; the pullChange() and release() functions. Since those are the functions that actually control the card moving, you should be able to bind them to a button click with a slight caveat. pullChange() utilizes the DeltaX variable and expects it to be there to tell it how far to move, so you'll need to set this by hand since there won't be a drag event telling it how far.

Body:
Hello

I'm currently working on a project that is very similar to the following codepen that I found a long while ago. It's essential a Tinder-like application;

https://codepen.io/suez/pen/MaeVBy

Within the codepen is the following JavaScript/jQuery:

function pullChange() {
    animating = true;
    deg = pullDeltaX / 10;
    $card.css("transform", "translateX("+ pullDeltaX +"px) rotate("+ deg +"deg)");

    var opacity = pullDeltaX / 100;
    var rejectOpacity = (opacity >= 0) ? 0 : Math.abs(opacity);
    var likeOpacity = (opacity <= 0) ? 0 : opacity;
    $cardReject.css("opacity", rejectOpacity);
    $cardLike.css("opacity", likeOpacity);
};

$(document).on("mousedown touchstart", ".demo__card:not(.inactive)", function(e) {
      if (animating) return;

      $card = $(this);
      $cardReject = $(".demo__card__choice.m--reject", $card);
      $cardLike = $(".demo__card__choice.m--like", $card);
      var startX = e.pageX || e.originalEvent.touches[0].pageX;

      $(document).on("mousemove touchmove", function(e) {
        var x = e.pageX || e.originalEvent.touches[0].pageX;
        pullDeltaX = (x - startX);
        if (!pullDeltaX) return;
        pullChange();
      });

      $(document).on("mouseup touchend", function() {
        $(document).off("mousemove touchmove mouseup touchend");
        if (!pullDeltaX) return; // prevents from rapid click events
        release();
      });
});

What I'm looking to achieve is the implementation of two buttons to "simulate" the mouse dragging. So - if you play with the codepen - you'll see that it's possible to drag the cards left and right. A "like" or "dislike" decision is then made based upon how far left or right it was dragged. Also, if you drag a card too far or too little in one direction, the card will snap to a set point upon release.

I want to give the users an option to click a "Like" or 'Dislike" button instead of dragging. Hitting one of these buttons will then perform the same actions as if the card had been dragged.

Is this simple to do? Can anybody give me any guidance? I've spent a bit of time with this, and can't seem to get it to work, so any help would be greatly appreciated!

Let me know if you need more data or information.

Thanks!


问:
Make an algorithm start again?
So I'm pretty new to coding with Java (started yesterday). What I am trying to do is to make an Input of an Integer, if the int c it is higher than 1 or lower than 0 (if it is not 1 or 0), I want it to start again. If int c equals either 1 or 0, I want the alogrithm to continue. I tried to insert some kind of loops after if(c > 1 || c < 0) but it does not seem to work and only spams my console with the result. Is there any easy way to make the algorithm start over again? I'm already trying to fix this for more than 2 hours, but I'm just confusing me over and over again.

```<code>// more code up here but it is unimportant
int c = sc.nextInt();

    if(c > 1 || c < 0) {
        result = result + wrong;
        System.out.println(result);
    } else if (c == 1) {
        result = result + notImplemented;
        System.out.println(result);
    } else if (c == 0) { //more code follows here but is unimportant
</code>```

答:
You can use while in this case and use break to exit:

```<code>while (scanner.hasNext()) {
  int c = sc.nextInt();

    if(c > 1 || c < 0) {
        result = result + wrong;
        System.out.println(result);
    } else if (c == 1) {
        result = result + notImplemented;
        System.out.println(result);
        break;
    } else if (c == 0) {
       ...
       break;
    }
}

scanner.close();
</code>```

Title: Make an algorithm start again?

Body:
So I'm pretty new to coding with Java (started yesterday). What I am trying to do is to make an Input of an Integer, if the int c it is higher than 1 or lower than 0 (if it is not 1 or 0), I want it to start again. If int c equals either 1 or 0, I want the alogrithm to continue. I tried to insert some kind of loops after if(c > 1 || c < 0) but it does not seem to work and only spams my console with the result. Is there any easy way to make the algorithm start over again? I'm already trying to fix this for more than 2 hours, but I'm just confusing me over and over again.

// more code up here but it is unimportant
int c = sc.nextInt();

    if(c > 1 || c < 0) {
        result = result + wrong;
        System.out.println(result);
    } else if (c == 1) {
        result = result + notImplemented;
        System.out.println(result);
    } else if (c == 0) { //more code follows here but is unimportant

Body:
You can use while in this case and use break to exit:

while (scanner.hasNext()) {
  int c = sc.nextInt();

    if(c > 1 || c < 0) {
        result = result + wrong;
        System.out.println(result);
    } else if (c == 1) {
        result = result + notImplemented;
        System.out.println(result);
        break;
    } else if (c == 0) {
       ...
       break;
    }
}

scanner.close();


问:
Input dispatching timed out ANR
I am getting the following ANR a lot in my application

```<code>Input dispatching timed out (Waiting to send key event because the focused window has not finished processing all of the input events that were previously delivered to it. Outbound queue length: 0. Wait queue length: 1.)
</code>```

the log says that the problem in onActivityStopped method

this is the code that I have added in this method

```<code>try {
            boolean foreground = new ForegroundCheckTask().execute(getApplicationContext()).get();
            if(!foreground) {

                AdServerManager.getInstance().incrementImpression(activity, ForSaleDataManager.getInstance().getBannerImpression(),
                        ForSaleDataManager.getInstance().getOfferImpression(), new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {

                                ForSaleDataManager.getInstance().clearOfferImpression();
                                ForSaleDataManager.getInstance().clearBannerImpression();
                            }
                        });

                String lastOffers = TextUtils.join("," , ForSaleDataManager.getInstance().getVisitedOffersIds());
                //Appboy.getInstance(activity).getCurrentUser().setCustomUserAttribute(AppBoyAttributeName.LAST_TEN_OFFER_IDS.getValue() , lastOffers);
                ForSaleDataManager.getInstance().clearVisitedOffersIds();

                String lastCategories = TextUtils.join("," , ForSaleDataManager.getInstance().getVisitedCategoriesIds());
                //Appboy.getInstance(activity).getCurrentUser().setCustomUserAttribute(AppBoyAttributeName.LAST_TEN_CATEGORY_IDS.getValue() , lastCategories);
                ForSaleDataManager.getInstance().clearVisitedCategoriesIds();

                String lastSearch = TextUtils.join("," , ForSaleDataManager.getInstance().getVisitedSearchTerms());
                //Appboy.getInstance(activity).getCurrentUser().setCustomUserAttribute(AppBoyAttributeName.LAST_TEN_SEARCH_TERMS.getValue() , lastSearch);
                ForSaleDataManager.getInstance().clearVisitedSearchTerms();

                // clear landing page
                PhoneUtils.addBooleanToSharedPreference(activity, ForSaleConstants.IS_CATEGORIES_LANDING_SHOWEN, false);
                PhoneUtils.addBooleanToSharedPreference(activity, ForSaleConstants.IS_LISTING_LANDING_SHOWEN, false);
                PhoneUtils.deleteWithPrefixFromSharedPreference(activity, ForSaleConstants.IS_SUB_CATEGORIES_LANDING_SHOWEN_PREFIX, false);
                PhoneUtils.deleteWithPrefixFromSharedPreference(activity, ForSaleConstants.IS_SUB_CATEGORIES_LANDING_SHOWEN, false);

                // reset for last activity
                PhoneUtils.addBooleanToSharedPreference(activity, ForSaleConstants.SET_LAST_ACTIVITY_CALLED, false);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
</code>```

the system requirement of my app that I have to send some data to server and also clear local data so I have implemented the interface Application.ActivityLifecycleCallbacks

can anyone advice how to meet my system requirement without generating ANR ?

EDIT

this is the code after I put it in AsyncTask and it does not work

```<code>@Override
    public void onActivityStopped(final Activity activity) {

        //new AsyncTask<Void, Void, Void>() {

            //@Override
            //protected Void doInBackground(Void... voids) {

                try {
                    boolean foreground = new ForegroundCheckTask().execute(getApplicationContext()).get();
                    if(!foreground) {

                        AdServerManager.getInstance().incrementImpression(activity, ForSaleDataManager.getInstance().getBannerImpression(),
                                ForSaleDataManager.getInstance().getOfferImpression(), new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {

                                        ForSaleDataManager.getInstance().clearOfferImpression();
                                        ForSaleDataManager.getInstance().clearBannerImpression();
                                    }
                                });

                        String lastOffers = TextUtils.join("," , ForSaleDataManager.getInstance().getVisitedOffersIds());
                        //Appboy.getInstance(activity).getCurrentUser().setCustomUserAttribute(AppBoyAttributeName.LAST_TEN_OFFER_IDS.getValue() , lastOffers);
                        ForSaleDataManager.getInstance().clearVisitedOffersIds();

                        String lastCategories = TextUtils.join("," , ForSaleDataManager.getInstance().getVisitedCategoriesIds());
                        //Appboy.getInstance(activity).getCurrentUser().setCustomUserAttribute(AppBoyAttributeName.LAST_TEN_CATEGORY_IDS.getValue() , lastCategories);
                        ForSaleDataManager.getInstance().clearVisitedCategoriesIds();

                        String lastSearch = TextUtils.join("," , ForSaleDataManager.getInstance().getVisitedSearchTerms());
                        //Appboy.getInstance(activity).getCurrentUser().setCustomUserAttribute(AppBoyAttributeName.LAST_TEN_SEARCH_TERMS.getValue() , lastSearch);
                        ForSaleDataManager.getInstance().clearVisitedSearchTerms();

                        // clear landing page
                        PhoneUtils.addBooleanToSharedPreference(activity, ForSaleConstants.IS_CATEGORIES_LANDING_SHOWEN, false);
                        PhoneUtils.addBooleanToSharedPreference(activity, ForSaleConstants.IS_LISTING_LANDING_SHOWEN, false);
                        PhoneUtils.deleteWithPrefixFromSharedPreference(activity, ForSaleConstants.IS_SUB_CATEGORIES_LANDING_SHOWEN_PREFIX, false);
                        PhoneUtils.deleteWithPrefixFromSharedPreference(activity, ForSaleConstants.IS_SUB_CATEGORIES_LANDING_SHOWEN, false);

                        // reset for last activity
                        PhoneUtils.addBooleanToSharedPreference(activity, ForSaleConstants.SET_LAST_ACTIVITY_CALLED, false);
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (ExecutionException e) {
                    e.printStackTrace();
                }

                //return null;
        //    }
        //}.execute();

    }
</code>```

答: Move all of that logic into a background thread. That is how you solve any ANR that comes from your code.</p>

Title: Input dispatching timed out ANR

Body:
I am getting the following ANR a lot in my application

Input dispatching timed out (Waiting to send key event because the focused window has not finished processing all of the input events that were previously delivered to it. Outbound queue length: 0. Wait queue length: 1.)

the log says that the problem in onActivityStopped method

this is the code that I have added in this method

try {
            boolean foreground = new ForegroundCheckTask().execute(getApplicationContext()).get();
            if(!foreground) {

                AdServerManager.getInstance().incrementImpression(activity, ForSaleDataManager.getInstance().getBannerImpression(),
                        ForSaleDataManager.getInstance().getOfferImpression(), new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {

                                ForSaleDataManager.getInstance().clearOfferImpression();
                                ForSaleDataManager.getInstance().clearBannerImpression();
                            }
                        });

                String lastOffers = TextUtils.join("," , ForSaleDataManager.getInstance().getVisitedOffersIds());
                //Appboy.getInstance(activity).getCurrentUser().setCustomUserAttribute(AppBoyAttributeName.LAST_TEN_OFFER_IDS.getValue() , lastOffers);
                ForSaleDataManager.getInstance().clearVisitedOffersIds();

                String lastCategories = TextUtils.join("," , ForSaleDataManager.getInstance().getVisitedCategoriesIds());
                //Appboy.getInstance(activity).getCurrentUser().setCustomUserAttribute(AppBoyAttributeName.LAST_TEN_CATEGORY_IDS.getValue() , lastCategories);
                ForSaleDataManager.getInstance().clearVisitedCategoriesIds();

                String lastSearch = TextUtils.join("," , ForSaleDataManager.getInstance().getVisitedSearchTerms());
                //Appboy.getInstance(activity).getCurrentUser().setCustomUserAttribute(AppBoyAttributeName.LAST_TEN_SEARCH_TERMS.getValue() , lastSearch);
                ForSaleDataManager.getInstance().clearVisitedSearchTerms();

                // clear landing page
                PhoneUtils.addBooleanToSharedPreference(activity, ForSaleConstants.IS_CATEGORIES_LANDING_SHOWEN, false);
                PhoneUtils.addBooleanToSharedPreference(activity, ForSaleConstants.IS_LISTING_LANDING_SHOWEN, false);
                PhoneUtils.deleteWithPrefixFromSharedPreference(activity, ForSaleConstants.IS_SUB_CATEGORIES_LANDING_SHOWEN_PREFIX, false);
                PhoneUtils.deleteWithPrefixFromSharedPreference(activity, ForSaleConstants.IS_SUB_CATEGORIES_LANDING_SHOWEN, false);

                // reset for last activity
                PhoneUtils.addBooleanToSharedPreference(activity, ForSaleConstants.SET_LAST_ACTIVITY_CALLED, false);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

the system requirement of my app that I have to send some data to server and also clear local data so I have implemented the interface Application.ActivityLifecycleCallbacks

can anyone advice how to meet my system requirement without generating ANR ?

EDIT

this is the code after I put it in AsyncTask and it does not work

@Override
    public void onActivityStopped(final Activity activity) {

        //new AsyncTask<Void, Void, Void>() {

            //@Override
            //protected Void doInBackground(Void... voids) {

                try {
                    boolean foreground = new ForegroundCheckTask().execute(getApplicationContext()).get();
                    if(!foreground) {

                        AdServerManager.getInstance().incrementImpression(activity, ForSaleDataManager.getInstance().getBannerImpression(),
                                ForSaleDataManager.getInstance().getOfferImpression(), new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {

                                        ForSaleDataManager.getInstance().clearOfferImpression();
                                        ForSaleDataManager.getInstance().clearBannerImpression();
                                    }
                                });

                        String lastOffers = TextUtils.join("," , ForSaleDataManager.getInstance().getVisitedOffersIds());
                        //Appboy.getInstance(activity).getCurrentUser().setCustomUserAttribute(AppBoyAttributeName.LAST_TEN_OFFER_IDS.getValue() , lastOffers);
                        ForSaleDataManager.getInstance().clearVisitedOffersIds();

                        String lastCategories = TextUtils.join("," , ForSaleDataManager.getInstance().getVisitedCategoriesIds());
                        //Appboy.getInstance(activity).getCurrentUser().setCustomUserAttribute(AppBoyAttributeName.LAST_TEN_CATEGORY_IDS.getValue() , lastCategories);
                        ForSaleDataManager.getInstance().clearVisitedCategoriesIds();

                        String lastSearch = TextUtils.join("," , ForSaleDataManager.getInstance().getVisitedSearchTerms());
                        //Appboy.getInstance(activity).getCurrentUser().setCustomUserAttribute(AppBoyAttributeName.LAST_TEN_SEARCH_TERMS.getValue() , lastSearch);
                        ForSaleDataManager.getInstance().clearVisitedSearchTerms();

                        // clear landing page
                        PhoneUtils.addBooleanToSharedPreference(activity, ForSaleConstants.IS_CATEGORIES_LANDING_SHOWEN, false);
                        PhoneUtils.addBooleanToSharedPreference(activity, ForSaleConstants.IS_LISTING_LANDING_SHOWEN, false);
                        PhoneUtils.deleteWithPrefixFromSharedPreference(activity, ForSaleConstants.IS_SUB_CATEGORIES_LANDING_SHOWEN_PREFIX, false);
                        PhoneUtils.deleteWithPrefixFromSharedPreference(activity, ForSaleConstants.IS_SUB_CATEGORIES_LANDING_SHOWEN, false);

                        // reset for last activity
                        PhoneUtils.addBooleanToSharedPreference(activity, ForSaleConstants.SET_LAST_ACTIVITY_CALLED, false);
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (ExecutionException e) {
                    e.printStackTrace();
                }

                //return null;
        //    }
        //}.execute();

    }


问:
RadComboBox OnClientItemsRequested not firing
Is there anything about my code below that would prevent the client event "OnClientItemsRequested" from firing?  I have a couple RadComboBox elements on a page that sometimes get into a state where they load nothing and don't fire the "OnClientItemsRequested" event.  Is there anything I could do to FORCE this event to fire?</p>

```<code><telerik:RadComboBox
  ID="SomeFilter"
  runat="server"
  Height="230px" Width="300px" style="margin-bottom:5px"
  DropDownWidth="298px"
  EmptyMessage="Choose..."
  HighlightTemplatedItems="true"
  EnableLoadOnDemand="true"
  EnableVirtualScrolling="true"
  ItemRequestTimeout="500"
  ShowMoreResultsBox="True"
  OnClientSelectedIndexChanging="OnClientSelectedIndexChanging"
  OnClientDropDownClosing="OnClientDropDownClosing"
  OnClientBlur="OnClientBlur"
  OnItemsRequested="TaskEmployeesFilter_ItemsRequested"
  OnClientItemsRequested="OnClientItemsRequested"
  EnableItemCaching="false">
  <ItemTemplate>
    ...
  </ItemTemplate>
</telerik:RadComboBox>
</code>```

答:
How are you binding it to data?  You can invoke the event by calling the method: requestItems(), which this method makes the request from the client to the server.

See more about it here: http://www.telerik.com/help/aspnet/combobox/combo_client_model.html

Are you binding via web service, or another way?

HTH.

Body:
Is there anything about my code below that would prevent the client event "OnClientItemsRequested" from firing?  I have a couple RadComboBox elements on a page that sometimes get into a state where they load nothing and don't fire the "OnClientItemsRequested" event.  Is there anything I could do to FORCE this event to fire?

<telerik:RadComboBox
  ID="SomeFilter"
  runat="server"
  Height="230px" Width="300px" style="margin-bottom:5px"
  DropDownWidth="298px"
  EmptyMessage="Choose..."
  HighlightTemplatedItems="true"
  EnableLoadOnDemand="true"
  EnableVirtualScrolling="true"
  ItemRequestTimeout="500"
  ShowMoreResultsBox="True"
  OnClientSelectedIndexChanging="OnClientSelectedIndexChanging"
  OnClientDropDownClosing="OnClientDropDownClosing"
  OnClientBlur="OnClientBlur"
  OnItemsRequested="TaskEmployeesFilter_ItemsRequested"
  OnClientItemsRequested="OnClientItemsRequested"
  EnableItemCaching="false">
  <ItemTemplate>
    ...
  </ItemTemplate>
</telerik:RadComboBox>