Q: Unable to deserialize the execution context after upgrading to spring boot 2.0 for a spring cloud dataflow task I updated my spring boot (Task) application to spring boot 2.0 from 1.5. Now when I run it I get a deserializable error.
2018-10-29 15:03:00.346 ERROR 713 --- [           main] o.s.boot.SpringApplication               : Application run failed

java.lang.IllegalStateException: Failed to execute CommandLineRunner
    at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:795) [spring-boot-2.0.6.RELEASE.jar!/:2.0.6.RELEASE]
    at org.springframework.boot.SpringApplication.callRunners(SpringApplication.java:776) [spring-boot-2.0.6.RELEASE.jar!/:2.0.6.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:315) [spring-boot-2.0.6.RELEASE.jar!/:2.0.6.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1242) [spring-boot-2.0.6.RELEASE.jar!/:2.0.6.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1230) [spring-boot-2.0.6.RELEASE.jar!/:2.0.6.RELEASE]
    at com.mediaiq.miq.batch.MiqBatchApplication.main(MiqBatchApplication.java:42) [classes!/:na]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_191]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_191]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_191]
    at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_191]
    at org.springframework.boot.loader.MainMethodRunner.run(MainMethodRunner.java:48) [aiq-miq-batch-2.18-SNAPSHOT.jar:na]
    at org.springframework.boot.loader.Launcher.launch(Launcher.java:87) [aiq-miq-batch-2.18-SNAPSHOT.jar:na]
    at org.springframework.boot.loader.Launcher.launch(Launcher.java:50) [aiq-miq-batch-2.18-SNAPSHOT.jar:na]
    at org.springframework.boot.loader.JarLauncher.main(JarLauncher.java:51) [aiq-miq-batch-2.18-SNAPSHOT.jar:na]
Caused by: java.lang.IllegalArgumentException: Unable to deserialize the execution context
    at org.springframework.batch.core.repository.dao.JdbcExecutionContextDao$ExecutionContextRowMapper.mapRow(JdbcExecutionContextDao.java:325) ~[spring-batch-core-4.0.1.RELEASE.jar!/:4.0.1.RELEASE]
    at org.springframework.batch.core.repository.dao.JdbcExecutionContextDao$ExecutionContextRowMapper.mapRow(JdbcExecutionContextDao.java:309) ~[spring-batch-core-4.0.1.RELEASE.jar!/:4.0.1.RELEASE]
    at org.springframework.jdbc.core.RowMapperResultSetExtractor.extractData(RowMapperResultSetExtractor.java:93) ~[spring-jdbc-5.0.10.RELEASE.jar!/:5.0.10.RELEASE]
    at org.springframework.jdbc.core.RowMapperResultSetExtractor.extractData(RowMapperResultSetExtractor.java:60) ~[spring-jdbc-5.0.10.RELEASE.jar!/:5.0.10.RELEASE]
    at org.springframework.jdbc.core.JdbcTemplate$1.doInPreparedStatement(JdbcTemplate.java:667) ~[spring-jdbc-5.0.10.RELEASE.jar!/:5.0.10.RELEASE]
    at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:605) ~[spring-jdbc-5.0.10.RELEASE.jar!/:5.0.10.RELEASE]
    at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:657) ~[spring-jdbc-5.0.10.RELEASE.jar!/:5.0.10.RELEASE]
    at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:688) ~[spring-jdbc-5.0.10.RELEASE.jar!/:5.0.10.RELEASE]
    at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:700) ~[spring-jdbc-5.0.10.RELEASE.jar!/:5.0.10.RELEASE]
    at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:756) ~[spring-jdbc-5.0.10.RELEASE.jar!/:5.0.10.RELEASE]
    at org.springframework.batch.core.repository.dao.JdbcExecutionContextDao.getExecutionContext(JdbcExecutionContextDao.java:112) ~[spring-batch-core-4.0.1.RELEASE.jar!/:4.0.1.RELEASE]
    at org.springframework.batch.core.explore.support.SimpleJobExplorer.getJobExecutionDependencies(SimpleJobExplorer.java:202) ~[spring-batch-core-4.0.1.RELEASE.jar!/:4.0.1.RELEASE]
    at org.springframework.batch.core.explore.support.SimpleJobExplorer.getJobExecutions(SimpleJobExplorer.java:83) ~[spring-batch-core-4.0.1.RELEASE.jar!/:4.0.1.RELEASE]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_191]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_191]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_191]
    at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_191]
    at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:343) ~[spring-aop-5.0.10.RELEASE.jar!/:5.0.10.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:197) ~[spring-aop-5.0.10.RELEASE.jar!/:5.0.10.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163) ~[spring-aop-5.0.10.RELEASE.jar!/:5.0.10.RELEASE]
    at org.springframework.batch.core.configuration.annotation.SimpleBatchConfiguration$PassthruAdvice.invoke(SimpleBatchConfiguration.java:127) ~[spring-batch-core-4.0.1.RELEASE.jar!/:4.0.1.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185) ~[spring-aop-5.0.10.RELEASE.jar!/:5.0.10.RELEASE]
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:212) ~[spring-aop-5.0.10.RELEASE.jar!/:5.0.10.RELEASE]
    at com.sun.proxy.$Proxy185.getJobExecutions(Unknown Source) ~[na:na]
    at org.springframework.batch.core.JobParametersBuilder.getNextJobParameters(JobParametersBuilder.java:264) ~[spring-batch-core-4.0.1.RELEASE.jar!/:4.0.1.RELEASE]
    at org.springframework.boot.autoconfigure.batch.JobLauncherCommandLineRunner.execute(JobLauncherCommandLineRunner.java:162) ~[spring-boot-autoconfigure-2.0.6.RELEASE.jar!/:2.0.6.RELEASE]
    at org.springframework.boot.autoconfigure.batch.JobLauncherCommandLineRunner.executeLocalJobs(JobLauncherCommandLineRunner.java:179) ~[spring-boot-autoconfigure-2.0.6.RELEASE.jar!/:2.0.6.RELEASE]
    at org.springframework.boot.autoconfigure.batch.JobLauncherCommandLineRunner.launchJobFromProperties(JobLauncherCommandLineRunner.java:134) ~[spring-boot-autoconfigure-2.0.6.RELEASE.jar!/:2.0.6.RELEASE]
    at org.springframework.boot.autoconfigure.batch.JobLauncherCommandLineRunner.run(JobLauncherCommandLineRunner.java:128) ~[spring-boot-autoconfigure-2.0.6.RELEASE.jar!/:2.0.6.RELEASE]
    at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:792) [spring-boot-2.0.6.RELEASE.jar!/:2.0.6.RELEASE]
    ... 13 common frames omitted
Caused by: com.fasterxml.jackson.databind.exc.InvalidTypeIdException: Could not resolve type id '' as a subtype of [simple type, class java.lang.Object]: no such class found
 at [Source: (ByteArrayInputStream); line: 1, column: 11] (through reference chain: java.util.HashMap["map"])
    at com.fasterxml.jackson.databind.exc.InvalidTypeIdException.from(InvalidTypeIdException.java:43) ~[jackson-databind-2.9.7.jar!/:2.9.7]
    at com.fasterxml.jackson.databind.DeserializationContext.invalidTypeIdException(DeserializationContext.java:1635) ~[jackson-databind-2.9.7.jar!/:2.9.7]
    at com.fasterxml.jackson.databind.DeserializationContext.handleUnknownTypeId(DeserializationContext.java:1187) ~[jackson-databind-2.9.7.jar!/:2.9.7]
    at com.fasterxml.jackson.databind.jsontype.impl.ClassNameIdResolver._typeFromId(ClassNameIdResolver.java:53) ~[jackson-databind-2.9.7.jar!/:2.9.7]
    at com.fasterxml.jackson.databind.jsontype.impl.ClassNameIdResolver.typeFromId(ClassNameIdResolver.java:44) ~[jackson-databind-2.9.7.jar!/:2.9.7]
    at com.fasterxml.jackson.databind.jsontype.impl.TypeDeserializerBase._findDeserializer(TypeDeserializerBase.java:156) ~[jackson-databind-2.9.7.jar!/:2.9.7]
    at com.fasterxml.jackson.databind.jsontype.impl.AsArrayTypeDeserializer._deserialize(AsArrayTypeDeserializer.java:97) ~[jackson-databind-2.9.7.jar!/:2.9.7]
    at com.fasterxml.jackson.databind.jsontype.impl.AsArrayTypeDeserializer.deserializeTypedFromAny(AsArrayTypeDeserializer.java:71) ~[jackson-databind-2.9.7.jar!/:2.9.7]
    at com.fasterxml.jackson.databind.deser.std.UntypedObjectDeserializer$Vanilla.deserializeWithType(UntypedObjectDeserializer.java:712) ~[jackson-databind-2.9.7.jar!/:2.9.7]
    at com.fasterxml.jackson.databind.deser.std.MapDeserializer._readAndBindStringKeyMap(MapDeserializer.java:529) ~[jackson-databind-2.9.7.jar!/:2.9.7]
    at com.fasterxml.jackson.databind.deser.std.MapDeserializer.deserialize(MapDeserializer.java:364) ~[jackson-databind-2.9.7.jar!/:2.9.7]
    at com.fasterxml.jackson.databind.deser.std.MapDeserializer.deserialize(MapDeserializer.java:29) ~[jackson-databind-2.9.7.jar!/:2.9.7]
    at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:4013) ~[jackson-databind-2.9.7.jar!/:2.9.7]
    at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3077) ~[jackson-databind-2.9.7.jar!/:2.9.7]
    at org.springframework.batch.core.repository.dao.Jackson2ExecutionContextStringSerializer.deserialize(Jackson2ExecutionContextStringSerializer.java:70) ~[spring-batch-core-4.0.1.RELEASE.jar!/:4.0.1.RELEASE]
    at org.springframework.batch.core.repository.dao.Jackson2ExecutionContextStringSerializer.deserialize(Jackson2ExecutionContextStringSerializer.java:50) ~[spring-batch-core-4.0.1.RELEASE.jar!/:4.0.1.RELEASE]
    at org.springframework.batch.core.repository.dao.JdbcExecutionContextDao$ExecutionContextRowMapper.mapRow(JdbcExecutionContextDao.java:322) ~[spring-batch-core-4.0.1.RELEASE.jar!/:4.0.1.RELEASE]

One person had suggested that :
This error happens when the execution context of your job is serialized with version 3 (using XStream by default) and then deserialized with version 4 (using Jackson by default). So either downgrade Spring Batch to version 3 or configure your job repository to use the XStreamExecutionContextStringSerializer.
In your case, you have already defined a bean of type BatchConfigurer, so you can override the createJobRepository method and configure the XStream serializer. For example:
@Bean
BatchConfigurer configurer(@Qualifier("dataSource") DataSource dataSource, PlatformTransactionManager transactionManager) {
    return new DefaultBatchConfigurer(dataSource) {
        @Override
        protected JobRepository createJobRepository() throws Exception {
            JobRepositoryFactoryBean factory = new JobRepositoryFactoryBean();
            factory.setDataSource(dataSource);
            factory.setTransactionManager(transactionManager);
            factory.setSerializer(new XStreamExecutionContextStringSerializer());
            factory.afterPropertiesSet();
            return factory.getObject();
        }
    };
}

I added the above bean to my main class but still got the error.

A: In the batch_job_execution_context table, you may have some records which are created by the spring batch version 3. While you are trying to execute new execution with spring batch version 4, it trying to compare previous records. So it trying to deserialize those older records. this is why you are getting this issue.
Spring batch version 3 records are like bellow in the batch_job_execution_context table

{"map":[{"entry":{"string":["key","value"]}}]}

