text:
Q: Different ways of building a query in Joomla? Just starting out, this should be a simple one but I haven't been able to find a good source, especially with the 1.5 to 1.6/1.7/2.5 changeover.
Building a component and among other issues keep running into syntax issues.
For example, here's one way I'm building a query:
[TYPE 1]
$query->SELECT('u.id as UserID
    , u.name AS Name
    , uppi.profile_value AS Hair
    , uppi2.profile_value AS Height
    ');
$query->FROM (' #__users AS u');
$query->LEFTJOIN (' #__user_profiles AS uppi ON u.id = uppi.user_id AND uppi.ordering = 1 ');
$query->LEFTJOIN (' #__user_profiles AS uppi2 ON u.id = uppi2.user_id AND uppi2.ordering = 2 ');
$query->GROUPBY (' u.id
    , u.name
    , uppi.profile_value
    ');

Another way:
[TYPE 2]
$query->SELECT('u.id as UserID
    , u.name AS Name
    , uppi.profile_value AS Hair
    , uppi2.profile_value AS Height
    ')
->FROM (' #__users AS u')
->LEFTJOIN (' #__user_profiles AS uppi ON u.id = uppi.user_id AND uppi.ordering = 1 ')
->LEFTJOIN (' #__user_profiles AS uppi2 ON u.id = uppi2.user_id AND uppi2.ordering = 2 ')
->GROUPBY (' u.id
    , u.name
    , uppi.profile_value
    ');

Confusing part about both of those is that mysql calls like "LEFTJOIN" are one word instead of two.  So then if I want to use INSERT…ON DUPLICATE KEY UPDATE I'm totally lost.
Here's a third:
[TYPE 3]
$query->SELECT('u.id as UserID
    , u.name AS Name
    , uppi.profile_value AS Hair
    , uppi2.profile_value AS Height
    ');
$query->FROM (' #__users AS u');
$query->JOIN ('LEFT', ' #__user_profiles AS uppi ON u.id = uppi.user_id AND uppi.ordering = 1 ');
$query->JOIN ('LEFT', ' #__user_profiles AS uppi2 ON u.id = uppi2.user_id AND uppi2.ordering = 2 ');
$query->GROUPBY (' u.id
    , u.name
    , uppi.profile_value
    ');
$query->ORDER ('u.name ASC');

This is another way I've seen queries built but can't get to work [EDITED - working now, thanks @cppl!]
[Type 4]
$query= "SELECT `u`.`id` as UserID
    , `u`.`name` AS Name
    , `uppi`.`profile_value` AS Hair
    , `uppi2`.`profile_value` AS Height
FROM `#__users` AS u
LEFT JOIN `#__user_profiles` AS uppi ON `u`.`id` = `uppi`.`user_id` AND `uppi`.`ordering` = 1
LEFT JOIN `#__user_profiles` AS uppi2 ON `u`.`id` = `uppi2`.`user_id` AND `uppi2`.`ordering` = 2
    ";

I've gone through the Joomla MVC tutorial and Lynda...neither one really addresses this beyond "here's some code - PLOP."
References:
    --//www.theartofjoomla.com/home/9-developer/135-database-upgrades-in-joomla-16.html
    --//stackoverflow.com/questions/8467858/joomla-1-7-db-query-does-not-work-when-query-has-an-ampersand
    --developer.joomla.org/standards/ch03s10.html
    --forum.joomla.org/viewtopic.php?p=2506722
    --forum.joomla.org/viewtopic.php?p=1200668
    --docs.joomla.org/API16:JDatabaseQuery
    --//fsadventures.com/2011/01/some-basic-joomla-database-call-functions/
    --//www.sourcecodester.com/php/3863/updating-multiple-rows-mysql-using-php.html
    --//stackoverflow.com/questions/7047471/mysql-query-syntax-error

Questions:
1)  Are there any differences between these?
2)  Is there a reason to use one method over another?
3)  Is there a good source for learning different ways of building these?  I've searched for hours and haven't found anything comprehensive.
Thanks!

A: *

*Your type 1,2 & 3 are using the newer JDatabaseQuery object, whereas type 4 is using the older style to set the query to an SQL string.

*If type 4 isn't working do you get an SQL error? (Have you turned on Joomla's debug mode so you can get the SQL error dumped out with the app profile?)

*JDatabaseQuery is used to provide the abstraction required to support multiple SQL databases rather than just mySQL, thats why the $query object has functions like select(),where(),join(), etc...

*Remember that the ->leftJoin() is a PHP call to the JDatabaseQuery function called leftJoin() and therefore must be one word ie. it can't be two.

*leftJoin() actually just calls join('LEFT',$conditions) so it's a readability implementation more than a functional difference.

*So, types 1,2 & 3 are effectively the same they're just have different degrees of readability (eg. IMHO type 2 & 3 are harder to read and maintain than type 1).

You seem to have found all the online sources for Joomla! documentation, apart from the Joomla! Google Groups (CMS Dev, General Dev and Platform Dev).
The only other source is Andrew Eddies "Learn the Art of Joomla!". I haven't used Andrew's stuff myself but I've heard lots of good things about it a the last Joomla! Day I attended.
Edit
Based on the error I would say it's because you have the identifier u.id encased as one identifier. Try something like:
SELECT `u`.`id` AS "UserID" FROM `#__users` AS `u`


text:
Q: Applying Conditional Formatting to all computed values in LibreOffice Calc In LibreOffice Calc, how can I use the Conditional Formatting feature to apply a style to all cells which contain a computed value (via formula, as opposed to a directly input value)?

*

*LibreOffice version 4.1.4.2

*Ubuntu 13.10

A: There a two ways:

*

*Define a conditional formatting rule, based on "Formula is" and use the ISFORMULA() function:

ISFORMULA(A1)

The cell reference depends on your starting point. If you want to apply the conditional formatting to range B8:F20, it would be ISFORMULA(B8); LibreOffice adapts the cell reference for all cells of the selected range automatically.

(If you need more control, e.g. to distinguish between text, number, bool or error, you could also use the TYPE function.)

*Alternatively, to simply display computed values and text/number values in different color globally, just activate "Value Highlighting" from the Calc options. This will display computed values in a different color than text/number values. The setting affects all ods files, and (AFAIK) you can't modify the style how to display values / formula results.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Ubuntu 17.10 login screen wallpaper I like the wallpaper of Ubuntu 17.10 login screen and I would like to set it as my main wallpaper, too. Can you tell me where it is located in my files? Thanks in advance.

A: Using Nautilus navigate to /usr/share/backgrounds:

You will find more images in the subdirectories. For example gnome has many wallpapers and yours might be in it.


text:
Q: How do I create a drop down menu and make contents drop? I'm having issues creating a dropdown menu using the a tag. I'm not sure why, but the drop down menu isn't working at all/doesn't seem to register. When the dropdown menu shows, I would like it to make the contents beneath drop down as well. Any help on this?

        About

        Portfolio

            Portraits
            Stationary Cards

        Video

        Contact

A: You need to add hover state to your style
  a#dropDownPortfolio:hover +  #dropDownCnt{
      display:block;
   }

        About

        Portfolio

            Portraits
            Stationary Cards

        Video

        Contact

        About

        Portfolio

            Portraits
            Stationary Cards

        Video

        Contact

A: on hover over #dropDown then expend #dropDownCnt
add this at the end
#dropDownCnt {
    max-height: 0px;
    overflow: hidden;
    visibility: hidden;
    transition: all 200ms ease;
  }
  #dropDown:hover #dropDownCnt{
    max-height: 100px;
    visibility: visible;
    overflow: auto;
  }

and remove this
#dropDownCnt{
            display: none;
            position:absolute;

        }


text:
Q: C# ¿Que resultado me devuelven estos problemas? De que otra forma podría realizar estas mismas operaciones (usando for, while o algo parecido, exceptuando el problema 3)
está en C#
internal long[][][] nums;
internal long[][][] tree;

// Problema 1
long sum += tree[i][j][k];

// Problema 2
int value
nums[x][y][z] = value;

// problema 3
            long[][][] newArray = new long[size1][][];
            for (int array1 = 0; array1 < size1; array1++)
            {
                newArray[array1] = new long[size2][];
                if (size3 > -1)
                {
                    for (int array2 = 0; array2 < size2; array2++)
                    {
                        newArray[array1][array2] = new long[size3];
                    }
                }
            }

A: Si la idea es iterar un array de varias dimensiones vas a necesitar tantos for como dimensiones tengas.
Matrices
entonces usarias
long sum = 0;

for(int i=0; i<10; i++)
    for(int j=0; j<10; j++)
       for(int k=0; k<10; k++)
          sum += tree[i][j][k];

de esta forma sumarias conociendo la cantidad de items que tiene cada dimension
Nota: como es una linea no necesitas las { } en los for

Si necesitas iterar sin conocer la cantidad de items de cada dimension te puede ayudar el
Array.GetUpperBound(Int32) Method


text:
Q: Getting currently logged in user I am trying to get the currently logged in user in my spring boot project. my entities and their relationships are given below:-
User.java
@Entity
@Table(name = "user_account")
public class User {

@Id
@Column(unique = true, nullable = false)
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;

private String email;
private String username;
private String userType;

@OneToOne(mappedBy = "user")
private BankUserDetails bankUserDetails;

@OneToOne(mappedBy ="user")
private SctUserDetails sctUserDetails;

@Column(length = 60)
private String password;

private boolean enabled;

@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(name = "users_roles", joinColumns =
@JoinColumn(name = "user_id", referencedColumnName = "id"),
        inverseJoinColumns = @JoinColumn(name = "role_id",
referencedColumnName = "id"))
private Collection<Role> roles;

public User() {
    super();
    this.enabled = true;
}
}

Role.java
@Entity
public class Role {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @ManyToMany(mappedBy = "roles")
    private Collection<User> users;

    @ManyToMany()
    @JoinTable(name = "roles_privileges", joinColumns =
    @JoinColumn(name = "role_id", referencedColumnName = "id"),
            inverseJoinColumns = @JoinColumn(name = "privilege_id",
    referencedColumnName = "id"))
    private Collection<Privilege> privileges;

    private String name;

    public Role() {
        super();
    }

    public Role(final String name) {
        super();
        this.name = name;
    }

    }

Privilege.java
@Entity
public class Privilege {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    private String name;

    @ManyToMany(mappedBy = "privileges")
    private Collection<Role> roles;

    public Privilege() {
        super();
    }

    public Privilege(final String name) {
        super();
        this.name = name;
    }

so on my controller (for now) i am trying to print the currently logged in user like this:-
@RequestMapping("/admin")
public String adminPage(Model model){
    System.out.println("logged user "+UserController.getLoggedInUser());
    return "admin";
}

on my UserController class i have defined one static method to retrieve the currently logged in user like this:-
   public static String getLoggedInUser(){
        String username = null;
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();

        if(principal instanceof UserDetails){
            username =  ((UserDetails) principal).getUsername();
        }else {
            username = principal.toString();
        }
        return username;

    }

my spring security configuration class looks like this:-
@Configuration
@ComponentScan(basePackages = { "com.infodev.pcms.security" })
@EnableWebSecurity
public class SecSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private MyUserDetailsService userDetailsService;

