text:
Q: PasswordEncoder mapped for the id "null" Estoy haciendo los CORS en SpringBoot y he tenido una serie de problemas que los he solucionado importando 1 dependencia.
El pom.xml:
  <!-- Spring Boot -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-core</artifactId>
    <version>5.0.0.RELEASE</version>
 </dependency>
      <!-- JPA Data -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

           <!-- MySQL Connector-J -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>

        <dependency>
            <!-- Tomcat embedded container -->
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <optional>true</optional>
        </dependency>

          <!-- Data REST -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-rest</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
    </dependencies>

Y WebSecurityConfigurerAdapter
package com.service.configure;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;

@Configuration
@EnableWebSecurity
@ComponentScan(basePackages = "com.service")

public class ServiciosConfig  extends WebSecurityConfigurerAdapter {

    //@Value("${usrRest}")
   // private String usrRest;

    //@Value("${passRest}")
   // private String passRest;
    //@PropertySource("file:${ruta_properties}")

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable();
        http.authorizeRequests().antMatchers("/").permitAll().anyRequest().authenticated().and().httpBasic().and()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    }

    @Override

    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers(HttpMethod.OPTIONS);
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().withUser("admin").password("admin").roles("USER");

    }

}

Al principio me daba error, pero lo solucioné con
 <dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-core</artifactId>
    <version>5.0.0.RELEASE</version>
 </dependency>

Porque decía que tenía problemas con uno de los imports...
El caso es que después de añadir esa dependencia, actualizar el proyecto, ejecuto y obtengo :
java.lang.IllegalArgumentException: There is no PasswordEncoder mapped for the id "null"
    at org.springframework.security.crypto.password.DelegatingPasswordEncoder$UnmappedIdPasswordEncoder.matches(DelegatingPasswordEncoder.java:236) ~[spring-security-core-5.0.0.RELEASE.jar:5.0.0.RELEASE]
    at org.springframework.security.crypto.password.DelegatingPasswordEncoder.matches(DelegatingPasswordEncoder.java:196) ~[spring-security-core-5.0.0.RELEASE.jar:5.0.0.RELEASE]
    at org.springframework.security.authentication.dao.DaoAuthenticationProvider.additionalAuthenticationChecks(DaoAuthenticationProvider.java:86) ~[spring-security-core-5.0.0.RELEASE.jar:5.0.0.RELEASE]
    at org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider.authenticate(AbstractUserDetailsAuthenticationProvider.java:166) ~[spring-security-core-5.0.0.RELEASE.jar:5.0.0.RELEASE]
    at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:174) ~[spring-security-core-5.0.0.RELEASE.jar:5.0.0.RELEASE]
    at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:199) ~[spring-security-core-5.0.0.RELEASE.jar:5.0.0.RELEASE]

En la web:
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.

Wed Jul 04 08:51:28 CEST 2018
There was an unexpected error (type=Internal Server Error, status=500).
There is no PasswordEncoder mapped for the id "null"

A: Remplaza
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
    auth.inMemoryAuthentication().withUser("admin").password("admin").roles("USER");

}

por
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
    auth.userDetailsService(userDetailsService());

}
@Bean
@Override
public UserDetailsService userDetailsService() {
    UserDetails user =
            User.withDefaultPasswordEncoder()
                    .username("admin")
                    .password("admin")
                    .roles("USER")
                    .build();

    return new InMemoryUserDetailsManager(user);
}

Explicación:
El InMemoryUserDetailsManager se encarga de la creación de usuarios por tí mediante su constructor:
 public InMemoryUserDetailsManager(UserDetails... users) {
    UserDetails[] var2 = users;
    int var3 = users.length;

    for(int var4 = 0; var4 < var3; ++var4) {
        UserDetails user = var2[var4];
        this.createUser(user);
    }

}


text:
Q: how to count the png files in windows page by using selenium webdriver how to count the png files in windows page by using selenium webdriver
http://www.thefind.com/search?query=camera
go to above website and count the number of camera present in page by using seleniumwebdriver program
            driver.get("http://www.thefind.com/search?query=camera");
    List<WebElement> wb=driver.findElements(By.tagName("a"));

    System.out.println(wb.size());

A: I would change the locator strategy. By short investigation of the page I realised that all camera are in same class with name tf_search_item_productimage
So change this line
List<WebElement> wb=driver.findElements(By.tagName("a"));

to
List<WebElement> wb=driver.findElements(By.className("tf_search_item_productimage"));

And it should do the trick

redpajama_set_name: RedPajamaStackExchange


