text:
Q: JavaScript move an image with arrow keys I've seen lots of people ask similar questions here, but none of them seem to work for me. I have an img, with the id 'character'. I want it to move left on left click and right on right click. This is the code I have:
var bound = window.innerWidth;
function left(id) {
    document.getElementById(id).style.left.match(/^([0-9]+)/);
    var current = RegExp.$1;
    if(current <=bound){
        document.getElementById(id).style.left = current - 0 + 'px';
    }
    else{
        document.getElementById(id).style.left = current - 5 + 'px';
    }
}

function right(id) {
    document.getElementById(id).style.left.match(/^([0-9]+)/);
    var current = RegExp.$1;
    if(current >= (bound - 5){
        document.getElementById(id).style.left = current + 0 + 'px';
    }
    else{
        document.getElementById(id).style.left = current + 1 + 'px';
    }
}

document.onkeyup = KeyCheck;
function KeyCheck() {

    var KeyID = event.keyCode;
    switch(KeyID)
    {
    case 39:
    right('character');
    break;
     case 37:
    left('character');
    break;
    }
}

I don't know if I should fix this code, or if there is something simpler. If you have a simpler way of doing this, please let me know.

A: Why not use jQuery?
$("body").keydown(function(e) {
  var max = $('body').width();
  var min = 0;
  var move_amt = 10;
  var position = $("#my_image").offset();
  if(e.which == 37) { // left
    var new_left = ((position.left-move_amt < min) ? min : position.left-move_amt);
    $("#my_image").offset({ left: new_left})
  }
  else if(e.which == 39) { // right
    var new_left = ((position.left+move_amt > max) ? max : position.left+move_amt);
    $("#my_image").offset({ left: new_left})
  }
});

Here is a demo of it in action

A: Your steps are different in the left and right function. use one variable to avoid that. Example
 var step = 5;
function left(id) {
    document.getElementById(id).style.left.match(/^([0-9]+)/);
    var current = RegExp.$1;
    if(current <=bound){
        document.getElementById(id).style.left = current - 0 + 'px';
    }
    else{
        document.getElementById(id).style.left = current - step + 'px';
    }
}

function right(id) {
    document.getElementById(id).style.left.match(/^([0-9]+)/);
    var current = RegExp.$1;
    if(current >= (bound - 5){
        document.getElementById(id).style.left = current + 0 + 'px';
    }
    else{
        document.getElementById(id).style.left = current + step + 'px';
    }
}


text:
Q: Reading Alpha Channels from each Pixel in Qt how can I read from an image the RGBA values in QT?
I hope that somebody can help me.

A: In Qt5 there is a QImage::pixel(int x, int y) method. You can access the RGBA values of the return value via the qBlue, qRed, qGreen and qAlpha functions.

A: You can convert to format RGBA using convertToFormat as below:
    QImage myImage( ":/Images/images.jpg" );
    myImage = myImage.convertToFormat(QImage::Format_RGBA8888);

Now you can get R,G,B,A values in sequence with proper data alignment as below:
    uchar *bits = myImage.bits();
    for (int i = 0; i < (myImage.width() * myImage.height() * 4); i++)
    {
        qDebug() << (int) bits[i];    // Here printing the RGBA values in sequence
    }

This will give you R,G,B,A of every pixel after every 4th cycle.

A: Assuming an initialized QImage mImage
for( int y = 0; y < height; y++ ) {
    QRgb *lineOut = (QRgb *)mImage.scanLine(y);
    for( int x = 0; x < width; x++ ) {
        int r = 255, g = 0, b = 255;
        lineOut[x] = qRgb(r, g, b);
    }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Assign value if empty if not increment the value (Matlab) Is it possible in matlab to check if a value is empty and if it is empty assign a value, else (if it is not empty) increment the value during an assignment ?
For example:
In this code I increment majorityList{l}, though at the start this cell is empty (not 0), therefore i can't increment it. This means I need to check this first before I can increment it. Can this be done during the assignment itself ?
 majorityList{l,2} = 'test';
 majorityList{l}=  majorityList{l}+1;

A solution I wrote is:
if length(majorityList{l})==0
     majorityList{l} = 0;
     majorityList{l} = majorityList{l} +1;
else
    majorityList{l} = majorityList{l} +1;
 end

though this looks rather ugly for something so easy...

A: Use isempty for that
if ~isempty(var)
   var=var+1;
end

If on the other hand you do not know, if the variable exists at all, use exist.

A: If you are incrementing single-value variables, and not matrices elementwise, you can do the one-liner, no-checker
var = sum(var) + 1;

Sum will give 0 for empty matrices and the actual value of var otherwise (as single-element sum). From the non-empty outputs of operators on empty matrices, sum will give a correct output for both empty and non-empty values.

A: If you know you're going to increment it in a loop, the easiest solution is just to initialize majorityList to zero outside the loop:
majorityList{1} = 0;
while loop==running
    majorityList{1} = majorityList{1}+1;
end


text:
Q: Cover and avoidance properties of chief factors: can we avoid exactly the ones we want? If $G$ is a finite solvable group with chief series $1 = G_0 \leq \ldots \leq G_n = G$ (so each $G_i \unlhd G$ and if $G_{i-1} < H < G_i$ then $H$ is not normal in $G$) and $I \subseteq \{ 1,\ldots,n\}$.  Does there exist a subgroup $H \leq G$ such that $G_{i-1} H \geq G_i$ when $i \in I$ and $G_i \cap H \leq G_{i-1}$ when $i \notin I$?
In other words, can I choose which chief factors a subgroup covers and avoids?
(If so, can we describe how to find such a subgroup? If not, are there easy properties $I$ needs to have, like containing all the Frattini chief factors?)

Here are some example sets $I$ that we can use:

*

*$I_p = \{ i : [G_i:G_{i-1}] \text{ is divisible by } p \}$, $H$ is a Sylow $p$-subgroup

*$I_{p'} = \{ i : [G_i:G_{i-i}] \text{ is not divisible by } p \}$, $H$ is a Sylow $p$-complement

*$I_{\pi} = \{ i : [G_i:G_{i-1}] \text{ is a $\pi$-number} \}$, $H$ is a Hall $\pi$-subgroup

*$I_c = \{ i  : G_i/G_{i-1} \leq Z(G/G_{i-1}) \}$, $H$ is a Sylow system normalizer

*$I_\Phi = \{ i : G_i/G_{i-1} \leq \Phi(G/G_{i-1}) \}$, then $H$ is a pre-Frattini subgroup

Indeed these can almost by used as definitions for the $H$ (there is a technical condition about behaving well with a Sylow system for the last one or two, I think). All of these subgroups exist in every finite soluble group.
Do the allowable $I$ at least form a Boolean algebra? $I_c \cup I_\Phi$ is allowable (by Hawkes, though I don't know the details). What about the complement of $I_c$?


text:
Q: How do i resolve the Error trying to install postgis? On AWS Linux, I tried to install postgis by
CREATE EXTENSION postgis;
However, I got this error.

SQL Error [58P01]: ERROR: could not open extension control file
"/usr/pgsql-13/share/extension/postgis.control": No such file or
directory

I could not find a way to resolve this... Any help?


text:
Q: gcc preprocessor typedef name replacement Is there a way to get the gcc preprocessor to replace a type with what defined by the typedef, i.e.
something like this:
typedef unsigned char Uint8

int main(void)
{
    Uint8 a = 1;
    Uint8 b = 2;
    Uint8 c;

    c = a + b;

    return 0;
}

Would get preprocessed into something like this:
int main(void)
{
    unsigned char a = 1;
    unsigned char b = 2;
    unsigned char c;

    c = a + b;

    return 0;
}

A: No, there isn't, because type aliasing is part of compilation stage and not a pre-processing stage. Therefore pre-processor cannot know anything about types by design and cannot perform any operations on those types. Also, you forgot to put ; at the end of typedef statement.


text:
Q: How to access JSF templates, classes of one maven module from another maven module I have a Maven project which consists of 2 Maven modules.
One module has some common UI functionality which the Other module can reuse.
The common UI module has its own classes,dependencies,JSF templates
and organized as per maven webapp structure.
It doesn't work if we add the common module in the dependency of calling module.
How can we call the Templates and related classes from the Other maven module?

A: For classes simply use maven dependency with jar.
For web resources (jsf templates etc) use maven overlay and merge resources from modules into one war module.

Overlays are used to share common resources across multiple web applications.

It is good practice to separete shared part of code (classes and webresources) into separate module (jar for classes and war for base war)


text:
Q: Crash when doing multi thread operation on SQLite database using Qt I have a code which performs 3 async make operation on a database. This code crashs if I run 3 async operations, but if it's only one there is no problem. How to organize multi threaded operation on SQLite? I have tried QMutex.lock but It did not work.
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QtConcurrent/QtConcurrentRun>
#include <database.h>

int main(int argc, char *argv[])
{

QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
Database *db0=new Database();
Database *db1=new Database();
Database *db2=new Database();

QString param0="Select LastUpdateDate From TableLastUpdateLog Where TableName='T1'";
 QString param1="Select LastUpdateDate From TableLastUpdateLog Where TableName='T2'";
  QString param2="Select LastUpdateDate From TableLastUpdateLog Where TableName='T3'";

QtConcurrent::run(db0,&Database::Select,param0);
QtConcurrent::run(db1,&Database::Select,param1);
QtConcurrent::run(db2,&Database::Select,param2);

return app.exec();

}
database.cpp
void Database::Select(QString query) {

m_db=QSqlDatabase::addDatabase("QSQLITE","myconn");
m_db.setDatabaseName("./mytask.db");
bool result=m_db.open();
if(result==false)
    qDebug()<<"Failed";
else
{
    qDebug()<<"Connection is Success";
    m_qry=new QSqlQuery(m_db);
    m_qry->exec("PRAGMA foreign_keys = ON;");
    m_qry->exec("DSQLITE_THREADSAFE=2");
    m_qry->prepare(query);
    if(m_qry->exec()!=true)
    {
        qDebug()<<"Query Failed:"<<m_qry->lastError();
        qDebug()<<m_qry->lastQuery();
    }
    else
    {
        QSqlRecord rec=m_qry->record();
        while(m_qry->next())
        {
            qDebug()<<m_qry->value("LastUpdateDate").toDateTime();
        }

    }
}

m_db.close();
m_db.removeDatabase("myconn");

//mutex.unlock();
}

A: Your code crashes because you are still using the same connection to access the database from each thread. In Qt connections are identified by their names, ie the value "myconn" passed to addDatabase.
Not only Qt will misbehave, but sqlite driver too. From Qt docs
Warning: If you add a connection with the same name as an existing connection,
the new connection replaces the old one.

Your statement SQLITE_THREADSAFE=2 allow multithreading as long as no two threads attempt to use the same database connection, which is not the case.
The solution is to provide a different connection name for each of your objects.


text:
Q: Android - Open app at specific time daily I have an app with socket based push to app to open and show the user critical work like receiving orders on store.
I have a requirement to sound an alarm 10 mins before store goes online daily.
I decided go ahead with AlarmManager  as below
Calendar alarmFor = Calendar.getInstance();
alarmFor.set(Calendar.HOUR_OF_DAY, 7);
alarmFor.set(Calendar.MINUTE, 45);
alarmFor.set(Calendar.SECOND, 0);

Intent MyIntent = new Intent(getApplicationContext(), BroadcastNotification.class);
PendingIntent MyPendIntent = PendingIntent.getBroadcast(getApplicationContext(), 0,
MyIntent, PendingIntent.FLAG_CANCEL_CURRENT);

AlarmManager MyAlarm = (AlarmManager) getSystemService(ALARM_SERVICE);
MyAlarm.setAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, alarmFor.getTimeInMillis(),
MyPendIntent);

and then in onRecieve() will open the app as below with sound
@Override
public void onReceive(Context context, Intent intent) {
Log.d("MyAPP", "onReceive() called");
// -> open app activity with alarm sound
}

But above solution seems pretty old school.
I have also tried with WorkManager OneTimeRequest to set and trigger the job at specific time.
But in Android Daily Job-Evernote it is mentioned that WorkManager donot guarantee to run at specific time and also daily job.
Request you to suggest better and unified approach to open the app with guarantee at specific time.
Thanks in advance.

A: AlarmManager won't work either.  Doze mode prevents it (or rather, it will go off, but it may be as much as 15 minutes late).  You have two options:
1)Don't use websockets.  Use FCM.  FCM allows you to send a high priority push message which will wake the device.
2)Have the user whitelist your from Doze mode.  This cannot be done programaticly (the most you can do is launch the preference page to do it).  This has to be done by the user by hand.
I really suggest #1 if you want an end to end system.  #2 and requiring the user to do something outside the app is always a bit iffy, and many users won't do it.


text:
Q: C# UTF8 console output I'm trying to make something like http://www.a1k0n.net/2011/07/20/donut-math.html but with unicode characters.
To achieve this, I'd originally tried to alter the encoding of the console. However, there don't seem to be any console fonts that support the characters I'd like to use. Does anyone know:

*

*How I can change the font used by the console to one that supports unicode characters, such as Arial?

*Whether this is a good solution to the problem, rather than (say) using a text box in a windows form?

A: I would not suggest changing the font on a console window. It's not designed to be that type of user interface. Any power user will get mad if your application changes their command prompt outside of the application. If you want 'pretty' then I would suggest a Winform. Otherwise I think you are opening a Pandora's box.
IF you insist then I would suggest checking out Console.InputEncoding and to change font in the console you will need to access the kernel itself... not suggested solution.. this article has the details on the implementation http://blogs.microsoft.co.il/pavely/2009/07/23/changing-console-fonts/

A: You can try this. But it will work only on your pc.


text:
Q: I am drawing a plot in ggplot in R and all I am getting as the result is a line with points in vertical direction with no x-labels or markings ggplot(data=df, aes(x='Matcing_Probability', y=Locus_Name, group=1)) +
+     geom_line(color="#aa0022", size=1.75) +
+     geom_point(color="#aa0022", size=3.5)

This is the graph I am getting from the code.

A: You need to send ggplot2 symbols (unquoted column names) in aes() if you are assigning an aesthetic to a column in your dataset.  Otherwise, it will assume you are sending the string of a new symbol.  So:
# your original
ggplot(data=df, aes(x='Matching_Probability', y=Locus_Name, group=1))

# change to this:
ggplot(data=df, aes(x=Matching_Probability, y=Locus_Name, group=1))

Consider the difference in the following example to highlight why even more:
# this works fine
df <- data.frame(x=1:10, y=1:10)
ggplot(df, aes(x=x,y=y)) + geom_point()

# this doesn't:
ggplot(df, aes(x="x",y=y)) + geom_point()


text:
Q: I GET 404 ERROR IN AXON SAGA IMPLEMENTATION WHEN I SEND POST REQUEST.WHAT MIGHT BE THE REASON? i implemented SAGA using Axon and Spring Boot.It is simple order and customer service.Everything looks fine,however when i send post request via postman ,i got 404 NOT FOUND.I guess the problem is related to OrderManagementSaga.java Please help me!
OrderManagementSaga.java
@Saga
public class OrderManagementSaga {

    @Inject
    private transient CommandGateway commandGateway;

    @StartSaga
    @SagaEventHandler(associationProperty = "orderId")
    public void handle(OrderCreatedEvent orderCreatedEvent){

       SagaLifecycle.associateWith("customerId", orderCreatedEvent.customerId);

            commandGateway.send(new CreateInvoiceCommand(orderCreatedEvent.customerId,orderCreatedEvent.price,orderCreatedEvent.orderId));

    }

    @SagaEventHandler(associationProperty = "customerId")
    public void handle(InvoiceCreatedEvent invoiceCreatedEvent){

        SagaLifecycle.associateWith("orderId",invoiceCreatedEvent.orderId);

        commandGateway.send(new UpdateOrderStatusCommand(invoiceCreatedEvent.orderId, invoiceCreatedEvent.price, invoiceCreatedEvent.customerId));

    }

    @SagaEventHandler(associationProperty = "orderId")
    public void handle(OrderUpdatedEvent orderUpdatedEvent){
        SagaLifecycle.end();
    }
}

OrderCommandController.java
@RestController
public class OrderCommandController {

    private OrderCommandService orderCommandService;

    public OrderCommandController(OrderCommandService orderCommandService) {
        this.orderCommandService = orderCommandService;
    }

    @PostMapping("/orders")
    public CompletableFuture<String> createOrder(@RequestBody OrderCreateDTO orderCreateDTO){
        return orderCommandService.createOrder(orderCreateDTO);
    }

}

OrderAggregate.java
@Aggregate
public class OrderAggregate {

    @AggregateIdentifier
    private String orderId;

    private BigDecimal price;

    private OrderStatus orderStatus;

    private String customerId;

    public OrderAggregate() {
    }

    @CommandHandler
    public OrderAggregate(CreateOrderCommand createOrderCommand) {
        AggregateLifecycle.apply(new OrderCreatedEvent(createOrderCommand.orderId,createOrderCommand.price, createOrderCommand.customerId));
    }

    @EventSourcingHandler
    protected void on(OrderCreatedEvent orderCreatedEvent) {
        this.orderId = orderCreatedEvent.orderId;
        this.customerId = orderCreatedEvent.customerId;
        this.orderStatus = OrderStatus.CREATED;
    }

    @CommandHandler
    protected void on(UpdateOrderStatusCommand updateOrderStatusCommand) {
        AggregateLifecycle
                .apply(new OrderUpdatedEvent(updateOrderStatusCommand.orderId,updateOrderStatusCommand.customerıd,updateOrderStatusCommand.price,OrderStatus.CREATED));
    }

    @EventSourcingHandler
    protected void on(OrderUpdatedEvent orderUpdatedEvent) {
        this.customerId = orderUpdatedEvent.customerId;
        this.orderId = orderUpdatedEvent.orderId;
        this.orderStatus = OrderStatus.APPROVED;
        this.price = orderUpdatedEvent.price;
    }

CustomerAggregate.java
@Aggregate
public class CustomerAggregate {

    @AggregateIdentifier
    private String customerId;

    private BigDecimal budget;

    private String orderId;

    public CustomerAggregate(String customerId, BigDecimal budget, String orderId) {
        super();
        this.customerId = customerId;
        this.budget = budget;
        this.orderId = orderId;
    }
    @CommandHandler
    public CustomerAggregate(CreateInvoiceCommand createInvoiceCommand){

        AggregateLifecycle.apply(new InvoiceCreatedEvent(createInvoiceCommand.price, createInvoiceCommand.customerId, createInvoiceCommand.orderId));

    }
    @EventSourcingHandler
    protected void on(InvoiceCreatedEvent invoiceCreatedEvent){

        this.customerId = invoiceCreatedEvent.customerId;
        this.budget = this.budget.subtract(invoiceCreatedEvent.price);
        this.orderId = invoiceCreatedEvent.orderId;

    }

    public String getCustomerId() {
        return customerId;
    }
    public void setCustomerId(String customerId) {
        this.customerId = customerId;
    }
    public BigDecimal getBudget() {
        return budget;
    }

    public void setBudget(BigDecimal budget) {
        this.budget = budget;
    }

}

I don't think the problem is related with command and event classes ,so i only share one of them as example;
CreateOrderCommand.java
public class CreateOrderCommand {

     @TargetAggregateIdentifier
        public final String orderId;
        public final String customerId;
        public final BigDecimal price;
        public CreateOrderCommand(String orderId, String customerId, BigDecimal price) {
            super();
            this.orderId = orderId;
            this.customerId = customerId;
            this.price = price;

        }

}

A: 404 indicates that you can not reach the REST controller in the first place. Can this be debugged and checked? If this is working as expected, then the implementation of this controller could be examined in more detail: what is orderCommandService that is injected in the REST controller. Hopefully, it is using the Axon command gateway to send the command to OrderAggregate. The OrderAggregate will publish an event of type OrderCreatedEvent which should start the Saga.


text:
Q: MongoDB stage to C# API hope you are all fine.
I had my first contact with MongoDB the last weekend e and now I'm facing a problem.
I just would like to limit the data that is going to be shown in the front end..
I've got a C# API with Get action
[HttpGet]
public ActionResult<dynamic> Get(string country)
{
    if(country is null)
        return  _country.Find<dynamic>(new BsonDocument()).ToList();

    var filter= Builders<dynamic>.Filter.Eq("country", country);
    return _country.Find(filter).ToList();
}

and I also got a simple MongoDB stage
new BsonArray
{
    new BsonDocument("$limit", 5),
    new BsonDocument()
}

I've spent many hours trying to figure out hot to implement the MongoDB code to my API but I just can't imagine how.
Can anyone give a tip?

A: You missed that a stage is a concept that is used in aggregation. In your example you're using a find operation that has appropriate options class

A: I've just solved it.
The only thing I needed to get what i wanted was to code ".limit(number)".
The final code got like this
return  _employees.Find<dynamic>(new BsonDocument()).Limit(4).ToList();


text:
Q: Xamarin.Forms Push Multiple Pages on NavigationStack What is the most efficient way to push multiple pages on the stack to keep the order. I have about 25 pages which the user is nagivating through. Each page pushes the next page on the NavigationStack.
However, the user has to have the option to navigate directly to any page out of the 25. That means if he navigates to page n, n pages have to be pushed on the NavigationStack such that he can keep on navigating form there. I thought of putting all pages into an array and if the user selects page 10 for example, I will push each page from 0-9 on the NavigationStack. I don't know if it will work that way and if it will even be super slow. What would be the best way to handle such a scenario?

A: You can make use of NavigationPage.Navigation.InsertPageBefore(Page, Page) and NavigationPage.Navigation.RemovePage(Page)
You can use Shell Navigation if its not too big of a change now.


text:
Q: Unable to implement CustomAuthenticationProvider with Spring Security: BeanCreationException while autowiring I am implementing CustomAuthenticationProvider in Spring Security. I have created the CustomAuthenticationProvider class which implements AuthenticationProvider. However, when I define this CustomAuthenticationProvider in my SecurityConfiguration class and autowire it, the application throws following error:
2020-03-08 19:27:42 [main] ERROR o.s.web.context.ContextLoader - Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'securityConfiguration': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.highrise.isimwebapp.config.customauth.CustomAuthenticationProvider com.highrise.isimwebapp.config.SecurityConfiguration.authProvider; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.highrise.isimwebapp.config.customauth.CustomAuthenticationProvider] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

I have included the @Component annotation in my CustomAuthenticationProvider class. Also, the package under which this class is defined, is included in the @ComponentScan. The context is not picking up CustomAuthenticationProvider bean. The other defined classes are successfully getting picked up by the context as defined in the @ComponentScan and no such error is received on their autowired objects. What could be wrong from my side? Any help regarding how this can be fixed would be highly appreciated.
CustomAuthenticationProvider.java
@Component
public class CustomAuthenticationProvider implements AuthenticationProvider {

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    // TODO Auto-generated method stub
    String name = authentication.getName();
    String password = authentication.getCredentials().toString();
    if(name.equalsIgnoreCase("testuser1") && password.equalsIgnoreCase("demo"))
        return new UsernamePasswordAuthenticationToken(name, password);
    else
        throw new BadCredentialsException("Authentication failed");
}

@Override
public boolean supports(Class<?> authentication) {
    // TODO Auto-generated method stub
    return authentication.equals(UsernamePasswordAuthenticationToken.class);
}

}

SecurityConfiguration.java
@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

@Autowired
private CustomAuthenticationProvider authProvider;

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.authenticationProvider(authProvider);
}