Spring batch version 4 records are like bellow in the batch_job_execution_context table
{"key":"value"}

Remove all the records created by version 3. This will fix the issue.


Q: How can integrate Keycloak with kafka? I have configured 3 nodes kafka cluster. Now we want to setup security with Keycloak for kafka. Please let me know what are the ways to do the same.
Question 1: How to implement security for kafka broker to kafka broker with keycloak?
Question 2: How to implement security for kafka client to kafka broker with keycloak?
Note: We had already Keycloak setup.

A: You can configure Kafka to use AUTHBEARER which is implemented in latest kafka release , You can find more info how to configure here .
And also get more information about the feature from Kafka doc
You need to implement  org.apache.kafka.common.security.auth.AuthenticateCallbackHandler to get token from keycloak  and validate token from Keycloak.


Q: Pandas - get the mean of one column using descending N rows of another column I have this dataframe:
             team        opponent home_dummy     round     points
0     Athlético-PR       Flamengo          0        13      22.91
1     Athlético-PR    Atlético-GO          0        17       23.6
2     Athlético-PR      Fortaleza          1        20      28.58
3     Athlético-PR      Fortaleza          0         1      75.71
4     Athlético-PR          Ceará          1        14      42.22
5     Athlético-PR       Coritiba          1        10      52.91
6     Athlético-PR          Goiás          1         2      39.82
7     Athlético-PR          Goiás          0        21      65.13
8     Athlético-PR  Internacional          0        15      43.09
9     Athlético-PR         Grêmio          1        18      15.38
10    Athlético-PR          Sport          0        19      13.09
11    Athlético-PR         Santos          1        22      65.45
12    Athlético-PR         Santos          0         3      28.04
13    Athlético-PR      Palmeiras          1         4      -7.31
14    Athlético-PR      Palmeiras          0        23      11.02
15    Athlético-PR          Vasco          0         8      15.93
16    Athlético-PR     Fluminense          1         5       9.16
17    Athlético-PR          Bahia          1        12      59.78
18    Athlético-PR    Corinthians          1        16      18.22
19    Athlético-PR       Botafogo          1         9      29.35
20    Athlético-PR     Bragantino          1         7      20.07
.......

The dataframe above has another 19 teams, other than 'Athlético-PR'.

How do I group this dataframe, getting, for each team:

*

*Mean points for the last N rounds, say N=6, which would get the mean of round 23, 22, 21, 20, 19, 18.

*Mean points for the last N rounds passing 'home_dummy' as condition, which would get the mean of either rounds 23, 21, 19, 17, 15, 13 or rounds 22, 20, 18, 16, 14, 12.

ending up with:
    team           mean_total   mean_home_0   mean_home_1
 0  Athlético-PR       mean x        mean y        mean z
  ...

A: I think you can to do two separate groupby:
df = df.sort_values(['team','round'])

out = (df.groupby(['team','home_dummy']).tail(6)
         .groupby(['team','home_dummy'])['points'].mean()
         .unstack('home_dummy')
         .add_prefix('mean_home_')
      )

out['mean_total'] = df.groupby('team').tail(6).groupby('team')['points'].mean()

Output:
home_dummy    mean_home_0  mean_home_1  mean_total
team
Athlético-PR    29.806667    38.271667   33.108333

Another option is to write a udf so as to reduce the two groupby to one:
def last6mean(x):
    return x.tail(6).mean()

out = (df.groupby(['team','home_dummy'])['points']
        .apply(last6mean)
        .unstack('home_dummy')
        .add_prefix('mean_home_')
     )

out['mean_total'] = df.groupby('team')['points'].apply(last6mean)

A: You can create two dataframes for filtering for the 6 largest with groupby and then get the means and merge together:
First make sure they are numeric:
df['round'] = df['round'].astype(int)
df['points'] = df['points'].astype(float)

OR
df['round'] = pd.to_numeric(df['round'], errors='coerce')
df['points'] = pd.to_numeric(df['points'], errors='coerce')

Then, you can run the following:
df1 = (df.loc[df.index.isin(df.groupby('team')['round'].nlargest(6).reset_index().iloc[:,1]),
        ['team', 'points']].groupby('team')['points'].mean().rename('mean_total').reset_index())
df2 = (df.loc[df.index.isin(df.groupby(['team','home_dummy'])['round'].nlargest(6).reset_index().iloc[:,2]),
        ['team', 'home_dummy', 'points']].groupby(['team','home_dummy'])['points'].mean()
       .unstack(1).add_prefix('mean_home_').reset_index())
df1.merge(df2, on='team')
Out[1]:
           team  mean_total  mean_home_0  mean_home_1
0  Athlético-PR   33.108333    29.806667    38.271667

You could also create a function to make cleaner:
def f(df, cols):
    return df.loc[df.index.isin(df.groupby(cols)['round'].nlargest(6).reset_index().iloc[:, len(cols)]),
        cols + ['points']].groupby(cols)['points'].mean()

(f(df, ['team']).rename('mean_total').reset_index().merge(
    f(df, ['team', 'home_dummy']).unstack(1).add_prefix('mean_home_').reset_index()))
Out[2]:
       team  mean_total  mean_home_0  mean_home_1
0  Athlético-PR   33.108333    29.806667    38.271667

A: I know that there's already awesome answers here, but I'd just like to share one using pivot_table:
If your DataFrame looks something like this
   team  home_dummy  round  points
0     A           0      1       3
1     A           0      2       4
2     A           1      3       7
3     A           1      4       8
4     B           0      1       3
5     B           1      2       6
6     B           1      3       9
7     B           0      4      12
8     C           0      1       5
9     C           1      2       5
10    C           1      3       5
11    C           0      4       5

Then you could do something like:
N = 2
df['points'] = df['points'].astype(float)

result = df.pivot_table(index='team',
                        columns='home_dummy',
                        values='points',
                        aggfunc=lambda x: x.tail(N).mean())

result.rename({i: f"mean_home_{i}" for i in result.columns}, axis=1, inplace=True)
result.columns.name = None

result['mean_total'] = df.groupby('team').tail(N).groupby('team')['points'].mean()

Which will give you the following dataframe
      mean_home_0  mean_home_1  mean_total
team
A             3.5          7.5         5.5
B             7.5          7.5         7.5
C             5.0          5.0         5.0


Q: Problem on import a react native component I'm having a error once import a component, react native says me that the file path is wrong, but it's not!
My main component where I'm trying to import a component and my file structure:

I'm on pages/Main/index and wanna import a file from components/Header/index, I'm sure about the path, I'm I think this is because of some react native project config, something like this
(I'm a windwos user and tryed to use /index in the path too)
The error:

A: Try passing '../components/Header'
Please let me know if it works. Thanks

A: Your .'./components/Header' path is right..
In your Header component folder there is no any styles.js but you are importing in index.js which is in Header folder.. The above error is regarding path to styles.js in header folders Index.js
Read the error carefully. They have mentioned original Path and target path.
Hope you get it.


Q: Найти минимальную дату из трех в формате ДД.ММ.ГГГГ? Найти минимальную дату из трех в формате ДД.ММ.ГГГГ
 min(D, 31.12.2017, today())
Минимальную - значит самую раннюю
D - любая входящая дата в формате   ДД.ММ.ГГГГ

A: Все просто:

var now = new Date()
var day1 = new Date(2018, 07, 12);
var day2 = new Date(2018, 06, 12);
var day3 = new Date(2018, 05, 12);
if(day1 < day2 && day1 < day3){
  alert(1);
}
else if(day2 < day3 && day2 < day1){
  alert(2);
}
else if(day3 < day2 && day3 < day1){
  alert(3);
}

A: Предложу 2 пути, какой лучше в плане универсальности формата дат и кросс-браузерности может подскажут в комментариях
var day1 = new Date("31.12.2017");
...
...
min=Math.min(day1,day2,day3);

.parse()
var day1 = Date.parse("31.12.2017");
...
...
min=Math.min(day1,day2,day3);


Q: Why UITableView is not getting any user interaction as it's ViewController is added to a UITabBarController as subView I'm setting a left side menu programatically to a UITabBarController. To do this I am inserting a viewController with 0 index as subView to the TabBarController. When I press menu icon first tabView move right and menu UITableView is shown but I can not interact with the UITableView where did I make wrong?

Total UITabBarController.swift file
import UIKit

class MainTabBarController: UITabBarController {

// MARK: Properties

var menuController: MenuController!
var centerController: UIViewController!
var isExpanded = false

// MARK: Initialization

override func viewDidLoad() {
    super.viewDidLoad()
    configureHomeController()
}

override var preferredStatusBarStyle: UIStatusBarStyle {
    return .lightContent
}

override var preferredStatusBarUpdateAnimation: UIStatusBarAnimation {
    return .slide
}

override var prefersStatusBarHidden: Bool {
    return isExpanded
}

// MARK: Handlers

func configureHomeController() {
    let navigationController = self.viewControllers![0] as! UINavigationController
    let homeController =  navigationController.viewControllers[0] as! FirstViewController
    homeController.homeControllerDelegate = self
    centerController = homeController
}

//Configuring Side Menu Controller

func configureMenuController() {
    if menuController == nil {
        // add menu controller here
        menuController = MenuController()
        menuController.homeControllerDelegate = self
        // Add Child View Controller
        addChild(menuController)
        // Add Child View as Subview
        view.insertSubview(menuController.view, at: 0)
        // Configure Child View
        menuController.view.frame = view.bounds
        menuController.view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
        // Notify Child View Controller
        menuController.didMove(toParent: self)
    }
}

func animateSideMenuOpeningAndClosing(shouldExpand: Bool, menuItem: MenuItem?) {
    if shouldExpand {
        // Show Menu
        UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 0, options: .curveEaseInOut, animations: {
            self.centerController.view.frame.origin.x = self.centerController.view.frame.width - 80
        }, completion: nil)
    } else {
        // Hide Menu
        UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 0,options: .curveEaseInOut, animations: {
            self.centerController.view.frame.origin.x = 0
        }) { (_) in
            guard let menuItem = menuItem else {return}
            self.didSelectMenuItem(menuItem: menuItem)
        }
    }
    animateStatusBar ()
}

func didSelectMenuItem(menuItem: MenuItem) {
    switch menuItem {
    case .Dashboard:
        print("Show Dashboard")
    case .Profile:
        print("Show Profile")
    case .Notifications:
        print("Show Notifications")
    case .Contacts:
        let controller = SettingsController()
        controller.username = "YAMIN"
        present(UINavigationController(rootViewController: controller), animated: true, completion: nil)
    }
}

func animateStatusBar () {
    UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 0,options: .curveEaseInOut, animations: {
        self.setNeedsStatusBarAppearanceUpdate()
    }, completion: nil)
}

}

extension MainTabBarController: HomeControllerDelegate {
func handleMenuToogle(forMenuItem menuItem: MenuItem?) {
    print("Pressed")
    if !isExpanded {
        configureMenuController()
    }
    isExpanded = !isExpanded
    animateSideMenuOpeningAndClosing(shouldExpand: isExpanded, menuItem: menuItem)
}

}

A: You insert subview at 0 index, so, I think there are some views which are higher in subviews hierarchy.
You can look at your subviews with "Debug View Hierarchy button"


Q: how to make invisible some layers with actionscript? I have a map and i can use on (release), on (rollover) but i can't use onload function. I want some cities will be invisible on load. My code is here with images;
Here is my city code:
on (rollOver) {              //this code is on all city.
y = new String(_name);
a = y.slice(1, 3);
_parent.rbtxt(a);
}
on (rollOut) {
_parent.rbalon(a);
}
on (release) {
_parent.rpress(a);
}