text:
Q: Could someone clarify the code snippet $("#gameCanvas").mousedown(function(e) {
    var canvasPosition = $(this).offset();
    var mouseX = e.layerX || 0;
    var mouseY = e.layerY || 0;
}

From what I understand. the e.layerX and e.layerY will give me the cursor coordinates relative to the canvas window.
What would the canvasPosition = $(this).offset(); do?
When I look at the rest of the block of code (didn't want to paste it all, there's too much) canvasPosition is not used. What would I use it for? Basically the code allows me to move a circle, drawn on the canvas, around using the mouse.

A: According to the documentation (http://api.jquery.com/offset/) the jQuery offset function give the position of an element.
So, in this case, it will return an object containing the position of the canvas, in pixel, relative to the whole page.

A: Here in this code snippet, the portion var canvasPosition = $(this).offset(); is doing nothing. Surely leftover. Coder might have thought of using canvas position to identify locaiton of mouse pointer relative to canvas.


text:
Q: NoClassDefFound on tomcat in eclipse, but i have added it to classpath Ive looked at other answers to this question, and ive tried following them. Basically here is the scenario: I have a class which is called via a jsp page. That class has a class which is found in a jar file. When I go to that page, i get a class not found exception, for the class that is in the jar.
Upon deployment if I go to the folder it is deployed in I find the jar file in question, and it has the class inside the jar. Ive also tried adding it to eclipse's deployment assembly to no avail.
Any ideas I could try?
This is a dynamic web project in eclipse on tomcat7. Thanks for your input.
edit: it gets ever freakier. I can call other classes from the same folder in the same jar as the one that is generating the class not found exception.
Edit again: its a noclassdeffound exception, not class not found exception. Apologies.

A: alright, this was a very specific question and I apologize for asking it haha. The class not found was not actually the one it was saying. It was just throwing that for some reason I never found, but it actually couldnt find another Exception class which it was trying to throw. The reason it was doing that is because I needed a fedlet set up for my application. So yea, this issue was specific to my application.


text:
Q: Does position-momentum uncertainty principle apply to a two-body wavefunction when we frame boost to its center of mass reference frame? The heart of my question is below in bold. The rest is clarifying information or additional points of discussion - in case my assumptions are the heart of my misunderstanding.
In a two body attractive quantum mechanical system (namely the simplified Hydrogen atom - ignoring spin etc.), it can be shown that this reduces into two Hamiltonians. We find one Hamiltonian for the center of mass, and one for the behavior of the individual particles.
Assuming the individual particles are bound by their mutually attractive potential, the Hamiltonian has discrete Energy Eigenstates. The center of mass Hamiltonian, $H_{com}$, is a free particle solution. Does position-momentum uncertainty principle still apply to the wavefunction describing solutions to $H_{com}$ ?
In my undergrad QM class, the professor said that when we're in the center of mass reference frame, we ignore $H_{com}$. When I pressed him further on this, he said it wouldn't make sense for the atom's wavefunction to "spread out" in the center of mass frame (due to a $k$-space distribution of $\psi$). This didn't sit well with me, because being in the center of mass frame of the atom implies we know the center of mass momentum exactly (or to extreme accuracy), and therefore can't know the exact position (or only have an extremely inaccurate knowledge).

A: Yes it holds because the corresponding operators satisfy the standard commutation relations. It can be proved in various ways. The most elementary way is to describe the system using the so-called Jacobi coordinates (in the phase space) which include the coordinates of CM and the total momentum. Assuming that the position and momentum operstors of every single particle satisfy the standard commutation rules, it arises that the position of CM and the total momentum satisfy the same relations.
However the typical time a wavefunction spends in spreading out in space, when it freely evolves,  is related to the value of the mass of the system: large masses imply large times. This implies that the wavefunction of the center of mass (assuming the total wavefunction factorised) needs a typical time larger than the times of the single particles, if these are not subjected to mutual interactions.


text:
Q: How to move up a modal UIView inside of a UIViewcontroller (StoryBoard) i've got a UIView, dragged of Object Library, inside of a UIViewcontroller created by StoryBoard.
Inside of this UIView, I put two Text Field to grab user name and password, and one button to log in.
How can I move only this View when the keyboard appears? I'm able to move the whole View Controller, but i can't find a solution to move only the View.
I just dragged one View of the Object Library, inside my Viewcontroller and created one Outlet in .h Viecontroller - @property (weak, nonatomic) IBOutlet UIView *contentView; and connected do this View, i'm in doubt too if I need to do something more to add the view to the project.
Thanks in advance!!
View inside UIViewController;

A: You have to subscribe for
UIKeyboardWillShowNotification and UIKeyboardWillHideNotification. Then move modal view up when keyboard appears, down when keyboard hides.
Then animate modal view up or down whether keyboard will show or hide:
Move up:
[UIView animateWithDuration:ANIMATION_DURATION animations:^{
    CGRect currentFrame = modalView.frame;
    currentFrame.origin.y -= VIEW_FRAME_OFFSET;
    modalView.frame = currentFrame;
}];

Move down:
[UIView animateWithDuration:ANIMATION_DURATION animations:^{
    CGRect currentFrame = modalView.frame;
    currentFrame.origin.y += VIEW_FRAME_OFFSET;
    modalView.frame = currentFrame;
}];

Also if you want you can use other keyboard notifications listed here.


text:
Q: Do decorators consume more memory? On a Corey Schafer tutorial, he wrote the following code to measure the amount of memory a specific function has consumed.
import time
import random
import memory_profiler

names = ['john', 'Corey', 'Adam', 'Steve', 'Rick', 'Thomas']
majors = ['Math', 'Engineering', 'CompSci', 'Art', 'Business']
print('Memory (before): {}Mb'.format(memory_profiler.memory_usage()))

def people_list(num_of_people):
    result = []
    for i in range(num_of_people):
        person = {'id': i,
                  'name' : random.choice(names),
                  'major' : random.choice(majors)}
        result.append(person)
    return result

t1 = time.process_time()
people_list(1000000)
t2 = time.process_time()
print('Memory (After): {}Mb'.format(memory_profiler.memory_usage()))
print('Took {} seconds'.format(t2-t1))

The results were
Memory (before): [34.21875]Mb
Memory (After): [34.47265625]Mb
Took 2.390625 seconds

but when I tried to create a decorator to add the memory and time measuring functionality to my function, the difference in memory before and after the function execution was huge.
This is my code
import time
import random
import memory_profiler

names = ['john', 'Corey', 'Adam', 'Steve', 'Rick', 'Thomas']
majors = ['Math', 'Engineering', 'CompSci', 'Art', 'Business']

def decorator(original_func):
    def wrapper(*args, **kwargs):
        before_memory = memory_profiler.memory_usage()
        print('Memory (before): {} Mbs'.format(before_memory))
        t1 = time.time()
        output = original_func(*args, **kwargs)
        t2 = time.time()
        time_diff = t2 - t1
        after_memory = memory_profiler.memory_usage()
        print("Memory (after): {} Mbs".format(after_memory))
        print('{} ran in {} seonds'.format(original_func.__name__, time_diff))
        return output
    return wrapper

@decorator
def people_list(num):
    result = []
    for i in range(num):
        person = {'id' : i+1,
                  'name' : random.choice(names),
                  'major' : random.choice(majors)}
        result.append(person)
    return result

people_list(1000000)

and the results were
Memory (before): [47.07421875] Mbs
Memory (after): [319.875] Mbs
people_list ran in 2.5296807289123535 seonds

A: Without decorator you discard the result of your function call at once. In the decorator example, the result is kept in output, when looking at memory usage.
Try the first example with:
t1 = time.process_time()
output = people_list(1000000)
t2 = time.process_time()
print('Memory (After): {}Mb'.format(memory_profiler.memory_usage()))
print('Took {} seconds'.format(t2-t1))

and you should get the same memory usage.


text:
Q: Deserialising json, hoisting subclass objects to top level instead of nested classes I'm deserialising json response from an api, I have a working code, but the only thing of my concern are the elements within the Object class, how can I eliminate the Object class entirely and just return the elements directly from the ListUsers class?
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

import java.util.List;

public class ListUsers{

    @SerializedName("meta")
    @Expose
    private Meta meta;
    @SerializedName("objects")
    @Expose
    private List<Objects> objects = null;

    public Meta getMeta() {
        return meta;
    }

    public void setMeta(Meta meta) {
        this.meta = meta;
    }

    public List<Objects> getObjects() {
        return objects;
    }

    public void setObjects(List<Objects> objects) {
        this.objects = objects;
    }

    private class Meta {
        @SerializedName("limit")
        @Expose
        private int limit;
        @SerializedName("offset")
        @Expose
        private int offset;
        @SerializedName("total_count")
        @Expose
        private int totalCount;

        public int getLimit() {
            return limit;
        }

        public void setLimit(int limit) {
            this.limit = limit;
        }

        public int getOffset() {
            return offset;
        }

        public void setOffset(int offset) {
            this.offset = offset;
        }

        public int getTotalCount() {
            return totalCount;
        }

        public void setTotalCount(int totalCount) {
            this.totalCount = totalCount;
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (!(o instanceof Meta)) return false;
            Meta meta = (Meta) o;
            return getLimit() == meta.getLimit() &&
                    getOffset() == meta.getOffset() &&
                    getTotalCount() == meta.getTotalCount();
        }

        @Override
        public int hashCode() {
            return java.util.Objects.hash(getLimit(), getOffset(), getTotalCount());
        }

        @Override
        public String toString() {
            return "Meta{" +
                    "limit=" + limit +
                    ", offset=" + offset +
                    ", totalCount=" + totalCount +
                    '}';
        }
    }

    private class Objects {
        @SerializedName("address_one")
        @Expose
        public String addressOne;
        @SerializedName("address_three")
        @Expose
        public String addressThree;
        @SerializedName("address_two")
        @Expose
        public String addressTwo;
        @SerializedName("country_code")
        @Expose
        public String countryCode;
        @SerializedName("cs_domain_id")
        @Expose

        public String getAddressOne() {
            return addressOne;
        }

        public void setAddressOne(String addressOne) {
            this.addressOne = addressOne;
        }

        public String getAddressThree() {
            return addressThree;
        }

        public void setAddressThree(String addressThree) {
            this.addressThree = addressThree;
        }

        public String getAddressTwo() {
            return addressTwo;
        }

        public void setAddressTwo(String addressTwo) {
            this.addressTwo = addressTwo;
        }

        public String getCountryCode() {
            return countryCode;
        }

        public void setCountryCode(String countryCode) {
            this.countryCode = countryCode;
        }
    }
}

A: Write an Adapter (this is a wikipedia link).

*

*Create a class hierarchy to represent the JSON.
Success, this is your example source.

*Create an adapter class that wraps your JSON representation class.
This will expose the blam0-blah stuff
(in your case, the nicely named Objects List)
is some fun and creative way (perhaps a getAddressLine1 method and such).

Depending on how the Adapter will be used,
you might parse the List<Objects> into a Map<Objects> for easier use.


text:
Q: How to remove a CSS class from a Wicket component? It's pretty straightforward to dynamically add a CSS class to a component in Java code using an AttributeAppender:
component.add(new AttributeAppender("class", true, new Model<String>("foo"), " "));

Or, if you've extracted the above into an appropriate utility method or class, simply something like:
component.add(WicketUtils.cssClassAppender("foo"));

But how can I remove a CSS class?
You can easily remove all CSS classes by clearing the class attribute altogether:
component.add(new SimpleAttributeModifier("class", ""));

...but that is not acceptable if the component has other CSS classes that you do not wish to remove.
Wicket 1.4 (but feel free to post advice specific to later versions too).

A: Building on Jonik's answer, the following adds negative lookahead to ignore occurrences in the middle of a different style class (and is case insensitive).
public class StyleClassRemover extends AttributeModifier {

    public StyleClassRemover(final String cssClass) {
        super("class", false, Model.of(cssClass));
    }

    @Override
    protected String newValue(final String currentValue, final String valueToRemove) {
        if (currentValue == null) {
            return "";
        }

        final String patternString = "(^|\\s+)" + Pattern.quote(valueToRemove) + "(?!\\S)";
        return Pattern.compile(patternString, Pattern.CASE_INSENSITIVE).matcher(currentValue).replaceAll("");
    }
}

Tested input:
http://fiddle.re/ah0ca6

A: Here's one way I came up with:
public class CssClassRemover extends AttributeModifier {
    public CssClassRemover(String cssClass) {
        super("class", false, new Model<String>(cssClass));
    }

    @Override
    protected String newValue(String currentValue, String valueToRemove) {
        // NB: naive approach; breaks with e.g. "foo foo-bar" & "foo"
        return currentValue.replaceAll(valueToRemove, "");
    }
}

The code that uses the above helper would then be:
component.add(new CssClassRemover("foo"))

(Of course you can also just create anonymous AttributeModifier subclasses as needed, but putting the logic in a separate utility class or method cleans it up a lot.)
Edit: An improved version of newValue() that handles corner cases better (see comment by biziclop). NB: uses Guava. (You're welcome to post simpler (regex?) versions.)
@Override
protected String newValue(String currentValue, String valueToRemove) {
    if (currentValue == null) return "";

    Set<String> classes = Sets.newHashSet(Splitter.on(" ").split(currentValue));
    classes.remove(valueToRemove);
    return Joiner.on(" ").join(classes);
}

A: Wicket 1.5+ has org.apache.wicket.AttributeModifier#remove()


text:
Q: Hive Error Parse Exception Tried to extract the the last updated time using below query.
hive is throwing exception Error: Error while compiling statement: FAILED: ParseException line 4:7 cannot recognize input near ''cast((cast(sys_extract_utc(update_time) AS DATE) - TO_DATE('' '01' '-' in expression specification (state=42000,code=40000)

select cast(10000 as int),
           case data_type
            when 'TIMESTAMP' then
        concat('     ,cast((cast(sys_extract_utc(update_time) AS DATE) - TO_DATE('01-01-1970 00:00:00', 'DD-MM-YYYY HH24:MI:SS')) * 86400 AS INT) last_date_time_ts')
            else
              concat('     ,#unknown data_type : ', data_type)
           end
      from (select row_number() over() ln, table_name, column_name, data_type, column_id
              from test.all_tab_columns
             where date_key in (select max(date_key) from test.all_tab_columns)
               and table_name = 'test_table'
                      ) data


text:
Q: Remove console.log during Angular 6.x library compilation I have an Angular 6.x library project and compiling the library with --prod does not remove calls to console.log. Is there a parameter that will remove all console.log calls during compilation?

A: in main.ts file add this
f(your_env === 'prod') {
   window.console.log = function(){};
}

A: a simple fix would be
if (environment.production) {
      enableProdMode();
      if(window){
        window.console.log=function(){};
      }
    }


text:
Q: Change UIAlertController text color I have created an UIAlertController like this and I wanted to change the back button (action1) text color. How can I do it?
When I updated the code it worked but when the button is pressed the text became blue.
@IBAction func Horario(sender: AnyObject) {

    let alert = UIAlertController(title: "Horario de Apertura", message: "\(horario)", preferredStyle: UIAlertControllerStyle.Alert)
    let action1 = UIAlertAction(title: "Atrás", style: UIAlertActionStyle.Cancel, handler: nil)

    alert.view.tintColor = UIColor.redColor()

    alert.addAction(action1)

    self.presentViewController(alert, animated: true, completion: nil);

}

A: Yes you can do that using this
alert.view.tintColor = UIColor.redColor() // your custom color


text:
Q: Understanding & operator in MySQL where clause I am trying to solve a programming problem in MySQL. I have the following table.

I want to get the names of people who have "reading" and "drawing" as interests.
One of the possible outcomes that were given with the solutions is the below.
SELECT name
    FROM people_interests
    WHERE interests & 1 AND interests & 8
    ORDER BY name

However, I don't understand why this query works here. Can someone explain why this works and what the & operator does here?

A: I struggled with the same problem but you are missing some important information in your question:
interests - the set of interests or hobbies this person has, given as a comma-joined string. This column has datatype

set('reading','sports','swimming','drawing','writing','acting','cooking','dancing','fishkeeping','juggling','sculpting','videogaming').

this set is specially important because it is telling you the position of the values you are looking for, in this case 'reading' and 'drawing' position 1 and 4 respectively.

Now, here is the tricky part:
to convert that to binary you are using their position to set the binary value, for example:
reading , position 1 sets the first bit in a binary number 00000001 (remember that the LSB or least significant bit is from right to left).
drawing, position 4 sets the fourth bit in a binary number which is 00001000
hopefully at this point you realize that if you convert those binary values to decimal they become 1 and 8, and that is the reason of why it works.

A: This is quite odd.  I suspect that the intention is to introduce you to the set data type in MySQL.  The documentation is here.
The reason this is strange is the semicolons in the column.  Sets generally use commas as the separator -- this is the documented separator and I don't think there is any way to change them.
That said, sets are generally not recommended for the following reasons:

*

*They are specific to MySQL.

*They are limited in the number of values that can be stored in the set.

*They can be confusing, because they confound strings, integers, and bit positions.

Under some specific circumstances they can be useful, but most databases do quite well without them.


text:
Q: add a matrix to a tibble I want to add a new column to an existing tibble, and each element of the new column is a matrix. Here is what I did,
Add it to the tibble WY_reg using list
WY_reg <- WY_reg %>%
           add_column(NewMat = list(Mat1, Mat2,Mat3) )

That indeed adds a new column. However, it seems that when I execute WY_reg$NewMat[1], it returns a list, rather than a matrix, so that I cannot do usual matrix operations.
I also tried as.matrix but fails.
Is there any way I can put a new column and each element is a matrix? so that they can involve later operations? Thanks


text:
Q: Can we say "I sat in the front and my sister sat in the back of the dolphin"? We often say "in the front" when we are inside something not on something.
For example, "She always sits in the front of the class."

Can we use  "in the front" when we are on something like a motorbike or a dolphin?
For example, "I sat in the front and my sister sat in the back of the dolphin"?

A: I sat in front of my sister on the dolphin, succinctly expresses the action depicted in your illustration.
Without the picture to aid in understanding, you may want to add ...that we were riding, onto the end of the sentence.  A listener probably would not assume you were riding a dolphin unless you made it clear.
To sit in the front of something requires that you be inside the thing you are sitting in the front of.  You can sit in the front of the train (meaning a train car at the beginning of the line of train cars or the first row of a particular train car) and you can sit in the front of the class[room] (meaning you are sitting in the front row of a classroom).  You cannot, however, sit in the front of a dolphin unless a Dolphin is a type of boat.


text:
Q: Windows service and kernel driver relationship After lurking around S.O. for a long time, it's time to join this awesome community of developers and hopefully get some answers to my questions. My first post so please be gentle.
I am trying to create a service and a driver "relationship", but I am very confused.
As an example, take the following:

*

*MyService.exe

*MyDriver.sys

I have followed this and this article with small changes. Now my questions are:

*

*Why do I have to start each of them manually using StartService? I thought that there can be a "relationship" between them so I only need to start MyService.exe and MyDriver.sys would also load automatically.

*How can I make them depend on each other? For example, if MyService.exe is stopped, unload MyDriver.sys as well, or the other way around.

*How to "protect" MyService.exe from being exploited? Do I need something like ObCallback or this does not apply for MyService.exe?

Thank you


text:
Q: Linq To Sql Row not found or changed I have the following code which actually is quite simple:
   foreach (var pr in b.Receipes)
   {
       var br = prod.Where(o => o.ProductID == pr.ProductID).FirstOrDefault();
       string entity = "piece";
       if (pr.SelectedEntity != null)
           entity = pr.SelectedEntity.Type;
       if (br != null)
       {
           br.TotalQuantity = br.TotalQuantity - b.Amount * pr.QuantityUsage;
           br.Amount = (Int32)(br.TotalQuantity / br.UnitQuantity);
       }
       dc.SRAddInvoiceDetailsConsumable(inv.InvoiceID, pr.ProductID, entity, pr.QuantityUsage, b.Amount);
       dc.SubmitChanges();
   }

So I execute this stored procedure which inserts record in a table with a for loop and on the second cycle i get the error row not found or changed.
The table structure is like:
[Id] INT IDENTITY NOT NULL PRIMARY KEY,
[InvoiceID] INT NOT NULL,
[ProductID] INT NOT NULL,
[Entity] NVARCHAR(300) NULL,
[QuantityUsage] float NOT NULL,
[Amount] int NOT NULL

The stored procedure:
 CREATE PROCEDURE [dbo].[SRAddInvoiceDetailsConsumable]
    @InvoiceID INT,
    @ProductID INT,
    @Entity NVARCHAR(300),
    @QuantityUsage float,
    @Amount INT
AS
BEGIN
    INSERT INTO SRInvoiceDetailsConsumables
    (InvoiceID, ProductID, Entity, QuantityUsage, Amount)
    VALUES
    (@InvoiceID, @ProductID, @Entity, @QuantityUsage, @Amount)
END

Things that did not worked for me following previous posts for the error.
1.The dbml structure is extacly the same as the table.
2.I replaced the dbml with the with the server tables to re-generate the dbml.
3.In the dbml property of the table i set the property "Update check" to never.
I am passing actual values to the stored procedure there are none null-able values.
I`m running out of ideas any help would be great!
BIG EDIT:
I found a solution which works.
 if (br != null)
 {
     br.TotalQuantity = br.TotalQuantity - b.Amount * pr.QuantityUsage;
     br.Amount = (Int32)(br.TotalQuantity / br.UnitQuantity);
     dc.Refresh(System.Data.Linq.RefreshMode.KeepChanges, br);
 }

The problem was not in the stored procedure as I initially thought.


text:
Q: CSS: Table & TD with no border Using angularjs with bootstrap 3 here.
I am trying to create dynamic rows when user clicks button. I have wrapped this inside a table and using ng-repeat.
When the second row is added it creates a separation b/w the two.
Below is my code:

        Text
        Value

        {{m.Name}}
        {{m.Country}}

          <input type="text" class="form-control" ng-model="Name" required />

          <input type="text" class="form-control" ng-model="Country" required />

I also created a demo at:
http://jsfiddle.net/Lyxbhosv/
Any inputs on how to remove the line or border in between two TD

A: I am not entirely sure what you're asking but via your example there is a double border whenever another row is added. To remove the double border and keep it a single just modify your code with the following:

If you can explain further that would be great!

A: While I'm examining your code you have already awarded the answer. But here I'm coming up with what I have learned from your code and this answer:

 This will create lots of Repeatable `' in your code.
But if you placed your code 'ng-repeat="m in options"' to the child
' tag it will repeat the ` each time. and it will not create any repeatable border any more.

So the choice is yours!


text:
Q: JavaFX - Interaction between circle and rectangle I want to know how I can make an interaction when rectangle collapses with a circle . Like some kind of action that happens when circle and rectangle collapses. There is also a problem that circle can go out of frame, which I don't know how to limit it's movement. I'm not even sure if it's possible to do what I want this way.This is supposed to be a game where I need to dodge all rectangles and this is best I could do. Thanks it advance :)
       public class Java2 extends Application {

       public static final int KRUG_WIDTH = 10;
       public static final int PANEL_WIDTH = 600;
       public static final int PANEL_HEIGHT = 600;

       private int mX = (PANEL_WIDTH - KRUG_WIDTH) / 2;
       private int mY = (PANEL_HEIGHT - KRUG_WIDTH) / 2;
       Random ran = new Random();

        @Override
        public void start(Stage primaryStage) {

            Rectangle rekt = new Rectangle(20, 20);
            Rectangle rekt1 = new Rectangle(20, 20);

            Circle r1 = new Circle(mX,mY,KRUG_WIDTH);

            Pane root = new Pane(); //PANE

            r1.setFill(Color.WHITE);
            r1.setStroke(Color.BLACK);

            root.getChildren().add(r1);
            root.getChildren().add(rekt);
            root.getChildren().add(rekt1);

            Scene scene = new Scene(root, PANEL_WIDTH, PANEL_HEIGHT);

    PathTransition pathTransition = new PathTransition();
    Path path = new Path();

    //REKT-PATH
    pathTransition.setDuration(javafx.util.Duration.millis(600));
    pathTransition.setPath(path);
    pathTransition.setNode(rekt);
    pathTransition.setOrientation(PathTransition.OrientationType.ORTHOGONAL_TO_TANGENT);
    pathTransition.setCycleCount(2);
    pathTransition.setAutoReverse(true);
            pathTransition.setOnFinished(e -> {

                pathTransition.setPath(createPath());
                pathTransition.play();

            });
    pathTransition.play();

    PathTransition pathTransition1 = new PathTransition();
    Path path1 = new Path();

    //REKT1-PATH
    pathTransition1.setDuration(javafx.util.Duration.millis(550));
    pathTransition1.setPath(path1);
    pathTransition1.setNode(rekt1);
    pathTransition1.setOrientation(
PathTransition.OrientationType.ORTHOGONAL_TO_TANGENT);
    pathTransition1.setCycleCount(Timeline.INDEFINITE);
    pathTransition1.setAutoReverse(true);
            pathTransition1.setOnFinished(e -> {

                pathTransition1.setPath(createPath());
                pathTransition1.play();

            });
    pathTransition1.play();

    r1.setOnKeyPressed(e -> {
               switch (e.getCode()) {
                     case DOWN: r1.setCenterY(r1.getCenterY()+ 10);
                            break;
                     case UP: r1.setCenterY(r1.getCenterY()- 10);
                            break;
                     case LEFT: r1.setCenterX(r1.getCenterX() - 10);
                            break;
                     case RIGHT: r1.setCenterX(r1.getCenterX() + 10);
                            break;
                     case SPACE:
                         break;

                     default:

               }
             });

            primaryStage.setTitle("Hello World!");
            primaryStage.setScene(scene);
            primaryStage.show();
            r1.requestFocus();
        }

    private Path createPath() {
            int loc2 = ran.nextInt(600 - 300 + 1) + 300;
            int loc = ran.nextInt(600 - 20 + 1) + 20;

            Path path = new Path();

            path.getElements().add(new MoveTo(20, 20));
            path.getElements().add(new LineTo(loc, loc2));

            return path;

        }
        /**
         * @param args the command line arguments
         */
        public static void main(String[] args) {
            launch(args);
        }

    }

A: Your approach isn't one I would take. Usually you have a timer as a game loop in which all the magic is happening, i. e. move sprites, check collision, update sprites in the UI. In JavaFX this would be an AnimationTimer.
In your code you miss several important things, among them the keyboard or mouse input. Or how you check the collision. There is e. g. an intersects method for the nodes, but that checks only the rectangular bounds of a node. You however have a circle, which makes matters more complex. However, if performance isn't an issue for your game, you could use the Shape's intersect method to create a new shape out of Rectangle and Circle and depending on the result decide whether you have a collision or not.
Some time ago I created example code about how to move sprites on the screen and check if they collide with others.
Regarding bouncing off the scene bounds in that code you simply check the scene bounds and change the movement delta to a bouncing value, i. e. if the sprite moves from left to right (dx is positive) and is at the right side, you set the delta dx to a negative value so that it moves in the opposite direction.
You can also take a look at a simple Pong game which uses a slightly modified version of that engine.

Example for shape intersection with your code:
Shape shape = Shape.intersect(rekt, r1);
boolean intersects = shape.getBoundsInLocal().getWidth() != -1;
if( intersects) {
  System.out.println( "Collision");
}

That alone raises the question where you'd put the check. Normally you'd have to perform it when anything moves, i. e. in both path transitions like this
pathTransition.currentTimeProperty().addListener( e -> {
...
});

and in the circle transition. That would be 2 checks too many.


text:
Q: How should I use Guava's Hashing#consistentHash? I'm looking into using a consistent hash algorithm in some java code I'm writing.  The guava Hashing library has a consistentHash(HashCode, int) method, but the documentation is rather lacking.   My initial hope was that I could just use consistentHash() for simple session affinity to efficiently distribute load across a set of backend servers.
Does anyone have a real-world example of how to use this method?  In particular I'm concerned with managing the removal of a bucket from the target range.
For example:
@Test
public void testConsistentHash() {
    List<String> servers = Lists.newArrayList("server1", "server2", "server3", "server4", "server5");

    int bucket = Hashing.consistentHash(Hashing.md5().hashString("someId"), servers.size());
    System.out.println("First time routed to: " + servers.get(bucket));

    // one of the back end servers is removed from the (middle of the) pool
    servers.remove(1);

    bucket = Hashing.consistentHash(Hashing.md5().hashString("blah"), servers.size());
    System.out.println("Second time routed to: " + servers.get(bucket));
}

Leads to the output:

First time routed to: server4
Second time routed to: server5

What I want is for that identifier ("someId") to map to the same server after removal of a server earlier in the list.  So in the sample above, after removal I guess I'd want bucket 0 to map to "server1", bucket 1 to map to "server3", bucket 2 to map to "server4" and bucket 3 to map to "server5".
Am I supposed to maintain a separate (more complicated than a list) data structure to manage bucket removal and addition?  I guess I had envisioned perhaps a more complicated Hashing API that would manage the remapping after adding and removal of particular buckets for me.
Note: I know the sample code is using a small input and bucket set.  I tried this with 1000s of input across 100 buckets and the result is the same.  Inputs that map to buckets 0-98 stay the same when I change the buckets to 99 and bucket 99 gets distributed across the remaining 99 buckets.

A: I don't think there's a good way to do this at the moment. consistentHash in its current form is useful only in simple cases -- basically, where you have a knob to increase or decrease the number of servers... but always by adding and removing at the end.
There's some work underway to add a class like this:
public final class WeightedConsistentHash<B, I> {
  /** Initially, all buckets have weight zero. */
  public static <B, I> WeightedConsistentHash<B, I> create(
      Funnel<B> bucketFunnel, Funnel<I> inputFunnel);

  /**
   * Sets the weight of bucket "bucketId" to "weight".
   * Requires "weight" >= 0.0.
   */
  public void setBucketWeight(B bucketId, double weight);

  /**
   * Returns the bucket id that "input" maps to.
   * Requires that at least one bucket has a non-zero weight.
   */
  public B hash(I input);
}

Then you would write:
WeightedConsistentHash<String, String> serverChooser =
    WeightedConsistentHash.create(stringFunnel(), stringFunnel());
serverChooser.setBucketWeight("server1", 1);
serverChooser.setBucketWeight("server2", 1);
// etc.

System.out.println("First time routed to: " + serverChooser.hash("someId"));

// one of the back end servers is removed from the (middle of the) pool
serverChooser.setBucketWeight("server2", 0);

System.out.println("Second time routed to: " + serverChooser.hash("someId"));

And you should get the same server each time.  Does that API look suitable?

A: I'm afraid that no data structure can do it really right with the current consistentHash. As the method accepts only the list size, nothing but appending and removal from the end can be supported. Currently, the best solution consist probably of replacing
servers.remove(n)

by
server.set(n, servers.get(servers.size() - 1);
servers.remove(servers.size() - 1);

This way you sort of swap the failed and the very last server. This looks bad as it makes the assignments to the two swapped servers wrong. This problem is only half as bad as one of them have failed. But it makes sense, as after the following removal of the last list element, everything's fine, except for the assignments to the failed server and to the previously last server.
So twice as much assignments as needed change. Not optimal, but hopefully usable?

A: The guava API does not have any knowledge of your server list. It can only guarantee this:
int bucket1 = Hashing.consistentHash(Hashing.md5().hashString("server1"),N);
int bucket2 = Hashing.consistentHash(Hashing.md5().hashString("server1"),N-1);

assertThat(bucket1,is(equalTo(bucket2))); iff bucket1==bucket2!=N-1

you need to manange the bucket to your server list yourself

A: The answer proposed in the question is the correct one:

Am I supposed to maintain a separate (more complicated than a list) data structure to manage bucket removal and addition?

Guava is hashing into a ring with ordinal numbers. The mapping from those ordinal numbers to the server ids has to be maintained externally:

*

*Given N servers initially - one can choose some arbitrary mapping for each ordinal number 0..N-1 to server-ids A..K (0->A, 1->B, .., N-1->K). A reverse mapping from the server id to it's ordinal number is also required (A->0, B->1, ..).

*On the deletion of a server - the ordinal number space shrinks by one. All the ordinal numbers starting with the one for the deleted server need to be remapped to the next server (shift by one).
So for example, after the initial mapping, say server C (corresponding to ordinal number 2) got deleted. Now the new mappings become: (0->A, 1->B, 2->D, 3->E, .., N-2->K)

*On the addition of a server L (say going from N to N+1 servers) - a new mapping can be added from N->L.
What we are doing here is mimicking how nodes would move in a ring as they are added and deleted. While the ordering of the nodes remains the same - their ordinal numbers (on which Guava operates) can change as nodes come and leave.


text:
Q: Dynamically create variables in R using a vector of strings I'm trying to dynamically create variables in a loop. For example, I tried the following:
subjects <- c("math", "english", "french")
for (i in subjects){
below_i <- ifelse(i_score<40, 1, 0)
}

where I want the code to loop over subjects. So below_math will be 1 if math_score is below 40, and so on. I want the variables to be named
below_math, below_english, below_french. Not sure what I'm doing wrong. Thanks!


text:
Q: How to create text-shadow in Axure My Goal
Im using Axure for prototyping and I've created widgets which reflect my application UI.
One thing I would like to achieve is the ability to add text-shadow onto certain elements, without having to type the same text twice and layer them over each other.

What I've tried so far
I've tried several methods and hacks to get this to work with no luck.
The closest I have got is creating 2 dynamic panels, one which I type the desired text into and then when previewing the protoype, I can click on the element to trigger the onclick event to update the shadow element. Which is far from ideal.

Existing Examples
Im pretty sure this can be achieved as I have seen it done in other peoples Axure libraries.
For Example:
http://axutopia.com/axure-widgets-libraries/axure-iphone-widgets-library/

A: What you're seeing in this screenshot is an image, it's not formatted in Axure. Your best bet would be to layer text panels so you get the shadow effect.


text:
Q: User input timer I'm making a text-based game.  I'm trying to have a little "health bar". When the user hit space, and when the button is pressed it will make health go up by 5, but while this is also happening I need something to be running in the background that is doing the same as if it was a AI, except I want it to subtract 1 every time and for it to only hit it once every second.
I tried getch(); the most but the problem with that is that it stops everything and waits for the user to use a input so nothing can be going on in the background that is subtracting health.
If you could use the _getch(); command in any way to accomplish this, because I already know how to use it well.


text:
Q: In what format is ActiveJob :at key I am trying to understand in what format :at for ActiveJob is, so I can use assert_enqueued_with with :at parameter.
Currently I've got this test which passes:
tomorrow = 1.day.from_now.to_date
assert_enqueued_with(job: ActionMailer::DeliveryJob) do
  onboarding.start_onboarding
  job_date = ActiveJob::Base.queue_adapter.enqueued_jobs[0][:at]
  assert_equal tomorrow, Time.at(job_date).to_date
end

But then I've realised that assert_enqueued_with has :at parameter and I would prefer to use it instead of last two lines in the block. Problem is, tomorrow variable seems to be in a different format than :at, which makes this fail:
tomorrow = 1.day.from_now.to_date
assert_enqueued_with(job: ActionMailer::DeliveryJob, at: tomorrow) do
  onboarding.start_onboarding
end

with this error:
Minitest::Assertion: No enqueued job found with {:job=>ActionMailer::DeliveryJob, :at=>Wed, 31 May 2017 13:12:05 UTC +00:00}

As you can see, tomorrow is a date, say Wed, 31 May 2017, while job_date is some kind of a large number, say 1496236366.183789. Hence I am trying to convert tomorrow into the same format.
Would really appreciate some help with this. Perhaps I am using :at wrongly or you know what format :at in and help me convert tomorrow.
start_onboarding is just a AASM event, which calls this method to schedule email delivery (a bit modified for privacy reasons):
def notify(id)
  person = User.find(id)
  PersonMailer.onboarding_reminder(person).
    deliver_later(wait_until: 1.day.from_now)
end

A: The argument for the wait_until method needs to match what your test uses.  The date serialized into the queue does get turned into a float by rails.  And in your #notify method, you're passing in a ActiveSupport::TimeWithZone instance when your test is passing in a Date instance.
See here:
1.day.from_now
=> Wed, 31 May 2017 13:56:36 UTC +00:00
1.day.from_now.class
=> ActiveSupport::TimeWithZone
1.day.from_now.to_date
=> Wed, 31 May 2017
1.day.from_now.to_date.class
=> Date
1.day.from_now == 1.day.from_now.to_date
=> false

That means your job is getting enqueued with time information but your test is expecting a simple date.  I'm not sure which is more correct the test date or the code date but they need to match for this test to pass.
Per the comments, here's how you might use Timecop to help you out:
  tomorrow = 1.day.from_now.to_date
  Timecop.freeze(tomorrow)
  assert_enqueued_with(job: ActionMailer::DeliveryJob, at: tomorrow) do
    onboarding.start_onboarding
  end
  Timecop.return

A: The at option should be a Time.
See an example in the docs here


text:
Q: datagridview cell validation for integers in vb.net How do i make validation to pass through only positive integers? I have a column which can triggers an error if it is a non-integer however users can still key in negative integer into the cells of that column .

A: How about using javascript code? add this js event
onkeypress=""return allowOnlyNumber(event);

then all you need is
function allowOnlyNumber(evt)
{
  var charCode = (evt.which) ? evt.which : event.keyCode
  if (charCode > 31 && (charCode < 48 || charCode > 57))
    return false;
  return true;
}

Or else you can use FilteredTextBoxExtender from AjaxControlToolkit as
<asp:TextBox ID="txtbox1" runat="server"></asp:TextBox>
            <cc1:FilteredTextBoxExtender id="ftbe" runat="server" targetcontrolid="txtbox1"
                  filtertype="Numbers" validchars="0123456987" />

A: Nvm i found it i willl update the link later The column index = indicates if your current cell is in that column validate it using the following code sorry for the trouble guys. The link is here Here
           If grdDataGrid.CurrentCell.ColumnIndex = 4 Then
           If Not Integer.TryParse(e.FormattedValue.ToString(), newInteger) _
            OrElse newInteger < 0 Then

            e.Cancel = True
            Me.grdDataGrid.Rows(e.RowIndex).ErrorText = "the value must be a non-negative         integer"
            MsgBox("You must enter a positive number")
        End If
     End If

A: Try it in your Datagridview EditingControlShowing Event ...
Private Sub DataGridView1_EditingControlShowing(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewEditingControlShowingEventArgs) Handles DataGridView1.EditingControlShowing
    Try

        If UCase(sCellName) = "QUANTITY"

             AddHandler e.Control.KeyPress, AddressOf TextNumberKeypress

        End If

    Catch ex As Exception
        '...
    End Try
End Sub

Sub TextNumberKeypress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs)
    Dim k As Byte = Asc(e.KeyChar)

    If Not IsNumSimple(k) Then
        e.Handled = True
        If Not (k = 8 Or k = 13 Or k = 1 Or k = 3 Or k = 22) Then e.Handled = True
    End If
End Sub


text:
Q: Visual basic 6 program in windows 10 still using mdb after it has been deleted I am using a visual basic 6 program in windows 10 which uses an mdb file. The problem is that if I delete or rename the mdb file the program somehow still uses a copy of the database. I can't find this copy anywhere, it appears to be a ghost file. The problem only exists in Windows 10.

A: Your 32 bit app stored data somewhere where it is no longer allowed too (probably program files). All changes will be directed to "C:\Users\Username\AppData\Local\VirtualStore"
This allows programs that wouldn't otherwise be allowed to run on Windows Vista to Windows 10 to run without being an administrator.
This also applies to writes to the System registry key.


text:
Q: Data Transfer Speed Hardware Config First off, I am sorry if this gets a little scattered, it encompasses a large problem for me I have been dealing with for some time.
Here is a little background: I operate an educational website with video on demand for online classes. For 4 years we hosted all our own media using 6 dedicated Wowza servers around the world to deliver our media. Our cost on that was around $1,500/month.
In an effort to improve service, we enlisted a CDN, which has been doing well, but now our hosting costs are up near $6,000/month and we would like to go back to hosting 98% ourselves, and only outsourcing to a CDN as a last resort with a rollover script.
When we had all our own dedicated servers, we would typically use a 2X quad core 2.66GHz w/ 16GB ram and 2 SSD in a RAID0. Even though we were ordering the same thing from the same hosting company, just in different parts of the world, we would notice large performance differences, that seemed to be on a hardware level, never network level.
We struck a deal to do some collocating with them at a great price, but now I am stuck with trying to determine how to get the best performance for what I need.
================================
Now for my question
Say I want the best data transfer / seek times to deliver the highest number of simultaneous videos? If I have 1000 users online at a time, they may have up to 250-400 individual video files open at the same time. I realize I can get 8 SSD SAS drives and put them in a RAID, but what about the processor, or RAM?
Looking on ebay, I see stuff like:
PowerEdge R810 1U Server (4X) 1.87GHz Eight-Core Xeon L7555 192GB RAM
POWEREDGE R810 SERVER FOUR X7550 2.0GHZ 96GB

From a processor perspective, I can find ones with 8MB - 30MB L3 Cache, but does it really matter for this? Am I better off with 2 quad core processors, or do I need 4 eight core to really get the most out of this?
I understand from the software vendor that more ram is better when you have multiple files open, but overall, they refuse to give more details about what type of hardware will actually give you a specific result. All they say is:
http://www.wowza.com/products/streaming-engine/specifications
High-load recommended production hardware
CPU: Dual Quad-Core or a single Hex-Core, 3.00 GHz or better
RAM: 16-32GB
Disk: 2 or more in RAID 0 (striping)
Network: 10Gbps Ethernet

Which is great, but it doesn't say what the result would be with this config. I typically on any given day need to be able to stream 15,000 videos over the course of the full day, with 1,500 peak simultaneous. From a bandwidth perspective, I could achieve that with a single internet connection, if the hardware could keep up. I know there are benefits to having multiple locations, but I could still save over $50,000/year if I can just figure out the hardware issues.
In the end I guess I am wondering if I did have a super high performance RAID, what is the order of things I need to worry about next? Should I focus only on clock speed, L3 cache, RAM?
=================================
Update:
I purchased a new server and am learning more about RAID configurations and performances, if you want to follow along, you can see the next part of the saga here:
New RAID hdparm slow

A: I don't think it's possible to say: Buy X, install Y, and your problem will be instantly solved. This is going to take several iterations to get through, and you'll need to put more work into identifying the bottlenecks when they inevitably appear. For the most part I'm going to avoid recommending specific hardware, as that would be out of date by the time I click the submit button.
So, since we don't have good data on what the bottlenecks were, let's just pretend this is a greenfield project. This is how I would approach it:

*

*Video streaming doesn't require that much RAM or CPU, but it does require fast storage. Let's say four 400GB SAS SSDs in RAID 10, for 800GB usable space, to store your videos. You may want to increase that, though, if you plan to have a lot more videos to serve in the next few years. Say, four 800GB SAS SSDs in RAID 10, for 1600GB usable space.

*Don't cheap out on the NIC. Your NIC should support, at minimum, TCP/IP offload (even if you end up not using it), receive side scaling and receive side coalescing. Some NICs such as those from Intel have further features to improve performance. You might spend a little time researching this.

*Though you do need to pay attention and make sure your server's networking is configured and tuned well, network throughput problems are sometimes the fault of the network infrastructure. If you're colocated and don't control this, be prepared to argue a lot with your datacenter. In particular, make sure that you aren't buying a network port which is throttled to some fraction of the link speed, and that the datacenter actually has more than enough bandwidth to accommodate you at peak times.

*The CPU doesn't matter a lot, but it does matter. The web server won't use much CPU, but processing interrupts from the NIC may use as much CPU as the web server does, and quite possibly more. You probably don't need something top of the line, but you shouldn't cheap out here either.

*You will have additional tuning work to do if you use a dual-CPU system. In such a system each CPU can access half the RAM quickly, and the other half more slowly, and vice versa for the other CPU. This is called NUMA, and you will need to watch out for bottlenecks related to your web server or interrupt handling running on one CPU and accessing memory from the other. Linux does include tools to help you deal with this.

*You don't need that much RAM to serve videos, but your server will make use of all the RAM you can give it, as a very fast disk cache. You aren't likely to hit a bottleneck here, I think, so I'd start small and upgrade the RAM if necessary. 32GB might make a good start; 192GB would be overkill unless you already knew you needed it.

*I would use the nginx web server. I always do, since it is much more capable of handling thousands of simultaneous connections than Apache, by default. You may need to increase the number of file descriptors on the system though.

*I would build this on Red Hat Enterprise Linux 7, and purchase and keep the subscription active for the life of the server. Besides Red Hat's comprehensive documentation on its distribution and on performance tuning, and its extensive knowledge base, Red Hat Support can help you identify and resolve bottlenecks when they appear, which is easily worth the price of admission.

*Be prepared to upgrade components if circumstances warrant. You might want to upgrade the NIC, RAM or the CPU based on actual issues discovered after you go into production.

*All of this assumes you are building multiple servers, and that requests are load balanced between them somehow. You should build the servers with more capacity than they need, so that in the event one fails or needs to be rebooted, upgraded, etc., the remainder can take up the slack.


text:
Q: What value has Visual Studios CSS support? So I'm supposed to be a .Net Developer but have found myself getting stuck with allot of css and html stuff lately. I would now consider myself to be very strong in css and all it's intricacies. With that said I still see any use it any of the Visual Studio support for it outside of the intellisense (when it works).
I want to ask if anyone developers that view themselves strong in css are using any of the Visual Studio 2008 css support features and if so what they are and why they use them over say firebug?
Thanks,
Denis

A: Hand coded all the way for me.
Firebug is really good for getting to the bottom of wierd browser issues, but generally I have IE, Chrome and Firefox open when I'm coding html & CSS, and I just make sure I hit the refresh button often enough in all three of them to make sure I don't get any nasty suprises after writing a pile of css.

A: Typically I turn off all of the Visual Studio CSS stuff.  It's not exactly well made.  Instead I've been using MS Expression to build master pages and manage CSS files.  It is light years ahead of VS.
That said, I see firebug as a complimentary product, not really a replacement.  I use FireBug and the equivalents in safari, chrome, and IE 8 to see what's going on with the internals of a particular element on a page.  I use Expression to edit and maintain the css.


text:
Q: NSPredicate that ignores whitespaces I need to use NSPredicate to match two strings, case-insensitive,  diacritic insensitive, and whitespace-insensitive.
The predicate would look something like this:
[NSPredicate predicateWithFormat:@"Key ==[cdw] %@", userInputKey];

The 'w' modifier is an invented one to express what I'd like to use.
I can't just trim the userInputKey because the data-source "Key" values might have whitespaces in them too (they need those whitespaces, I can't just trim them beforehand).
For example, given a userInputKey "abc" the predicate should match all of {"abc", "a b c", " a B    C   "} and so on. Given a userInputKey"a B C" the predicate should also match all the values in the set above.

This can't be so hard to do, can it?

A: Swift 4:
func ignoreWhiteSpacesPredicate(id: String) -> NSPredicate {
    return NSPredicate(block: { (evel, binding) -> Bool in
        guard let str = evel as? String else {return false}
        let strippedString = str.components(separatedBy: CharacterSet.whitespaces).joined(separator: "")
        let strippedKey = id.components(separatedBy: CharacterSet.whitespaces).joined(separator: "")
        return strippedString.caseInsensitiveCompare(strippedKey) == ComparisonResult.orderedSame
    })
}

Example:
let testArray:NSArray =  ["abc", "a bc", "A B C", "AB", "a B d", "A     bC"]
let filteredArray = testArray.filtered(using: ignoreWhiteSpacesPredicate(id: "a B C"))

Result:

["abc", "a bc", "A B C", "A     bC"]

A: How about defining something like this:
+ (NSPredicate *)myPredicateWithKey:(NSString *)userInputKey {
    return [NSPredicate predicateWithBlock:^BOOL(NSString *evaluatedString, NSDictionary *bindings) {
        // remove all whitespace from both strings
        NSString *strippedString=[[evaluatedString componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] componentsJoinedByString:@""];
        NSString *strippedKey=[[userInputKey componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] componentsJoinedByString:@""];
        return [strippedString caseInsensitiveCompare:strippedKey]==NSOrderedSame;
    }];
}

Then use it like this:
NSArray *testArray=[NSArray arrayWithObjects:@"abc", @"a bc", @"A B C", @"AB", @"a B d", @"A     bC", nil];
NSArray *filteredArray=[testArray filteredArrayUsingPredicate:[MyClass myPredicateWithKey:@"a B C"]];
NSLog(@"filteredArray: %@", filteredArray);

The result is:
2012-04-10 13:32:11.978 Untitled 2[49613:707] filteredArray: (
    abc,
    "a bc",
    "A B C",
    "A     bC"
)


text:
Q: Handling Long Processing Corona SDK In my program I have some processing-intensive code that takes about a minute to process some strings for my app. However, in the corona simulator, my app locks up and says it is not responding until the processing completes then it will act normal. So my question is if there exists a way to notify the phone in some way to tell it that the app is not locked up but merely processing data so the users won't think it is failing and quit the app.

A: You can easily add an event listener to show something and remove it when it finishes. I have done one for a simple touch event.
local function rotate(event)
  if event.phase=="began" then
  contactName= display.newText( "test", 185, 100, native.systemFont, 24)

 end

  if event.phase=="ended" then
   contactName:removeSelf()
  end
end
Runtime:addEventListener("touch", rotate)

If you don't have any listener for that function simply show a text that something is happening and the text value tied to your process results.
If not working tell us what is your exact process so something may work for it.

A: The simplest way is to show an activity indicator.  See:  http://docs.coronalabs.com/api/library/native/setActivityIndicator.html
This will tell the user the app is busy.  However, when people get spinning cursors for long periods of time, they think things are hung up.  If you can break it into chunks that will help.
You might want to consider coroutines.  Coroutines are documented on the Lua site and Corona SDK supports them.  We are planning a tutorial on them for Tuesday 2/10 (assuming it doesn't get bumped).  http://coronalabs.com/blog/


text:
Q: EF4: LINQ 2 Entities query works in C# but not in VB [EDITED: I left the original question below, with some more context and code to reproduce the problem. The short version below contains the essence of the question]
Short version: the query below throws a System.NotSupportedException: "Unable to cast the type 'System.Linq.IOrderedQueryable1' to type 'System.Linq.IQueryable1'. LINQ to Entities only supports casting Entity Data Model primitive types." The exception is only raised in the VB.Net version. When translated to C#, no exception is raised.
   Dim doesThisCrash = From outerOrder In orders
        Where outerOrder.ProductId =
        (From p In products Join o In orders On p.Id Equals o.ProductId
         Order By p.Id
         Select p.Id).FirstOrDefault()
        Select outerOrder
    doesThisCrash.ToList()

So, to make it crash, it seems that we need a subquery where the original ObjectSet (orders) is joined with another ObjectSet (products), and ordered. When using just the orders or the products set, no crash occurs. When leaving out the Order By, also no crash.
I'm inclined to think this is a (VB.Net) compiler bug, unless there is something obvious that I'm overlooking here...
For now my question still stands:

*

*why does a seemingly exact same query work in C# but not in VB?

*can this query be made to work in VB.Net?

[/EDIT]
Optional, longer version (original question):
My domain looks very different, but I translated the problem to a simpler version, with the following entities (note: I actually defined these using the .edmx designer, so this is a simplified version):
    public class Product
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public DateTime DateCreated { get; set; }
    }

    public class Order
    {
        public int Id { get; set; }
        public int CustomerId { get; set; }
        public int ProductId { get; set; }
        public DateTime OrderDate { get; set; }
    }

    public class Customer
    {
        public int Id { get; set; }
    }

I'm trying to work out a linq-to-entities query that should strucurally look like this, in VB.Net:
    Dim db = New SampleEntities()
    Dim orders As IQueryable(Of Order) = db.Orders
    Dim products As IQueryable(Of Product) = db.Products
    Dim currentDate = DateTime.Now

    Dim qLinq = From outerOrder In orders
                Where outerOrder.OrderDate = currentDate AndAlso
                outerOrder.ProductId =
                    (From p In products Join o In orders On p.Id Equals o.ProductId
                     Where o.OrderDate = outerOrder.OrderDate AndAlso
                            outerOrder.CustomerId = o.CustomerId
                     Order By p.DateCreated
                     Select p.Id).FirstOrDefault()
                Select outerOrder

This raises a System.NotSupportedException:
"Unable to cast the type 'System.Linq.IOrderedQueryable1' to type 'System.Linq.IQueryable1'. LINQ to Entities only supports casting Entity Data Model primitive types."
When leaving out the 'Order By' part, no exception is raised.
I don't really see a reason why this query would not be supported... So I decided to try the same thing in C#:
var qLinq = from oOut in orders
            where oOut.OrderDate == currentDate
                  && oOut.ProductId ==
                          (from p in products join o in orders on p.Id equals o.ProductId
                           where oOut.OrderDate == o.OrderDate
                           && oOut.CustomerId == o.CustomerId
                           orderby p.DateCreated
                           select p.Id).FirstOrDefault()
                    select oOut;

To my surprise, this works! Then I translated the C# query to extension method syntax, and then back to VB, but got the same results (the C# version works, the VB.Net version raises the same exception).
So I guess my question is twofold:

*

*why does a seemingly exact same query work in C# but not in VB?

*can this query be made to work in VB.Net?

For reference, here are the queries in extension method syntax:
C# version:
        var q = orders.Where(outerOrder =>
            outerOrder.OrderDate == currentDate &&
            outerOrder.ProductId ==
            (products
                .Join(orders,
                    f => f.Id,
                    o => o.ProductId,
                    (f, o) => new { f, o })
                .Where(t => t.o.OrderDate == outerOrder.OrderDate
                           && outerOrder.CustomerId == t.o.CustomerId)
                .OrderByDescending(t => t.f.DateCreated)
                .Select(t => t.f.Id))
                .FirstOrDefault());

VB.Net version:
    Dim q = orders.Where(Function(outerOrder) outerOrder.OrderDate = currentDate AndAlso
                             outerOrder.ProductId = (products.Join(orders,
                               Function(p) p.Id,
                               Function(o) o.ProductId,
                               Function(p, o) New With {.p = p, .o = o}).
                           Where(Function(x) x.o.OrderDate = outerOrder.OrderDate AndAlso
                                     outerOrder.CustomerId = x.o.CustomerId).
                           OrderByDescending(Function(x) x.p.DateCreated).
                           Select(Function(x) x.p.Id).
                           FirstOrDefault()))

A: I think the following works, the SQL is ugly though:
Dim qLinq = From outerOrder In orders
                Where outerOrder.OrderDate = currentDate AndAlso
                outerOrder.ProductId =
                    (From x In (From p In products
                                 Join o In orders On p.Id Equals o.ProductId
                                 Where o.OrderDate = outerOrder.OrderDate AndAlso
                                        outerOrder.CustomerId = o.CustomerId
                                 Select p.Id)
                    Order By x).FirstOrDefault()
                Select outerOrder

A: Does this work?
    Dim a = From p In products Join o In orders On p.Id Equals o.ProductId
            Order By p.DateCreated
            Select New With {.id = p.Id, .OrderDate = o.OrderDate, .CustomerId = o.CustomerId, .DateCreated = p.DateCreated}

    Dim b = From outerOrder In orders _
            Where outerOrder.OrderDate = currentDate _
            AndAlso outerOrder.ProductId = _
            (From x In a Where x.OrderDate = outerOrder.OrderDate _
             AndAlso x.CustomerId = outerOrder.CustomerId _
             Select x.id).FirstOrDefault

A: Moving the Order By p.DateCreated line as per my edited answer allows the query to run without any exceptions. However, the emitted SQL is different so I don't think you are getting back the correct result.
Dim qLinq = From outerOrder In orders
            Let id = (From p In products
                      Order By p.DateCreated
                      Join o In orders On p.Id Equals o.ProductId
                      Where o.OrderDate = outerOrder.OrderDate AndAlso
                            outerOrder.CustomerId = o.CustomerId
                      Select p.Id).FirstOrDefault()
            Where outerOrder.OrderDate = currentDate AndAlso
                  outerOrder.ProductId = id
            Select outerOrder

A: hi
this can be made to work quite easy...
Instead of an IQueryable
Dim orders As IQueryable(Of Order) = db.Orders
use a List
Dim orders as List(of Order) = db.Orders.ToList()


text:
Q: How reliable is to use client-side XSLT in mobile browsers I know pretty well the state of xslt support by major desktop browsers. In short, this support  is quite decent. And what major mobile browsers. Do they support client side XSLT? Are there any pitfalls and/or limitations?

A: I should probably make this a comment since I haven't done this in over a year but client side  XSLT was poor then, sadly, and nowhere near as good as the desktop. I don't think it's improved enough today. It's the reason I won't consider its usage now and it's a shame on all browser vendors that they don't offer great XML family support in all areas.


text:
Q: Bubble sorting with linked list I am writing a bubble sort function to sort nodes in a doubly linked list. My function is very close to working, but I am missing something simple and I can't figure it out.
void sort (struct lnode** head, void (*swapPtr) (struct lnode** head, struct lnode* n1, struct lnode* n2),
                            int(*comparePtr) (void* v1, void* v2)) {

struct lnode* next;
struct lnode* temp = *head;
int comp;
struct lnode* temp2;
int count = 0;

while (temp != NULL) {
    temp2 = nodeGetNext(temp);
    temp = temp2;
    count++;

}

temp = *head;
for(int i = 0; i < count; i++) {
    next = nodeGetNext(temp);

    comp = comparePtr(temp,next);
    if (comp == 1)
        swapPtr(head, temp, next);
    else if (comp == -1)
        swapPtr(head, next, temp);

    temp = nodeGetNext(next);
}

}

When I run the function, It only swaps the first two nodes. I'm guessing I am not setting temp properly at the end of the for loop. I have tried a few different things but have not had any success. I would appreciate any help!

A: It seems like you make only one pass on over the list. You need to keep looping over the list and keep swapping until there's nothing to swap. Check this answer for an example and Wikipedia for the detailed algorithm description.

A: I've done this using a nested loop since the number of traverses you have go through a list is equal to number of nodes minus 1, that is in worst case scenario. The loop for passes shall stop when there are no swaps done from previous pass (thanks to detunized).
hasSwap = 1; /* enable the first pass to execute */
for(i=0; i<len-1 && hasSwap == 1; i++)
{
    hasSwap = 0; /* initially, there is no swap in this pass */
    for(j=0; j<len-1; j++)
    {
       if(l[j] > l[j+1])
       {
            t = l[j];
            l[j] = l[j+1];
            l[j+1] = t;
            hasSwap = 1; /* the pass has at least 1 swap, if not set, there will be no other pass */
       }
    }

    printf("Pass %d: ", i);
    for(k=0; k<len; k++)
    {
       printf("%d", l[k]);
    }
    printf("\n");
}

Example 1: Worst case scenario, list is sorted in descending order.
5, 4, 3
First pass:
i = 0, j = 0, hasSwap = 1  ->  [5], [4], 3
i = 0, j = 1, hasSwap = 1  ->   4 , [5], [3]
Has swaps from previous pass? Yes, proceed.
Second pass:
i = 1, j = 0, hasSwap = 1  ->  [4], [3], 5
i = 1, j = 1, hasSwap = 1  ->   3 , [4], [5]
Has swaps from previous pass? No, but reached the maximum number of pass.
Example 2: And this is sorted already.
3, 4, 5
First pass:
i = 0, j = 0, hasSwap = 0  ->  3, 4, 5
i = 0, j = 1, hasSwap = 0  ->  3, 4, 5
Has swaps from previous pass? None, stop.


text:
Q: Excisting Joomla Photogallery script: Extract creation date from EXIF (photo) to show on website Not sure if this will work, but since Stackoverflow is the best place to ask, here we go:
I got a Joomla CMS installed, added a customized template, added a (paid) photogallery and after all sorts of tweaks the thing is running pretty decent.
The photogallery (component) works in layers. You'll open the website and you'll be in the top layer. Let's say you'll see 4 maps: 2012, 2013, 2014 and 2015. Within those top categories you can add endless sub-categories and in the end, there's the photo's, displayed on individual image-pages.
Example built-up categories:
-Main (home website, basically the top category)
-- 2015 (sub-category)
--- January (sub-category of sub-category)
----- Image.jpg (individual image page located within sub-category January)
The photogallery component consists of a huge amount of files (PHP mostly). Since I'm no PHP-pro (but I do know my way around in small bits), I tried to figure out how the photogallery component works as it comes to reading EXIF data from its photo's.
The idea is to extract the date when the photo was taken from the EXIF-extraction and display it on the individual image-pages.
From what I could find, the EXIF data is being extract with this 'functions' PHP-file. The code-segment: http://pastebin.com/hT40vJnj
Then, there's the PHP-file for the individual image-pages. The next code is being shown beneath each photo and display's a couple of things. The author, some technical stuff (resolution, filetype and filesize) and also there's a mouse-over icon which shows all extracted EXIF-data in a balloon. Even the date which I was talking about to extract and to be able to drop wherever I want: http://pastebin.com/RzbjkP4e
IMAGE: EXIF Balloon (i.stack.imgur.com/S7Njc.png)
The next attempt (which probably is a stupid one) which I already tried didn't work. I simply tried to copy some code from the functions PHP file and tried to mix it up with the next code in the image PHP file:
echo ' '.strftime($ad_datef == 'customdate' ? $ad_datefc : $ad_datef, strtotime($exif_data['DateTimeOriginal'])).'
';
        }

Again, I mixed some functions PHP code with the original code from the image PHP file, as seen below (this piece of code shows the owner name of the photo on the image page)
echo ' '.$link.'
';
        }

Is there any simple way to come up with a string/code that I can use to show the date when the photo was taken? Or do I need to dig deeper?
Thanks so much!

A: The issue is that your function is looking just for DateTimeOriginal.
Unfortunately not always this field is provided by the camera.
Other possible fields that you can use instead of DateTimeOriginal are :

*

*Datetime

*DateTaken

*DateModified

*DateTimeDigitized

To check all the fields you have use var_dump($exif_data);
So to extend the current behaviour you have to modify your EXIF php file replacing the $exif_data['DateTimeOriginal'] if statement (lines 28, 29, 30 in pastebin)  with that :
$date = '';
if (isset ($exif_data['DateTimeOriginal']) != '') {
    $date = $exif_data['DateTimeOriginal'];
} elseif (isset ($exif_data['DateTimeDigitized']) != '') {
    $date = $exif_data['DateTimeDigitized'];
} elseif (isset ($exif_data['DateTaken']) != '') {
    $date = $exif_data['DateTaken'];
} elseif (isset ($exif_data['DateModified']) != '') {
    $date = $exif_data['DateModified'];
} elseif (isset ($exif_data['Datetime']) != '') {
    $date = $exif_data['Datetime'];
}

if ($date != '') {
    $dg_exif .= JText::_('COM_DATSOGALLERY_EXIF_DATETIME').': '. strftime($ad_datef == 'customdate' ? $ad_datefc : $ad_datef, strtotime($date)).'';
}


text:
Q: Dynamic datatable In a Dataset I have a datatable. This datable can be divided in a certain number of cycles ( defined by a function).
After finding the cycles I want to generate Datable for each cycles. So my question is to know how to declare dynamically Datable ?
Thanks

A: Your question is a little unclear, but if I understand you correctly, would this be the sort of thing you are looking to do??
DataSet cyclesDataSet = new DataSet("Cycles");
someclass.CycleComplete(cyclesDataSet, "C1");
.
.
.
public void CycleComplete(DataSet dataset, String cycleId)
{
    var cycleTable = dataset.Tables.Add("cycleId");
    // Manipulate table here.
}

Cheers,
Chris.


text:
Q: How to increase the buffer size in Handler? I'm working on plotting graph on android app.
I want to use a buffer with size equal to 512 to store the incoming data from arduino. After the buffer is full then the graph will be plotted and keep going.
How can I change the code to achieve this?
Handler mHandler = new Handler(){
    @Override
    public void handleMessage(Message msg) {
        // TODO Auto-generated method stub
        super.handleMessage(msg);
        switch(msg.what){
        case Bluetooth.SUCCESS_CONNECT:
            Bluetooth.connectedThread = new Bluetooth.ConnectedThread((BluetoothSocket)msg.obj);
            Toast.makeText(getApplicationContext(), "Connected!", 0).show();
            String s = "successfully connected";
            Bluetooth.connectedThread.start();
            break;
        case Bluetooth.MESSAGE_READ:

            byte[] readBuf = (byte[]) msg.obj;
            String strIncom = new String(readBuf, 0, 5);                 // create string from bytes array

            Log.d("strIncom", strIncom);
            if (strIncom.indexOf('.')==2 && strIncom.indexOf('s')==0){
                strIncom = strIncom.replace("s", "");
                if (isFloatNumber(strIncom)){
                    Series.appendData(new GraphViewData(graph2LastXValue,Double.parseDouble(strIncom)),AutoScrollX);

                    //X-axis control
                    if (graph2LastXValue >= Xview && Lock == true){
                        Series.resetData(new GraphViewData[] {});
                        graph2LastXValue = 0;
                    }else graph2LastXValue += 0.1;

                    if(Lock == true)
                        graphView.setViewPort(0, Xview);
                    else
                        graphView.setViewPort(graph2LastXValue-Xview, Xview);

                    //refresh
                    GraphView.removeView(graphView);
                    GraphView.addView(graphView);

                }
            }

            break;
        }
    }

    public boolean isFloatNumber(String num){
        //Log.d("checkfloatNum", num);
        try{
            Double.parseDouble(num);
        } catch(NumberFormatException nfe) {
            return false;
        }
        return true;
    }

};

this is my Bluetooth code:
public class Bluetooth extends Activity implements OnItemClickListener{

public static void disconnect(){
    if (connectedThread != null) {
        connectedThread.cancel();
        connectedThread = null;
    }
}

public static void gethandler(Handler handler){//Bluetooth handler
    mHandler = handler;
}
static Handler mHandler = new Handler();

static ConnectedThread connectedThread;
public static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
protected static final int SUCCESS_CONNECT = 0;
protected static final int MESSAGE_READ = 1;
ArrayAdapter<String> listAdapter;
ListView listView;
static BluetoothAdapter btAdapter;
Set<BluetoothDevice> devicesArray;
ArrayList<String> pairedDevices;
ArrayList<BluetoothDevice> devices;
IntentFilter filter;
BroadcastReceiver receiver;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_bluetooth);
    init();
    if (btAdapter==null){
        Toast.makeText(getApplicationContext(), "No bluetooth detected", 0).show();
        finish();
    }else{
        if (!btAdapter.isEnabled()){
            turnOnBT();
        }
        getPairedDevices();
        startDiscovery();
    }

}

private void startDiscovery() {
    // TODO Auto-generated method stub
    btAdapter.cancelDiscovery();
    btAdapter.startDiscovery();
}

private void turnOnBT() {
    Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
    startActivityForResult(intent, 1);
}

private void getPairedDevices() {
    devicesArray = btAdapter.getBondedDevices();
    if (devicesArray.size()>0){
        for(BluetoothDevice device:devicesArray){
            pairedDevices.add(device.getName());
        }
    }
}

private void init(){
    listView = (ListView)findViewById(R.id.listView);
    listView.setOnItemClickListener(this);
    listAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,0);
    listView.setAdapter(listAdapter);
    btAdapter = BluetoothAdapter.getDefaultAdapter();
    pairedDevices = new ArrayList<String>();
    filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
    devices = new ArrayList<BluetoothDevice>();
    receiver = new BroadcastReceiver(){
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (BluetoothDevice.ACTION_FOUND.equals(action)){
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                devices.add(device);
                String s = "";
                for(int a=0;a<pairedDevices.size();a++){
                    if (device.getName().equals(pairedDevices.get(a))){
                        //append
                        s = "(Paired)";
                        break;
                    }
                }
                listAdapter.add(device.getName()+" "+s+" "+"\n"+device.getAddress());

            }else if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)){

            }else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)){

            }else if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)){
                if (btAdapter.getState() == btAdapter.STATE_OFF){
                    turnOnBT();
                }
            }
        }

    };

    registerReceiver(receiver, filter);
    IntentFilter filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
    registerReceiver(receiver, filter);
    filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
    registerReceiver(receiver, filter);
    filter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
}