@Override
protected void configure(HttpSecurity http) throws Exception {

  http.authorizeRequests()
    .antMatchers("/resources/**").permitAll()
    .antMatchers("/icon/**").permitAll()
    .anyRequest().authenticated()
    .and().formLogin().loginPage("/login").usernameParameter("username").passwordParameter("password").permitAll().defaultSuccessUrl("/persons/listall")
    .and().csrf().disable();

}
}

SpringWebConfig.java
@EnableWebMvc
@Configuration
@ComponentScan({ "com.highrise.isimwebapp.config", "com.highrise.isimwebapp.config.customauth", "com.highrise.isimwebapp.config.servlet3", "com.highrise.isimwebapp.web", "com.highrise.isimwebapp.service", "com.highrise.isimwebapp.dao",
    "com.highrise.isimwebapp.exception", "com.highrise.isimwebapp.validator" })
public class SpringWebConfig extends WebMvcConfigurerAdapter {

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}

@Bean
public InternalResourceViewResolver viewResolver() {
    InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
    viewResolver.setViewClass(JstlView.class);
    viewResolver.setPrefix("/WEB-INF/views/jsp/");
    viewResolver.setSuffix(".jsp");
    return viewResolver;
}

@Bean
public ResourceBundleMessageSource messageSource() {
    ResourceBundleMessageSource rb = new ResourceBundleMessageSource();
    rb.setBasenames(new String[] { "messages/messages", "messages/validation" });
    return rb;
}

}