    @Autowired
    private AuthenticationSuccessHandler myAuthenticationSuccessHandler;

    @Autowired
    private CustomLogoutSuccessHandler myLogoutSuccessHandler;

    @Autowired
    private AuthenticationFailureHandler authenticationFailureHandler;

    /*@Autowired
    private CustomWebAuthenticationDetailsSource authenticationDetailsSource;*/

    private BCryptPasswordEncoder passwordEncoder() {
        return SecurityUtils.passwordEncoder();
    }

    @Autowired
    private UserRepository userRepository;

    public SecSecurityConfig() {
        super();
    }

    private static final String[] PUBLIC_MATCHERS = {
            "/css/**",
            "/js/**",
            "/images/**",
            "**/",
            "/newUser",
            "/forgetPassword",
            "/login",
            "/uploads/**",
            "/assets/**",
            "/api/updateCardStatus"
    };

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

    @Override
    public void configure(final WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/resources/**","/listAllUsers/**");
    }

    @Override
    protected void configure(final HttpSecurity http) throws Exception {
        // @formatter:off

        http
            .authorizeRequests()

        /*  antMatchers("/**").*/
            .antMatchers(PUBLIC_MATCHERS).
            permitAll().anyRequest().authenticated();
        http
            .csrf().disable()
            .authorizeRequests()
                .antMatchers("/login*","/login*", "/logout*", "/signin/**",
            "/signup/**", "/customLogin",
                        "/user/registration*", "/registrationConfirm*",
            "/expiredAccount*", "/registration*",
                        "/badUser*", "/user/resendRegistrationToken*" ,
            "/forgetPassword*", "/user/resetPassword*",
                        "/user/changePassword*", "/emailError*", "/resources/**",
         "/old/user/registration*","/successRegister*","/qrcode*").permitAll()
                .antMatchers("/invalidSession*").anonymous()
                .antMatchers("/user/updatePassword*","/user/savePassword*","/updatePassword*")
         .hasAuthority("CHANGE_PASSWORD_PRIVILEGE")
                .anyRequest().hasAuthority("READ_PRIVILEGE")
                .and()
            .formLogin()
                .loginPage("/login")
                .defaultSuccessUrl("/homepage.html")
                .failureUrl("/login?error=true")
                .successHandler(myAuthenticationSuccessHandler)
                .failureHandler(authenticationFailureHandler)

            .permitAll()
                .and()
            .sessionManagement()
                .invalidSessionUrl("/invalidSession.html")
                .maximumSessions(1).sessionRegistry(sessionRegistry()).and()
                .sessionFixation().none()
            .and()
            .logout()
                .logoutSuccessHandler(myLogoutSuccessHandler)
                .invalidateHttpSession(false)

                .deleteCookies("JSESSIONID")
                .permitAll();
    }

    // beans

    @Bean
    public DaoAuthenticationProvider authProvider() {
        final CustomAuthenticationProvider authProvider =
        new CustomAuthenticationProvider();
        authProvider.setUserDetailsService(userDetailsService);
        authProvider.setPasswordEncoder(passwordEncoder());
        return authProvider;
    }

    @Bean
    public SessionRegistry sessionRegistry() {
        return new SessionRegistryImpl();
    }

}

MyCustomUserDetails
@Override
public UserDetails loadUserByUsername(final String username)
throws UsernameNotFoundException {
    final String ip = getClientIP();
    if (loginAttemptService.isBlocked(ip)) {
        throw new RuntimeException("blocked");
    }

    try {
        final User user = userRepository.findByUsername(username);
        if (user == null) {
            throw new UsernameNotFoundException
       ("No user found with username: " + username);
        }

        org.springframework.security.core.userdetails.User usr=
       new org.springframework.security.core.userdetails.User
    (user.getUsername(), user.getPassword(), user.isEnabled(),
                true, true, true, getAuthorities(user.getRoles()));
        return usr;
    } catch (final Exception e) {
        throw new RuntimeException(e);
    }
}

// UTIL

private final Collection<? extends GrantedAuthority>
 getAuthorities(final Collection<Role> roles) {
    return getGrantedAuthorities(getPrivileges(roles));
}

private final List<String> getPrivileges(final Collection<Role> roles) {
    final List<String> privileges = new ArrayList<String>();
    final List<Privilege> collection = new ArrayList<Privilege>();
    for (final Role role : roles) {
        collection.addAll(role.getPrivileges());
    }
    for (final Privilege item : collection) {
        privileges.add(item.getName());
    }

    return privileges;
}

private final List<GrantedAuthority> getGrantedAuthorities
(final List<String> privileges) {
    final List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
    for (final String privilege : privileges) {
        authorities.add(new SimpleGrantedAuthority(privilege));
    }
    return authorities;
}

when the adminPage method invokes it calls getLoggedInUser() as expected but it won't go inside the if(principal instanceof UserDetails){ line. rather it will execute else clause and returns the whole user  object.

I need to get the currently logged in user on my controller. how can i do it ?

A: You should read this. However you were almost there.
Instead of
SecurityContextHolder.getContext().getAuthentication().getPrincipal()

, you should use
SecurityContextHolder.getContext().getAuthentication().getName()

, and then
userDetailsService.loadUserByUsername(name)

will give you the UserDetails.
Or
Just modify your code like this:

@RequestMapping("/admin")
public String adminPage(Principal principal, Model model)

And spring will inject the principal for you, inspect what principal contains and if necessary do the same (load the UserDetails using the name of the logged in user) as I suggested above.


text:
Q: Why the result is 0? See these code as below:
#include<stdio.h>
#include<stdlib.h>

int main()
{
 char a[1000];
 int i;
 for(i = 1;i<1000;i++)
 {
  a[i] = 5;
 }

 printf("%d\n",strlen(a));

 return 0;
}

the result is 0 , why? Any explanation will be appreciated.

A: You never assign or intialize a[0]. In this case, it just happened to be '\0', so strlen(a) returns 0.
It's worth noting that calling strlen on a here is undefined behaviour, as you're indirectly trying to read that uninitialized, garbage memory that is a[0] as the first step on the search to find a null terminator. Even setting that to 0 explicitly would still cause problems with it running off of the end of the array until it finds a 0, crashes, or blows up.

A: strlen() starts counting from 0 not 1.
Do this and you will be going:
for(i = 0;i<1000;i++)

A:  #include<stdio.h>
 #include<stdlib.h>
 int main()
 {
     char a[1000];
     int i;
     for(i = 0;i<1000;i++)//starts with 0 not 1
       a[i] = 5;
     a[i] = '\0';//NULL terminator shall be there
     printf("%d\n",strlen(a));//1000

     return 0;
 }


text:
Q: months worth of data in database table help I have a table of records like the following
Month Amount  Sum
1     100     100
2     50      150
3     NULL    NULL
4     NULL    NULL
5     50      200
ETC.

How do I keep a running total sum column and I'd like to cascade the previous valid sum into null records like follows in one SQL Statement?
1     100     100
2     50      150
3     0       150
4     0       150
5     50      200

Any ideas?

A: This isn't something you'd typically store in the database, but rather get with a query.  You would do a subquery on the table to get a sum:
SELECT
  t1.Month, t1.Amount,
  SUM(SELECT t2.Amount FROM my_table t2 WHERE t2.Month <= t1.Month)
FROM my_table t1

In this way I use the table twice, once as t1 and once as t2.

A: Assuming the new month and amount being inserted are represented by variables @month and @amount:
INSERT INTO t (Month, Amount, [Sum])
SELECT @month,
       CASE WHEN @amount IS NULL THEN 0 ELSE @amount END,
       CASE WHEN @amount IS NULL THEN SUM(Amount) ELSE SUM(Amount) + @amount END
FROM t

If the months are always going to consecutive, you could use MAX(Month) + 1 instead of @month as the inserted value.
(Though I agree with @JHolyHead's caveat that I'd be hesitant to store a running total inside the table...)

A: Either store the running sum value somewhere else where you can read and update it on every transaction, or do some clever logic in a SP that calculates it during the transaction.
If I'm honest, I wouldn't store it. I'd probably prefer to calculate it in the application when I need it. That way you can filter by date/whatever other criteria you like.

A: Works from version 2005
;with a as(
select month, coalesce(amount, 0) amount, row_number() over(order by /*year?,*/ month) rn
from yourtable
),
cte as
(
select month, amount, amount [sum1]
from a where rn = 1
union all
select a.month, a.amount, a.amount + b.amount
from cte join a on a.rn = cte.rn - 1
)
select month, amount, [sum1] from cte

I surgest you do not use column names like 'sum' not even for computed columns.
Don't waste a table column on a sum, imagine what happens when someone updates a column in the database. Just use a computed column in a view.


text:
Q: Change confusing message when vote is locked in When I try and undo a vote on a question after the grace period has expired, the message given is:

You last voted on this answer 47 mins ago.
  Your vote is now locked in unless this answer is edited
(emphasis mine)

The use of the phrase "Your vote is now locked in" implies I just did something that affects the status of my vote. But this is not true: my vote has been locked in from the moment the grace period expired.
When I first started to use the site, I used to think I had double-clicked by accident and had inadvertently locked in an up-vote that I tried to undo.
Some suggested new wording:

Votes lock after 5 minutes; you voted 20 minutes ago. Your vote cannot be changed unless this answer is edited.

This also has the benefit of alerting users to the grace period duration.


text:
Q: while downloading MiKTeX packages in windows 7 I got the following error
I am trying to download MiKTeX in my laptop(windows 7 64 bit) but whenever i download, after some time the following screen appears and the downloading discards. I have no idea how to fix it, so, I would be grateful for any suggestions regarding it.