@Override
protected void onPause() {
    // TODO Auto-generated method stub
    super.onPause();
    unregisterReceiver(receiver);
}

protected void onActivityResult(int requestCode, int resultCode, Intent data){
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == RESULT_CANCELED){
        Toast.makeText(getApplicationContext(), "Bluetooth must be enabled to continue", Toast.LENGTH_SHORT).show();
        finish();
    }
}

@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
    // TODO Auto-generated method stub
    if (btAdapter.isDiscovering()){
        btAdapter.cancelDiscovery();
    }
    if (listAdapter.getItem(arg2).contains("(Paired)")){

        BluetoothDevice selectedDevice = devices.get(arg2);
        ConnectThread connect = new ConnectThread(selectedDevice);
        connect.start();
    }else {
        Toast.makeText(getApplicationContext(), "device is not paired", 0).show();
    }
}

private class ConnectThread extends Thread {
    private final BluetoothSocket mmSocket;
    private final BluetoothDevice mmDevice;

    public ConnectThread(BluetoothDevice device) {
        // Use a temporary object that is later assigned to mmSocket,
        // because mmSocket is final
        BluetoothSocket tmp = null;
        mmDevice = device;

        // Get a BluetoothSocket to connect with the given BluetoothDevice
        try {
            // MY_UUID is the app's UUID string, also used by the server code
            tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
        } catch (IOException e) { }
        mmSocket = tmp;
    }