A: The problem is probably in the ordering of the package scanning, I can suggest you two approaches:

*

*Move the @ComponentScan("com.highrise.isimwebapp.config.customauth") to the SecurityConfiguration class.

*Remove the @Component annotation from the CustomAuthenticationProvider class and declare the @Bean inside the SecurityConfiguration, something like the following:

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

  @Override
  protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.authenticationProvider(customAuthProvider());
  }

  @Override
  protected void configure(HttpSecurity http) throws Exception {

    http.authorizeRequests()
      .antMatchers("/resources/**").permitAll()
      .antMatchers("/icon/**").permitAll()
      .anyRequest().authenticated()
 .and().formLogin().loginPage("/login").usernameParameter("username").passwordParameter("password").permitAll().defaultSuccessUrl("/persons/listall")
    .and().csrf().disable();

  }

  @Bean
  public CustomAuthenticationProvider customAuthProvider() {
    return new CustomAuthenticationProvider();
  }
}


text:
Q: How to debug in production envirnment for ASP.NET web site? Our client recently complains that when they work on our production server, the user menu switch randomly, but this happens only occasionally .
The application has two types of user menu: regular user and restricted user. The target browser is IE. It's a ASP.NET3.5 application written in C#.
We can never reproduce this issue in our local environment. So it is very difficult to debug it.
Anybody met this type of issue or any clue how to debug it?

A: Web App Logging
Have you looked into adding a variable to your web.config  to have your application perfrom less or more logging. I've done this in the past to track down bugs.
Client-side Logging
Perhaps not the intended use, but http://www.clicktale.com/ provides a javascript site analytics tools that can record all user mouse/keyboard activity that you could correlate to the web app logs. However it cost $$$.

A: Log Messages.  Log them all over that has anything to do with the menu.  Then the next time the user reports seeing it look at the log message.

A: Does the production environment use any load balancing s/w? Perhaps there is a problem with some session scope variables.


text:
Q: Populating a matrix with random numbers and computing sums of those numbers The title says it all.
The hardest part I'm having with this problem is that I'm not allowed to use sum().
I don't know how to create matrices, and I was looking for some help creating and populating one.
This is what I've figured out so far.
def random():
    import random
    x=random.random()
    return x

def create_matrix(x,y):
    random.seed(1)

def main():
    random()

main()

I'm sorry it isn't much if anything, and I appreciate any help I receive.
Enter the number of rows: 3
Enter the number of columns: 2
Enter the threshold for column sum: .5
---------------------------------------
||     ||   1    |   2    |   sum    ||
---------------------------------------
||  1  ||  0.134 |  0.847 |    0.982 ||
||  2  ||  0.764 |  0.255 |    1.019 ||
||  3  ||  0.495 |  0.449 |    0.945 ||
---------------------------------------
|| sum ||   0.63 |   0.70 |      2.9 ||
---------------------------------------

I am given this table, but I also am lacking in the knowledge of how to format this.
I recognize that the dashes are equal to the length of the formatted lines and the numbers denoting the rows and columns are centered.
Also, the decimals only carry out three places, the ones on the bottom are two places, and the final sum is only one place.

A: Is something like this useful?
import random

def create_matrix(x,y):
    matrix = []
    for i in range(x):
        matrix.append([])
        for j in range(y):
            matrix[i].append(random.random())
    return matrix

def main():
    matrix = create_matrix(3, 2)
    for row in matrix:
        print row

main()

Edit
To handle ValueError:
def main():
    while(True):
        try:
            x=int(input('Enter the number of rows: '))
            y=int(input('Enter the number of cols: '))
            matrix = create_matrix(x, y)
            for row in matrix:
                print row
            break
        except ValueError:
            print "Just give integers please. Try again."

Edit 2
def print_matrix(matrix):
    print "-" + "------------"*len(matrix[0])
    for i in range(len(matrix)):
        print "|",
        for j in range(len(matrix[i])):
            print "{0:9} |".format(matrix[i][j]),
        print
    print "-" + "------------"*len(matrix[0])


text:
Q: "while she danced" vs "while she was dancing"
1.The singer waved to the people while she danced to the music.
2.The singer waved to the people while she was dancing to the music.

Are these two sentences grammatically correct?
Do they vary in meaning?

A: "When", "while", and "as" to talk about two things that happen at the same time.
"While" is mostly used with the past continuous verb tense. It is usually used as Event A + while + Event B and to emphasis a time frame as in "during that time."
Even though both of your sentences are correct grammatically and logically, the past continuous tense is preferred to emphasis conjunction "while."
Source

A: The difference is one of emphasis.
One just describes a past action: She waved to the people while she danced.
The other describes a past action where one action was ongoing then: She waved to the people while she was dancing.
During the time she was dancing, she waved to the people.
In the second one, it can mean that she waved more than once.
Another example might illustrate this difference in emphasis better:
As she was walking to town, she saw the man on the bicycle.
As she walks to town, she saw the man on the bicycle.
So, do you want to just say something about a past event or do you want to express that one event was ongoing in the past?
What do you want to say?

A: Both of the sentences are grammatically correct.
Both 'while she danced' and 'while she was dancing' mean the same.
while she danced - longer action
while she was dancing - longer action
The singer waved to the people while she danced to the music. -Two longer actions went on simultaneously.
The singer waved to the people while she was dancing to the music. -Two longer actions went on simultaneously.
We can say--
The singer was waving to the people while she was dancing to the music. or
The singer waved to the people while dancing to the music.

A: They are correct and interchangeable. However, many people would prefer the first version because "is" is a weak verb, and the second sentence is unnecessarily wordy.


text:
Q: Please set theme of AdActivity to @android:style/Theme.Translucent to enable transparent background interstitial ad I get the above message in logs and as a result, I believe I do not get as many interstitial ads as I can. I have already updated my manifest with the following line
    <activity android:name="com.millennialmedia.android.MMActivity"
         android:theme="@android:style/Theme.Translucent.NoTitleBar"
         android:configChanges="keyboardHidden|orientation|keyboard" />

But I still get this error. Apparently there is something else I need to do to get this working.
Any ideas?

A: Add the android:theme="@android:style/Theme.Translucent" into manifest file. Same as follow
    <activity
        android:name="com.google.android.gms.ads.AdActivity"
        android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"
        android:theme="@android:style/Theme.Translucent" />

A: Maybe you need to add AdActivity to your manifest file?
    <activity
        android:name="com.google.android.gms.ads.AdActivity"
        android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"
        android:theme="@android:style/Theme.Translucent" />

and set theme to it?


text:
Q: Set Typeface for View Holder TextView using Dagger2 DI I want to set a custom typeface for a Textview in ListView Adapter ViewHolder.
My typeface font file is in assets folder, so I will need a context reference in my adapter class to access the assets path and also I don't want to pass a context reference to my adapter class constructor.
Should I use context reference through Dagger2 DI or should I make a separate DI Component to get reference of my font Typeface class.
Thanks in advance.

A: In ViewHolder you have access to View and all Views have access to context by getContext method.


text:
Q: Fast way of filtering pandas dataframes according to element positions in another dataset
I am working with 3 pandas dataframes that contain information about differential gene expression for multiple cell groups. It's essentially a multi-dimentional dataframe, where one dataframe (names) is the index of where to look for in the p-value and foldchange dataframes for the corresponding values.
columns = ['g0','g1','g2','g3']
names = pd.DataFrame(data = [
   ['Fxyd3', 'Apoe', 'Apoe', 'Apoe'],
   ['Apoe', 'Hspg2', 'Hspg2', 'Ltbp3'],
   ['Tpm1', 'Ltbp3', 'Ltbp3', 'Hspg2'],
   ['App', 'Serpinh1', 'Fxyd3', 'Fxyd3'],
   ['Ltbp3', 'Fxyd3', 'Serpinh1', 'Lgr5'],
   ['Hspg2', 'Lgr5', 'Lgr5', 'App'],
   ['Slc6a6', 'App', 'App', 'Serpinh1'],
   ['Serpinh1', 'Slc6a6', 'Slc6a6', 'Slc6a6'],
   ['Lgr5', 'Tpm1', 'Tpm1', 'Tpm1'],
   ['Krt15', 'Krt15', 'Krt15', 'Krt15']],
   columns = columns)

np.random.seed(0)
pvalues = pd.DataFrame(data = np.random.rand(10,4)/100, columns = columns)
foldchanges = pd.DataFrame(data =np.random.rand(10,4)*100, columns = columns)

What I would like to do is to find the minimum p-value for each gene and the corresponding foldchange and group name. After hours of trying to wrap my head around this, I came to this solution:
gene_set = ['Hspg2', 'Ltbp3', 'Lgr5', 'Krt15', 'Serpinh1', 'Tpm1', 'App', 'Apoe', 'Slc6a6', 'Fxyd3']
df = pd.DataFrame(index = gene_set, columns = ['pvalues', 'foldchanges', 'group'], data = 0)

for gene in gene_set:
    bool_df = names.values == gene
    values = pvalues.values[bool_df]
    df['pvalues'].loc[gene] = min(values)
    df['foldchanges'].loc[gene] = foldchanges.values[bool_df][values==min(values)]
    values = pvalues.T.values[bool_df.T] #Fix to get out correct group name
    df['group'].loc[gene] = columns[np.where(values==min(values))[0][0]]

Resulting in an output like this:
           pvalues  foldchanges group