Here is my actionscript codes:
ilad="a,Adana,Adıyaman,Afyon,Ağrı";  //.. more city
ilurl="a,adana,adıyaman,afyon,ağrı"; //.. more city
passivearray="b,adana,afyon"         //must be passive this cities.

function rbtxt(a) {
var Register_1_ = a;
var Register_2_ = this;
balon._visible = true;
arbtxt = ilad.split(",");
balon.txt.text = arbtxt[Register_1_];
Register_2_[("x" + Register_1_)].play();
balon._x = Register_2_[("x" + Register_1_)]._x;
balon._y = (Register_2_[("x" + Register_1_)]._y - Register_2_[("x" + Register_1_)]._height / 2) - 25;
}

function rbalon(a) {
balon._visible = false;
this[("x" + a)].gotoAndStop(1);
 }

Should be passive array is => passivecities.
How can i make invisible somecities ?

A: At the beginning of your script, you can use
movieclipName._visible=false;
Then you modify the same property to reverse that.

A: Have you tried:
on(load){
    this._visible = false;
}


Q: c# printing through PDF drivers, print to file option will output PS instead of PDF After struggling whole day, I identified the issue but this didn't solve my problem.
On short:
I need to open a PDF, convert to BW (grayscale), search some words and insert some notes nearby found words. At a first look it seems easy but I discovered how hard PDF files are processed (having no "words" concepts and so on).
Now the first task, converting to grayscale just drove me crazy. I didn't find a working solution either commercial or free. I came up with this solution:

*

*open the PDF

*print with windows drivers, some free PDF printers

This is quite ugly since I will force the C# users to install such 3'rd party SW but.. that is fpr the moment. I tested FreePDF, CutePDF and PDFCreator. All of them are working "stand alone" as expected.
Now when I tried to print from C#, obviously, I don't want the print dialog, just select BW option and print (aka. convert)
The following code just uses a PDF library, shown for clarity only.
                Aspose.Pdf.Facades.PdfViewer viewer = new Aspose.Pdf.Facades.PdfViewer();
                viewer.BindPdf(txtPDF.Text);

                viewer.PrintAsGrayscale = true;
                //viewer.RenderingOptions = new RenderingOptions { UseNewImagingEngine = true };

                //Set attributes for printing
                //viewer.AutoResize = true;         //Print the file with adjusted size
                //viewer.AutoRotate = true;         //Print the file with adjusted rotation
                viewer.PrintPageDialog = true;   //Do not produce the page number dialog when printing

                ////PrinterJob printJob = PrinterJob.getPrinterJob();

                //Create objects for printer and page settings and PrintDocument
                System.Drawing.Printing.PrinterSettings ps = new System.Drawing.Printing.PrinterSettings();
                System.Drawing.Printing.PageSettings pgs = new System.Drawing.Printing.PageSettings();
                //System.Drawing.Printing.PrintDocument prtdoc = new System.Drawing.Printing.PrintDocument();

                //prtdoc.PrinterSettings = ps;

                //Set printer name
                //ps.PrinterName = prtdoc.PrinterSettings.PrinterName;

                ps.PrinterName = "CutePDF Writer";
                ps.PrintToFile = true;

                ps.PrintFileName = @"test.pdf";
                //
                //ps.

                //Set PageSize (if required)
                //pgs.PaperSize = new System.Drawing.Printing.PaperSize("A4", 827, 1169);

                //Set PageMargins (if required)
                //pgs.Margins = new System.Drawing.Printing.Margins(0, 0, 0, 0);

                //Print document using printer and page settings
                viewer.PrintDocumentWithSettings(ps);
                //viewer.PrintDocument();

                //Close the PDF file after priting

What I discovered and seems to be little explained, is that if you select
ps.PrintToFile = true;
no matter C# PDF library or PDF printer driver, Windows will just skip the PDF drivers and instead of PDF files will output PS (postscript) ones which obviously, will not be recognized by Adobe Reader.
Now the question (and I am positive that others who may want to print PDFs from C# may be encountered) is how to print to CutePDF for example and still suppress any filename dialog?
In other words, just print silently with programmatically selected filename from C# application. Or somehow convince "print to file" to go through PDF driver, not Windows default PS driver.
Thanks very much for any hints.

A: I solved conversion to grayscale with a commercial component with this post and I also posted there my complete solution, in care anyone will struggle like me.
Converting PDF to Grayscale pdf using ABC PDF


Q: PHP: Uncaught Error Cannot use object of type mysqli_result as array I have a simple section in which I am displaying data from the database,
If the user clicks eg construction and selects eg Algeria, I am displaying [251, 211,712] if a user clicks eg Power and selects eg. Egypt I am displaying [406, 228,559] etc
Now I want if the user clicks the button All available industries and select eg. Algeria I want to display this [251+203+130, 211,712+179,877+154,946] in a simple way like this in SQL
SELECT sum(SumofNoOfProjects) as sum_projects, sum(SumofTotalBudgetValue) as sum_value FROM `meed` WHERE Countries = 'Algeria'

Which give me this [611, 546535]
Here is my solution
HTML

        Construction

        Power

        Oil

        All available industries

Here is js ajax
$("#interactive-layers").on("click", ".video-btns", function(){
    if( $(e.target).find("span.label").html()=="Confirm" ) {

        var selectedCountries = [];

        $('.video-btns .selected').each(function () {
            selectedCountries.push( $(this).parent().find("span.label").html() ) ;
        });

        if( selectedCountries.length>0 ) {
            if(selectedCountries.indexOf("All available countries")>-1) {
                selectedCountries = [];
            }

        } else {

            return;
        }

        var ajaxurl = "";
        if(selectedCountries.length>0) {
            ajaxurl = "data.php";
        } else {
            ajaxurl = "dataall.php";

        }

        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                    countries: selectedCountries.join(","),
                    sector: selectedSector
            },
            success: function(result){
                console.log(result);
                result = JSON.parse(result);
                $(".video-btns").each(function () {
                    var getBtn = $(this).attr('buttonid');
                    if (getBtn == 106) {
                        var totalProjects = $(""+ result[0] + "");
                        $(this).append(totalProjects)
                    }else if(getBtn ==107){
                        var resultBudget = result[1]
                        var totalBudgets = $(""+ '&#36m' +" " + resultBudget +"");
                        $(this).append( totalBudgets)
                    }
                });
                return;
              }
        });
    }
});

UPDATE Here is Updated  data.php
      <?php

$selectedSectorByUser = $_POST['sector'];
$countries = explode(",", $_POST['countries']);
echo '$countries';

 $conn = mysqli_connect("localhost", "root", "", "meedadb");
 if (mysqli_connect_errno())   {
   echo "Failed to connect to MySQL: " . mysqli_connect_error();
 }

 $result = mysqli_query($conn, "SELECT * FROM meed");
 $data = array();

 $wynik = [];