    public void run() {
        // Cancel discovery because it will slow down the connection
        btAdapter.cancelDiscovery();

        try {
            // Connect the device through the socket. This will block
            // until it succeeds or throws an exception
            mmSocket.connect();
            //connectedThread = new ConnectedThread(mmSocket);
        } catch (IOException connectException) {
            // Unable to connect; close the socket and get out
            try {
                mmSocket.close();
            } catch (IOException closeException) { }
            return;
        }

        // Do work to manage the connection (in a separate thread)
        mHandler.obtainMessage(SUCCESS_CONNECT, mmSocket).sendToTarget();
    }

    /** Will cancel an in-progress connection, and close the socket */
    public void cancel() {
        try {
            mmSocket.close();
        } catch (IOException e) { }
    }
}

static class ConnectedThread extends Thread {
    private final BluetoothSocket mmSocket;
    private final InputStream mmInStream;
    private final OutputStream mmOutStream;

    public ConnectedThread(BluetoothSocket socket) {
        mmSocket = socket;
        InputStream tmpIn = null;
        OutputStream tmpOut = null;

        // Get the input and output streams, using temp objects because
        // member streams are final
        try {
            tmpIn = socket.getInputStream();
            tmpOut = socket.getOutputStream();
        } catch (IOException e) { }

        mmInStream = tmpIn;
        mmOutStream = tmpOut;
    }
    StringBuffer sbb = new StringBuffer();
    public void run() {

        byte[] buffer;  // buffer store for the stream
        int bytes; // bytes returned from read()

        // Keep listening to the InputStream until an exception occurs
        while (true) {
            try {
                try {
                    sleep(30);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

                buffer = new byte[1024];
                // Read from the InputStream
                bytes = mmInStream.read(buffer);
                // Send the obtained bytes to the UI activity
                mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer).sendToTarget();
            } catch (IOException e) {
                break;
            }
        }
    }