Hspg2     0.004376    21.038256    g2
Ltbp3     0.000202    65.310833    g0
Lgr5      0.004562    97.676109    g0
Krt15     0.006121    28.280696    g0
Serpinh1  0.005218    83.794491    g0
Tpm1      0.000188    73.926358    g2
App       0.001434    82.099323    g2
Apoe      0.004237    66.676672    g0
Slc6a6    0.001183    19.658236    g0
Fxyd3     0.000710    20.887676    g2

Now, my issue is that in the full dataset, I have 20+ groups and around 50,000 genes, which ends up taking about 15-20 minutes to run. And I would like to run this code for multiple datasets. So I was wondering if there maybe is a more elegant and faster way to achieve the same goal?
Edit: Added random seed for reproducibility and added a fix to get out correct group names

A: It is essential to have all relevant data in the body of the dataframe and in this sense, the melt() function is an important ally to organize your data.
df_melted = pd.melt(pvalues, var_name="group", value_name="pvalues")
df_melted['foldchanges'] = pd.melt(foldchanges, var_name="group", value_name="foldchanges")['foldchanges']
df_melted['gene'] = pd.melt(names, var_name="group", value_name="gene")['gene']

Now, you can simply do some basic grouping to get the indexes with the minimum pvalues
min_idx = df_melted.groupby(by=["gene"])["pvalues"].idxmin()
out_df = df_melted.iloc[min_idx]

Some formatting to get the output on the format you want
out_df = out_df.set_index('gene').rename_axis(None)[['pvalues', 'foldchanges', 'group']]

And you are good to go
           pvalues  foldchanges group
Apoe      0.004237    66.676672    g0
App       0.001434    82.099323    g2
Fxyd3     0.000710    20.887676    g2
Hspg2     0.004376    21.038256    g2
Krt15     0.006121    28.280696    g0
Lgr5      0.004562    97.676109    g0
Ltbp3     0.000202    65.310833    g0
Serpinh1  0.005218    83.794491    g0
Slc6a6    0.001183    19.658236    g0
Tpm1      0.000188    73.926358    g2

A: I want to avoid looping to speed up the process. So we recombine the three data frames into a long format. Group them together in a new data frame and aggregate the minimum p-value. Extract a new data frame with the obtained gene names and P-values. What differs from your logic is the timing of the extraction of the group names. The group name corresponding to the P-value is obtained from the beginning. If this approach is wrong, we can only help you speed up the process partially. Thank you for your understanding.
g0 = pd.concat([names['g0'],pvalues['g0'],foldchanges['g0']],axis=1)
g0.columns = ['names','pvalues','foldchanges']
g0['group'] = 'g0'

g1 = pd.concat([names['g1'],pvalues['g1'],foldchanges['g1']],axis=1)
g1.columns = ['names','pvalues','foldchanges']
g1['group'] = 'g1'

g2 = pd.concat([names['g2'],pvalues['g2'],foldchanges['g2']],axis=1)
g2.columns = ['names','pvalues','foldchanges']
g2['group'] = 'g2'

g3 = pd.concat([names['g3'],pvalues['g3'],foldchanges['g3']],axis=1)
g3.columns = ['names','pvalues','foldchanges']
g3['group'] = 'g3'

all_df = pd.concat([g0, g1, g2, g3], axis=0)

gb = all_df.groupby('names')['pvalues'].agg('min').reset_index()
all_df[(all_df['names'].isin(gb['names'])) & (all_df['pvalues'].isin(gb['pvalues']))]

    names   pvalues foldchanges group
1   Hspg2   0.004153    59.926384   g1
3   Serpinh1    0.007515    30.217304   g1
5   Lgr5    0.003352    15.884651   g1
7   Slc6a6  0.003947    99.277559   g1
8   Tpm1    0.000299    36.480099   g1
3   Fxyd3   0.000485    0.583842    g2
6   App   0.000566  23.006282   g2
0   Apoe    0.003422    11.763652   g3
1   Ltbp3   0.003203    25.222484   g3
9   Krt15   0.005134    80.433481   g3


text:
Q: Cumulative distribution function using Cauchy Formula I really need assistance solving this problem.
Here's the question:
The cumulative distribution function of a random varible X is $$F(x)=\displaystyle\frac{1}{2}+\frac{\arctan x}{\pi}.$$ Compute $P(X> -0.4|X< 3.25)$.
Here's what I tried to do:
$$
P(X=3.25)=\displaystyle\frac{1}{2}+\frac{\arctan 3.25}{\pi}
$$
$$
P(X=-0.4)=\displaystyle\frac{1}{2}+\frac{\arctan -0.4}{\pi}
$$
Then $[P(X=3.25)-P(X=-0.4)]/P(X=3.25) = 0.31$ which is nowhere near the possible answer for this multiple choices problem.
Thanks in advance!

A: First, recall that
$$
P(X>-0.4\mid X<3.25)=\frac{P(X>-0.4,\ X<3.25)}{P(X<3.25)}.
$$
So, the point here is to compute each of these quantities using the given CDF.
The denominator is easy, since it coincides with the definition of the CDF. (Well, nearly -- technically, $F(3.25)=P(X\leq3.25)$; but, because the CDF is continuous there, we get that $P(X=3.25)=0$ and therefore $F(3.25)=P(X<3.25)$ as well.)
For the numerator, note that
$$
P(X>-0.4,\ X<3.25)=P(X<3.25)-P(X\leq-0.4).
$$

A: You're misunderstanding what a cdf is.  $F(x)$ is the probability that the associated random variable $X$ is less than or equal to $x,$ not the probability that $X=x.$
In this example, the cdf is continuous, so $P(X=x)$ equals $0$ for any specific $x.$ As a result, we have
$$P(X\le x)=P(X\lt x)=F(x)$$
and
$$P(X\ge x)=P(X\gt x)=1-F(x).$$
So
\begin{align}P(X\gt−0.4\mid X\lt3.25)&=\frac{P(X\gt-0.4\text{ and }X\lt 3.25)}{P(X\lt 3.25)}
\\&=\frac{F(3.25)-F(-0.4)}{F(3.25)}.
\end{align}


text:
Q: Radzen Blazor DropDown on dynamic data from external API I'm getting data from an external API and the code looks like this (this part is fine):
@code {
    IEnumerable<IDictionary<string, object>> data;
    int count;
    bool isLoading;

    async Task LoadData(LoadDataArgs args)
    {
        isLoading = true;
        var uri = new Uri("https://services.radzen.com/odata/Northwind/Employees")
            .GetODataUri(filter: args.Filter, top: args.Top, skip: args.Skip, orderby: args.OrderBy, count: true);

        var response = await new HttpClient().SendAsync(new HttpRequestMessage(HttpMethod.Get, uri));

        var result = await response.ReadAsync<ODataServiceResult<IDictionary<string, object>>>();

        data = result.Value.AsODataEnumerable();
        count = result.Count;
        isLoading = false;
    }
}

On the dropdown menu I want to display the EmployeeID, but cannot access it (the Data="@data.Employee.ID" is incorrect and not sure what to put in there to make it work).
<RadzenDropDown Data="@data.EmployeeID" TextProperty="EmployeeID" ValueProperty="EmployeeID" Name="Dropdown1" TValue="string">
            </RadzenDropDown>

Thanks!

A: The problem is that the Data Property is:
 IEnumerable<IDictionary<string, object>> data;

It should be:
IEnumerable<Employee>data;

So then you can acess to Employee class properties.
<RadzenDropDown Data="@data.EmployeeID" TextProperty="EmployeeID" ValueProperty="EmployeeID" Name="Dropdown1" TValue="Employee">
            </RadzenDropDown>


text:
Q: Intel IA-32 Assembly I'm having a bit of difficulty converting the following java code into Intel IA-32 Assembly:
 class Person() {
   char name [8];
   int age;

   void printName() {...}

   static void printAdults(Person [] list) {
     for(int k = 0; k < 100; k++){
       if (list[k].age >= 18) {
         list[k].printName();
       }
     }
  }
}

My attempt is:
Person:
    push ebp; save callers ebp
    mov ebp, esp; setup new ebp
    push esi;    esi will hold name
    push ebx;    ebx will hold list
    push ecx;    ecx will hold k

init:
    mov esi, [ebp + 8];
    mov ebx, [ebp + 12];
    mov ecx, 0;    k=0

forloop:
    cmp ecx, 100;
    jge end;    if k>= 100 then break forloop
    cmp [ebx + 4 * ecx], 18 ;
    jl auxloop;    if list[k].age < 18 then go to auxloop
    jmp printName;

printName:

auxloop:
    inc ecx;
    jmp forloop;

end:
    pop ecx;
    pop ebx;
    pop esi;
    pop ebp;

Is my code correct?
NOTE:
I'm not allowed to use global variables.

A: You have it a little wrong, first, you are coding it like you are getting a name and an age as parameters, you are not, you just need ebx to hold the address to the list. And you have your pointer math a little off, assuming chars are 1 byte (thus 8 bytes in your array), integers and pointers 4 bytes this may work :
Person:
    push ebp; save callers ebp
    mov ebp, esp; setup new ebp

init:
    mov ebx, [ebp + 4];
    mov ecx, 0;    k=0

forloop:
    cmp ecx, 100;
    jge end;    if k>= 100 then break forloop
    cmp [ebx + 8 + 12 * ecx], 18 ; 12 * ecx to advance 12 bytes (8 char 4 int), plus 8 to compare the integer, which is 8 bytes away from the start of the pointer.
    jl auxloop;    if list[k].age < 18 then go to auxloop
    jmp printName;

printName:

auxloop:
    inc ecx;
    jmp forloop;

end:
    pop ebp;

A: here is my version, should be a little faster(with stack frame pointer, could probably be removed :P)
_start:
    PUSH EBP
    MOV EBP,ESP
    PUSH EDI
    PUSH ESI
    MOV ESI, [EBP + 8]      ; __stdcall assumed -> get arg: list
    MOV EDI, 100        ; i=100 -> iterations of the loop

_loop:
    CMP [ESI + 8], 18       ; pPerson->age >= 18
    JL _next
    MOV ECX,ESI
    CALL printName      ; __thiscall assumed

_next:
    ADD ESI,12          ; list += sizeof(person)
    SUB EDI,1                    ; i--
    JNZ _loop

_end:
    POP ESI
    POP EDI
    POP EBP
    RETN 4


text:
Q: showing that there is a shape which has three connected black squares We have square lattice with dimensions $n × n$, such that $n \ge 2$. Some of the squares on this lattice are coloured black. How can we show that there are at least 3 connected black squares if there are $$1+\frac{n^{2}}{2}$$ black squares when $n$ is even and $$\frac{n(n+1)}{2}$$ black squares when $n$ is odd?

A: If $n$ is even, just cut the board into $2\times2$ tiles. At least one of these tiles must contain three black squares.

A: Note that any $2\times 2$ tile can contain at most $2$ black squares. In addition, any path of $k$ squares can contain at most $2(k+1)/3$ black squares.  For an $n\times n$ square region where $n$ is even, the decomposition into $\frac{1}{4}n^2$ tiles gives an upper bound of $\frac{1}{2}n^2$ black squares.  For an $n\times n$ square region where $n$ is odd, the decomposition into $\frac{1}{4}(n-1)^2$ tiles and a path of length $2n-1$ gives an upper bound of $\frac{1}{2}(n-1)^2+\frac{4}{3}n=\frac{1}{2}n^2+\frac{1}{3}n+\frac{1}{2}$ black squares.  This latter is a tighter bound than the one in the problem, which is $\frac{1}{2}n^2+\frac{1}{2}n-1$.
Note that the checkerboard pattern with black squares in the four corners, which is an obvious candidate for optimality in the odd-$n$ case, has only $\frac{1}{2}n^2+\frac{1}{2}$ black squares.  To see that this is not optimal, consider the $5\times5$ region.  The checkerboard pattern has $13$ black squares; but a pattern with $14$ black squares is obtained by placing $4$ black squares in the first, third, and fifth columns and a single black square in the second and fourth columns.