text:
Q: SQL Show two text and their values as one in my view I am looking to show "Carers Paid" and "Carers Unpaid" to show as a Carers Leave in my view.
below is my code
SELECT a.EmployeeUID AS [Employee ID]
       ,b.LongName AS [Leave type] (here i wanna show two leave type as one mentioned above)
       ,a.Mins AS [Leave balance
FROM   [dbo].[AbsenceBalance] a
JOIN   [dbo].[AbsenceTypes] b ON     a.AbsenceTypesUID = b.UID
WHERE  b.UID IN (3,4,5,6,7)

Thanks.enter image description here


text:
Q: Prime number greater than n Consider the follwing problem:
Given $n$ (in binary) output a prime number $p \geq n$ (not necessarily the first prime number after $n$)
Are there better techniques than the trivial one that scans $n,n+1,n+2,...$ until a prime is found?
And can we do better if the full factorization of $n$ is given?

A: A major optimization of your method would be
if n<2**74207281-1:
    return 2**74207281-1
else:
    n=n|1 #makes n odd
    while True:
        if is_prime(n):
            return n
        n+=2

A: Currently, there is no method known to construct arbitary large prime numbers, so the problem is currently out of reach.
A solution to this problem would be very useful because high rewards have been promised to find large prime numbers.


text:
Q: How to set Pinterest sourceURL and description using UIActivityViewController with Pinterest.sharextension For iOS 8, Pinterest has an share extension.  How do I set image source URL and description attributes?  I am using UIActivityViewController.  Do I create a custom class with UIImage, NSURL for sourceURL and NSString for description and return?  I'm not sure how Pinterest would know to set the source URL and description.

A: Assuming that you are implementing a share method on a UIViewController subclass, the code below should meet your expectations:
Objective-C
- (void)share {
    NSString *textToShare = @"Hello Pinterest!";
    NSURL *url = [NSURL URLWithString: @"http://blank.org"];
    UIImage *imageToShare = [UIImage imageNamed:@"so-logo"];
    NSArray *activityItems = @[textToShare, url, imageToShare];
    UIActivityViewController *activityViewController = [[UIActivityViewController alloc] initWithActivityItems: activityItems applicationActivities: nil];

    [self presentViewController: activityViewController animated: YES completion: nil];
}

Swift (3.0.2)
func share() {
    let textToShare = "Hello Pinterest!"
    let url = URL(string: "http://blank.org")!
    let imageToShare = UIImage(named: "so-logo")!
    let activityItems: [Any] = [textToShare, url, imageToShare]
    let activityViewController = UIActivityViewController(activityItems: activityItems, applicationActivities: nil)

    self.present(activityViewController, animated: true, completion: nil)
}

And the results should be something like this:


text:
Q: What is the correct way to write `Vec` content to a file? I'm having trouble writing Vec<u16> content to a file:
use std::fs::File;
use std::io::{Write, BufWriter};
use std::mem;

#[derive(Debug, Copy, Clone, PartialEq)]
pub enum ImageFormat {
    GrayScale,
    Rgb32,
}

#[derive(Debug, Copy, Clone, PartialEq)]
pub struct ImageHeader {
    pub width: usize,
    pub height: usize,
    pub format: ImageFormat,
}

pub struct Image {
    pub header: ImageHeader,
    pub data: Vec<u16>,
}

fn write_to_file(path: &str, img: &Image) -> std::io::Result<()> {
    let f = try!(File::create(path));
    let mut bw = BufWriter::new(f);
    let slice = &img.data[..];
    println!("before length: {}", slice.len());
    let sl: &[u8];
    unsafe {
        sl = mem::transmute::<&[u16], &[u8]>(slice);
    }
    println!("after length: {}", sl.len());
    try!(bw.write_all(sl));
    return Ok(());
}

fn main() {}

Since write_all() asks for a &[u8], I'm doing an unsafe conversion of &[u16] to &[u8]. Because the conversion does not change the slice length (slice.len() and sl.len() have the same values), only half of the image data is output to the file.
It would be better if I don't need any unsafe conversion or copying.

A: I recommend using existing libraries for serialization such as serde and bincode:
extern crate bincode;
extern crate serde;
#[macro_use]
extern crate serde_derive;

use std::error::Error;

#[derive(Serialize, Deserialize, Debug, Copy, Clone, PartialEq)]
pub enum ImageFormat {
    GrayScale,
    Rgb32,
}

#[derive(Serialize, Deserialize, Debug, Copy, Clone, PartialEq)]
pub struct ImageHeader {
    pub width: usize,
    pub height: usize,
    pub format: ImageFormat,
}

#[derive(Serialize, Deserialize)]
pub struct Image {
    pub header: ImageHeader,
    pub data: Vec<u16>,
}

impl Image {
    fn save_to_disk(&self, path: &str) -> Result<(), Box<Error>> {
        use std::fs::File;
        use std::io::Write;
        let bytes: Vec<u8> = try!(bincode::serialize(self, bincode::Infinite));
        let mut file = try!(File::create(path));
        file.write_all(&bytes).map_err(|e| e.into())
    }
}

fn main() {
    let image = Image {
        header: ImageHeader {
            width: 2,
            height: 2,
            format: ImageFormat::GrayScale,
        },
        data: vec![0, 0, 0, 0],
    };

    match image.save_to_disk("image") {
        Ok(_) => println!("Saved image to disk"),
        Err(e) => println!("Something went wrong: {:?}", e.description()),
    }
}

A: To do it directly you'd want to use std::slice::from_raw_parts():
use std::{mem, slice};

fn main() {
    let slice_u16: &[u16] = &[1, 2, 3, 4, 5, 6];
    println!("u16s: {:?}", slice_u16);

    let slice_u8: &[u8] = unsafe {
        slice::from_raw_parts(
            slice_u16.as_ptr() as *const u8,
            slice_u16.len() * mem::size_of::<u16>(),
        )
    };

    println!("u8s: {:?}", slice_u8);
}

It does require unsafe because from_raw_parts() can't guarantee that you passed a valid pointer to it, and it can also create slices with arbitrary lifetimes.
See also:

*

*How to slice a large Vec<i32> as &[u8]?

*Temporarily transmute [u8] to [u16]
This approach is not only potentially unsafe, it is also not portable. When you work with integers larger than one byte, endianness issues immediately arise. If you write a file in this way on a x86 machine, you would then read garbage on an ARM machine. The proper way is to use libraries like byteorder which allow you to specify endianness explicitly:
use byteorder::{LittleEndian, WriteBytesExt}; // 1.3.4

fn main() {
    let slice_u16: &[u16] = &[1, 2, 3, 4, 5, 6];
    println!("u16s: {:?}", slice_u16);

    let mut result: Vec<u8> = Vec::new();
    for &n in slice_u16 {
        let _ = result.write_u16::<LittleEndian>(n);
    }

    println!("u8s: {:?}", result);
}

Note that I've used Vec<u8> here, but it implements Write, and write_u16() and other methods from the WriteBytesExt trait are defined on any Write, so you could use these methods directly on a BufWriter, for example.
Once written, you can use methods from the ReadBytesExt trait to read the data back.
While this may be slightly less efficient than reinterpreting a piece of memory, it is safe and portable.
See also:

*

*How can I convert a buffer of a slice of bytes (&[u8]) to an integer?


text:
Q: How to create a condition with TWIG and Drupal 8 to check the type of store? I have a Drupal Site 8 with Drupal Commerce. I create 2 types of store:

*

*personal_store

*professional_store

I'm working on the template of my products and I want to display the code above only if the parent store is of type store_professional
Is it possible ?
How to create a condition with TWIG and Drupal 8 to check the type of store?
Here is the code that I want to put in the templates of my products only if the parent store is of type store_professional :

Informations légales

            <button type="button" class="btn btn-default btn-sm btn-cgv" data-toggle="modal" data-target="#modal-cgv">
               Conditions générales de vente
            </button>

                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Conditions générales de vente

                    {{ store.field_professionnel_cgv }}

                    <button type="button" class="btn btn-default" data-dismiss="modal">Fermer</button>

            <button type="button" class="btn btn-default btn-sm btn-shipping-methods" data-toggle="modal" data-target="#modal-shipping-methods">
               Modes de livraison
            </button>

                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Modes de livraison

                    {{ store.field_professionnel_livraison }}

                    <button type="button" class="btn btn-default" data-dismiss="modal">Fermer</button>

            <button type="button" class="btn btn-default btn-sm btn-payment-gateways" data-toggle="modal" data-target="#modal-payment-gateways">
               Modes de paiement
            </button>

                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Modes de paiement

                    {{ store.field_professionnel_paiement }}

                    <button type="button" class="btn btn-default" data-dismiss="modal">Fermer</button>

A: Do you have a field called "type" in your store? If yes, you can simply check like this:
{% if store.type == "store_professional" %}


text:
Q: Is $\frac{O(f(x))}{O(g(x))}=O\left(\frac{f(x)}{g(x)}\right)$? Is the following true.
$$\frac{O(f(x))}{O(g(x))}=O\left(\frac{f(x)}{g(x)}\right)$$
If not under what conditions is it?
For example, the function,
$$h(x)=\frac{x^3+2x}{2x+1}$$
has $O(x^3)/O(x)$. And the total function has $O(x^2)$. My concern is that $2x+1$ can have $O(x^n)$ for $n\geq 1$. Thus making it seem false. Perhaps the big theta notation has this property.

A: We have $O(f(x)) O(g(x)) = O(f(x) g(x))$. In words: a function that is at most a constant times $f(x)$, multiplied by a function that is at most a constant times $g(x)$, is at most a constant times $f(x) g(x)$. (We assume that $f$ and $g$ are positive functions, so that we can say "at most" instead of "in absolute value at most".)
(Note that when dealing with $O$ notation, the "$=$" sign is like the English "is", and is not necessarily symmetric: if you wish, you can view each side as the set of functions of that type, and replace the "$=$" with "$\subset$". But in this case it's also true that $O(f(x) g(x)) = O(f(x)) O(g(x))$.)
Also we have $$g(x) = \Omega(h(x)) \iff \frac{1}{g(x)} = O\left(\frac{1}{h(x)}\right)$$
(again, assuming the functions are positive, etc.)
So the right statement is that
$$\frac{O(f(x))}{\Omega(g(x))} = O\left(\frac{f(x)}{g(x)} \right)$$
in your case, what matters is not that $2x + 1 = O(x)$, but that $2x + 1 = \Omega(x)$.
That it is also true with $\Theta$ is a corollary.

A: $$x^4\in O(x^5)\quad x\in O(x^3)\quad\frac{x^4}x\notin O\left(\frac{x^5}{x^3}\right)\quad (x\to\infty)$$
$$
f\in\Theta(F)\quad\&\quad g\in\Theta(G)\implies\frac{f}g\in\Theta\left(\frac{F}G\right)$$


text:
Q: Mysql Update using value from select I have a weather app, and I'm storing meteo data every hour in a database.
Recently i discovered a tiny bug which lead to the writing of few hundreds faulty records.
To fix the issue i decided to update all the faulty record using the average values for that given day.
I have the following 3 queries to retrieve the value I need:
select TRUNCATE( ( sum(temperature) / count(*) ), 2) as myTempAvg  from MY_TABLE where rawData not in ('chron', 'fallback') and DATE(transmissionDate) = DATE('2019-01-27');
select TRUNCATE( ( sum(humidity) / count(*) ), 2) as myHumyAvg  from MY_TABLE where rawData not in ('chron', 'fallback') and DATE(transmissionDate) = DATE('2019-01-27');
select TRUNCATE( ( sum(pressure) / count(*) ), 0) as myPressAvg  from MY_TABLE where rawData not in ('chron', 'fallback') and DATE(transmissionDate) = DATE('2019-01-27');

I'm trying to figure out a way to use the above query in an UPDATE statement. Something like:
update MY_TABLE set temperature = $QUERY_1_RESULT , humidity = $QUERY_2_RESULT , pressure = $QUERY_3_RESULT where rawData in ('chron', 'fallback')  and DATE(transmissionDate) = DATE('2019-01-27');

Note: $QUERY variables are  explaining purpose placeholders.
any idea?

A: You can try below -
update MY_TABLE
(
select TRUNCATE( ( sum(temperature) / count(*) ), 2) as myTempAvg ,
TRUNCATE( ( sum(humidity) / count(*) ), 2) as myHumyAvg,
TRUNCATE( ( sum(pressure) / count(*) ), 0) as myPressAvg
from MY_TABLE
where rawData not in ('chron', 'fallback') and DATE(transmissionDate) = DATE('2019-01-27')
)as src
set temperature=myTempAvg ,humidity = myHumyAvg , pressure = myPressAvg
where rawData in ('chron', 'fallback')  and DATE(transmissionDate) = DATE('2019-01-27')

A: You should be able to do it similarly to the below.
INSERT INTO MY_TABLE (temperature)
SELECT TRUNCATE( ( sum(temperature) / count(*) ), 2) as myTempAvg
FROM MY_TABLE
WHERE rawData not in ('chron', 'fallback')
AND DATE(transmissionDate) = DATE('2019-01-27');


text:
Q: JPA Replace Business key with Primary Key I'm working with a legacy database.
I'm using JPA 2.x
I have :

*

*a table BUSINESS_ORDER containing domain objects with a PK + a Natural Business Key

*a table BUSINESS_LEDGER containing domain objects with a PK + a Composite Natural Business Key

*a table INTEGRATION containing a mapping betweenthe 2 previous tables : a PK + FK_BUSINESS_ORDER + FK_BUSINESS_LEDGER

In my JPA entities :

*

*for BUSINESS_ORDER entity, I would like to hide the ID, in favor to expose the Business Key. Exposing business and not the infrastruture key.

*for BUSINESS_LEDGER entity, same thing. Encapsulate the id and expose a buiness Key

*for INTEGRATION entity I would like to use the business keys and not the ID. I don't really want to map relationships. Only references because that doesn't make sense from a business point of view. Just keeping the references (business keys) is relevant and useful. The integration entity is for querying and keeping links (like a join table :D)

My question is : how to design the INTEGRATION entity ? I instanciate a new Integration entity, set the Business Keys (order code and ledger code) and save it. During save, the codes are tanslated into their PK and voila. When loading an INTEGRATION entity, the PK is converted to its code.

*

*If I don't use the @ManyToOne annotation ;

*If I use a @Converter, I need to convert from a business key to a PK and need to make a query each time inside a Converter (ewwww). Seems a bit overkill or complicated.

*If I use a @SecondaryTable (not the default usecase for this annotation). I don't really know how to implement it

Update 1:
Perhaps the answer is to use a @Embeddable with a @OneToOne to the ORDER entity for example or a partial vie of the Order entity (only id/code) inside the embeddable.


text:
Q: How to fix the font sizes of DB browser for sqlite, which got tiny due to remote Windows server update?
Recently after an update in Windows server 2016 OS (64-bit), few apps font size went too tiny to be able to read. Currently my interest is for "DB browser for sqlite". Tried to fix it with below approaches:

*

*Control Panel > Display Settings > Custom scaling

*BTW, Display settings customization isn't allowed as this OS is hosted on a remote session in AWS

*Changing sqlite DB browser own font sizes; Though I was not able to read them at first, I managed from some screenshots available in other forums

*Reinstalling the DB browser itself

None of these worked. How to make them readable like before?

A: By trial and error method, I was able to solve the issue by clicking "Restore Defaults" at the bottom left!!


text:
Q: How to read matrix from stdin(console)? I'm trying to read from stdin and the first line specify the dimension of matrix always square matrix
but my code reads only the first line
Example Input
  3
     0   2   3
     2   4   1
     3   1   4

My code
def read_matrix(formatted_string):
    list_of_lists = [list(map(int, row.split())) for row in formatted_string.split('\n')]

    return list_of_lists

x = input("enter the list of lists of numbers?")
print(read_matrix(x))

A: You're only asking the number of rows but not the content of rows themselves. Following code shows how to generate the full matrix:
def read_matrix(count):
    list_of_lists = [list(map(int, input('Enter a row: ').split())) for _ in range(count)]

    return list_of_lists

x = input("enter the list of lists of numbers?")
print(read_matrix(int(x)))

It will first query the user the number of rows and pass that number to read_matrix which will ask the user to input every line.

A: According to the official documentation,

The function then reads a line from input,
  converts it to a string (stripping a trailing newline)

Please, note reads a line. But here you are trying to read 4 lines with one call to input. You might want to run a loop to take this input.


text:
Q: Web Site URL for analytics-tracking in a Spotify-App? I want to track pageviews and userinteractions in a Spotify-app.
Spotify says it's possible: https://developer.spotify.com/technologies/apps/guidelines/integration/#usertrackinganalytics
Which »Web Site URL« do i enter when setting up a property for analytics-tracking in a Spotify-App?
Or am I doing it wrong and have to do it in another way?

A: It doesn't matter.
You can use a fake one if you will.
The only place where GA uses that is when creating links back from the reports to your website. Since your website doesn't exist, it's more like an extension from what I understand. Then you don't need those links anyway.
If feeling not-creative just use:
http://my-spotify-app.com


text:
Q: BIOS int 10h printing garbage on QEMU I have a problem while writing an x86 real mode assembly program that runs as a  bootloader in QEMU. I'm trying to print text through BIOS interrupt 0x10. My code is:
print:
    pusha
.loop:
    mov AL, [SI]
    cmp AL, 0
    je .end
    call printChar
    inc SI
    jmp .loop
.end:
    popa
    ret

printChar:
    pusha
    mov AH, 0x0E
    mov BH, 0
    mov BL, 0x0F
    int 0x10
    popa
    ret

I'm using [ORG 0x7c00] as an origin point. I tested the printChar label and calling it with some letter in AL and it works fine. When I try to load a memory address to a message like this:
loadMsg      db "Loading",0
mov SI, loadMessage
call print

I get garbage like 'U' as output on QEMU emulator. Yesterday, I wrote a code really similar to this one and have no problem at all. What is causing my problem and how can it be fixed?

A: I recently wrote some General Bootloader Tips in a Stackoverflow answer that may be of some use to you. Likely Tip #1 applies to your problem:

When the BIOS jumps to your code you can't rely on CS,DS,ES,SS,SP registers having valid or expected values. They should be set up appropriately when your bootloader starts. You can only be guaranteed that your bootloader will be loaded and run from physical address 0x00007c00 and that the boot drive number is loaded into the DL register.

Based on the fact that printChar works, and that writing an entire string out doesn't suggests that DS:SI is not pointing at the proper location in memory where your string resides. The usual cause of this is that developers incorrectly assume the CS and/or DS register is set appropriately when the BIOS jumps to the bootloader. It has to be manually set. In the case of an origin point of 0x7c00, DS needs to be set to 0. In 16-bit real mode physical memory addresses are computed  from segment:offset pairs using the formula (segment<<4)+offset . In your case you are using an offset of 0x7C00. A value in DS of 0 would yield the correct physical address of (0<<4)+0x7c00 = 0x07c00 .
You can set DS to 0 at the start of your program with something like:
xor ax, ax       ; set AX to zero
mov ds, ax       ;     DS = 0

In the case of QEMU, the BIOS jumps to 0x07c0:0x0000 . This also represents the same physical memory location (0x07c0<<4)+0 = 0x07c00 . Such a jump will set CS=0x07c0 (not CS=0). Since there are many segment:offset pairs that map to the same physical memory location, you need to set DS appropriately. You can't rely on CS being the value you expect. So in QEMU, code like this wouldn't even set DS correctly (when using ORG 0x7c00):
mov ax, cs
mov ds, ax       ; Make DS=CS

This may work on some emulators like DOSBOX and some physical hardware, but not all. The environments where this code would work is when the BIOS jumps to 0x0000:0x7c00 . In that case CS would be zero when it reaches your bootloader code, and copying CS to DS would work. Don't assume CS will be zero in all environments is the main point I am making. Always set the segment registers to what you want explicitly.
An example of code that should work is:
    BITS  16
    ORG   0x7c00
    GLOBAL main

main:
    xor ax, ax        ; AX = 0
    mov ds, ax        ; DS = 0
    mov bx, 0x7c00

    cli               ; Turn off interrupts for SS:SP update
                      ; to avoid a problem with buggy 8088 CPUs
    mov ss, ax        ; SS = 0x0000
    mov sp, bx        ; SP = 0x7c00
                      ; We'll set the stack starting just below
                      ; where the bootloader is at 0x0:0x7c00. The
                      ; stack can be placed anywhere in usable and
                      ; unused RAM.
    sti               ; Turn interrupts back on

    mov SI, loadMsg
    call print

    cli
.endloop:
    hlt
    jmp .endloop      ; When finished effectively put our bootloader
                      ; in endless cycle

print:
    pusha
.loop:
    mov AL, [SI]      ; No segment on [SI] means implicit DS:[SI]
    cmp AL, 0
    je .end
    call printChar
    inc SI
    jmp .loop
.end:
    popa
    ret

printChar:
    pusha
    mov AH, 0x0E
    mov BH, 0
    mov BL, 0x0F
    int 0x10
    popa
    ret

; Place the Data after our code
loadMsg db "Loading",0

times 510 - ($ - $$) db 0   ; padding with 0 at the end
dw 0xAA55                   ; PC boot signature

A: This is a problem:
loadMsg    db "Loading",0
mov        SI, loadMessage
call    print

Unless the program jumps over the "loading" text, it executes whatever instructions which those bytes may (or may not) represent.  Something like this fixes it:
    jmp      print_msg
    loadMsg    db "Loading",0
print_msg:
    mov        SI, loadMessage
    call    print


text:
Q: How to restore Windows Live Mail Contacts? I recently rebuilt my dad's computer, from Windows Vista to Windows 7. I have everything back now, except for the contacts in Windows Live Mail. How do I restore these from backup? I had his whole user directory C:\Users\<user>\ being backed up to a NAS. So I located the contacts.edb file from the backup, located at
C:\Users\<user>\AppData\Local\Microsoft\Windows Live Contacts\<guid>\DBStore\contacts.edb

So I copied that file (along with the others stored there contacts.pat, dbstore.ini, edb.chk) to where I found contacts.edb after installing the latest version of Windows Live Mail 2011:
C:\Users\<user>\AppData\Local\Microsoft\Windows Live\Contacts\Default\15.4\DBStore
C:\Users\<user>\AppData\Local\Microsoft\Windows Live\Contacts\Default\15.4\DBStore\Backup\new
C:\Users\<user>\AppData\Local\Microsoft\Windows Live\Contacts\Default\DBStore
C:\Users\<user>\AppData\Local\Microsoft\Windows Live\Contacts\Default\W4CR1\DBStore

But this does not seem to have restored the contacts. When I open WLM and go to Contacts it tells me there are 0 contacts. How can I restore the old contacts?? Of course I did look first for a Windows Live Contacts folder to restore them into, but there is no such folder under the new WLM apparently.
Failing this, is there some way to extract the contacts from the EDB file, into a format which can be imported into WLM (csv, wab, .contact)?

A: To anyone finding this in the future, THIS CAN BE DONE! Use this program - EseDbViewer - to export the file to a CSV file, and then you can import that where ever you want.
Note that you pretty much need the whole file structure containing the edb, not just the edb file.
Hat-tip to @MicrosoftHelps on twitter.

A: What you will need to do is find the contact folder for WLM.
If you open it you should see the contact as: John.contact. Copy all your contacts to the user account contact folder located: C:\User\{username}\contacts.
Then in Windows Live Mail, open up your contact list and click Import. Choose Import from local user account. It should successfully import those contacts into your WLM contact list.

A: Copy all files from C:\Users\user.name\AppData\Local\Microsoft\Windows Live\Contacts\Default\15.5\DBStore
copy and paste to equivalent location on destination PC.
This worked for Win 7 to Win 7, Windows Live 11 to Windows Live 12.
Most of the files in the DBStore folder are hidden and/or system files. In order to copy them, you must first open Folder Options > View tab, then (1) choose "Show hidden files, folders and drives" and (2) uncheck "Hide protected operating system files". The same thing applies when you copy them back into the equivalent location. After copying, you can reset Folder Options if you want. I have done this successfully many times. In your case you may not have backed up the files you need, in which case you're out of luck.

A: I've had good luck using Nirsoft's LiveContactsView.  It will work even if you just have a backup of the Windows Live Contacts folder, whereas EseDbViewer must be run under the OS where Windows Live Mail was used.
LiveContactsView is free (as in beer) and I've used quite a few of NirSoft's utilities and can vouch for their legitimacy.

A: You have to "export" them (CVS format) using Live mail on the original system., if the installation is wiped you cannot.
I have never found a way to do it by the copy paste method, when you install WLM it creates a unique mail profile for that particular system and user account.


text:
Q: How to specify return type and describe the return value in one-line ReST docstring? I know I can abbreviate the following ReST docstring
"""
:type flag: bool
:param flag: new value for the flag
"""

as
"""
:param bool flag: new value for the flag
"""

Can I abbreviate in a similar manner the following?
"""
:rtype: bool
:returns: new value of flag
"""

A: It is not possible. The description must be specified in returns or return and the return type in a rtype. Merging these into one line is not allowed.


text:
Q: Recurrence relation: $T(n) = T(n-1) + 1/n$
\begin{align}
T(0) & = 0 \\
T(n) & = T(n-1) + \dfrac{1}{n}
\end{align} solve the recurrence relation

My work so far:
\begin{align}
T(1) & = 1 \\
T(2) & = 1 + \dfrac{1}{2} \\
T(3) & = 1 + \dfrac{1}{2} + \dfrac{1}{3} \\
&\vdots
\end{align}
this is the harmonic series, which diverges.
What is the solution to the recurrence relation?

A: The harmonic series diverges when you take the sum to infinity, but this is just the sum to n, which can be calculated. What I'm basically saying is that I think the harmonic series is the right approach.


text:
Q: Is using namespaces to partition a project bad practice? I have recently learnt about namespaces in PHP, and was wondering, would it be bad practice to do this?
<?php

namespace String; // string helper functions

    function match($string1, $string2)
    {

        $string1 = trim($string1);
        $string2 = trim($string2);

        if (strcasecmp($string1, $string2) == 0) // are equal
        {
            return true;
        } else {
            return false;
        }
    }

?>

Before I had this as a static method to a String class, but this always seemed wrong to me... Which is the better alternative? I have a desire to categorise my helper functions, and want to know which is the better way to do it.
Edit
So how do I then access the match function if I have declared it in a namespace? How do I stop the namespace declaration, say if I include a file beneath it which declared a new namespace, would it automatically stop references to the first? And how do I go about returning to global namespace?

A: I'd put it in a namespace. A class is a describes a type in php, and though you maybe operating over a type with a similar name, it's not the same type, strictly speaking. A namespace is just a way to logically group things, which is what you're using a class to do anyways. The only thing you lose is extensibility, but as you said, it's only a collection of static methods.

A: If they're all string-related functions, there's nothing wrong with making them static methods.
A namespace would be the better choice if you've got a bunch of global functions and/or variables which you don't want cluttering up global scope, but which wouldn't make sense in a class. (I've got a class in my own code which would be a lot better suited to a namespace).
It's good practice to stick everything in some sort of container if there's any chance your code will get reused elsewhere, so you don't scribble on other people's global vars...
As for your edit there:

*

*Namespaces are tied to the file they're defined in, IIRC. Not sure how this affects included files from there but I'd guess they aren't inherited.

*You can call the global scope by saying ::trim().

A: Because namespaces are so new to php, people have been doing for a long time what you did - create a class, add static methods, and use the class as if it were a namespace. It looks to me as if you are thinking about it properly.

A: You would use classes to categorized some sort of functions on a certain dat. Like let say you have a Student class which will hold student information and student age and student ID number;and alose there some sort of methods that return and set these data.
Moreover, you would use namespace to categorized the Classes;let say now you have another class which handle the University registration for those students and alose the other classes for managing courses. Personaly, I would put all these classes under a category (i.e. namespace) called University.
Thus, it is not even a bad practice, also it gives you more readability in your code. And that would be more underestandable for other programmers if you are working in a group.
So personally I strongly suggest you use those in your project wherever you think it is proper to use it.

A: Ideally, it would be best to put functions in a namespace. If you depend on autoloading though, which only works for classes, you need to put them in one or more classes.


text:
Q: performance of system clock in c and c++11 I have noticed that C-style to compute the elapsed time is faster than if I do it using C++11. The difference is getting smaller if the execution needs more time.
#include <iostream>
#include <chrono>
#include <ctime>

long fibonacci(int n)
{
    if (n < 3) return 1;
    return fibonacci(n-1) + fibonacci(n-2);
}

int main()
{
    /* C++11-Style */
    std::chrono::time_point<std::chrono::system_clock> start, end;

    /* C-Style */
    clock_t c_start, c_end;
    double c_elapsed;

    /* Start */
    start = std::chrono::system_clock::now();
    c_start = clock();

    std::cout << "f(30) = " << fibonacci(30) << '\n';

    /* End */
    c_end = clock();
    end = std::chrono::system_clock::now();

    /* Compute Elasped time */
    c_elapsed = ((double)(c_end-c_start))/CLOCKS_PER_SEC;
    std::chrono::duration<double> elapsed_seconds = end-start;
    std::time_t end_time = std::chrono::system_clock::to_time_t(end);

    std::cout << "finished computation at " << std::ctime(&end_time)
              << "  elapsed time: " << elapsed_seconds.count() << "s\n";
    std::cout << "c_elapsed time: " << c_elapsed << "s" << std::endl;
}

The result is
f(30) = 832040
finished computation at Fri Jul  4 05:03:10 2014
  elapsed time: 0.00417783s (C++11)
c_elapsed time: 0.003686s   (C)

Why this is the case?

A: There are several things wrong with this test.

*

*It's one sample.
Who knows what will happen next time one runs it. For all we know the difference could fluctuate between 0.002 and -42.1723 and this sample happens to show a difference close to 0.002. How can one know if the results are reproducible, or how the results vary if one only tries it once?

*It's one sample taken with clocks of completely unknown characteristics.
What if the first clock can only measure in increments of 0.00417783s and the second one can only measure in increments of 0.003686s but the experiment actually ran in 0.005s? How can one know if the difference in results is meaningful if one has no idea how well the clocks can measure?

*It measures a different thing for each clock.
The first clock measurement includes two calls to the second clock's code. How can one know if the difference in results is explained by a difference in the clocks if the clocks are not the only thing that changed from one measurement to the other?
The test is therefore meaningless.
A better test should:

*

*Ascertain the characteristics of the clocks.
First and foremost one needs to know how precise the clocks can measure time. Knowing that, one can scale the experiment so that the effect of low precision can be reduced to the point we don't care about it.

*Measure the same thing with both clocks.
Compare apples to apples. There should be no difference in the two measurements other than the part one is interested in: the clocks.

*Take more than one sample.
By sampling more than once one gets to know if the result was a single fluke (possibly caused by external factors) and how the results can vary.

A: Your test is hardly fair! This is for several reasons.
Broken benchmarking
You have clock() calls surrounding only the fibonacci calculation, but std::chrono::system_clock::now() calls surrounding the fibonacci calculation plus two clock() calls!
Let's look at that again:
  C                | C++11
  ====================================
  fibonacci(30)    | clock()
                   | fibonacci(30)
                   | clock()

It seems wholly reasonable that your C++11 version should result in a higher duration.
Re-run your benchmark with isolated mechanisms (such as an entirely separate file for each variant of code), and also increase the size of the calculation being timed to get more meaningful results; run it 100 times and take an average, or something.
Different semantics
That being said, I am seeing fairly consistently that clock() is slower:
#include <ctime>
#include <chrono>

int main()
{
    for (size_t i = 0; i < 20000; i++)
#ifdef CSTYLE
        clock();
#else
        std::chrono::system_clock::now();
#endif
}

g++ -std=c++11 -O2 -Wall -pedantic main.cpp && time ./a.out &&
g++ -std=c++11 -O2 -Wall -pedantic -DCSTYLE main.cpp && time ./a.out
real  0m0.027s
user  0m0.008s
sys   0m0.016s

real  0m0.038s
user  0m0.000s
sys   0m0.036s

I don't know why this is but, consequently, comparing elapsed_seconds.count() and c_elapsed and expecting to make any firm rationalisations about the result is largely folly.


text:
Q: Community specific site icons are not displaying in top of the sites in mobile web view In the mobile web view, the community specific icons are not displaying in the top, before the site names except the Stack Overflow.
The Stack Overflow icon is displaying on it's site and for the remaining sites the Stack Exchange icon only displaying.
Screenshot taken from SO and DBA:

So the community specific icons which are displaying in the Your Communities menu, can be display in the top of the page, before the site name in the mobile web view too.


text:
Q: Bind textbox value to datagrid according to selected value in combobox I'm very new to WPF, and I have no idea how to solve the problem.
I have following DataGrid:
 <DataGrid x:Name="testDataGrid" Grid.Row="1"
              CanUserAddRows="True" CanUserReorderColumns="False" CanUserResizeRows="False" CanUserSortColumns="True"
              AutoGenerateColumns="False"
              HorizontalAlignment="Left" VerticalAlignment="Top">
        <DataGrid.Columns>
            <DataGridTextColumn Binding="{Binding SomeString}" Header="SomeString"/>
            <DataGridTextColumn Binding="{Binding quantity, ConverterCulture='de-DE', StringFormat={}{0:N3}}" Header="Quantity">
                <DataGridTextColumn.ElementStyle>
                    <Style TargetType="{x:Type TextBlock}">
                        <Setter Property="HorizontalAlignment" Value="Right"/>
                    </Style>
                </DataGridTextColumn.ElementStyle>
            </DataGridTextColumn>
            <DataGridTextColumn Binding="{Binding Unit}" Header="Unit"/>
            <DataGridTextColumn Binding="{Binding shortText}" Header="ShortText"/>
            <DataGridTextColumn Binding="{Binding PositionKind}" Header="PositionKind"/>
        </DataGrid.Columns>

        <DataGrid.RowDetailsTemplate>
            <DataTemplate>
                <Grid>
                    <DataGrid CanUserAddRows="True" CanUserReorderColumns="False" CanUserResizeRows="False" CanUserSortColumns="True"
                              AutoGenerateColumns="False"
                              ItemsSource="{Binding Document}"
                              ScrollViewer.CanContentScroll="True"
                              ScrollViewer.VerticalScrollBarVisibility="Auto" ScrollViewer.HorizontalScrollBarVisibility="Auto"
                              MaxHeight="300" MaxWidth="{Binding ElementName=DocumentDataGrid, Path=ActualWidth}"
                              MouseDoubleClick="DataGrid_MouseDoubleClick">

                        <DataGrid.Columns>
                            <DataGridTextColumn Binding="{Binding FNr}" Header="FNr"/>
                            <DataGridTextColumn Binding="{Binding KZ}" Header="KZ"/>
                            <DataGridTextColumn Binding="{Binding Minus}" Header="Minus"/>
                            <DataGridTextColumn Binding="{Binding Factor}" Header="Factor"/>
                            <DataGridTextColumn Binding="{Binding R1}" Header="R1"/>
                            <DataGridTextColumn Binding="{Binding Value1}" Header="Value1"/>
                            <DataGridTextColumn Binding="{Binding R2}" Header="R2"/>
                            <DataGridTextColumn Binding="{Binding Value2}" Header="Value2"/>
                            <DataGridTextColumn Binding="{Binding R3}" Header="R3"/>
                            <DataGridTextColumn Binding="{Binding Value3}" Header="Value3"/>
                            <DataGridTextColumn Binding="{Binding R4}" Header="R4"/>
                            <DataGridTextColumn Binding="{Binding Value4}" Header="Value4"/>
                            <DataGridTextColumn Binding="{Binding R5}" Header="R5"/>
                            <DataGridTextColumn Binding="{Binding Value5}" Header="Value5"/>
                            <DataGridTextColumn Header="Result"/>
                        </DataGrid.Columns>
                    </DataGrid>
                </Grid>
            </DataTemplate>
        </DataGrid.RowDetailsTemplate>
    </DataGrid>

I have a window, which opens by double clicking on the each row of the DataGrid with the following combobox in it:
 <ComboBox x:Name="ComboBoxFormulas" SelectionChanged="ComboBoxFormulas_SelectionChanged" RenderTransformOrigin="0.333,-5.696" Grid.Column="1" Grid.Row="1" Margin="0,0,-190,0">
            <ComboBoxItem x:Name="oneD">SomeItem1</ComboBoxItem>
            <ComboBoxItem x:Name="oneP">SomeItem2</ComboBoxItem>

Depending on selected ComboBoxItem different textLabels and textBoxes become visible:
<TextBox x:Name="txtBox1" Grid.Column="0" Grid.Row="1"  PreviewTextInput="TextBox_PreviewTextInput_Numeric" Grid.ColumnSpan="2">
            <TextBox.Style>
                <Style TargetType="TextBox">
                    <!--by default elements for formula input are invisible-->
                    <Setter Property="Visibility" Value="Collapsed" />
                    <Style.Triggers>
                        <!--show elements only when needed-->
                        <DataTrigger Binding="{Binding ElementName=oneD, Path=IsSelected}" Value="True">
                            <Setter Property="Visibility" Value="Visible"/>

So what happens is: user double clicks on a row in datagrid and a new window appers. He can input values in textBoxes depending on selected comboBoxItem, then he clicks Enter and these values have to appear in the DataGrid. Could you please help me? I'm really stuck and I don't even know where to start. Any help and suggestions would be greatly appreciated.
edit1: The code behind the Window I'm talking about is something like this:
public partial class FormelAssistent : Window
{
    //public ObservableCollection<LPosition> OZList { get; set; }
    //LPosition Oz = new LPosition();

    public FormelAssistent()
    {
        InitializeComponent();
        //this.DataContext = new { OZList = OZList };
        //OZs.ItemsSource = OZList;
        //this.OZList = new ObservableCollection<LPosition>();
        //this.OZList.Add(Oz);
    }

    //switch between labels according to selected formulas
    private void ComboBoxFormulas_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        ComboBox comboBox = sender as ComboBox;
        ComboBoxItem item = comboBox.SelectedItem as ComboBoxItem;
        string content = item.Content.ToString();

        Image img = new Image();
        switch (content)
        {
            case "Formel01 - Dreieck":
                img.Source = new BitmapImage(new Uri("/Im/Formel01_Dreieck.jpg", UriKind.Relative));
                break;
            case "Formel01 - Prisma":
                img.Source = new BitmapImage(new Uri("/Im/Formel01_Prisma.jpg", UriKind.Relative));
                break;
            case "Formel02 - Dreieck":
                img.Source = new BitmapImage(new Uri("/Im/Formel02_Dreieck.jpg", UriKind.Relative));
                break;

...
It does nothing special related to my question. It changes the images depending on comboBoxItems selected.
edit2: The DataGrid where the new rows read from the Window textboxes looks like this:DataGrid


text:
Q: JavaRx on ErrorReturn return the different type Observable is tied to a type. When onError I don't want to return the same type but different Object. Example Response object with status=400. How to achieve this?
public class Test{
    @Autowired
    private Server server;

    public Response getResponse(String id){
        Observable<Person>  personObservable = server.get(id);
        ExecutorService executorService = Executors.newFixedThreadPool(100);

        List<Person> persons = new ArrayList<Person>();
        personObservable.onErrorReturn(new Func1<Throwable, Person>() {
        @Override
         public Person call(Throwable throwable) {
              //I would like to return a HttpResponseObject taking the message
              //from throwable error information how to do it?
              // How to use Transform() in this case ?
              return null;
         }
        }).subscribeOn(Schedulers.from(executorService)).subscribe(new Action1<Person>() {
            // If i use subscribe() will it be not async?
            // I think subscribe still run on the main thread so is this
            // subscribeOn use fine ?
            @Override
            public void call(Person person) {
                // Is this fine to use the list outside the observable ?
                persons.add(person);
            }
       });
        Response r = new Response;
        r.addPersons(persons);
        return r;
    }
}

A: Use onErrorResumeNext:
Observable<Person> personObservable = ...;
return personObservable
             .toList()
             .map(persons -> new Response(persons))
             .onErrorResumeNext(error -> new Response(error.getMessage())
             .toBlocking().single();


text:
Q: MySQL 5.6.x & PHP 5.6 - seems to intermittantly lock up I've got multiple computers with MySQL 5.6.21 installed. Some were upgraded from 5.5, others have only ever had 5.6 on them. Every one of them lock up every so often during routine SQL queries to where our PHP scripts can't run any further queries whatsoever. When the database locks up, there's two options to get it running again:

*

*restart the mysql server

*kill the process that's holding everything
else up

All the MySQL servers are running InnoDB databases and seem most likely to freeze up when running queries in quick succession or when running non-finalized queries that aren't written correctly, have syntax errors, etc during the development process. I've noticed that the process that are causing the database to lock up always seem to be a 'Sleep' Command (at least that's what "show processlist" indicates).
It should be noted that when these computers were working with MySQL 5.5.x the databases never locked up. These databases aren't networked in any way. These are developer machines with databases setup on localhost.
This seems very similar to someone else I knew that tried MySQL 5.6.x. He was running some queries within a threaded web application. Under MySQL 5.5.x, the large load of queries ran just fine, but after he upgraded to MySQL 5.6.x, he noticed that the threads that ran a bunch of queries all at once seemed to crash/lock-up the server. So, he just reverted back to MySQL 5.5.x.
Has anyone else come across anything like this?
I've read through these two threads:
MySQL 5.6 deadlock for locking the same rows twice?
https://dba.stackexchange.com/questions/87016/only-innodb-databases-locking-up/87017#87017
The first thread mentions it's a insert select issue. But we're coding in PHP and so don't ever execute multiple queries at once. And our databases lock up regardless of if transactions are being used.
The second thread mentions a bunch of InnoDB settings in the my.cnf file. We don't have any InnoDB settings configured in the my.cnf file, and I'd be really surprised if InnoDB's out-of-the-box MySQL settings caused the database to totally lock up.
Finally, here's what the my.cnf file looks like:
[mysqld]
datadir=/usr/local/mysql/data
socket=/tmp/mysql.sock
open_files_limit=5000
long_query_time=1

init_connect='SET collation_connection = utf8_unicode_ci'
init_connect='SET NAMES utf8'
character-set-server=utf8
collation-server=utf8_unicode_ci
skip-character-set-client-handshake
skip-name-resolve

[mysql.server]
user=mysql
basedir=/usr/local/mysql

[client]
socket=/tmp/mysql.sock

Thanks so much for your suggestions!
****** Update 08/04/2015 ******
After a few weeks of dealing with and looking into the issue, I've found that in fact MySQL doesn't lock up (because I can continue to use access the database via the terminal and other database tools such as Sequel Pro just fine). Nor does PHP lock up (because pages that are not dependant on the database load just fine).
So, something is causing PHP to not be able to connect to the MySQL server because PHP thinks the MySQL server has gone away or doesn't exist. That something seems related to one or multiple processes in MySQL's "show processlist" command. Are there any known compatibility issues with PHP Mysqli/PDO and Mysql 5.6? I've now seen this type of issue on OSX and Ubuntu servers running vastly different PHP code.
I turned logging on in MySQL to see if it's a certain type of query that causes the issue, but there's no one thing that causes it. Whenever the issue starts, the last PHP query is always a valid query that I can run in the terminal with no problem. Running the query again in PHP doesn't even guarantee that the issue will arise again.
Thanks for the help!
****** Update 11/16/2015 ******
As promised to Peter A, here's a screenshot of what the processlist looks like on one of our development machines last time a MySQL server locked up.

Interestingly, I couldn't create new MySQL connections, but could continue to query the same database via connections I already had open in SqlPro or the terminal. Killing process 109 didn't make any difference. Nothing would get any localhost webpage to load until the entire MySQL server was restarted.
The only common thread I can find when a MySQL 5.6 server locks up is that a PHP application caused it. It doesn't seem to matter what type of database connection the PHP application uses. We've seen PDO, Mysqli, and the deprecated Mysql extensions all cause the MySQL 5.6 server to lock up.


text:
Q: Retornar linhas não repetidas em um Select Estou usando o seguinte select no oracle
select DISTINCT delivery, dt_coletado from table1

e é retornado a seguinte linha
 DELIVERY      DT_COLETADO
8816619995  2019-05-17 00:51:04
8816619995  2019-05-16 20:06:56

quero saber uma forma de retornar apenas a linha que tem a data da coluna DT_COLETADO maior. Que no caso é a linha com a data do dia 17-05-2019.

A: SELECT
    delivery, max(dt_coletado)AS dt_coletado
FROM table1
GROUP BY delivery


text:
Q: Spring boot connecting to mariadb hosted in local docker Below is spring very basic starter application which is trying to connect to mariaDB which is running on docker locally & somehow spring is not able to connect to the mariaDB but when tried to connect from SQL Client with same credentials/configuration its looks fine.
Error:-

Application properties:-

Dependancies:-
<dependencies>
                <dependency>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-devtools</artifactId>
                    <optional>true</optional>
                </dependency>
                <dependency>
                    <groupId>org.mariadb.jdbc</groupId>
                    <artifactId>mariadb-java-client</artifactId>
                </dependency>
                <dependency>
                    <groupId>org.mariadb</groupId>
                    <artifactId>r2dbc-mariadb</artifactId>
                </dependency>
                <dependency>
                    <groupId>org.testcontainers</groupId>
                    <artifactId>mariadb</artifactId>
                    <scope>test</scope>
                </dependency>
            </dependencies>

A: Please paste your pom.xml or check there are correct dependencies:
 <groupId>org.mariadb</groupId>
 <artifactId>r2dbc-mariadb</artifactId>

 <groupId>org.mariadb.jdbc</groupId>
 <artifactId>mariadb-java-client</artifactId>


text:
Q: JavaScript(React)- Uncaught TypeError: Cannot read properties of undefined (reading 'style') I am working in a project using React Js. When I wrote this, Syntax:  movieRef.current.style.transform = translateX(210px); it's not working. It shows an error- can't read 'style'. How can I solve this problem. I have attached my codes here.

import React, { useState, useRef } from "react";
import { useGetMoviesQuery } from "../../services/movieApi";
import SingleMovie from "../SingleMovie/SingleMovie";
import "./MovieRow.scss";
import "../SingleMovie/SingleMovie.scss";
import { MdArrowForwardIos, MdArrowBackIos } from "react-icons/md";

// const MovieRow = ({title}) => {codes}
const MovieRow = (props) => {
  const { title, fetchURI } = props;
  const { data, isLoading } = useGetMoviesQuery(fetchURI);
  const movieRef = useRef();
  // console.log("data:", data);

  if (isLoading) {
    return (

Loading...

    );
  }
  const handleClick = (direction) => {
    if (direction === "left") {
      movieRef.current.style.transform = `translateX(210px)`;
    }
  };
  return (
    <>

{title}

          <MdArrowForwardIos
            className="slider right-arrow"
            onClick={() => handleClick("right")}
          />

            {data?.results.map((movie, index) => (
              <SingleMovie key={movie?.id} singleMovie={movie} index={index} />
            ))}

          <MdArrowBackIos
            className="slider left-arrow"
            onClick={handleClick("left")}
          />

    </>
  );
};

export default MovieRow;
//MovieRow.scss file

h1 {
  font-family: sans-serif;
  font-size: 100%;
  color: white;
}
// non-global css
.movie-row-container {
  margin-top: 25px;
  margin-left: 22px;
  .wrapper {
    position: relative;
    .slider {
      height: 100%;
      width: 70px;
      background-color: rgba(12, 42, 214, 0.438);
      color: white;
      position: absolute;
      z-index: 99;
      margin: 0 auto;
      cursor: pointer;

      &.right-arrow {
        right: 0;
      }

      &.left-arrow {
        left: 0;
      }
    }
    .movie-row-block {
      display: flex;
      overflow-x: scroll;
      overflow-y: hidden;
      transform: translateX(210px);
    }
  }
  .movie-row-block::-webkit-scrollbar {
    display: none;
  }
}

A: This part is firing infinitely even before the first render, that's why you'll get undefined on style:
          <MdArrowBackIos
            className="slider left-arrow"
            onClick={handleClick("left")}
          />

Change it to this:
           <MdArrowBackIos
             className="slider left-arrow"
             onClick={handleClick.bind(undefined, "left")}
           />


text:
Q: a Non-linear Mass-spring system with different force and vibration frequency? I got a classic mass-spring system with zero damp ratio, having weird behaviour.
The input frequency of external force is twice that of the output displacement results. While linear systems' input & output frequency should be the same. My case should be a non-linear vibration.
In other words, $f_{vibration}=f_n=1/2\pi*\sqrt{k/m}$ but the unexplainable is that $f_{external force}=2f_n$.

In addition, the system is driven by moving fluid around the object with mass. There is some fluid-structure interaction taking place. The resonance actually occurred at the fluid natural frequency, yet this is at 1 time of structural natural frequency.
Have you encountered any non-linear system with such feature?
More fundamentally, is it possible for the external force to affect the linearity of a mass-spring-undamped system?
Appreciate any help!

A: What you are observing is most likely a subharmonic oscillation, presumably imposed by some nonlinear characteristic of your system. I would expect the fluid. The paper here explains the mechanisms of subharmonic oscillations in nonlinear systems and offers at least one example where the subharmonic occurs at half the drive frequency.

A: The external force is able to influence the linearity of the vibrational systems, as $F(t)$ can be $F(\dot{x},t)$ etc.
More materials found online, I am still trying to figure out:
"Vibrations of a Forced Self-excited System with Time lag" by Yutaka 1983
Parametric oscillator:
Michael Faraday (1831) was the first to notice oscillations of one frequency being excited by forces of double the frequency, in the crispations (ruffled surface waves) observed in a wine glass excited to "sing".


text:
Q: String manipulation required Here is a sample string . I would like to get the output from this in the specified format.
String:
/vob/TEST/.@@/main/ch_vobsweb/1/VOBSWeb/main/ch_vobsweb/4/VobsWebUI/main/ch_vobsweb/2/VaultWeb/main/ch_vobsweb/2/func.js
filename;path to file
func.js;VOBSWeb/VosWebUI/VaultWeb/func.js
The filename is listed at the end of the whole string , and it's path is supposed to be stripped using the characters after each numeric value (eg. /1/VOBSWeb/ and then /4/VobsWebUI and then /2/vaultWeb)

A: one way
$ string="/vob/TEST/.@@/main/ch_vobsweb/1/VOBSWeb/main/ch_vobsweb/4/VobsWebUI/main/ch_vobsweb/2/VaultWeb/main/ch_vobsweb/2/func.js"
$ path=$(echo "$string" | sed "s|\/[0-9]\/|\n|g"|sed 's|\/.*||' | tr "\n" "/"|sed 's/\/$//')
$ echo ${path##*/}
func.js
$ echo ${path%\/*}
/VOBSWeb/VobsWebUI/VaultWeb


text:
Q: CSS Selector in a tree like structure I have a tree like structure in HTML, and starting from the root, I would like to access only the content of its direct children using CSS selectors. Note that I don't have control on the structure of the HTML, so I cannot change it.
An example will help a lot here. Consider the following HTML code:

Quarter-Final 1

Semi-Final 1

Quarter-Final 2

Semi-Final 2

Final

I would like to get only the names of Semi-Final 1 and Semi-Final 2. Ideally with one CSS selector. How can it be done?
Thanks

A: Something along these lines (works only with jQuery at the moment, will work in CSS4):
.node > .children > .node > .content > .name:not(.node > .children > .node > .children .content > .name)


text:
Q: Programming in C - Problem in Functions int fn()
{
    return 10;
}

int main()
{
    printf("%d\n\n",fn);
    system("pause");
}

This program gives a random number, but when a function call is made, then it returns the value 10.
Can I conclude that when we use function name in a printf statement, it gives a garbage value or there is some other concept in it ?
Thanks

A: It should be:
  printf("%d\n\n",fn());

fn corresponds to a ponter address of the function. That's why you get the garbage number.
In order to call a function you must use parentheses like this:
foo();
foo(parameter1, ..., parameterN);

A: You are printing the actual adress of fn code in memory, not calling it. Call it and your life will enlight !
printf("%d\n\n", fn());

And please, put a space after comma, like always.

A: Forgot to call the function :)
change fn to fn()
printf("%d\n\n", fn());

Now this is what you get with ellipsis - no type checks...

A: *

*When you say to fn() it will make a function call

*When you say to fn it refers to the address of the function where the call should be made

So   printf("%d\n\n",fn);   will print the address of the address of the function actually not a random number, and printf("%d\n\n", fn()); will call the function and print what was returned.
Note the difference:
int fn (void)
{
  return 10;
}
int main (void)
{
  int x, y;
  x = fn();
  y = fn;
}

Here is the compiler output:
fn:
        push    ebp
        mov     ebp, esp
        mov     eax, 10
        pop     ebp
        ret
        .size   fn, .-fn
.globl main
        .type   main, @function
main:
        lea     ecx, [esp+4]
        and     esp, -16
        push    DWORD PTR [ecx-4]
        push    ebp
        mov     ebp, esp
        push    ecx
        sub     esp, 20

        ; below code does x=fn();
        call    fn                                 ; calls fn, return value in eax
        mov     DWORD PTR [ebp-12], eax            ; stores eax in ebp-12, the location for x on the local stack allocated by compiler

        ; below code does x=fn;
        mov     DWORD PTR [ebp-8], OFFSET FLAT:fn  ; stores the label address in ebp-8, the location for y on local stack allocated by compiler

        add     esp, 20
        pop     ecx
        pop     ebp
        lea     esp, [ecx-4]
        ret

A: fn() not fn
printf("%d\n\n",fn());

A: You aren't calling the function, when you type fn() THAT is when your'e calling the function and that should give you correct results.(SEE BELOW)
int fn()
{
    return 10;
}

int main()
{
    printf("%d\n\n" , fn() );
    system("pause");
}

A: You should change your printf() statement to this
printf("%d \n", fn());
Now, this will work fine.


text:
Q: Rewrite URL is not working from localhost I tried hiding my .php extensions with .htaccess at first.. It did work fine after including this in the file
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php

and also including this in my function.php
//==== Strip .php extension from requested URI
function strip_php_extension()
{
  $uri = $_SERVER['REQUEST_URI'];
  $ext = substr(strrchr($uri, '.'), 1);
  if ($ext == 'php')
  {
    $url = substr($uri, 0, strrpos($uri, '.'));
    redirect($url);
  }
}

//==== Redirect. Try PHP header redirect, then Java, then http redirect
function redirect($url)
{
  if (!headers_sent())
  {
    /* If headers not yet sent => do php redirect */
    header('Location: '.$url);
    exit;
  }
  else
  {
    /* If headers already sent => do java redirect */
    echo '<script type="text/javascript">';
    echo 'window.location.href="'.$url.'";';
    echo '</script>';

    /* If java is disabled => do html redirect */
    echo '<noscript>';
    echo '<meta http-equiv="refresh" content="0; url='.$url.'" />';
    echo '</noscript>';
    exit;
  }
}

Thing is the url for dynamic pages did not change.. I still have page.php?p=5
and blog.php?post=5 not changing to page?p=5 and blog?post=5..
I do want to change the above dynamic pages url to something nice like www.yourdomian.com/5 for page.php and www.yourdomain.com/blog/5 for the blog, but this is not reading it from my ReWrite rule in htacces
RewriteEngine On
RewriteRule ^([a-zA-Z0-9_-]+)$ page.php?p=$1
RewriteRule ^([a-zA-Z0-9_-]+)/$ page.php?p=$1

Kindly point me in the right direction as to what am doing wrong. and how to fix it.

A: You can use these rules in /MyApp/.htaccess:
Options -MultiViews
RewriteEngine On
RewriteBase /MyApp/

RewriteCond %{THE_REQUEST} /page\.php\?([a-z])=([^&\s]+)
RewriteRule ^ %1/%2? [R=302,NE,L]

RewriteCond %{THE_REQUEST}  /blog\.php\?post=([^&\s]+) [NC]
RewriteRule ^ blog/%1? [R=302,NE,L]

RewriteCond %{REQUEST_FILENAME} -d [OR]
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^ - [L]

RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.+?)/?$ $1.php [L]

RewriteRule ^blog/([^/]+)/?$ blog.php?post=$1 [L,NC,QSA]

RewriteRule ^([a-z])/([^/.]+)/?$ page.php?$1=$2 [L,QSA]


text:
Q: Android Custom Slide Menu I created my custom Slide Menu. I used FrameLayout to show my custom slide menu. I have one problem. In a small divice my slide menu is working perfectly ,but in a large device fragment is not working. I can not show fragments components (for example buttons etc.).
This is my code:
<com.android.slidingmenuexample.MainLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@drawable/geo"
    android:orientation="vertical" >

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:background="@drawable/geocell" />

    <ListView
        android:id="@+id/menu_listview"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
    </ListView>
</LinearLayout>

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:background="@drawable/header"
        android:orientation="horizontal" >

        <Button
            android:id="@+id/button_menu"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/menumm"
            android:onClick="toggleMenu" />
    </LinearLayout>

    <FrameLayout
        android:id="@+id/activity_main_content_fragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >
    </FrameLayout>
</LinearLayout>

public class MainLayout extends LinearLayout {

private static final int SLIDING_DURATION = 500;
private static final int QUERY_INTERVAL = 16;
int mainLayoutWidth;
private View menu;
private View content;
private static int menuRightMargin = 45;

private enum MenuState {
    HIDING, HIDDEN, SHOWING, SHOWN,
};

private int contentXOffset;
private MenuState currentMenuState = MenuState.HIDDEN;
private Scroller menuScroller = new Scroller(this.getContext(),
        new EaseInInterpolator());
private Runnable menuRunnable = new MenuRunnable();
private Handler menuHandler = new Handler();
int prevX = 0;
boolean isDragging = false;
int lastDiffX = 0;

public MainLayout(Context context, AttributeSet attrs) {
    super(context, attrs);
}

public MainLayout(Context context) {
    super(context);
}

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);

    mainLayoutWidth = MeasureSpec.getSize(widthMeasureSpec);
    menuRightMargin = mainLayoutWidth * 50 / 100;
}

@Override
protected void onAttachedToWindow() {
    super.onAttachedToWindow();

    menu = this.getChildAt(0);
    content = this.getChildAt(1);
    content.setOnTouchListener(new OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            return MainLayout.this.onContentTouch(v, event);
        }
    });
    menu.setVisibility(View.GONE);
}

@Override
protected void onLayout(boolean changed, int left, int top, int right,
        int bottom) {
    if (changed) {
        LayoutParams contentLayoutParams = (LayoutParams) content
                .getLayoutParams();
        contentLayoutParams.height = this.getHeight();
        contentLayoutParams.width = this.getWidth();
        LayoutParams menuLayoutParams = (LayoutParams) menu
                .getLayoutParams();
        menuLayoutParams.height = this.getHeight();
        menuLayoutParams.width = this.getWidth() - menuRightMargin;
    }
    menu.layout(left, top, right - menuRightMargin, bottom);
    content.layout(left + contentXOffset, top, right + contentXOffset,
            bottom);

}

public void toggleMenu() {

    if (currentMenuState == MenuState.HIDING
            || currentMenuState == MenuState.SHOWING)
        return;

    switch (currentMenuState) {
    case HIDDEN:
        currentMenuState = MenuState.SHOWING;
        menu.setVisibility(View.VISIBLE);
        menuScroller.startScroll(0, 0, menu.getLayoutParams().width, 0,
                SLIDING_DURATION);
        break;
    case SHOWN:
        currentMenuState = MenuState.HIDING;
        menuScroller.startScroll(contentXOffset, 0, -contentXOffset, 0,
                SLIDING_DURATION);
        break;
    default:
        break;
    }
    menuHandler.postDelayed(menuRunnable, QUERY_INTERVAL);
    this.invalidate();
}

protected class MenuRunnable implements Runnable {
    @Override
    public void run() {
        boolean isScrolling = menuScroller.computeScrollOffset();
        adjustContentPosition(isScrolling);
    }
}

private void adjustContentPosition(boolean isScrolling) {
    int scrollerXOffset = menuScroller.getCurrX();

    content.offsetLeftAndRight(scrollerXOffset - contentXOffset);

    contentXOffset = scrollerXOffset;
    this.invalidate();
    if (isScrolling)
        menuHandler.postDelayed(menuRunnable, QUERY_INTERVAL);
    else
        this.onMenuSlidingComplete();
}

private void onMenuSlidingComplete() {
    switch (currentMenuState) {
    case SHOWING:
        currentMenuState = MenuState.SHOWN;
        break;
    case HIDING:
        currentMenuState = MenuState.HIDDEN;
        menu.setVisibility(View.GONE);
        break;
    default:
        return;
    }
}

protected class EaseInInterpolator implements Interpolator {
    @Override
    public float getInterpolation(float t) {
        return (float) Math.pow(t - 1, 5) + 1;
    }

}

public boolean isMenuShown() {
    return currentMenuState == MenuState.SHOWN;
}

public boolean onContentTouch(View v, MotionEvent event) {
    if (currentMenuState == MenuState.HIDING
            || currentMenuState == MenuState.SHOWING)
        return false;
    int curX = (int) event.getRawX();
    int diffX = 0;

    switch (event.getAction()) {
    case MotionEvent.ACTION_DOWN:

        prevX = curX;
        return true;

    case MotionEvent.ACTION_MOVE:
        if (!isDragging) {
            isDragging = true;
            menu.setVisibility(View.VISIBLE);
        }
        diffX = curX - prevX;
        if (contentXOffset + diffX <= 0) {
            diffX = -contentXOffset;
        } else if (contentXOffset + diffX > mainLayoutWidth
                - menuRightMargin) {
            diffX = mainLayoutWidth - menuRightMargin - contentXOffset;
        }
        content.offsetLeftAndRight(diffX);
        contentXOffset += diffX;
        this.invalidate();

        prevX = curX;
        lastDiffX = diffX;
        return true;

    case MotionEvent.ACTION_UP:
        Log.d("MainLayout.java onContentTouch()", "Up lastDiffX "
                + lastDiffX);

        if (lastDiffX > 0) {
            currentMenuState = MenuState.SHOWING;
            menuScroller.startScroll(contentXOffset, 0,
                    menu.getLayoutParams().width - contentXOffset, 0,
                    SLIDING_DURATION);
        } else if (lastDiffX < 0) {
            currentMenuState = MenuState.HIDING;
            menuScroller.startScroll(contentXOffset, 0, -contentXOffset, 0,
                    SLIDING_DURATION);
        }
        menuHandler.postDelayed(menuRunnable, QUERY_INTERVAL);
        this.invalidate();
        isDragging = false;
        prevX = 0;
        lastDiffX = 0;
        return true;

    default:
        break;
    }

    return false;
}

}
And MainActivity java class
ublic class MainActivity extends FragmentActivity {

MainLayout mLayout;

ProgressDialog dialog;
Button btMenu;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    mLayout = (MainLayout) this.getLayoutInflater().inflate(
            R.layout.activity_main, null);
    setContentView(mLayout);
    dialog = ProgressDialog.show(this, "Please Wait... ", "Loading... ");
    dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

    btMenu = (Button) findViewById(R.id.button_menu);
    btMenu.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            // Show/hide the menu
            toggleMenu(v);
        }
    });

    Handler handler = new Handler();
    handler.postDelayed(new Runnable() {
        public void run() {

            FragmentManager fm = MainActivity.this
                    .getSupportFragmentManager();
            FragmentTransaction ft = fm.beginTransaction();
            Layout1 fragment = new Layout1();
            ft.add(R.id.activity_main_content_fragment, fragment);
            ft.commit();

            if (dialog != null) {
                dialog.dismiss();

            }
        }

    }, 10000);

}