$totalProjects = 0;
$totalBudget = 0;

 while ($row = mysqli_fetch_array($result))
 {
    if($row['Sector']==$selectedSectorByUser && in_array($row['Countries'],$countries ) ) {

     $totalProjects+= $row['SumofNoOfProjects'];
     $totalBudget+= $row['SumofTotalBudgetValue'];

    }elseif($selectedSectorByUser =="All available industries"){
      $result = mysqli_query($conn,
      "SELECT sum(SumofNoOfProjects) as 'SumofNoOfProjects, sum(SumofTotalBudgetValue) as SumofTotalBudgetValue
      FROM `meed`
      WHERE Countries = '$countries'");

      while( $row=mysqli_fetch_array($result,MYSQLI_ASSOC)) {
         echo json_encode([ $row['SumofNoOfProjects,'], $row['SumofTotalBudgetValue '] ] );
         exit;
        }

      exit;
    }
 }

 echo json_encode([ $totalProjects, $totalBudget ] );
exit();
?>

Now when the user clicks All available industries btn and selects a country I  get the following error

b>Fatal error:  Uncaught Error: Cannot use object of type mysqli_result as array in C:\custom-xammp\htdocs\editor\data.php:23

What do I need to change to get what I want? any help or suggestion will be appreciated,

A: you  should fecth a row (at least)
if (mysqli_connect_errno())   {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$result = mysqli_query($conn,
    "SELECT sum(SumofNoOfProjects) as sum_projects, sum(SumofTotalBudgetValue) as sum_value
    FROM `meed`
    WHERE Countries = '$countries'");

while( $row=mysqli_fetch_array($result,MYSQLI_ASSOC);) {
 echo json_encode([ $row['sum_projects'], $row['sum_value'] ] );
 exit;
}

for the multiple countries
Asuming you  $_POST['countries'] contains "'Egypt','Algerie'"
then you could use a query as
"SELECT sum(SumofNoOfProjects) as sum_projects, sum(SumofTotalBudgetValue) as sum_value
    FROM `meed`
    WHERE Countries IN (" . $_POST['countries'] . ");"


Q: Can electricity flow up down-flowing water? I would imagine there are various things at play such as gravity, trepidation of the water (if any), strength of the electric current, and speed of the flowing water.
For example, if a pool of water at the base of a sink was electrified could a person washing their hands under the faucet get electrocuted?

A: The answer is yes, electricity will travel up moving water.  In fact it is a known problem that men urinating can get a very unpleasant shock if they hit a live wire.  Electricity travels much much faster than water.
Edit: I've just learned that Myth busters disproved this some years ago.  A urine stream breaks apart into droplets so will not conduct electricty.  But I won't test it myself.


Q: Minecraft EXCEPTION_ACCESS_VIOLATION (0xc0000005) [ig8icd64.dll+0x16b87] When I launch Minecraft (modded or unmodded) I get this error:
EXCEPTION_ACCESS_VIOLATION (0xc0000005)
Problematic frame as [ig8icd64.dll+0x16b87]

I have tried every solution on the internet and it is still not working, some people suggest getting new graphic card, but my computer is like 6 months old and I have the latest soft drivers installed. I have got Intel Iris Graphics 6100 with an i3 core processor (I have not found out a code name yet).
I used to have this error and it just randomly fixed itself like 3 months ago. For any other info just ask me.


Q: Dealing with single quotes in excel vba sql queries I am using excel sql queries to fetch data from the backend according to the selection i make in a dropdown box.However my sql queries are not working in cases where there is a single quote(') in the dropdown box value. For example-- Men's Wear . Please suggest me a way to deal with this problem
    SQL = "select Segment,Weeks,Value from [Category performance data$] where       Departments='" &       Sheet3.Range("Dept_name").Value & _
     "' and Metric ='Total Spend' group by Segment,Weeks,Value"
    Call execQry

A: Departments='" & replace(Sheet3.Range("Dept_name").Value, "'", "''") & _ "' and Metric


Q: Encrypting data at rest protect me against what type of attack? Encrypt data at rest is one of the major 101 of security for a lot of compliance (if not all of them). I am  however not sure I understand against which attack this protect me.
Let say I am in AWS cloud. I encrypt my S3 data at rest using KMS provided service.
The protection I get is, if someone get access to AWS network  and were able to access the data, it would get encrypted data. So basically, I am encrypting my data in case AWS is getting hacked. Now as unlikely it is, I understand the value.
Is there another kind of attack possible that encrypting data protecting me against?

A: Somebody could get access to a resource via a misconfigured IAM role for example. This is especially relevant for S3, where public access might sometimes be configured inadvertently. If you have encryption via KMS, access to the key would also have to be granted, which provides an additional layer of security, and something you can monitor and alert on easily. This also applies to your own components, some of which will be granted access to the KMS key, but others (like a frontend server) might not, because they don't need it, and you want to implement the least privilege principle to limit the impact of a potential breach. Of course you will not only rely on key access to implement access control to your resources, but it provides a single point where rules and actual access can easily be enforced and audited.
Also think about backups and disposed media. Maybe more usual to consider this when you host stuff yourself, but it is still relevant for public clouds. You probably trust AWS to manage backups and disposed media securely, but while they're pretty good at it, they might not be perfect, and you have zero control. If you store your data encrypted, there is no way for it to be recovered from a dumpster.


Q: Angular 2+ routage basic Complete a simple Angular component named MenuDisplayComponent having menu-display-component as selector.
Complete the declaration of the appRoutes variable.
The component must contain two  elements. They symbolize a menu of the application:
When we click on the  element with id="menu1" the component associated with the /menu1 route should be loaded.
When the  element with id="menu2" is clicked the component associated with the /menu2 route must be loaded.
Initially, neither component is loaded.
You must create the corresponding routes in appRoutes. Menu1Component corresponds to the menu1 path, Menu2Component corresponds to the menu2 path.
You only need to update MenuDisplayComponent (+ its template) and appRoutes.
 import { Component, Input, NgModule } from '@angular/core';
    import {APP_BASE_HREF} from '@angular/common';
    import { RouterModule, Routes } from '@angular/router';

    @Component({
      selector:'menu1-component',
      template: `

You are at menu 1.

      `
    })
    export class Menu1Component {
    }

    @Component({
      selector:'menu2-component2',
      template: `

You are at menu 2.

      `
    })
    export class Menu2Component {
    }

    @Component({
      selector:'menu-display-component',
      template: `

You are at menu 2.

      `

    })
    export class MenuDisplayComponent {

    }

    export const appRoutes:Routes = [
      {path:"menu1",component:Menu1Component},
       {path:"menu2",component:Menu2Component}
    ];

    // #region Preview
    @Component({
        template: `
          <menu-display-component></menu-display-component>
        `
    })
    export class PreviewComponent { }
    // #endregion Preview

    // #region Module declaration - Do not Change
    @NgModule({
      imports: [RouterModule.forRoot(appRoutes, {useHash: true})],
      exports: [RouterModule]
    })
    export class AppRoutingModule {
    }

    @NgModule({
        imports: [
          RouterModule,
          AppRoutingModule
        ],
        declarations: [PreviewComponent, Menu1Component, Menu2Component, MenuDisplayComponent],
        entryComponents: [PreviewComponent],
        providers: [{provide: APP_BASE_HREF, useValue : '/'}]
    })
    export class PreviewModule { }
    // #endregion Module declaration

A: One way you can do this is using children routes. This will help you load components inside of another component. You will need to add the router outlet tag inside the parent component for this to work. Let me know if that helps.


Q: Is it possible to add custom view on DefaultTimeBar in ExoPlayer Need to add custom views on the DefaultTimeBar in Exoplayer at particular timestamps to indicate that there is something which is coming up during the video play similar to what we have in terms of video ads.
Please find the attached image to understand the exact requirement.


Q: Split a pair of strings in bracket using python I want to split the following data into two columns, latitude and longitude and put them in a dataframe.
0     (45.349586099999996, -75.81031967988278)
1            (-37.77922725, 175.2010323246593)
2                   (-42.9945669, 170.7100413)
3                    (-39.2711067, 174.154795)
4                      (51.2800275, 1.0802533)
5           (-41.30222105, 172.89453190955697)
6                   (-35.3712702, 173.7405337)
7                   (-45.7255555, 168.2936808)
8                   (-40.3284102, 175.8190684)
9                   (-45.1299859, 169.5248818)
10           (-37.9503756, 176.93828736155422)

Can anyone help me please?

A: Another way:
data='''a  b
0     (45.349586099999996, -75.81031967988278)
1            (-37.77922725, 175.2010323246593)
2                   (-42.9945669, 170.7100413)
3                    (-39.2711067, 174.154795)
4                      (51.2800275, 1.0802533)
5           (-41.30222105, 172.89453190955697)
6                   (-35.3712702, 173.7405337)
7                   (-45.7255555, 168.2936808)
8                   (-40.3284102, 175.8190684)
9                   (-45.1299859, 169.5248818)
10           (-37.9503756, 176.93828736155422)'''
df = pd.read_csv(io.StringIO(data), sep=' \s+', engine='python')
df[['lat', 'lon']] = df.b.str[1:-1].str.split(',', expand=True)

     a                                         b                 lat                  lon
0    0  (45.349586099999996, -75.81031967988278)  45.349586099999996   -75.81031967988278
1    1         (-37.77922725, 175.2010323246593)        -37.77922725    175.2010323246593
2    2                (-42.9945669, 170.7100413)         -42.9945669          170.7100413
3    3                 (-39.2711067, 174.154795)         -39.2711067           174.154795
4    4                   (51.2800275, 1.0802533)          51.2800275            1.0802533
5    5        (-41.30222105, 172.89453190955697)        -41.30222105   172.89453190955697
6    6                (-35.3712702, 173.7405337)         -35.3712702          173.7405337
7    7                (-45.7255555, 168.2936808)         -45.7255555          168.2936808
8    8                (-40.3284102, 175.8190684)         -40.3284102          175.8190684
9    9                (-45.1299859, 169.5248818)         -45.1299859          169.5248818
10  10         (-37.9503756, 176.93828736155422)         -37.9503756   176.93828736155422

A: Data
          Position
0   (45.349586099999996,-75.81031967988278)
1          (-37.77922725,175.2010323246593)
2                 (-42.9945669,170.7100413)
3                  (-39.2711067,174.154795)
4                    (51.2800275,1.0802533)
5         (-41.30222105,172.89453190955697)
6                 (-35.3712702,173.7405337)
7                 (-45.7255555,168.2936808)
8                 (-40.3284102,175.8190684)
9                 (-45.1299859,169.5248818)
10         (-37.9503756,176.93828736155422)

Solution
 #Strip of the brackets if column is string and not tuple.
 #str.split column to make it a list
 #stack it to dataframe it

 pd.DataFrame(np.vstack(df['Position'].str.strip('\(\)').str.split(',')), columns=['Lat','Long'])

             Lat                Long
0   45.349586099999996  -75.81031967988278
1         -37.77922725   175.2010323246593
2          -42.9945669         170.7100413
3          -39.2711067          174.154795
4           51.2800275           1.0802533
5         -41.30222105  172.89453190955697
6          -35.3712702         173.7405337
7          -45.7255555         168.2936808
8          -40.3284102         175.8190684
9          -45.1299859         169.5248818
10         -37.9503756  176.93828736155422


Q: Passing Multidimensional array with variable size Passing dimensions of the array to function but still getting an error!
Code (You can directly scroll down to the error it gives and see only those lines in code)
class Solution {
    public:
    int mod = 1e9 + 7;
    int checkRecord(int n) {
        int dp[n + 1][2][3];
        memset(dp, -1, sizeof(dp));
        return helper(0, 1, 2, n + 1, 2, 3, dp);
    }
    int helper(int idx, int A, int startL, int N, int M, int K, int dp[N][M][K]) {
        if(idx == N) return;

        if(dp[idx][A][startL] != -1) {
            return dp[idx][A][startL];
        }

        dp[idx][A][startL] = helper(idx + 1, A, 2, N, M, K, dp) % mod;

        if(startL > 0) {
            dp[idx][A][startL] += helper(idx + 1, A, startL - 1, N, M, K, dp) % mod;
        }
        return dp[idx][A][startL];
    }
};

Error
 error: cannot initialize a parameter of type 'int (*)[*][*]' with an lvalue of type 'int [n + 1][2][3]'
        return helper(0, 1, 2, n + 1, 2, 3, dp);
                                            ^~
 note: passing argument to parameter 'dp' here
    int helper(int idx, int A, int startL, int N, int M, int K, int dp[][M][K]) {
                                                                    ^

A:
int checkRecord(int n) {
    int dp[n + 1][2][3];

The size of an array variable must be compile time constant in C++. n + 1 is not compile time constant and as such the program is ill-formed.
If you want to create an array with runtime size, then you must create an array with dynamic storage duration. simplest way to do that is to use std::vector.

int helper(int idx, int A, int startL, int N, int M, int K, int dp[N][M][K]) {

Same applies to parameters which are also variables. Though there is slight difference since the array parameter will be adjusted to be a pointer to the first element of the array and the outermost dimension of the array i.e. N is ignored. The type of dp would be int(*)[M][K] if M and K were compile time constant.

Yeah, but 3d vector is too much to type vector<vector<..

In order to write long class template instances, you should pace yourself so that you don't get exhausted before the end. In case you are overcome by fatigue, take a short break to recover and continue later. I believe that you can do it.
That said, the inner dimensions of your array seem to be constant, so you don't need to use vectors inside vectors.

if(idx == N) return;

This is an ill-formed return statement in a non-void function.

A: Seems like you are trying to solve a competitive programming problem. So my answer is going to focus on that. I think others pointed out why it is not valid C++.
In C++, I don't see any easy way to achieve what you want.
In practice, when it comes to competitive programming problems, you may just define a big global array(As problems have fixed input sizes usually. In this case, there would be the max number of N, M, and K) and you don't have to struggle with passing it. Reuse the array for each case, but make sure you initialize it every time. Yeah, this is not a good practice in general but pretty handy for competitive programming.
If you think about 3D vectors are overkill, you may consider this.


Q: Prove -1 Transformation (A binomial identity):$\binom{-p}{q}=\binom{p+q-1}{q}(-1)^q$ Prove the following binomial identity :
$$\begin{align*}
\binom{-p}{q}=\binom{p+q-1}{q}(-1)^q
\end{align*}
$$
I played with $\binom{-p}{q}$ for a while but found nothing .

A: Note that for real $\alpha$ and positive integer $q$, $\alpha\choose q$ is defined by:
$${\alpha\choose q}=\frac{\alpha(\alpha-1)(\alpha-2)\cdots(\alpha-(q-1))}{q!}.$$
So:
$${-p\choose q}= \frac{(-p)(-p-1)(-p-2)\cdots(-p-(q-1))}{q!}=
(-1)^q\cdot\frac{p(p+1)(p+2)\cdots (p+(q-1))}{q!}=\\ =(-1)^q\cdot\frac{(p+q-1)!}{q!(p-1)!}=
(-1)^q{p+q-1\choose q}.$$


Q: How to use setMenuVisibility in fragment? I have a sliding tabbed layout with seven fragments. I am saving my events in another activity and retrieving data from database in fragment and creating views.
Now when I save the data in add event activity and finish that activity and return to fragment, the events are not getting created.  I am using setMenuVisibility funcion to show this events. But when I did debug the setMenuVisibility never run when I return from activity.
What's wrong here? How can I show events on fragments when I return from activity?
Fragment code:
public class Mon extends Fragment {

    private FrameLayout fab;
    private EventTableHelper mDb;
    private Intent i;
    private ViewGroup dayplanView;
    private int minutesFrom,minutesTo;
    private List<EventData> events;
    private List<View> list;
    private EventData e;
    private LayoutInflater inflater;
    public  boolean editMode;
    private RelativeLayout container;
    RelativeLayout parent;
     View eventView;
    private boolean mCheckFragment;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_mon, container, false);
        list = new ArrayList<View>();

        dayplanView = (ViewGroup) view.findViewById(R.id.hoursRelativeLayout);

        showEvents();

        mCheckFragment = true;

        return view;
    }

    private void createEvent(LayoutInflater inflater, ViewGroup dayplanView, int fromMinutes, int toMinutes, String title,String location,final int id) {

       eventView = inflater.inflate(R.layout.event_view, dayplanView, false);
        RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) eventView.getLayoutParams();

        container = (RelativeLayout) eventView.findViewById(R.id.container);
        TextView tvTitle = (TextView) eventView.findViewById(R.id.textViewTitle);
        list.add(eventView);

        if (tvTitle.getParent() != null)
           ((ViewGroup) tvTitle.getParent()).removeView(tvTitle);

        if(location.equals(""))
        {
            tvTitle.setText("Event : " + title);
        }
        else
        {
            tvTitle.setText("Event : " + title + " (At : " + location +")");
        }
        int distance = (toMinutes - fromMinutes);
        layoutParams.topMargin = dpToPixels(fromMinutes + 9);
        layoutParams.height = dpToPixels(distance);

        eventView.setLayoutParams(layoutParams);
        dayplanView.addView(eventView);
        container.addView(tvTitle);

        eventView.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                i = new Intent(getActivity(), AddEventActivity.class);
                editMode = true;
                i.putExtra("EditMode", editMode);
                i.putExtra("id", id);
                startActivityForResult(i, 1);

            }
        });
    }

 @Override
 public void setMenuVisibility(final boolean visible) {
     super.setMenuVisibility(visible);
     if (visible) {

         if(mCheckFragment) {
             removeView();
             showEvents();
             Toast.makeText(getActivity(), "Monday", Toast.LENGTH_SHORT).show();
         }
         // ...
     }
 }

    public void showEvents()
    {
        mDb = new EventTableHelper(getActivity());
        events = mDb.getAllEvents("Mon");

        for (EventData eventData : events) {

            int id = eventData.getId();
            String datefrom = eventData.getFromDate();

            if (datefrom != null) {
                String[] times = datefrom.substring(11, 16).split(":");
                minutesFrom = Integer.parseInt(times[0]) * 60 + Integer.parseInt(times[1]);
            }
            String title = eventData.getTitle();
            String location = eventData.getLocation();
            String dateTo = eventData.getToDate();

            if (dateTo != null) {
                //times = dateTo.substring(11,16).split(":");
                String[] times1 = dateTo.substring(11, 16).split(":");
                minutesTo = Integer.parseInt(times1[0]) * 60 + Integer.parseInt(times1[1]);
            }
            createEvent(inflater, dayplanView, minutesFrom, minutesTo, title, location, id);
            id++;

        }
    }

    public void removeView()
    {
        for(int i=0; i<list.size(); i++)
        {
            View view = (View)list.get(i);
            dayplanView.removeView(view);
        }
    }

    private int dpToPixels(int dp) {
        return (int) (dp * getResources().getDisplayMetrics().density);
    }

}

Thank you.


Q: Why does it matter if other players are in a group? In How to know if teammates are in a premade squad or not?, we learned that it's not possible to directly determine whether your teammates are in a group together, and that some people on the Battle.net forums are displeased with this non-feature.
Why would anyone care?  Is it desirable (or undesirable) to be paired with a group of players?  Is it considered poor etiquette to form a group of three or four people and hit quick play (so that there are one or two odd people out)?
My friends and I usually play relatively casually, so we don't (for example) worry too much about strategically combining our heroes to make them more effective.  It seems to me that our presence would have a minimal effect on a game otherwise composed of individual players.

A: The reason you would care is because people who play as a group are more likely to have good synergy and teamwork, especially due to the fact that they are more likely to be using voice chat. While the game does indeed have in game voice chat, and as @DanmakuGrazer pointed out- that defaults to a private channel for groups, and very few people use in-game voice at all in my experience. They are much more likely to use something like teamspeak or curse voice as a group and coordinate strategies. I would consider is desirable to be paired with a group of players because of this, and I don't think it is poor etiquette to play as a group of people. If it were, the option probably wouldn't exist, and I personally prefer to play with my friends rather than random people. Though, if you do play as a group of 4 or 5, you may get accused of trying to pubstomp or tryharding.

A: The reason a lot of people care would be how matchmaking in most team based games works, it tries to match groups of players against teams that have other groups of players. So if you and your friends are a group of 4, it will try match you against another group of 4 and then fill in the extras.
Now from your side of things that seems fine, as it's a 4v4 team with some extras. Since you would both be equal in terms of communication and teamwork. Although imagine the reverse when you are one of the extra players, you are playing against a group of 4 with superior teamwork and communication while getting no benefits of a team yourself.
An example would be your group of 4 decide to ball up and roam together, player 5 has no idea what is happening as it hasn't been communicated to him, he goes off to do his own thing. He encounters the enemy team who have also decided to ball up and roam together, he dies.
I believe that may be why some people prefer the idea of a separate queue for solo play only, so they know no one has any extra teamwork advantage on them before going into a match.


Q: Shouldn't solar cells be nonreflective? If solar cells take energy from light, then why do they reflect it? How come they can take energy without actually affecting the source?
Shouldn't reflected light (as a minimum) have a lower frequency?
Assume that there exist a "perfect solar cell" (i.e. one that takes 100% energy from light). Shouldn't it be nonreflective?

A: Good question!
Solar cells made of silicon are naturally quite reflective (30%), and there is quite an art to making them less so - because any sunlight reflected is not available for power conversion. Antireflective coatings are not easy to make since they tend to work best at one wavelength and angle of incidence; you try to make them so the total power extracted from the sun will be greatest, but that may mean some wavelengths will be reflected. Note also that the reflected photons typically didn't make it into the silicon - in other words, the solar cell didn't extract some energy and reject a lower energy photon.
At this website you can see a more detailed description - I will just reproduce here the plot of reflectivity for "no coating", "under glass", and "optimized" coating. As you can see, a lot is done to mitigate the problem, but as mmesser314 pointed out, even things that are almost "perfectly" (99%) black will reflect 1% of the light, which is quite enough for the eye to pick up.

A: It is hard to make anything be truly black. At any frequency, some light will be absorbed, some reflected, and some transmitted.
Eye response to light is logarithmic - We can see bright light, but also much dimmer light. So if 99% of the light is absorbed, that still may not appear black.
Smooth surfaces produce a mirror like reflection. If illuminated by the Sun, all the photons arrive from more or less the same direction. They have the same direction after reflection. If you eye is in the path of the reflected light, it receives all the reflected light. This is much brighter than a diffuse reflection from a rough surface, where light is scattered in all directions, and you only receive a small fraction of the total.
Typically, reflection does not change the photons. It just reduces the number of them. If the reflected light is redder, it is because bluer photons were absorbed.

A: How come they can take energy without actually affecting the source?
Well the source is the sun, so it just sends out light and it doesn't matter where it goes, the sun will keep out sending out light, so it will be sunny tomorrow, amd the next day and the next day.....it will keep on going for a long time
Shouldn't reflected light (as a minimum) have a lower frequency?
It does. The light from the sun is actually a range of frequenies and the solar uses some of these frequencies to make electrical energy.   So the light coming in to the solar cell gives up some of its energy into the cell and the light reflected from the cell is at a lower frequency because it has lost energy.
Assume that there exist a "perfect solar cell" (i.e. one that takes 100% energy from light). Shouldn't it be nonreflective?
Sure, we would love to make a solar cell that good but we can't and yes it would be non reflective because all the solar energy going in would stay inside the cell, none comes back out so no reflection.


Q: HTML5 video not playing on IE9 Im trying to use HTML5 video on IE9 but doesn't play.
When i play it locally evrything works fine, but when i upload to the server doesn't work.
This is the URL: http://inoq.com/lxgo2/monumentos.html
It works fine in all other browsers(Chrome, Safari, Opera, Firefox..) just not IE9.
I already added the mime types too .htaccess file:
AddType video/ogg                      ogv
AddType video/mp4                      mp4 m4v
AddType video/webm                     webm
This image shows the network logs on IE9:
Network logs IE9 http://inoq.com/lxgo2/network-log.jpg
Any idea on what can be the problem?
Thanks
Bruno


Q: When does a matrix have an "invariant quadratic form"? Yesterday I computed that the matrix
$$
A = \begin{pmatrix} 2&1\\1&1\end{pmatrix}$$
satisfies $q(m,n) = q \left((m,n)A\right)$ for the quadratic form
$$q(m,n) = m^2 - mn - n^2.$$
E.g., $-1 = q(1,1) = q(3,2) = q(8,5) =\ \ldots\ $ which is quite satisfying.
On the other hand, the matrix
$$B = \begin{pmatrix} 1&1\\1&0 \end{pmatrix}$$
fixes no such quadratic form, although it does preserve $(m,n)\mapsto (q(m,n))^2$ (since $B^2 = A$ this is maybe unsurprising).
My question. Is it known when a square matrix with integer entries preserves a non-trivial quadratic form? Moreover, when does such a quadratic form have integer coefficients?
It seems easy to verify for individual examples, but is there a general theory?

A: I'll try to give a partial answer: when $A$ is symmetric a nondegenerate form $q$ with integer coefficients can be constructed if and only if $A$ has determinant $1$, or it is diagonal with eigenvalues $\pm 1$.
Let $Q$ be the matrix defining your quadratic form, in your example
$$Q = \begin{pmatrix} 1&-1/2\\-1/2&-1\end{pmatrix},$$
meaning that
$$q(v) = v^T Q v$$
if we write $v = \begin{pmatrix} m\\n\end{pmatrix}$.
This matrix will always be symmetric, and the quadratic form will have integer coefficients if the off-diagonal elements are half-integers, and the diagonal elements are integers.
In this notation, your question comes down to: given a matrix $A$ over the integers, can I find a matrix $Q$ such that the associated binary form $q$ has integer coefficients, and $q(Av) = q(v)$, which is the case when $A^TQA = Q$.
Note that this is a linear system in the coefficients of $Q$, hence $Q$, if it has solutions, has rational solutions, hence can be scaled to define a form with integer coefficients.
By taking determinants, you immediately see that $A$ must have determinant $\pm 1$, except possibly when $q$ is degenerate. Let's assume it is non-degenerate, so $Q$ is invertible, and we have to find out when it can hold that
$$QA^{-1}Q^{-1} = A^T$$
This says that $A^{-1}$ and $A^T$ are similar, which is a strong condition.
Let's first consider the case that $A$ is symmetric, like in your examples. Then $A$ is diagonalizable by an (orthogonal) matrix $S$: $A = S^{-1}DS = A^T$ for a diagonal matrix $D$, and we have
$$A^{-1} = S^{-1}D^{-1}S, \ \ \ \ A = A^T = S^{-1}DS,$$
The eigenvalues are of the form $\lambda, \pm\lambda^{-1}$ (because the determinant is $\pm 1$). $A^T$ has the same eigenvalues, and $A^{-1}$ has eigenvalues $\lambda^{-1}, \mu^{-1} = \pm\lambda$, again the same eigenvalues, possibly up to a sign.
Consider the case that $\det(A) = 1$. In this case either $D^{-1} = D$, or $D^{-1} = P^{-1}DP$, where $P$ is the permutation matrix
$$P = \begin{pmatrix} 0&1\\1&0\end{pmatrix}.$$
In the first case $A$ is $\pm1$ and preserves every form, in the second we can take $Q$ to be a suitable multiple of $S^{-1}PS$.
When the determinant is -1, the eigenvalues of $A$ and $A^{-1}$ being equal means that $\{\lambda, -\lambda^{-1}\}$ has to be equal to $\{\lambda^{-1}, -\lambda\}$. This is only possible when $\lambda = 1$, and then $D^{-1} = D$ and $A^{-1} = A$, and since $A\ne\pm I$, the characteristic polynomial of $A$ must be $X^2 - 1$ (by Cayley-Hamilton).
That means that $A$ must be traceless, hence of the form
$$A = \begin{pmatrix} a&b\\b&-a\end{pmatrix}$$
with $a^2 + b^2 = 1$. This leaves multiples of
$$A = \begin{pmatrix} 1&0\\0&-1\end{pmatrix}$$
and of
$$A = \begin{pmatrix} 0&1\\1&0\end{pmatrix}$$
as the only possibilities, and they should preserve the binary form given by the identity matrix, $q(m,n) = m^2 + n^2$, which indeed they do.
I'll edit later if I can think of a way to approach the general case.

A: There is something we can work out for determinant $-1.$ Namely, a 2 by 2 matrix of integers with determinant $-1$ is an automorphism if and only if it has trace zero.
Given $r,s,t$ integers with $r^2 + st = 1,$ but $rst \neq 0,$ we get an automorphism of
$$ f(x,y) = x^2 + rtxy+ t^2 y^2 $$
with matrix identity
$$
\left(
\begin{array}{cc}
 r & s \\
 t & -r \\
\end{array}
\right)
\left(
\begin{array}{cc}
 2 & rt  \\
 rt & 2 t^2 \\
\end{array}
\right)
\left(
\begin{array}{cc}
 r & t \\
 s & -r \\
\end{array}
\right)  =
\left(
\begin{array}{cc}
 2 & rt  \\
 rt & 2 t^2  \\
\end{array}
\right)
$$
There are other choices. Once $r^2 + st=1,$ the remaining condition on $Ax^2 + B xy + C y^2$ is just
$$ At = Br + Cs  $$

A: Thanks for these answers. Prompted by the $2\times2$ and $3\times3$ case, the following is apparent.
Proposition.
$A \in \mathbb R^{n,n}$ fixes a non-trivial quadratic form if and only if
$$
1 \in \left(\sigma(A)\right)^2 := \left\{\lambda \mu\,|\,\lambda,\mu \in \sigma(A)\right\},
$$
where $\sigma(A) = \{\lambda \in \mathbb C\,|\,\lambda\text{ is an eigenvalue of }A\}$.
I.e., either $\pm1$ is an eigenvalue of $A$, or there is some $\lambda\neq 0$ s.t. $\lambda$ and $\lambda^{-1}$ are both eigenvalues of $A$
Proof.
($1$): First, if $\lambda,\mu \in \sigma(A)$ satisfy $\lambda\mu=1$, then (letting $A^Tv = \lambda v$, $A^Tw = \lambda w$) $A$ preserves the quadratic form given by the matrix $Q = vw^T \in \mathbb R^{n,n}$ (with respect to standard basis on $\mathbb R$):
$$
A^TQA = (A^Tv)(A^Tw)^T = \lambda\mu\, vw^T = vw^T = Q.
$$
Moreover, $Q$ cannot be skew-symmetric, so defines a non-trivial quadratic form: the $(i,j)$th entry of $Q$, $Q_{i,j} =v_iw_j$ is non-zero for at least one $i,j$. If $i=j$ then we're done, so assume that thee exists $i\neq j$ with $v_iw_j\neq0$; and assume also that $v_jw_i + v_iw_j = 0$ (for skew-symmetry). This implies that either $v_iw_i\neq 0$ or $v_jw_j\neq 0$ by the following lemma, so we have a non-zero diagonal entry.

Lemma. If $(a,b,c,d)\in\mathbb R$ satisfy $$ ab + cd = 0, \quad ac = 0,\quad bd =0, $$ then $(a,b,c,d)=(0,0,0,0)$.
Proof of lemma:
Just multiply the first equation by $ad$ and $bc$, you get $a^2 + d^2=0$, and $b^2 + c^2 = 0$ respectively.

($2$) Conversely, suppose that $Q\in \mathbb R^{n,n}$ is symmetric and non-zero, and that $A$ preserves the quadratic form associated to $Q$. Then $$A^TQA = Q$$ (this must hold since the LHS is also symmetric).
Enumerating the elements above the diagonal of $Q$ by $(q_1,\ldots,q_{N})$, where $N = n(n+1)/2$, the previous equation is equivalent to the following.
$$
B\begin{pmatrix}q_1\\\vdots\\q_N\end{pmatrix} = \begin{pmatrix}0\\\vdots\\0\end{pmatrix},
$$
where $B$ is an $N\times N$ matrix whose entries are quadratic expressions in the entries of A: $(A_{i,j})_{i,j}$. In this light, $Q$ is non-trivial is the vector $(q_1,\ldots,q_N)$ is non-zero, i.e. $B$ is singular:
$$\det(B) = 0.$$
This is a degree $2N$-polynomial in $A_{i,j}$. now consider the following equation. Let $\lambda_1,\ldots, \lambda_n$ denote the eigenvalues of $A$. There exists a pair of eigenvalues which multiply to one is equivalent to the equation
$$
\prod_{1\leq i\leq j\leq n }\left(\lambda_i\lambda_j - 1\right) = 0.
$$
Now, the left hand side is a symmetric degree-$N$ polynomial in $(\lambda_1,\ldots, \lambda_n)$, therefore, by the fundamental theorem of symmetric polynomials, it is can be expressed in terms of the following:
$$
\left(1,\sum_i \lambda_i, \ \sum_{i<j}\lambda_i\lambda_j,\ \sum_{i<j<k}\lambda_i\lambda_j\lambda_k,\ \ldots\ , \ \lambda_1\cdots\lambda_n\right);
$$
That is, the equation above is a linear combination of multiples-of-polynomials from this list.) Magically, these also all appear as coefficients of the characteristic polynomial of $A$. Considering this, each polynomial in this list can be replaced by a homogeneous polynomial in $A_{i,j}$'s of the same degree.
Therefore the above degree $N$ polynomial in $\lambda_i$ can be written as a (monstrous) degree $N$ polynomial in the entries $A_{i,j}$, and this polynomial must be a factor of $\det(B)$, since by the first case it is sufficient to have some $\lambda_i\lambda_j=1$ to have $\det(B)=0$. But then they have the same degree ($N$), so $\det(B)$ cannot have any other non-scalar factors. Thus, the eigenvalue condition is actually sufficient. $\square$
Remark.
Mote that quadratic forms which are fixed by $A$ in fact form a vector space.
Extension.
From the above, my guess is that $A$ fixes a non-degenerate quadratic form if and only if $\{\lambda \in \sigma(A)\,|\,1 \in \lambda\cdot\sigma(A)\} = \sigma(A)$, i.e. all eigenvalues are involved. Equivalently, whenever $\lambda$ is an eigenvalue of $A$, $\lambda \neq 0$ and $1/\lambda$ is also an eigenvalue of $A$. Moreover, its Jordan normal form should be a diagonal matrix. Is this sufficient? I'm not sure.