    /* Call this from the main activity to send data to the remote device */
    public void write(String income) {

        try {
            mmOutStream.write(income.getBytes());
            for(int i=0;i<income.getBytes().length;i++)
            Log.v("outStream"+Integer.toString(i),Character.toString((char)(Integer.parseInt(Byte.toString(income.getBytes()[i])))));
            try {
                Thread.sleep(20);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        } catch (IOException e) { }
    }

    /* Call this from the main activity to shutdown the connection */
    public void cancel() {
        try {
            mmSocket.close();
        } catch (IOException e) { }
    }
}

}


text:
Q: Need to draw / animate a small square background image, then repeat it over x and y Basically, I would like to draw a small square, then draw another and then another until it fills the screen both horizontally and vertically.  I'd like to actually see the animation of each square being drawn.
I am not sure how to achieve this.  I know html canvas has a createPattern function but I think that uses an image and I need these squares to chain one after another (not all at once).
Any ideas?
A solution using jquery, canvas, svg, css3, html5 or maybe a popular svg or js library is fine.

A: You should try oCanvas, it's object oriented javascript, and it's based on the html5 canvas tag for drawing, it'll allow you to do some pretty neat stuff, and handle animation too.
Basically you need to define the canvas tag with an id like this:
<canvas id="canvas" width="354" height="100"></canvas>