text:
Q: How to stop Windows 10 muting audio playback when screen turns off I have found that on my new XPS 13 9360 with the creators update, if I am playing back music from any source (Spotify for example), when the screen turns off after a couple of minutes, audio seems to get muted.
Anyone know where the setting is to prevent this behaviour?

A: I encountered the same problem (also on the XPS13 interestingly). It seems to have to do with how the audio is actually played, see for example this thread. One solution that was suggested was to use a screensaver that's a black screen, and set your screen to never turn off.
Another was to disable so-called 'connected standby' in your registry.
The ultimately desired solution, of course, would be for Spotify to support this connected standby mode. But the problem has apparently been around for quite a while already, so that may not happen any time soon.
In the meantime, the 'blank screen screensaver' seems the best workaround.

A: If your sound is coming through a monitor via HDMI, maybe when the screen shuts off the sound stops.  Try telling it not to shut the monitor off when idle.

A: I think I have another solution, but it requires a second monitor/TV...
If you set it as "Duplicate screens", when you turn off both of them then sound (Spotify or another sound program) it continues on playing.

A: When my Win 7 PC goes to sleep (or put to sleep by me), I can power off the monitor (with built-in speakers). I just need to make sure that I turn on the monitor BEFORE I wake up my PC. If so, I have sound. Remote desktop wake-up will ruin this because I am not there to turn on the powered-off monitor.
Just keep in mind that anytime when the PC is NOT in the sleep mode, the monitor must be on. Otherwise, Win 7 will turn off sound because it senses no speakers. On my PC, the only way to get sound back is to restart. The "net stop audiosrv, ..." trick does not work.
Hopefully, my information will also apply to Win 10.


text:
Q: Confounded by special CSS case I was watching this video, it's a short demo for the Brackets IDE. I'm new to web development so I anticipate being confused by the code I see but there was something in there that I really don't get. Around the 8 minute mark the guy brings up the css line .galleryItem:nth-child(4n+1) Saying that it will only affect the first item in each row in a grid because of the :nth-child(4n+1) can some one please explain the syntax of this line and how it can be used.
P.S. For you Bret Victor fans out there, Brackets seems to do some of his stuff.

A: The idea here is simply that there are probably four items in each row, so using 4n+1 will affect the first item in each row because it is targeting 1st, 5th, 9th, etc. overall.
I think the 4n part can be thought of as a modulo division matcher (matches everywhere that mod 4 = 0) and the +1 simply shifts that 1 to the right. Thus it includes all the multiples of 4, each with 1 added. And since 0 is technically a multiple of 4, the 1st item is included in this list as well.


text:
Q: Hibernate Ms Sql Server, Incorrect syntax near the keyword 'public' I am new on Hibernate and ms sql server.
I have error like this:

Log: DEBUG SQL:109 - select opmtnasaba0_.id_opmt_nasabah as
  id_opmt_1_48_0_, opmtnasaba0_.alamat as alamat2_48_0_,
  opmtnasaba0_.flag_transfer as flag_tra3_48_0_,
  opmtnasaba0_.id_opdd_kategori_nasabah as id_opdd_4_48_0_,
  opmtnasaba0_.jabatan as jabatan5_48_0_, opmtnasaba0_.keterangan as
  keterang6_48_0_, opmtnasaba0_.ktp_npwp as ktp_npwp7_48_0_,
  opmtnasaba0_.nama as nama8_48_0_, opmtnasaba0_.id_opmt_instansi as
  id_opmt13_48_0_, opmtnasaba0_.penanggung_jawab as penanggu9_48_0_,
  opmtnasaba0_.tgl_lahir as tgl_lah10_48_0_, opmtnasaba0_.tgl_status as
  tgl_sta11_48_0_, opmtnasaba0_.usia as usia12_48_0_ from
  public.opmt_nasabah opmtnasaba0_ where opmtnasaba0_.id_opmt_nasabah=?
Error: com.microsoft.sqlserver.jdbc.SQLServerException: Incorrect
  syntax near the keyword 'public'

.
My jdbc.properties
jdbc.driverClassName=com.microsoft.sqlserver.jdbc.SQLServerDriver
jdbc.dialect=org.hibernate.dialect.SQLServer2008Dialect
jdbc.databaseurl=jdbc:sqlserver://localhost\\mssql;databaseName=databaseName
jdbc.username=username
jdbc.password=password

My Configuration
@Configuration
@ComponentScan("com.blah")
@EnableTransactionManagement
@PropertySource({"classpath:/jdbc.properties"})
public class ApplicationContextConfig implements TransactionManagementConfigurer {
    @Autowired
    Environment env;

    @Override
    @Bean
    public PlatformTransactionManager annotationDrivenTransactionManager() {
        // TODO Auto-generated method stub
        return txManager();
    }

    @Bean(name = "dataSource")
    public DataSource getDataSource() {
        BasicDataSource dataSource = new BasicDataSource();
        dataSource.setDriverClassName(env.getProperty("jdbc.driverClassName"));
        dataSource.setUrl(env.getProperty("jdbc.databaseurl"));
        dataSource.setUsername(env.getProperty("jdbc.username"));
        dataSource.setPassword(env.getProperty("jdbc.password"));

        return dataSource;
    }

    private Properties getHibernateProperties() {
        Properties properties = new Properties();
        properties.put("hibernate.show_sql", "true");
        properties.put("hibernate.dialect", env.getProperty("jdbc.dialect"));
        properties.put("hibernate.current_session_context_class",
                "com.jamkrindo.SyncSuretyBondCabang.config.TransactionAwareSessionContext");
        //      properties.put("hibernate.hbm2ddl.auto", "create-drop");
        return properties;
    }

    @Autowired
    @Bean(name = "sessionFactory")
    public SessionFactory getSessionFactory(DataSource dataSource) {
        LocalSessionFactoryBuilder sessionBuilder = new LocalSessionFactoryBuilder(dataSource);
        sessionBuilder.addProperties(getHibernateProperties());
        sessionBuilder.scanPackages("com.jamkrindo");
        return sessionBuilder.buildSessionFactory();
    }

    @Autowired
    @Bean(name = "transactionManager")
    public HibernateTransactionManager getTransactionManager(
            SessionFactory sessionFactory) {
        HibernateTransactionManager transactionManager = new HibernateTransactionManager(
                sessionFactory);
        //transactionManager.setRollbackOnCommitFailure(true);
        return transactionManager;
    }

    @Bean
    public PlatformTransactionManager txManager() {
        return new DataSourceTransactionManager(getDataSource());
    }
}

My Service
OpmtNasabah dmn = (OpmtNasabah) dao.get(OpmtNasabah.class, json.getIdOpmtNasabah());

My Dao
public Object get(Class clazz, Number id) {
        // TODO Auto-generated method stub
        return sessionFactory.getCurrentSession().get(clazz, id);
    }

My assumption is because hibernate use keyword public before table_name.
How to resolve this?
Thanks.

A: PUBLIC is a SQL Server reserved word and cannot be used as a bare identifier. Have it quoted as a delimited identifier (eg. "public" or [public]) or choose a different, non-reserved, name for the schema.

Microsoft SQL Server uses reserved keywords for defining, manipulating, and accessing databases. Reserved keywords are part of the grammar of the Transact-SQL language that is used by SQL Server to parse and understand Transact-SQL statements and batches.
Although it is syntactically possible to use SQL Server reserved keywords as identifiers and object names in Transact-SQL scripts, you can [use reserved words only when] using delimited identifiers.

To have hibernate quote all identifiers, see Make hibernate backquote all table / column names - however, this "solution" may be missing a more important issue of why public was not on the need-to-quote list for the specific adapter. (Could it be that a wrong dialect is being used?)
All things aside, I would probably use a more focused (and less reserved) name than "public" as the schema name to avoid similar issues with other tooling.


text:
Q: Linking Simple product to their page listed under Grouped product in Magento I want to add url for each simple product listed under Grouped product in Magento. I have changed it with below code in
app\design\frontend\blank\default\template\catalog\product\view\type\grouped.phtml

but still does not work for me it's link but with main group product (Example: Main Grouped product and three simple products Item1 Item2 Item3 but all simple product show same url of ain Grouped product)
<a href="<?php $_item->getUrlPath() ?>"><?php echo $this->htmlEscape($_item->getName()) ?>

and this also
<a href="<?php $_item->getProductUrl() ?>"><?php echo $this->htmlEscape($_item->getName()) ?>

Am I doing any mistakes? Please help how and where to change it?

A: Firstly, you'll need to echo the output of the Url methods:
<a href="<?php echo $_item->getProductUrl() ?>">

Then, I'm not sure about the code that you're using to get the items, but I'd guess that you might need to load the products first before you can call the getUrlPath and getProductUrl methods.
For example:
$product = Mage::getModel('catalog/product')->load($_item->getProductId());
echo $product->getProductUrl();

Try those out and see if they help.

A: Could you please specify where you're placing this code, if you're replacing code, etc.
As I understand: when viewing a grouped product, this will show each simple product title as a link to that simple product's page.
I assume you are replacing this code: <?php echo $this->htmlEscape($_item->getName()) ?>

A: Hey Chris thanks you, u r great it works, actually i m newbie for Magento so this help me a lot thanks again :)
what i did is here
<a href="<?php echo $_item->getProductUrl() ?>" target="_blank"><?php echo $this->htmlEscape($_item->getName()) ?>
and this work like a charm


text:
Q: How to restore edittext data i lost accidentally? I have accidentally closed my app and i lost data in editext after I open it. If it is small login page with username and password it is fine. But when it comes to registration page with all address information filled in it and lost after i open it is really annoying. How to solve this issues?
Thank you

A: Are you looking for saved state?
You implement onSaveInstanceState and onRestoreInstanceState methods, like:
public override fun onSaveInstanceState(savedInstanceState: Bundle) {
    super.onSaveInstanceState(savedInstanceState)

    // store variables
    savedInstanceState.putInt("yourInt", 123)
    savedInstanceState.putBoolean("yourBool", true)
    savedInstanceState.putString("yourString", "Hello")
}

public override fun onRestoreInstanceState(savedInstanceState: Bundle) {
    super.onRestoreInstanceState(savedInstanceState)

    val yourInt = savedInstanceState.getInt("yourInt")
    val yourBoolean = savedInstanceState.getBoolean("yourBool")
    val yourString = savedInstanceState.getString("yourString")
    // use variables ...
}

Note that this will save your form data if you accidentally close the app, but not when you click the back button and close the app normally.
If you want to implement save form data as draft, then you have to handle back button and store data in either Room or shared preferences.

A: did you try this code:
public override fun onSaveInstanceState(savedInstanceState: Bundle) {
    super.onSaveInstanceState(savedInstanceState)

    savedInstanceState.putString("yourEdittext", edittext.text)
}

public override fun onRestoreInstanceState(savedInstanceState: Bundle) {
    super.onRestoreInstanceState(savedInstanceState)

    edittext.text = savedInstanceState.getString("yourEdittext")
}

press Home on your device (not Back) and then run:
$ adb shell am kill com.packagename.appname
without the above code, text will not be restored
now, as I said before, if you are looking for save draft feature, it's quite different, you have to handle back key and show a confirmation dialog, then store it in Room or somewhere.