Q: 0x4 Decompression error in Python Confluent Kafka I've been having trouble getting python-confluent-kafka to work on my windows server.
When creating a simple consumer on my local machine, everything works fine.
However, once on the windows server, I will receive the messages but get the following error:

b'Decompression (codec 0x4) of message at 24023756 of 9550 bytes failed: Local: Not implemented'

I copied the exact conda environment I have on my local machine to the server.

A: Turns out it had to do with the .dll's not being found due to the Path/Environment Variables not being configured properly.


Q: MemCached on Windows x64 This question has previously been asked, but that was a year ago and I wanted to know if there had been any developments since then.
Basically we'd like to use a MemCached Server on a Windows Server 2008 R2 machine... which is only x64, obviously.
I haven't found any details on a Win64 version of MemCached, but there is still the solution from the previous thread (which I haven't tried yet) to use a bit of software called MemCacheD Manager running MemCached 1.2.6. However, the current version of MCd is 1.4.4 and I was wondering if there had been any improvements since then.

A: While I may not have quantitative data to highlight the differences between all these codebases, I still think the answer is "you don't want to do that".
Memcached is pretty deeply immersed into Unix and the Unix style kernel semaphores. Getting it to run as fast on Windows would require major effort; and this effort doesn't have any sponsors right now...
You should look at:

*

*Sharedcache -- open source, mature.

*Appfabric -- from Microsoft, quite mature despite being "late beta".

*NCache -- commercial, I don't know much about it.

*StateServer and family -- commercial, mature.
Edit: If you prefer Memcached, then there is nothing to stop you from using it -- but would it perhaps be easier to put a couple of Unix boxes on your network, run the Memcached server on the Unixes, and use f.x. the Enyim client from your Windows boxes to the servers?
Update 2011: This old answer popped up again, when the "provincial" comment was added below. Things have changed since the answer was given, the x64 Windows port of Memcached has a steady sponsor now.
Membase is built on top of Memcached, and to quote from Membase's page: "If desired, Membase can be configured to provide only Memcached services [...], disabling database functionality.".
I don't have any personal experience with Membase, but it seems worth checking out if you need Memcached on Windows x64.

A: I think NorthScale Memcached Server is the solution.

A: I'm using MemCached 1.2.6 on Windows 2003 x64 without a problem. It's running in 32-bit mode, so the amount of memory that can be allocated might be limited. If that's an issue: run multilple instances on different ports.
I know this is not an answer to your question about MemCached in 64-bit, but it might help to know it works flawlessly in 32-bit on Windows x64.

A: We're currently running memcached 1.2.6 on Windows 2003 R2 x64 and have been for quite a while. It runs like a champ.  As I recall we did not use MemCacheD Manager.
To test it, I just downloaded 1.2.6 again on my Windows 7 x64 workstation.  I had to change the compatibility to always run as administrator, but once I did that I was able to run memcached -d install and, after the obligatory prompt, it installed the service for me.
While it would be nice to have a native 64bit port, we haven't seen any issues running it this way in more than a year.  We haven't had any problem with the amount of allocated memory yet either, but we will simply run multiple instances if that arises.

A: Answer: There haven't been any developments since the question was last asked. There are no rumblings of an x64 version of MemCached anywhere.

A: On windows you might be better off using appfabric

A: I am running in to the issue of allocating the memory more than 2GB to memcached as service in windows x64 bit .NET version.
I want to use nearly 30 GB of RAM per Node in Windows Server 2008 R2
Idrees

A: I am using memcached rather extensively on my Windows Web application and have been running instances for the last three years. They're all 32-bit versions of memcached on 64-bit OS--incidentally, the same as yours.
What the 64-bit version gets you is the ability to allocate more than 4 GB of memory to a memcached instance. I'm only allocating 1.5 GB personally so I've never had a need for the 64-bit version. If your needs are the same, I can assure you that the 32-bit version is quite capable.
(Incidentally, I would recommend steering clear of the MemCacheD Manager application. I've had it reliably crash my memcached v1.4.4 instances. Use telnet and the stats command if you need to see what's going on.)


Q: Adding new unique grouping ID based on group_by variable I have a dataset with drugs being administered overtime. I want to create groups for each block of the drug being administered. I figured out a simple method to do this with a for-loop that I can apply to each patients set of drugs.
BUT I am curious if there is simple way to do this within the realm of tidyverse?
Not that it matters, but more so I am curious if there is a simple method already created for this problem.
Set-up
have <- tibble(
    patinet = c(1),
    date = seq(today(), today()+11,1),
    drug = c(rep("a",3), rep("b",3), rep("c",3), rep("a",3))
)

## Want

want <- tibble(
    patinet = c(1),
    date = seq(today(), today()+11,1),
    drug = c(rep("a",3), rep("b",3), rep("c",3), rep("a",3)),
    grp =  sort(rep(1:4,3))
)

> have
# A tibble: 12 × 3
   patinet date       drug
     <dbl> <date>     <chr>
 1       1 2022-03-16 a
 2       1 2022-03-17 a
 3       1 2022-03-18 a
 4       1 2022-03-19 b
 5       1 2022-03-20 b
 6       1 2022-03-21 b
 7       1 2022-03-22 c
 8       1 2022-03-23 c
 9       1 2022-03-24 c
10       1 2022-03-25 a
11       1 2022-03-26 a
12       1 2022-03-27 a