public void toggleMenu(View v) {
    mLayout.toggleMenu();
}

@Override
public void onBackPressed() {
    if (mLayout.isMenuShown()) {
        mLayout.toggleMenu();
    } else {
        super.onBackPressed();
    }
}

}
I  have problem only large screen resolution. In a small and medium screen resolution program working perfect. if i touch layot in a large screen  then working perfect but if i click Button tu call toggleMenu function  then not working. in my option problem is toggleMenu function ,but i do not know what is a wrong

A: You need to maintain different folders to support multiple screens in android.
The following is a list of resource directories in an application that provides different layout designs for different screen sizes and different bitmap drawables for medium, high, and extra high density screens.
res/layout/my_layout.xml             // layout for normal screen size ("default")
res/layout-small/my_layout.xml       // layout for small screen size
res/layout-large/my_layout.xml       // layout for large screen size
res/layout-xlarge/my_layout.xml      // layout for extra large screen size
res/layout-xlarge-land/my_layout.xml // layout for extra large in landscape orientation

res/drawable-mdpi/my_icon.png        // bitmap for medium density
res/drawable-hdpi/my_icon.png        // bitmap for high density
res/drawable-xhdpi/my_icon.png       // bitmap for extra high density

For more info refer this link


text:
Q: How to calculate Dynamodb provisioned capacity? I have to update one column from two dynamoDB table containing 15 million and 30 million records respectively.
Average item size is 300 bytes.
Will be using DynamoDBMapperConfig.DefaultBatchWriteRetryStrategy(10), (let me know if I should change this value?)
SQS -> Lambda
SQS containing all the partition keys as messages.
Lambda having the below code with SQS trigger with concurrency set to 5 (let me know if I should change this value?)
Code:
final DynamoDBQueryExpression<itemSchema> expression = createDynamoDBQueryExpression(partKey);
do {
    QueryResultPage<itemSchema> queryPage = mapper.queryPage(itemSchema.class, expression);
    List<itemSchema> itemSchema =  queryPage.getResults();

    for (itemSchema record : itemSchema) {
            record.setField1("Update");
            itemSchemaTableWriteItems.add(record);

            if (itemSchemaTableWriteItems.size()==25) {
                batchWrite(itemSchemaTableWriteItems);
                itemSchemaTableWriteItems = new ArrayList<>();
            }
    }
    expression.setExclusiveStartKey(queryPage.getLastEvaluatedKey());
} while (expression.getExclusiveStartKey() != null);

How much write capacity to provision to update all items within 2 hrs?

A: Since your items are 300 bytes on average we'll just assume they're all below 1 KB. That means you need 1 write unit for every item.
To update 45 million items in 2 hours means you need to sustain 45,000,000/(2*60*60) = 6,250 per second.
So that's a good ballpark answer. To achieve the target you'll need to make sure your load is spread well across PKs so you don't have hot partitions, and you need to make sure your client(s) can sustain at least this amount of send. I suggest short trials.
Note that if your table was provisioned low and then you raise the level higher than it's been before, it will take some time to add the capacity. A new table initially provisioned high will get that capacity right away upon creation.