text:
Q: pass an array in mysql statement using php I need to archive something like this:
$array['0']="ID='1'";
$array['1']="ID='2'";

mysql_query("SELECT * FROM users WHERE {$array}");

This is a special condition and this is just an example; I'm not worried about security here as no value is passed by end user.  Array values are auto generated and can be any size so I can't pass them manually.

A: only store the values in the array.
$array = ('aaa', 'bbb', 'ccc');

mysql_query("SELECT * FROM users WHERE ID IN ('".implode("','", $array)."')");

That will stick the array together and output somethin like:
mysql_query("SELECT * FROM users WHERE ID IN('aaa','bbb','ccc')");

you could leave out the ' if you only use Integers. But anything related to strings needs them in the SQL-statement, thus better use them from the getgo.
If you check for other things, you shoudl sticks thos with and AND or OR depending on how you want to check them and probably put them in different arrays
mysql_query("SELECT * FROM users WHERE ID IN ('".implode("','", $array_1 )."') OR name IN ('".implode("','", $array_2 )."')");


text:
Q: Jquery checkbox on select add a name attribute and increment on more than one selection Ok,i am building a fantansy football game using codeigniter , Grocery CRUD and Jquery. I have a view where user select 15 players from checkboxes where i will use the name attribute to select GK1,GK2,DEF1,DEF2,DEF3,DEF4,DEF5,MID1,MID2,MID3,MID4,MID5,FWD1,FWD2 and FWD3 and pass their value to the controller. My question is , how do i create  a javascript Jquery Code for maybe Midfielders (MID) in such a way that when a user click the first Midfielder the javascript  append input name="MID1"  and on checking another box  it becomes input name="MID2" without changing the name for MID1. So far i the javascript is working but when i click another player the name value changes in all players also if i deselect the name player for that particular player doesnt remove. Here is my JS..
<script>

    $(document).ready(function(){
        $(".gk").change(function() {
            var number=$('[class="gk"]:checked').length;
            if(this.checked) {

                $(".gk").each(function() {
                    $(".gk").attr('name',"GK"+number);
                });

            } else {
                $('.gk').attr('name', number);
            }
        });
    });

</script>

and here is my view
 <input type="checkbox" class="gk"  value="<?=$row->playerID ?>" > <?= $row->playerID?> </input>