> want
# A tibble: 12 × 4
   patinet date       drug    grp
     <dbl> <date>     <chr> <int>
 1       1 2022-03-16 a         1
 2       1 2022-03-17 a         1
 3       1 2022-03-18 a         1
 4       1 2022-03-19 b         2
 5       1 2022-03-20 b         2
 6       1 2022-03-21 b         2
 7       1 2022-03-22 c         3
 8       1 2022-03-23 c         3
 9       1 2022-03-24 c         3
10       1 2022-03-25 a         4
11       1 2022-03-26 a         4
12       1 2022-03-27 a         4

A: You can use data.table::rleid
have %>% mutate(group = data.table::rleid(drug))

# A tibble: 12 x 4
   patinet date       drug  group
     <dbl> <date>     <chr> <int>
 1       1 2022-03-16 a         1
 2       1 2022-03-17 a         1
 3       1 2022-03-18 a         1
 4       1 2022-03-19 b         2
 5       1 2022-03-20 b         2
 6       1 2022-03-21 b         2
 7       1 2022-03-22 c         3
 8       1 2022-03-23 c         3
 9       1 2022-03-24 c         3
10       1 2022-03-25 a         4
11       1 2022-03-26 a         4
12       1 2022-03-27 a         4


Q: Apply function to URL and write in new column in CSV I'm a newbie and surprised there's already not a clear answer similar to what I'm asking, apologies if this is a duplicate.
I have a list of URLs in a CSV file I'm trying to shorten, I want to loop through my CSV file and then write a new column with the shortened URL right next to the original URL.
from pyshorteners import Shortener
import csv

def generate_short(url):
    x = shortener.short(url)
    return x
with open('Links_Test.csv') as csvfile:
    my_date = csv.reader(csvfile, dialect = 'excel')
    for row in my_data:
        x = shortener.short(row)
        print(X)

EDIT:
I keep getting the error "ValueError: Please enter a valid url" and don't know how to proceed from here.....I'm sure I'm the problem.
Here's what my input data looks like:
URL
http://www.google.com
http://www.facebook.com
http://www.twitter.com
http://www.linkedin.com

and here's what I want my output to look like:
URL                        Short_URL
http://www.google.com      http://goo.gle
http://www.facebook.com    http://goo.g3c
http://www.twitter.com     http://goo.g3a
http://www.linkedin.com    http://goo.g2q

Thank you for your help.  I was very surprised there's not already a clear answer posted (at least I couldn't find it) so I'm sorry if this is a duplicate.

A: Apply the function on row[0] or row['URL']
Also you have to apply it on my_data.iterrows()and not on my_data
from pyshorteners import Shortener
import pandas as pd

def generate_short(url):
    x = shortener.short(url)
    return x
    my_date = pd.read_csv( 'Link-Tests.csv', sep = "\t") #seperator argument is optional. It can be a semi colon, a tab. Check your CSV file for knowing what the separator is.
    for index,row in my_data.iterrows():
        x = shortener.short(row[0])
        print(X)

If you can always store the shortened URL into a separate list, convert it into a DataFrame and then merge with the original dataframe based on index.
lst = []
my_date = pd.read_csv( 'Link-Tests.csv', sep = "\t")
    for index,row in my_data.iterrows():
        x = shortener.short(row[0])
        lst.append(X)
df = pd.DataFrame(lst, columns=["Short-Url"])
my_data = my_data.join(df, how= 'outer')

A: First try doing this:
from pyshorteners import Shortener
import csv

def generate_short(url):
    x = shortener.short(url)
    return x
with open('Links_Test.csv') as csvfile:
    my_data = csv.reader(csvfile, dialect = 'excel')
    for row in my_data:
        print(row) # output: ['URL'], ['google.com']...

You probably want to use next() or maybe look at this thread  to ignore the header. Also, you probably want to use row[0] to get the first item in the list. So your final code might be
from pyshorteners import Shortener
import csv

def generate_short(url):
    x = shortener.short(url)
    return x
with open('Links_Test.csv') as csvfile:
    next(csvfile) # skip the header row
    my_data = csv.reader(csvfile, dialect = 'excel')
    for row in my_data:
        print(row[0]) # output: 'google.com' ....
        # do the link shortener stuff here


Q: How to print a multi-dimensional array in a GridView? I print unidimensional array fine - it works.
http://aspsnippets.com/Articles/Binding-Arrays-to-GridView-in-ASP.Net.aspx
string[,] arr2D =
{
      { "John", "21" },
      { "Smith", "33" },
      { "Ryder", "15" },
      { "Jake", "18"},
      { "Tom","34" }
};

ArrayList arrList = new ArrayList();

for(int i=0;i<5;i++)
{
    arrList.Add(new ListItem(arr2D[i, 0], arr2D[i, 1]));
}

Grid2D.DataSource = arrList;
Grid2D.DataBind();

But the problem is when I try to put "ArrayList", it does not exist in the context of the language. any idea how to fix this, or another method to do this. and i try with this
protected void Page_Load(object sender, EventArgs e)
{
    if(!IsPostBack)
    {
        //enter code here
        BindGridview();
    }
}

private void BindGridview()
{
    string[,] arrlist = {
                    {"Suresh", "B.Tech"},
                    {"Nagaraju","MCA"},
                    {"Mahesh","MBA"},
                    {"Mahendra","B.Tech"}
                    };
    DataTable dt = new DataTable();
    dt.Columns.Add("Name");
    dt.Columns.Add("Education");

    for (int i = 0; i < arrlist.GetLength(0);i++)
    {
        dt.Rows.Add();
        dt.Rows[i]["Name"] = arrlist[i,0].ToString();
        dt.Rows[i]["Education"] = arrlist[i,1].ToString();
    }

    gvarray.DataSource = dt;
    gvarray.DataBind();
}

But DataTable doensn't exist.

A: your code to fill the datatable is not correct - please try the below eg.
 private void BindGridview()
{
    string[,] arrlist = {
                    {"Suresh", "B.Tech"},
                    {"Nagaraju","MCA"},
                    {"Mahesh","MBA"},
                    {"Mahendra","B.Tech"}
                    };
    DataTable dt = new DataTable();
    DataRow dr = null;
    dt.Columns.Add(new DataColumn("Name", typeof(string)));
    dt.Columns.Add(new DataColumn("Education", typeof(string)));
    //dr = dt.NewRow();
    for (int i = 0; i < arrlist.GetLength(0);i++)
    {
        dr = dt.NewRow();
        dr["Name"] = arrlist[i,0].ToString();
        dr["Education"] = arrlist[i,1].ToString();
    }
    gvarray.DataSource = dt;
    gvarray.DataBind();
}

A:   Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
        Dim str_array(,) As String ' 2D array declaration
        str_array = {{"Suresh", "B.Tech"}, {"Nagaraju", "MCA"}, {"Mahesh", "MBA"}, {"Mahendra", "B.Tech"}} ' array initialization
        For i As Integer = 0 To (str_array.Length / 2) - 1 'limit is set to this because the length includes both the indices and white space
            gv.Rows.Add(str_array(i, 0), str_array(i, 1))
        Next
  End Sub


Q: How to efficiently extract the visible areas of a Bitmap? I have a bitmap and would like to create and use a filter that would take all the visible parts of the bitmap (all pixels with alpha != 0) and set them into a particular value while drawing on an Android view.
I was able to achieve this with a simple for-loop on the bitmap:
private int maskAlpha = 0xAA;
private Paint maskPaint;
private Bitmap targetViewLayoutBitmap;

public CustomView(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    maskPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
    maskPaint.setColor(Color.argb(maskAlpha, 0, 0, 0));
}

...

private void setTargetViewLayoutBitmap(final Bitmap viewBmp) {
    for (int x = 0; x < viewBmp.getWidth(); x++) {
        for (int y = 0; y < viewBmp.getHeight(); y++) {
            int pixel = viewBmp.getPixel(x, y);
            boolean isVisiblePixel = ((pixel & 0xff000000) != 0);
            targetViewLayoutBitmap.setPixel(x, y, isVisiblePixel ? 0x00ffffff : 0xff000000);
        }
    }
}

@Override
protected void onDraw(Canvas canvas) {
    ...
    canvas.drawBitmap(targetViewLayoutBitmap, targetViewLeft, targetViewTop, viewMaskPaint);
}

Is there a more efficient way of achieving this?

A: You can use a PorterDuffColorFilter with a PorterDuff.Mode.SRC_IN.
This example takes a Drawable and changes every non transparent pixel to green:
drawable.setColorFilter(new PorterDuffColorFilter(Color.GREEN, PorterDuff.Mode.SRC_IN));

Note: You can easily apply it to a Bitmap converting it into a Drawable using
Drawable drawable = new BitmapDrawable(getResources(), yourBitmap);

A: After some testing I figured out the solution below using a ColorMatrixColorFilter works in an optimal way (applying the matrix takes less than 1/20 of the for-loop).
public CustomView(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);

    viewMaskPaint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.DITHER_FLAG);
    viewMaskPaint.setAlpha(maskAlpha);

    colorFilterMatrixPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
    colorFilterMatrixPaint.setColorFilter(new ColorMatrixColorFilter(new float[] {
        0, 0, 0, 255, 0,
        0, 0, 0, 255, 0,
        0, 0, 0, 255, 0,
        0, 0, 0, -255, 255
    }));
    setWillNotDraw(false);
}

private void setTargetViewLayoutBitmap(final Bitmap viewBmp) {
    targetViewLayoutBitmap = Bitmap.createBitmap(viewBmp.getWidth(), viewBmp.getHeight(), Config.ARGB_8888);
    Canvas canvas = new Canvas(targetViewLayoutBitmap);
    canvas.drawBitmap(viewBmp, 0, 0, colorFilterMatrixPaint);
}

@Override
protected void onDraw(Canvas canvas) {
    ...
    canvas.drawBitmap(targetViewLayoutBitmap, targetViewLeft, targetViewTop, viewMaskPaint);
}

Thank you for @Selvin for pointing me to the right direction (this solution was an interpretation of what you suggested).