and then instanciate the core object:
var canvas = oCanvas.create({
    canvas: "#canvas",
    background: "#0cc"
});

After that you could draw the squares with something like this:
var limit = 50;
var reduction = 2; //minus two pixels for iteration
var width = 202;
var height = 202;
for (var i = 1; i <= limit; ++i){

var rectangle = canvas.display.rectangle({
    x: 77,
    y: 77,
    width: width,
    height: height,
    fill: "#0aa"
    });
width = width - reduction;
height = width - reduction;

canvas.addChild(rectangle,false);

}

and then draw it all at once:
canvas.draw.redraw();

Or you can animate it too
And it's well documented

A: Is this the result you want?
<html>
<head>
<script>
var sq_size=10;
var sq_pos_x = 0-sq_size;//see comment in drawtick
var sq_pos_y = 0;
var can_width=800;
var can_height=600;
var tmr;
function startTimer(){
tmr = setInterval(function(){drawtick()}, 20);
}
function drawtick(){
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
//the first drawn square should not be on x+ sq_size
// instead of adding an extra if statement, I just initialized it on -sq_size
if(sq_pos_x+sq_size>=can_width)              {sq_pos_y=sq_pos_y+sq_size;sq_pos_x=0}else{sq_pos_x=sq_pos_x+sq_size;}
if(sq_pos_y>=can_height){clearInterval(tmr);alert('loop ended');}
ctx.rect(sq_pos_x,sq_pos_y,sq_size,sq_size);
ctx.stroke();
}
</script>
</head>
<body onload="startTimer()">
<canvas id="myCanvas" width="800" height="600" style="border:1px solid #000000;">
Your browser does not support the HTML5 canvas tag.
</canvas>
</body>
</html>