A: Regarding your issue of all players having their name changed, the culprit may be '.each()'. Isn't it supposed to be  more like :
$(".gk").change(function() {
        if(this.checked) {
            var number=$('[class="gk"]:checked').length;

            // $(".gk").each(function() {
                $(this).attr('name',"GK"+number);
            // });

A: Among other things, you have a problem when you deselect the players, since you are only running that piece of code that updates the name when the $(".gk") is checked... also, in order to add a different number to each one, you'll have to increment an index value, for example, and add it to the name, not the variable number, which will be the size of the selected elements... On top of this, the last variable "number" should be outside of the "if" otherwise you won't see it in the else...
Check this, see if it helps
$(document).ready(function(){
    $(".gk").change(function() {
        var checked=$('[class="gk"]:checked').length;
        alert("You have "+checked+" Gks checked")
        var index = 1;
        $(".gk").each(function() {
            if($(this).prop('checked')){
                $(this).attr('name',"GK"+index);
                alert("Getting GK "+index)
                alert("this GK name is "+$(this).attr('name')
                index++;
            }
            else {
                $('.gk').attr('name',"");
            }
        });
    });
});

http://jsfiddle.net/xn3P9/5/
Once you update the name it won't show on the page inspector.
You final solution should be this:
$(document).ready(function(){
    $(".gk").change(function() {
        var index = 1;
        $(".gk").each(function() {
            if($(this).prop('checked')){
                $(this).attr('name',"GK"+index);
                index++;
            }
            else {
                 $('.gk').attr('name',"");
            }
        });
    });
});

A: I still have a hard time understanding what you are looking for but maybe it is something similar to this:
$(document).ready(function(){
    $(".gk").change(function() {
        $(".gk:checked").each(function(index, gk) {
            //Will give each selected GK a unique name
            $(".gk:checked").attr("name", "GK"+index);
        });
    });
});


text:
Q: awk script for coverting BibTeX to XHTML I found several nawk and gawk scripts scattered all over the Internet for converting BibTeX files to HTML mostly written in 90s. A quick look into source code indicates, not surprisingly, that some of them will not produce valid XHTML 1.0 strict tags. Before I try to clear up somebody's nawk script (I do not use gawk) can anyone recommend me a script which works well from your own experience? I am OK with gawk as long as I do not have to fix anything. I would also consider a nice Perl or Python script. I must shamefully admit that I have not investigated Perl and Python solutions properly.

A: Biber aims eventually to deal with such cases. At the moment (as of version 0.9.8), you can use the --bltxml option to ouput a BibLaTeXML file instead of a .bbl. BibLaTeXML is experimental still but it's XML with a defined schema so converting this to HTML is likely to be much easier than from .bib format directly, using XSLT. This is generally a better approach as the actual HTML output will vary a lot depending on what you want it to look like exactly.


text:
Q: How to remove tmp directory on git checkout? I have rendered cached templates inside tmp directory. I have to clear the folder manually whenever I use git checkout or git pull. Can I configure git to do it automatically for me and all the users that are using repository?
I am using ember-cli with broccoli to manage assets. Broccoli is compiling templates and store them cached inside tmp directory that is not part of git repository. My team members can edit templates and I can pull the changes from git. The cache is usually outdated afterwards, because it is not a part of repository. At the moment I have to clear it manually. It is tiresome. I want to have it done automatically. I could define aliases to git commands but it is only an ugly workaround.

A: Git has hooks which are triggered after certain events. It sounds like you could use the post-checkout and post-merge hooks to clear out your assets. It might not solve all problems but it could save you a few seconds in certain cases.
http://git-scm.com/book/en/v2/Customizing-Git-Git-Hooks

A: Cache files shouldn't be part of the repository so you should exclude them from your repository.
To clear the cache you could use a deployment system like Jenkins or Travis and execute commands on your server where you can clear the cache and make some checks before you pull your changes.
Ok to clear you cache you can very simple write a batch or bash file where you execute all commends after another.


text:
Q: Why is the initialCapacity of Hashtable 11 while the DEFAULT_INITIAL_CAPACITY in HashMap is 16 and requires a power of 2? Comparing the HashMap and Hashtable source code in JDK 1.6, I saw the below code inside HashMap:
/**
 * The default initial capacity - MUST be a power of two.
 */
static final int DEFAULT_INITIAL_CAPACITY = 16;

    int capacity = 1;
    while (capacity < initialCapacity)
        capacity <<= 1;

However, in Hashtable, I saw this:
table = new Entry[initialCapacity];

public Hashtable() {
    this(11, 0.75f);
}

So my question is:
Why does HashMap require a power of 2 as the initial capacity, while Hashtable chooses 11 as the default initial capacity?
I assume this has nothing to do with the thing that Hashtable is thread-safe and does not allow null key or values.

A: Hashtable uses pseudo-prime number table sizes and grows the size of the table relatively slower.   HashMap uses a power of 2 as the bit wise and is faster than using modulus.
Ironically, a modulus of a power of 2 means a good hashCode() is needed as the top bits would be ignored so HashMap has a method to rearrange the hashCode you get to avoid this issue meaning it can actually be slower. :Z

A: This could help:
http://www.concentric.net/~Ttwang/tech/primehash.htm
Basicly, if I remember correctly, when you have a hash table with a size that is power of 2, it's easy to get a hash function based on the less relevant bits of the key.
Using a prime number (as in 11) as the size of the table, makes collision on the table rows less likely, so inserting is "cheaper".

A: The following article addresses this question in some detail: HashMap requires a better hashCode() - JDK 1.4 Part II.
According to that article, the main reason to move to power-of-two sizes was that bit masking is faster than integer division. This is not without adverse consequences, which are explained by one of the original authors:

Joshua Bloch: The downside of using a power-of-two is that the resulting hash table is very sensitive to the quality of the hash function (hashCode). It is imperative that any change in the input must affect the low order bits of the hash value. (Ideally, it should affect all bits of the hash value with equal likelihood.) Because we have no assurance that this is true, we put in a secondary (or "defensive") hash function when we switched to the power-of-two hash table. This hash function is applied to the results of hashCode before masking off the low order bits. Its job is to scatter the information over all the bits, and in particular, into the low order bits. Of course it has to run very fast, or you lose the benefit of switching to the power-of-two-sized table. The original secondary hash function in 1.4 turned out to be insufficient. We knew that this was a theoretical possibility, but we thought that it didn't affect any practical data sets. We were wrong. The replacement secondary hash function (which I developed with the aid of a computer) has strong statistical properties that pretty much guarantee good bucket distribution.

A: The requirement for the table size to be a power of two is an implementation detail, not known to the users of the class -- that is why the c'tor silently adjusts the value to the next larger power of two instead of flagging an error.
The Hashtable implementation assumes that the hash may not be evenly distributed, so it tries to use a number of bins that is prime in the hope of avoiding peaks in the frequency distribution of the hash.
The combination of these two implementation details leads to bad performance.
(e.g. a primitive hash function would be
int hash(String s, int nBins) {
    return s[0] % nBins;
}

If nBins is 32, e and E end up in the same bin, so the distribution of hash values correlates with the distribution of occurence of letters, which has distinct peaks -- so the frequency distribution would have a peak at 32.)


text:
Q: How to check which color has been assigned to a div by jquery random color script I got this script from here
http://jsfiddle.net/r74j6/6/
function get_random_color() {
var letters = '0123456789ABCDEF'.split('');
var color = '#';
for (var i = 0; i < 6; i++ ) {
    color += letters[Math.round(Math.random() * 15)];
}
return color;
 }

 $(function() {
$(".jump-response").each(function() {
    $(this).css("background-color", get_random_color());
});
});

it assigns a random color. I am applying it all the individual element of the page....
 $("div, a, p, img  ...etc").each(function() {
Then how can I check which div has which color?
ultimately id like to end up with a very poor man's firebug. ...so if you hover over an element it will tell you what it is.
Thanks for any ideas

A: You can use:
$(".jump-response").mouseover(function() {
    console.log($(this).css('background-color'));
});

Updated Fiddle
If you want to get hex value instead of rgb, than you can use a custom function like this:
function rgb2hex(rgb) {
    rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
    function hex(x) {
        return ("0" + parseInt(x).toString(16)).slice(-2);
    }
    return "#" + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]);
}

then call it using:
$(".jump-response").mouseover(function() {
    console.log(rgb2hex($(this).css('background-color')));
});

Fiddle Demo

A: You could add a title attribute that matches the color you've added to each element:
$(".jump-response").each(function() {

    var myColor = get_random_color();

    $(this)
        .css("background-color", myColor)
        .attr('title', 'Color: ' + myColor);

});

Here's a fiddle to demonstrate.


text:
Q: A variation on the induced topology (subspace topology) One of the easiest ways to find a topology on a set is to used the Induced Topology.
Induced Topology: Suppose you have a set $X$ and a topology on $X$ called $\mathcal{T}_X$. Suppose $Y \subseteq X.$ Then we can find a topology for $Y$ (call it $\mathcal{T}_Y$) as given by:
$\mathcal{T}_Y=\{O \cap Y  \mid O \in \mathcal{T}_X\}$.
My question is: does the induced topology still hold for sets $Y \not \subseteq X.$ Suppose $Y \cap X = \emptyset.$ Can we still inherit a topology on $Y$ if $X$ and $Y$ are disjoint? I'm going to say no.
Here's my test:
Let $X =\{1,2\}$ and $\mathcal{T}_X = \{\emptyset,\{1\},\{1,2\}\}$
Let $Y = \{5\}$
Then, following from our induced topology method,
$\mathcal{T}_Y=\{\{5\} \cap \emptyset, \{5\} \cap \{1\}, \{5\} \cap \{1,2\}\} = \{\emptyset,\emptyset,\emptyset\}$
But this fails to satisfy definition of topology since $Y=\{5\}$ and $Y \not \in \mathcal{T}_Y.$
So it would seem that we need $Y \subseteq X$ so that $Y \in \mathcal{T}_Y$, otherwise we end up with a bunch of empty sets.
Is my reasoning here correct?

A: No, this concept makes no sense unless $Y \subseteq X$. It will only be a topology if this is the case: We must have $Y \in \mathcal{T}_Y$ so $\exists O \in \mathcal{T}_X: O \cap Y = Y$ from which it follows that $Y \subseteq O \subseteq X$.
Note that the definition of $\mathcal{T}_Y$ is not an arbitrary one, it's the natural choice in that it is the smallest topology on $Y$ that makes the inclusion map $i: Y \to X$ continuous. Extending it to any $Y$, unrelated to $X$ does not solve such a natural problem, or is not especially useful in constructing new spaces. So don't consider it, it won't get accepted.

A: You can define
$\tau_Y=\{O\cap Y: O\in\tau_X\}\cup\{Y\}.$
This is a topology on $Y$. It is the topology generated by $\{O\cap Y: O\in\tau_X\}$, i.e. the smallest topolgy containing that family of sets.
(And in fact that topology carries informations only about $Y\cap X$.)
Basically you have a topology on the subset $Y\cap X$, and you promote it to a topology on $Y$ by adding $\{Y\}$.
If $Y\cap X=\emptyset$, then $\tau_Y=\{\emptyset, Y\}$ is just the trivial topology.


text:
Q: ASP.NET WebForms with Angular Postback im trying to use Angular framework in existing ASP.NET WebForms application and problem i ran into is this:
Client side code:
<select id="fooSelect" class="span8" runat="server" clientidmode="Static">
 <option ng-repeat="foo in foos" value="{{foo.Id}}">{{foo.Title}}</option>
</select>

When form gets submited (whole page postback),
value of fooSelect.Value
is "{{foo.Id}}"
How to get value of selected option on server side?

A: You can't use angular for server select tag. Actually, selected option value computed on server on postback. So as you have value="{{partner.Id}}" in markup, you getting exactly this value. In my opinion you can use plain select element without runat="server" attribute and bind selected id to hidden field, accessible on server-side:
<select ng-model="partner" ng-options="p.Title for p in partners" >
    <option value="">--Select partner--</option>
</select>
<br />
<input type="hidden" id="selectedPartnerId" runat="server" ng-value="partner.Id" />

A: ASP.Net is not a good candidate for integration with AngularJS (and maybe other SPA). The abstraction against which ASP.Net is build makes it nearly impossible to leverage any capability of Angular such as routing or data binding.
ASP.Net dynamically generates content, which you don't have much control over. It would generate contains (like span), dynamic client ids an all to keep the data in sync and detect changes on the server.
I seriously doubt, if one can achieve data-binding in AngularJS for content generated with ASP.Net. The best that can work would be input type binding with ng-model and getting that data on the server with postback.
I highly recommend you to switch to ASP.Net MVC


text:
Q: Cloud Firestore wildcard for indexing What is the syntax for a wildcard level in Cloud Firestore when setting up indexing?  I know there is one for security rules.
Thanks.

A: Cloud Firestore indexes are based on collection names, not full collection paths. So if you want to create indexes on users/{id}/messages, the correct way to do this is to create an index on messages.
All same-named collections, even if nested under documents, share the same indexes.


text:
Q: entity framework 6 code first change mapping from view to new table I am maintaining a WPF application that use Entity Framework Code First with migrations (not auto). Some of the POCOs in this application are mapped to views (that point to another DB). I guess the method used to do this is similar to what is done in this answer: how to use views in code first entity framework
Now I want one of the POCOs (Company) to point to a table in stead of a view. The POCO has also changed a bit since pointing to the view.
When I add a migration after doing the changes in the POCO and in the CompanyConfiguration-class (changing the ToTable()), then it seems that the migration think that the view is an existing table and tries to rename it. For example the start of the Up()-method will look like this:
    RenameTable(name: "dbo.vCompany", newName: "Company");

    AlterColumn("dbo.Company", "ParentAccount", c => c.String(maxLength: 160));
    AlterColumn("dbo.Company", "Country", c => c.String(maxLength: 100));

However, I don't want the view to be changed, I want the Company-table to be created from scratch matching the POCO. What would be the correct/good way to accomplish this? Is it possible without writing the Up() and Down() methods myself?
Currently the application uses Entity Framework 6.1, but when this Company/vCompany mapping was first created, it was version 4.3 I belive.

A: Not much info/help to get on this, but I did the following that worked for me (although very tidious work):
I had to completely rewrite the auto-created Up() and Down() methods in the migration. Used the CreateTable() to create the table in stead of renaming the view.
In the Up() method:
CreateTable(
            "dbo.Company",
            c => new
            {
                CompanyId = c.Guid(nullable:false),
                ParentAccount = c.String(maxLength:160),
                Country = c.String(maxLength:100),
                Address1_City = c.String(maxLength:4000),
                Address1_Country = c.String(maxLength: 4000),
                Address1_Line1 = c.String(maxLength: 4000),
                Address1_Line2 = c.String(maxLength: 4000),
                Address1_PostalCode = c.String(maxLength:50),
                Owner = c.String(maxLength:160),
                OwnerId = c.Guid(nullable:false),
                Name = c.String(maxLength:160),
                EMailAddress = c.String(maxLength:100),
                InvoiceEMailAddress = c.String(maxLength:100),
                Fax = c.String(maxLength:50),
                CreditLimit = c.Decimal(storeType:"money"),
                CreditOnHold = c.Boolean(nullable:false, defaultValue:false),
                IsPrivate = c.Boolean(nullable:false, defaultValue:false),
                StatusCode = c.Int(),
                CustomerTypeCode = c.Int(),
                BEGreenCreditLimit = c.Int(),
                IssuingBodyAccount = c.String(maxLength:20),
                CustomerType = c.String(maxLength:100),
                IsElProducer = c.Boolean(nullable:false, defaultValue:false),
                IsEnergyTrader = c.Boolean(nullable:false,defaultValue:false),
                VATNumber = c.String(maxLength:100),
                ContactPerson = c.String(maxLength:160),
                ContactPersonPhone = c.String(maxLength:50),
                ContactPersonFax = c.String(maxLength:50),
                ContactPersonEmail = c.String(maxLength:100)

            }
            )
            .PrimaryKey(p=>p.CompanyId)
            ;

The company values extracted from another database, ref the long maxLength for some of the columns.


text:
Q: iOS - Get sum of filesize in directory I have the following code I use to cache photos I load off Flickr in the device's memory:
NSURL *urlForPhoto = [FlickrFetcher urlForPhoto:self.photo format:FlickrPhotoFormatLarge];
NSString *rootPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *imagePath = [rootPath stringByAppendingString:[self.photo objectForKey:FLICKR_PHOTO_ID]];
NSData *dataForPhoto;
NSError *error = nil;
if ([[NSFileManager defaultManager] fileExistsAtPath:imagePath]) {
    dataForPhoto = [NSData dataWithContentsOfFile:imagePath];
} else {
    dataForPhoto = [NSData dataWithContentsOfURL:urlForPhoto];
    [dataForPhoto writeToFile:imagePath atomically:YES];
}

I want to limit this to 10MB and then if the limit is reached to remove the oldest photo in the cache, how can I get the total size of all the files I've saved and check which one is the oldest?

A: You can get the size of a file like so
NSError *attributesError = nil;

    NSDictionary *fileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:URL error:&attributesError];

    int fileSize = [fileAttributes fileSize];

So you can maybe iterate through all the files in the folder and add up the file sizes...not sure if theres a direct way to get the directory size, also theres this SO post talking about this aswell, you can find a solution here
To find the creation date of the file you can do
NSString *path = @"";
    NSDictionary* fileAttribs = [[NSFileManager defaultManager] attributesOfItemAtPath:path error:nil];
    NSDate *result = [fileAttribs valueForKey:NSFileCreationDate]; //or NSFileModificationDate

Hope it helps


text:
Q: monitoring HDMI cable state I want to monitor the HDMI cable state in my code. there is a file that changes when the cable gets connected and disconnected.
$cat /sys/devices/soc0/soc/20e0000.hdmi_video/cable_state
plugin
$cat /sys/devices/soc0/soc/20e0000.hdmi_video/cable_state
plugout

I used QFileSystemWatcher to monitor this file, but it didn't work.
    QFileSystemWatcher watcher;
    watcher.addPath("/sys/devices/soc0/soc/20e0000.hdmi_video/cable_state");
    QObject::connect(&watcher, &QFileSystemWatcher::fileChanged,
    [this]( const QString& path ) {
        qDebug() << path;
        QFile file(path);
        if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
            return;
        auto line = file.readLine();
        qDebug() << line;
    });

I think that it doesn't work because this file belongs to the sysfs and is not an ordinary file.
Is there any way to access a platform device attribute and get notified, without file monitoring, with code?
part of the code that define cable_state attribute in kernel:
static ssize_t mxc_hdmi_show_state(struct device *dev,
        struct device_attribute *attr, char *buf)
{
    struct mxc_hdmi *hdmi = dev_get_drvdata(dev);

    if (hdmi->cable_plugin == false)
        strcpy(buf, "plugout\n");
    else
        strcpy(buf, "plugin\n");

    return strlen(buf);
}

static DEVICE_ATTR(cable_state, S_IRUGO, mxc_hdmi_show_state, NULL);

A: You are correct: files in /sys are not regular files. Their contents are magic'ed up by the kernel when you actually read them.
You will have to resort to polling instead:
class HDMIWatcher : public QObject {
Q_OBJECT
public:
  HDMIWatcher(const QString& path, QObject* parent) : QObject(parent), path(file), timer(new QTimer(this)) {
    QObject::connect(timer, &QTimer::timeout, this, &HDMIWatcher::poll);
    timer->setInterval(5000);
    poll();
  }

public slots:
  void start() {
    timer->start();
  }

  void poll() {
    QFile file(path);
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
        return;
    auto line = file.readLine();
    if (last.isEmpty()) {
      last = line;
    }
    if (line != last) {
      emit changeDetected(last, line);
      last = line;
    }
  }

public signals:
  void changeDetected(const QString& old, const QString& new);

private:
  QString last;
};

A: The sysfs entry you are working with could be made to "appear" to have updated which would make your QFileSystemWatcher work the way you would expect, if only the Linux HDMI driver had made use of the function sysfs_notify when the "behind the scenes" data in the driver gets updated as a result of physically "plugging in" or "plugging out" the HDMI cable.
Short of patching the driver, and assuming you are using the mxc_hdmi driver like the driver code in your example seems to match up with...
You could still use the QFileSystemWatcher if you create a udev rule to update a file (of your choosing) whenever the HDMI "cable_connected" state changed.  Then you would use that QFileSystemWatcher class to "watch" the file that the udev rule updates.
If you were willing to do a bit more legwork, you could cut out the udev rule and just monitor the udev signals yourself using libudev or sd-device.  It might be a more "self-contained" solution, but it probably requires a bit more complexity in your userspace code.


text:
Q: Sorting a nested list in python I have a nested list:
a = [[{'aa': 2L}, {}, {'mm': 9L}, {}, {}], [{'aa': 1L}, {}, {'mm': 5L}, {}, {}], [{'aa': 2L}, {}, {'mm': 7L}, {}, {}], [{'aa': 5L}, {}, {'mm': 7L}, {}, {}]]

Desired Output:
a = [[{'aa': 1L}, {}, {'mm': 5L}, {}, {}], [{'aa': 2L}, {}, {'mm': 7L}, {}, {}], [{'aa': 5L}, {}, {'mm': 7L}, {}, {}], [{'aa': 2L}, {}, {'mm': 9L}, {}, {}]]

Output I am getting from a.sort() :
a = [[{'aa': 1L}, {}, {'mm': 5L}, {}, {}], [{'aa': 2L}, {}, {'mm': 7L}, {}, {}], [{'aa': 2L}, {}, {'mm': 9L}, {}, {}], [{'aa': 5L}, {}, {'mm': 7L}, {}, {}]]

Not desired.
Here I want to sort the list 'a' by considering any one of the keys of child lists.In this case I am using third dictionary and key 'mm'.Right now there is only one key 'mm' there may be multiple key value pairs but I should be able to avoid others and do the sorting on the basis of 'mm' keys value only.

A: You have a list of lists, so you need to sort each sublist if you want to order the sublists.
a_sorted = [sorted(sublist) for sublist in a]

Obviously, you can run sorted() on the list of sorted lists if you want the outer list to be sorted too.
You can pass the sorted() builtin a key argument - a function which takes the list item and returns the value to sort on. It's a little unclear exactly how you want to sort the list, you could clarify, although with this you should be able to work out a solution.
Your data structure seems a little odd, however. Where you have pairs in the form {key: value} you would normally be better off with a tuple: (key, value), or a single, larger dict that contains all of your pairs as keys and values, e.g:
a = [{'aa': 2L, 'mm': 7l}, {'aa': 2L, 'mm': 5L}, {'aa': 2L, 'mm': 9L}, {'aa': 2L, 'mm': 3L}]

In this case, we can use sorted(a, key=itemgetter("mm")) - using operator.itemgetter() - to sort on the value of 'mm'.
Or, if you need your empty pairs (without using keys to None, for example), as tuples:
a = [[('aa', 2L), (,), ('mm', 7L), (,), (,)], [('aa', 2L), (,), ('mm', 5L), (,), (,)], [('aa', 2L), (,), ('mm', 9L), (,), (,)], [('aa', 2L), (,), ('mm', 3L), (,), (,)]]

Here we can do a similar thing sorted(a, key=lambda sublist: sublist[2][1]) - we use lambda to make a quick function to extract the second item in the third item in the sublist.
If you wanted to keep your data structure as is - if, for example, you plan to expand the dictionaries with more content, then a similar plan would work sorted(a, key=lambda sublist: sublist[2]["mm"]) - this time using 'mm' to access in the dict.

A: I am not sure if I got the question correctly, but the answer seems simple to me as below.
Index the third item [3] in the key and then re-index the dictionary with key mm
>>> sorted(a,key=lambda key:key[2]['mm'])
[[{'aa': 1L}, {}, {'mm': 5L}, {}, {}], [{'aa': 2L}, {}, {'mm': 7L}, {}, {}], [{'aa': 5L}, {}, {'mm': 7L}, {}, {}], [{'aa': 2L}, {}, {'mm': 9L}, {}, {}]]
>>>


text:
Q: Give special permissions to groups about a specific directory I have Ubuntu server 16.04.3 installed, then I have 3 directories: /group1 , /group2 , /everyone .
Now I already have groups named group1 and group2 and want users in the group1 and group2 groups to be the only ones who can write to their respective directories. Anyone should be able to write to the /everyone directory, but they should not be able to delete files belonging to other users.
After searching the site, I used sudo chmod u=rwx,g=rwx,o=rx /group1to set permissions for /group1 & /group2.
How do I set permissions to /everyone?
Thanks!

A: This is exactly what sticky bit is for, look at /tmp.
You can do:
sudo chmod 1777 /everyone

Now, everyone can write to /everyone, but only owners will be able to remove/modify/rename their files. Obviously the directory owner:group can perform actions based on the permission assigned to them, which in this case, is anything. Go for something restrictive for them if you want more control over their permissions.


text:
Q: How to call a function that mutates a variable in Ruby? The standard method would be something like
foo = bar(foo)

But I'd like some kind of way to simply write
bar(foo)

That would change the value of foo like the first line. In C++ I could do this with pointers, but with Ruby I don't know how to.

A: This is not possible in Ruby.  You'll have to write foo = bar(foo).
Another option would be to let foo be a mutable object.  Then bar could call methods on it to mutate it.  For example, if foo is a String, Hash, or Array, bar could call foo.replace to modify the object that foo refers to.

A: This is not possible. What you are looking for is some form of pass-by-reference. However, Ruby is strictly pass-by-value.


text:
Q: Posgres Row Security Policy - Why Array faster than Bitstring? I have a question:
I have two row security policies to restrict the access to a table.
The first policy uses an Array-Column "rights".
The "rights" column is type 16-bit bit/integer array and each user is assigned an index.
If the array has the value 1 at an index, the user with that index can read the line. The policy for looks like this:
CREATE POLICY policy_testdata_select ON testdata
        FOR SELECT TO PUBLIC
        USING (rights[(select array_pos from account where username = current_user)] > 0);

The second policy uses bitstrings with the same logic so for example:
Value in the table: 1001010
User1 bit string: 0001000
User2 bit string: 0000100
1001010 & 0001000 = 0001000 -> User1 has access
1001010 & 0000100 = 0000000 -> User2 has no access
The policy looks like this:
CREATE POLICY policy_testdata_select ON testdata
        FOR SELECT TO PUBLIC
        USING ((bitstring & (select user_bitstring from account where username = current_user)) <> B'0'::BIT(16));

Intuitively, I would argue that the second option is more performant as a bit string does not consume a lot of memory and binary operations don't cost much, but if one compares the performance, the array version is even a little faster. How come?
Here are the two evaluation plans with the same test data (2 million lines and user has access to half):
Array:
                                                                 QUERY PLAN
---------------------------------------------------------------------------------------------------------------------------------------------
 Limit  (cost=10000000008.16..10000526114.16 rows=666667 width=1160) (actual time=0.025..2733.524 rows=1000000 loops=1)
   InitPlan 1 (returns $0)
     ->  Index Scan using username2_index on account2  (cost=0.14..8.16 rows=1 width=4) (actual time=0.014..0.014 rows=1 loops=1)
           Index Cond: (username = CURRENT_USER)
   ->  Seq Scan on testdata  (cost=10000000000.00..10000526106.00 rows=666667 width=1160) (actual time=0.025..2660.927 rows=1000000 loops=1)
         Filter: (rights[$0] > 0)
         Rows Removed by Filter: 1000000
 Planning Time: 0.181 ms
 Execution Time: 2768.561 ms
(9 rows)

Bitstring:
                                                                  QUERY PLAN
----------------------------------------------------------------------------------------------------------------------------------------------
 Limit  (cost=10000000008.16..10000266895.60 rows=1000000 width=1160) (actual time=0.026..2759.098 rows=1000000 loops=1)
   InitPlan 1 (returns $0)
     ->  Index Scan using username2_index on account2  (cost=0.14..8.16 rows=1 width=7) (actual time=0.013..0.014 rows=1 loops=1)
           Index Cond: (username = CURRENT_USER)
   ->  Seq Scan on testdata  (cost=10000000000.00..10000531106.00 rows=1990000 width=1160) (actual time=0.025..2685.145 rows=1000000 loops=1)
         Filter: ((bitstring & $0) <> '0000000000000000'::bit(16))
         Rows Removed by Filter: 1000000
 Planning Time: 0.167 ms
 Execution Time: 2794.719 ms
(9 rows)

Some comparison between the two versions (yellow and purple - blue without any policy) x-Axis: Count of Rows in thousand, y-Axis: Execution Time of the query - averaged:

And another question: is there a better way to filter access. It should be possible that the rights to a line are changeable.
Would it be possible, for example, to build an index that speeds up the filtering process?

A: It doesn't matter very much how big the data structure is, as long as the row is small enough not to get TOASTed (stored out of line, in which case access becomes more expensive).
The performance difference you measure might as well be the cost of the different operators (& vs. array element access).
I don't believe that you can do that more efficiently than you did. Row level security comes with a performance hit that is ideally proportional to the number of rows checked, and the performance impact will be most visible with a cheap access path like a sequential scan.


text:
Q: HTML Textarea reading newlines I have an HTML textarea that will accept a large block of text.  The textarea needs to read newlines.
For example.  If someone types the following:

Stack overflow is so cool.
I love it.

When I save it to the database and print it out again, it is shown as:
Stack overflow is so Cool.  I love it.
I need the newline (enter) to be recorded.
Anyone know how to do it?

A: Replace the HTML Text Area with CKEditor or FCKEditor Enabled control which take and save total html as per user entry for further use and display.

A: For PHP, you can use the function nl2br:
http://ca3.php.net/manual/en/function.nl2br.php


text:
Q: Cannot launch activity which extends MapActivity An activity (ShowPos) cannot be launched when it extends MapActivity. If I change to extends Activity, it launches.
It did work earlier, before I copy/pasted the java codes of the project to a new project in a new workspace when suddenly Eclipse inexplicably could no longer find any Android API, and none could be re-imported. Similar things have happened a few times before, it seems ordinary with Eclipse. But copy/paste has always worked before, for a while at least. And now it warns of no such error.
I do have an API-key, which has worked before.
maps.jar is now under Google API 2.2 under the project in the project explorer.
The editor notes no errors in any file in the project.
When launched, LogCat starts with:

 - D dalvikm Calling exit(1)
 - W dalvikm Unable to resolve superclass of Lintrax/three/ShowPos; (35)
 - W dalvikm Link of class 'Lintrax/three/ShowPos;' failed
 - D AndroidRuntime Shutting down VM
 - W dalvikm threadid=1: thread exiting with uncaught exception
   (groupnr)
 - E AndroidRuntime FATAL EXCEPTION: main

My project name is now "intrax.three". Why does it add an "L" to that?
The Manifest does contain:

    uses-library android:name="com.google.android.maps"
    uses-permission android:name="android.permission.INTERNET"

(Couldn't paste the Manifest file here)
Thanks for any help about how I can help Eclipse find stuff!

A: Go to Project -> Preferences -> Android -> Project Build Target and make sure that you created a project that uses the Google APIs

A: If you have already defined the Internet permission and uses-library
<uses-library android:name="com.google.android.maps" /> in your manifest.

Also make sure that the project target is set to google APi.
Third and imp thing is your package level need to be corrected and build the project again without any map.jar library provided explicitly. Only use google APi inbuilt maps.jar and creat new activity that extends the MapActivity (Also do declare in manifest).

A: I've followed the MapView tutorial and it works just fine without any errors.
The error in question is a link error where the Dalvik VM is not able to find your class. This means all the suggestions given here (uses-library, internet permission, setting Google APIs as the Build Target) don't even come into the picture yet. Link error means that Android OS is not able to find your class. So, I suggest you try creating a clean project where you create the new Class from Eclipse and then paste the code snippet instead of pasting files.
BTW, the L is used to identify an Object. Reference: Java Identifiers.
Happy Coding!