Q: More than one path from A*? I have written an A* that works nice. It gives me the shortest path between two nodes. However, I would like to have two or maybe even three paths. The best, the second best and the third path (if there is more than one path available). Kinda like directions on Google Maps where you can see multiple options between two cities.
Is this possible with A* or am I stuck with only getting the best result? If it is possible, please point me in the right direction. If not possible with A*, what algorithm should I look at that can do this?
My implementation of A* is from the pseudocode on wikipedia (http://en.wikipedia.org/wiki/A*_search_algorithm#Pseudocode), and is written in VB .NET. If that is of any importance.
Thank you.

A: when you perform A* search you change state of priority queue. When you come to finish you put away the best vertex nearest to the finish. Also there some other vertices near finish already, you can peek them from the queue too and get "another best path".
But you can get different results: sometimes the paths can diff in only last edge.
Like this: -------<=>finish. If there is really another best path with similar length then you will find it.
I think Google provides many paths because they use different metrics simultaneously. The metrics give different results and solve path optimization problem using different parameters.

A: Getting the exact second-shortest path requires something like this.
If you don't care about that kind of precision, then you can introduce a bit of randomness into the shortest path:

*

*Cut a vertex or edge from the shortest path and recompute.

*At some point along the shortest path, make an intentional wrong turn somewhere and recompute from there.

A: Recompute the A* algorithm using the same graph but with different weightings. The weighting on each arc, for the fastest journey, ought to be the time taken to traverse that arc, which is the length of the arc divided by the expected speed to travel along it.
You can create a new set of weightings using only the distance, not the expected speed (it is more convenient to assign the same speed to every arc). That will give the shortest path, not the fastest one.
You can then create a compromise between shortest and fastest. You now have three (possibly) different routes.
Other options:
(i) add a weight to every arc to account for the junctions at start and end; tinker with this weight, allowing you to create routes that minimise turns. You can also add extra weights for very sharp turns, or turns across the traffic flow (right turns in UK, Australia, India, etc.; left turns in USA, France, etc.).
(ii) Create a route that avoids motorways / freeways by setting the cost of them to a very high value.
(iii) Use time of day, or actual on-line information, to estimate traffic flow and modify weightings based on that.


Q: Using std::string in c++ for unmanaged c# dll I'm trying to set up an unmanaged DLL package for c# for a c++ SDK that a client has provided. This SDK uses std::string and std::wstring variables. I found out that it's hard/impossible to use STL variables like string and wstring for this but it's kind of my last resort. I'm really hoping for someone that could tell me a possible way of building a c# dll wrapper for c++ methods that use std::string & std::wstring.

A: Have you tried converting std::string to System::String^ as stated in MSDN docs


Q: Content Editor Web Part Does Not Allow Edits Once Added Via Designer I have created a page layout in SharePoint Designer 2010 and I added the content editor webpart so that users could add content in a specific part on the page. When i saved and published my page layout and created a new page, I could see the webpart but when the page was in edit mode, I could not edit it. It does not even show the "Click here to edit this web part" text. All i see is a box.
Is there a setting I am supposed to change within Designer? Am i trying to use this in the wrong way?

A: In order to get the content editor web part to work, you must first create a web part zone and place it on the page. Then you can add web parts to that section. Now when i go to the page in edit mode, i am able to add content and save.

A: In edit mode you should click on the box. That will bring up the ribbon tools for text editing.
Another alternative to your approach is by using RichHtmlField instead of content editor
<PublishingWebControls:RichHtmlField InputFieldLabel="centercontentbox" FieldName="6946f02c-c941-452e-be99-14126eb266ef" runat="server"></PublishingWebControls:RichHtmlField>


Q: Does only one Thread executing a Kernel implement the declaration of an array in Shared Memory in CUDA I am implementing the following CUDA kernel that stores an array in Shared Memory:
// Difference between adjacent array elements
__global__ void kernel( int* in, int* out )  {
   int i  = threadIdx.x + blockDim.x * blockIdx.x;

   // Allocate a shared array, one element per thread
   __shared__ int sh_arr[BOCK_SIZE];

   // each thread reads one element to sh_arr
   sh_arr[i] = in[i];

   // Ensure reads from all Threads in Block complete before continuing
   __syncthreads();
   if( i > 0 )
      out[i] = sh_arr[i] - sh_arr[i-1];
   // Ensure writes from all Threads in Block complete before continuing
   __syncthreads();
}

BLOCK_SIZE is a constant declared outside the kernel.
It seems like every Thread that executes this Kernel will create a new array because every Thread that executes this Kernel will see this line:
__shared__ int sh_arr[BOCK_SIZE];

Is it the case that only the first Thread that executes this Kernel will "see" this line, and all subsequent kernels overlook this line?

A: Shared variables in CUDA are shared between threads in the same block. I don't know exactly how it is done under the hood but threads in the same thread-block will see __shared__ int sh_arr[BOCK_SIZE]; however, since it has the __shared__ modifier, only one thread will create the array while the others will just use it.


Q: How can I remove some empty closing and opening divs? I'm working with some HTML markup that I can't change, and in some instances on particular pages it breaks a layout. What I need to do is remove  - using empty() or remove() or some other jQuery function - the tags commented below
 and
.
Can I do this with jQuery?
How can I select those two tags?
...

Text

 // Remove this closing div

  // Remove this opening div

        <form class="cart" action="example.com" method="post" enctype='multipart/form-data'>

...


Q: How to display website in cordova? i'm just wanted to know how to simply display my website into a crossplatform mobile app using cordova? What I need to change into index.html or config.xml?

A: You can use the Cordova plugin InAppBrowser https://cordova.apache.org/docs/en/latest/reference/cordova-plugin-inappbrowser/

A: No need to change, if you just want your cordova project would run on web as well then use below command :
cordova platform add browser

This works for me.


Q: [IfcOpneShell]Unabled to add instance from IFC2X3 schema to file with IFC4 schema I am using IfcOpenShell in python.
When I try to createed a new file and added entity, I get the following error.
How can I get rid of the error?
[program]
ifc_file = ifcopenshell.file()
ifc_file.add({IfcBuildingElementProxy})

[error]
Unabled to add instance from IFC2X3 schema to file with IFC4 schema

Thanks for any help.

A: I found my own answer.
I had to set 'schema'
ifc_file = ifcopenshell.file(schema=other_ifc_file.schema)
ifc_file.add({IfcBuildingElementProxy})


Q: R - Replace selective rows data frame I have a dataframe "A" with the following shape
log P1  P2  P3  P4  P5  Method  Round   #TSamples   #Samples0   #Samples1   FP  TN  TP  FN  Time    Det_Time
data1   2   0   0   0   LOF     1   3   3   0   0   3   0   0   0.00800108909606934 1
data1   2   0   0   0   Mahalanobis 1   3   3   0   0   3   0   0   0.00100016593933105 1
data1   2   0   0   0   Cook    1   3   3   0   0   3   0   0   0.00900101661682129 1
     ...........

And another dataframe "B" with
log P1  P2  P3  P4  P5  Method  Round   #TSamples   #Samples0   #Samples1   FP  TN  TP  FN  Time    Det_Time
data1   2   0   0   0   Mahalanobis 1   3   3   0   0   3   0   0   0.00200080871582031 1
data1   3   0   0   0   Mahalanobis 1   3   3   0   0   3   0   0   0.000999927520751953    1

Basically, I would like to replace the rows "FP", "TN", "TP" and "FN" from the dataframe A  from those from dataframe B when the columns "P1", "P2", "P3", "P4", "P5", "Method" and "Round" match in both A and B dataframe.
Raúl

A: Something like this:
  require(sqldf)

    C <- sqldf('select A.log, A.P1, A.P2, A.P3, A.P4, A.P5, A.Method, A.Round,  "A.#TSamples",   "A.#Samples0",   "A.#Samples1", B.FP,  B.TN,  B.TP,  B.FN, A.Time, A.Det_Time
                from A
                inner join B on (A.log = B.log and
                                A.P1 = B.P1 and
                                A.P2 = B.P2 and
                                A.P3 = B.P3 and
                                A.P4 = B.P4 and
                                A.P5 = B.P5 and and
                                A.Method  = B.Method and
                                A.Round = B.Round)
                ')

    C <- rbind(A,C)

    C <- C[!duplicated(C[c("log", "P1", "P2", "P3", "P4", "P5", "Method", "Round",  "#TSamples", "#Samples0", "#Samples1", "Time", "Det_Time")]),]


Q: Are differential line drivers "active" circuits? Some quadrature encoder datasheets describe their outputs as either Differential Line Driver or Line Driver. On closer inspection of the diagrams, they appear to be the same thing (differential line drivers).
However, my research tells me that a differential line driver provides 0-0.8v when Low, and 2-5v when High (TTL?). I.e. an "active" circuit without floating, and therefore no need for pull up/down resistors.
On the other hand, I found this definition for Line Driver:
"A line driver is a sourcing output. When in the on state, a line driver will supply Vcc. In the off state, a line driver will float. Because of this, a sinking input is required for proper operation. Please refer to the table below for a simple example of a line driver."
This implies a pull up/down resistor is needed.
So, what is the difference/similarity between the two, if any, in regards to quadrature encoders?


Q: Why are many of the characters of a string change when copied/pasted in JavaScript or assigned to a form input element I have built the following string in JavaScript using the String.fromCharCode function and assigned it to variable h.
var h=String.fromCharCode(127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146)
When I print the string using console.log, the a space and 19 boxes show up (there are 20 characters in the string).
Now if I select these characters, copy them and paste them in a Hex Editor it shows the following:
7F 3F 81 3F 3F 3F 3F 3F 3F 3F 3F 3F 3F 3F 8D 3F 8F 90 3F 3F
which are the ASCII codes for the characters in the given string.
7F is ok, but 3F is wrong, it should have been 80, 81 is correct but next 11 character are shown as 3F, then 8D but the next character code is again 3F then next 2 character i.e 8F and 90 are fine but next 2 character are again wrong.
Can anyone tell me why is this happening? h.charCodeAt(1) shows 128 though.
Thanks in advance


Q: Angular Form Validations - values have to be different to initial values I have reactive form validations set up as follows:
  ngOnInit(): void {
    this.userForm = this.formBuilder.group({
      status: {checked: this.selectedUser.status == 1},
      username: [this.selectedUser.username, [Validators.required, Validators.minLength(LlqaConstants.USERNAME_MIN_LENGTH)]],
      realname: [this.selectedUser.realname, [Validators.required, Validators.minLength(LlqaConstants.REALNAME_MIN_LENGTH)]],
      password: ['', this.selectedUser.passhash.length > 0 ? [Validators.required, Validators.minLength(LlqaConstants.PASSWORD_MIN_LENGTH)] : null],
      usercomment: [this.selectedUser.comment]
    });
  }

I'd like to enable the submit button, as soon as one input value is not equal to the initial value anymore. The simplest way I could find is:
disableSaveButton(): boolean {
  return !this.userform.dirty || this.userForm.invalid;
}

My problem with the dirty property ist, as soon as I enter something, dirty is true, also if I enter the same value as the initial value. I'd to have a property which tells me if one input value is not equal to the initial value. Is this possible out of the box or do I have to check each userForm.value equals to this.selectedUser.someValue?

A: I created a custom validator to solve this issue.
The validator:
export function oneValueHasToBeChangedValidator(values: { controlName: string, initialValue: string | number | boolean }[]): ValidatorFn {
  return (form: FormControl): { [key: string]: any } => {
    let sameValues = true;

    for (let comparingValues of values) {
      if (form.value[comparingValues.controlName] != comparingValues.initialValue) {
        sameValues = false;
        break;
      }
    }

    return sameValues ? {'sameValues': {values: values}} : null;
  };
}

How I took use of it:
this.userForm = this.formBuilder.group({
  status: this.selectedUser.status == 1,
  username: [this.selectedUser.username, [Validators.required, Validators.minLength(LlqaConstants.USERNAME_MIN_LENGTH)]],
  realname: [this.selectedUser.realname, [Validators.required, Validators.minLength(LlqaConstants.REALNAME_MIN_LENGTH)]],
  password: ['', [Validators.minLength(LlqaConstants.PASSWORD_MIN_LENGTH)]],
  usercomment: this.selectedUser.comment == null ? "" : this.selectedUser.comment
});

this.userForm.setValidators(oneValueHasToBeChangedValidator([{
  controlName: "status",
  initialValue: this.selectedUser.status == 1
}, {
  controlName: "username",
  initialValue: this.selectedUser.username
}, {
  controlName: "realname",
  initialValue: this.selectedUser.realname
}, {
  controlName: "password",
  initialValue: ""
}, {
  controlName: "usercomment",
  initialValue: this.selectedUser.comment == null ? "" : this.selectedUser.comment
}]));
this.userForm.updateValueAndValidity();

A: You could cache the initial value as soon as you set the form object. Then change your disableSaveButton method to check the equality of the two values.
For instance:
export class MyComponent {
    initialValue: any;

    constructor(private fb: FormBuilder) {
        this.form = fb.group({...});
        this.initialValue = this.form.value;
    }

    disableSaveButton() {
        return JSON.stringify(this.initialValue) === JSON.stringify(this.form.value);
    }
}

The disable method will check if the current form value is the same as the initial value.