or
http://jsfiddle.net/kKyA5/
it all depense on the draw animation


text:
Q: How to deactivate "Autodesk.VisualClusters" extension before unloading? I am using the viewer.loadExtension and viewer.unloadExtension functions to load and unload the "Autodesk.VisualClusters" extension. But if the user has already activated the extension then unloading it directly causes some residual data to remain in the viewer.
residual data
How do I call the VisualClusters deactivate function? I tried getExtension() and then calling deactivate but it dosen't seem to be working.
props.viewer.getExtension("Autodesk.VisualClusters").setActive();
let unloadval = props.viewer.unloadExtension("Autodesk.VisualClusters");

A: You can reset the layout of the extension like so:
viewer.getExtension('Autodesk.VisualClusters').reset();

After that you can unload the extension as usual.


text:
Q: Issue grabbing video Id from Youtube feed xml using jquery Ok, from what I understand, what I am trying to accomplish here is SUPER simple, basically I have constucted a search result out of a url string with the youtube API. If you browse to the url, you can see the xml returned, all is good. The url:
https://gdata.youtube.com/feeds/api/videos?q=all the small things&max-results=1&v=2&format=5&orderby=relevance&safeSearch=none
I have written a bit of jquery that should fill my div called agenda (<div id = "agenda">) which DOES exist in the html with, with the data that is in the <yt:videoid> xml element. Just to fill the div with the video ID, essentially. Here is my jQuery:
$(document).ready(function(){
    $.get("https://gdata.youtube.com/feeds/api/videos?q=all the small thing&max-results=1&v=2&format=5&orderby=relevance&safeSearch=none",{},function(xml){
        $('entry',xml).each(function(i){
            var vidID = $(this).find("yt:videoid").text();
        });//end find entry

        alert(vidID);
        $('#agenda').html(vidID);
    });//end ajax
});//end .ready

However literally nothing is happening, the alert does not go off, in fact it throws an error that vidID is undefined, from what I can tell EVERYTHING is set up the way it should be, I'll post the link if someone really needs to see it live, but currently it is on my raspberry pi server, so im not nuts about posting my IP, but I'm that desperate :p. If anyone can spot what I'm doing wrong I have been at this for hours and it's driving me nuts. Thanks in advance.

A: I am not sure what the format of data exactly is but issue is that your vId scope is only inside the $.each function. SO you need to move it out of the each block to be able to access its value. Next thing is if the node entry is going to be only 1 you can get rid of each.
Try
$(document).ready(function(){
    $.get("https://gdata.youtube.com/feeds/api/videos?q=all the small thing&max-results=1&v=2&format=5&orderby=relevance&safeSearch=none",{},function(xml){
        var vidID;
        $('entry',xml).each(function(i){
           vidID  = $(this).find('id').text();
        });//end find entry
      alert(vidID);
        $('#agenda').html(vidID);
    });//end ajax
});//end .ready

or
$(document).ready(function () {
    $.get("https://gdata.youtube.com/feeds/api/videos?q=all the small thing&max-results=1&v=2&format=5&orderby=relevance&safeSearch=none", {}, function (xml) {
        var vidID = $('entry', xml).find('id').text();
        alert(vidID);
        $('#agenda').html(vidID);
    }); //end ajax
}); //end .ready

Fiddle
Use JSON-C format for you tube data which is easy to manipulate
Example:- in your url just need to add alt=jsonc
https://gdata.youtube.com/feeds/api/videos?q=all%20the%20small%20thing&max-results=1&v=2&format=5&orderby=relevance&safeSearch=none&alt=jsonc

and loop through json if you need:- here in the example there is only one so i am just using json.data.item[0]. You will ideally loop though item.
$(document).ready(function () {
    $.get("http://gdata.youtube.com/feeds/api/videos?q=all%20the%20small%20thing&max-results=1&v=2&format=5&orderby=relevance&safeSearch=none&alt=jsonc", {}, function (json) {
      var vidID = json.data.items[0].id;
        alert(vidID);
        $('#agenda').html(vidID);
    }); //end ajax
}); //end .ready

Fiddle