text:
Q: Why are functions inherited in only one direction when CFCs extend each other? I have the following two CFCs:
component extends="Controller" displayName="foo" {
    public void function minifoo() {
    }
}

component extends="Foo" displayName="bar" {
    public void function minibar() {
    }
}

I know that any functions present in Foo.cfc will be available to Bar.cfc. But it seems that the reverse is not true. Can I make functions in Bar.cfc also available to Foo.cfc? Or does inheritance only work one way?

A: Inheritance only works in one direction as the name implies.
Its a little difficult for the father to inherit the son. ;)
It you have some common functions that you want to be widely available you probably need to look at some form of helper or dependancy injection.
If its not common but specific to parent & child CFC then you perhaps need to look at your application structure, the relationship between these two CFCs and where the functionality actually lives.

A: no, inheritance does not work that way.
Try Dependancy Injection, basically...
f = new Foo();
b = new Bar();
f.setBar(b);
b.setFoo(f);

And framework like ColdSpring or Lightwire or Wirebox can help you with that if you need.
Then they can talk to each other, but you should think HARD if that's really what you want.  Maybe you would like to design them differently.


text:
Q: Materialize framework: responsive logo in navbar I'm creating a website in materialize framework. I have a problem with logo in navbar. So my logo is very big (6202x3800 px) and I don't have any other version. I want to put this logo in navbar but it always exceeds the frame of nav-wrapper. I tried to add class responsive-img but it didn't work at all.
Here is my code:
#allcontent {
  background-color: white;
  margin: 2%;
}
body {
  background: #d26335;
}
nav {
  color: black;
}

search

colors

A: All you have to do is control the size of the image with CSS to whatever dimensions you want:
.navbar-material .nav-wrapper .brand-logo img {
    height: 64px;
}

Or use a image editor to resize the image to something more reasonable for a logo to start with. See Photoshop, GIMP or Sketch to name a few.
(*And definitely compress images; if you're not using a build system to do this there's always something like TINYpng)
See working example Snippet.
(**note all classes used are default MaterialCSS minus the .navbar-material class and it looks like you're mixing Bootstrap3 classes with MaterialCSS classes)

$(".button-collapse").sideNav();
body {
  background: #d26335;
}
nav.navbar-material {
  background: #d26335;
  border: none;
  box-shadow: none;
}
.navbar-material .nav-wrapper {
  background: white;
  margin: 20px;
}
.navbar-material .nav-wrapper > ul > li > a {
  color: black;
}
.navbar-material .nav-wrapper .brand-logo img {
  height: 64px;
}
.navbar-material .nav-wrapper .button-collapse i {
  color: black;
}
@media (max-width: 600px) {
  .navbar-material .nav-wrapper .brand-logo img {
    height: 56px;
  }
}

<link href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.1/css/materialize.min.css" rel="stylesheet" />
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

    menu

Sass

Components

Javascript

Mobile

Sass

Components

Javascript

Mobile

redpajama_set_name: RedPajamaStackExchange


text:
Q: holonomy and curvature I was trying to prove the following statement which relates the holonomy and curvature.
Given a Riemannian manifold $(M,g)$ assume it has two smooth vector fields $V,W$ such that $[V,W] = 0$ (therefore the induced flow commute). Assume that we parallel transport along the flow line as follows:(1) first we transport along flow for vector field $V$ for $\epsilon$ time, (2)then along flow for vector field $W$ for $\epsilon$ time , (3) then along $-V$ for $\epsilon$ time (4) finally for $-W$  for $\epsilon$ time.
Since the flow commute, it will come back to the original point (denote this point $p$). Therefore it's an element in the homology group base at that point, denoting this parallel transport $P_\gamma$. I want to show:
$$P_\gamma = Id +\epsilon^2 R(V,W) + O(\epsilon^2)$$
Where $R(V|_p,W|_p) \in End(T_pM)$ be the curvature tensor after eating two vector fields $V$ and $W$.

I have no idea how to prove it. If possible we may write everything in the coordinate?


text:
Q: Concat in Codeigniter Active Record I am trying a Concat for an autocomplete, Using CI's Active Record.
My Query is :
$this->db->select("CONCAT(user_firstname, '.', user_surname) AS name", FALSE);
$this->db->select('user_id, user_telephone, user_email');
$this->db->from('users');
$this->db->where('name', $term);

I keep getting an MySQL Error from this saying:

Error Number: 1054Unknown column 'name' in 'where clause'

Which is true, However I have just created in my Concat clause. I ideally need $term to match the Concatenated firstname and surname fields.
Any ideas what I can do to improve this? I am considering just writing this as an flat MySQL Query..
Thanks in advance

A: If cryptic solution doen't work then try it.
$query = "SELECT *
  FROM  (
        SELECT user_id, user_telephone, user_email, CONCAT(user_firstname, ' ', user_surname) name
        FROM users
    ) a
WHERE name LIKE '%".$term."%'";
$this->db->query($query);

Source: MySQL select with CONCAT condition

A: You have to SELECT the fields that you want concat like so:
$this->db->select('user_id, user_telephone, user_email, user_firstname, user_surname, CONCAT(user_firstname, '.', user_surname) AS name', FALSE);
$this->db->from('users');
$this->db->where('name', $term);

A: This will also solve the issue:
$this->db->select('user_id, user_telephone, user_email, user_firstname, user_surname, CONCAT(user_firstname,user_surname) AS name', FALSE);
$this->db->from('users');

A: $this->db->select('user_id, user_telephone, user_email, CONCAT(user_firstname, '.', user_surname) AS name', FALSE);
$this->db->from('users');
$this->db->where('name', $term);

Not sure why you are running multiple selects. So just put it as a single select. It's probably that the 2nd one is overriding the first one and thus overwriting the concatenation to create the name column.

A: $this->db->select("CONCAT((first_name),(' '),(middle_name),(' '),(last_name)) as candidate_full_name");

Try like above 100% it will work in ci.


text:
Q: C# Convert String to Integer I have finally taken the jump from VB.net to C# so I'm still having some issues.  I am making a simple weather app that connects through a RSS feed.  I want it to return a label that determines if it is freezing outside, however; I am having issues converting the temperature string to an integer so I can determine if the temperature is less than or equal to 32 degrees.  Any ideas?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;

namespace WeatherApp
{
    public partial class frmWeather : Form
    {
        string Temperature;
        public frmWeather()
        {
            InitializeComponent();
        }
        private void getWeather()
        {
            string query = string.Format("http://weather.yahooapis.com/forecastrss?w=" + txtZip.Text);
            XmlDocument wData = new XmlDocument();
            wData.Load(query);
            XmlNamespaceManager manager = new XmlNamespaceManager(wData.NameTable);
            manager.AddNamespace("yweather", "http://xml.weather.yahoo.com/ns/rss/1.0");
            XmlNode channel = wData.SelectSingleNode("rss").SelectSingleNode("channel");
            XmlNodeList nodes = wData.SelectNodes("/rss/channel/item/yweather:forecast", manager);
            Temperature = channel.SelectSingleNode("item").SelectSingleNode("yweather:condition", manager).Attributes["temp"].Value;
        }
        private void tmrWeather_Tick(object sender, EventArgs e)
        {
            getWeather();
            DateTime now = DateTime.Now;
            lblTemp.Text = "" + Temperature;
            if (lblTemp.Text <= "32")
            {
                lblResult.Text = "It is freezing outside!";
            }
        }
    }
}

A: You can use Convert.ToInt32() method to convert your String into integer
Try This:
      //lblTemp.Text = "" + Temperature;  this statement is not required.
      if (Convert.ToInt32(Temperature) <= 32)
        {
            lblResult.Text = "It is freezing outside!";
        }

OR
you can use int.TryParse() method to perform the proper conversion even if the data is invalid.
Try This:
        int temp;
        if (int.TryParse(Temperature,out temp))
        {
             if(temp <= 32)
             lblResult.Text = "It is freezing outside!";
        }

A: Another valid method would be
int temp = 0;
if (int.TryParse(lblTemp.Text, out temp))
{
     lblResult.Text = temp < 32 ? "It's freezing outside" : "Not yet freezing";
}
else
{
    // parsing error
}

Convert.ToInt() and int.parse() will also work, but int.TryParse() also guards you against exceptions in case the lblTemp.Text does not contain a valid integer. All of these methods, however, solve your initial problem, i.e. once you parse the string into a number, you can compare them to a fix value.

A: Convert it to integer,then compare with 32 ?
if (Convert.ToInt32(lblTemp.Text) <= 32)

Or just use Temperature variable which is an integer
if(Convert.ToInt32(Temperature) <= 32)

This line is pointless:
lblTemp.Text = "" + Temperature;

You might want to define Temperature as integer or double.

A: If temperature is integer, then don't use string to keep it's value. Keep temperature as integer (or double) type:
int Temperature;

And use it to compare with integer value 32:
private void tmrWeather_Tick(object sender, EventArgs e)
{
    getWeather();
    DateTime now = DateTime.Now;
    lblTemp.Text = Temperature.ToString();

    if (Temperature <= 32)
        lblResult.Text = "It is freezing outside!";
}

Also I suggest you to use Linq to Xml for parsing:
XDocument xdoc = XDocument.Load(query);
XNamespace yweather = "http://xml.weather.yahoo.com/ns/rss/1.0";
Temperature = (int)xdoc.Descendants("rss")
                       .Elements("channel")
                       .Elements("item")
                       .Element(yweather + "forecast")
                       .FirstOrDefault();

If you don't want to change your implementation, then simply parse temp value:
string temp = channel.SelectSingleNode("item")
                     .SelectSingleNode("yweather:condition", manager)
                     .Attributes["temp"].Value;
Temperature = Int32.Parse(temp);

NOTES: I suggest you to make int GetTemperature() method instead of void getWeather() method, because method name tells that it's query method which should return some value instead of changing class state (probably you will not need Temperature field in this case). Also instead of hard-coded value 32 create some constant integer value with name which describes what 32 means. And finally - use Capitalization Styles suggested by Microsoft.

A: Number("123") worked for me.


text:
Q: Add label/string to UITableView programmatically like seen in iPhone Settings I have an application with several tables separated exactly like seen in the Settings on the iPhone.  I would like to add a value to be displayed in this label exactly like seen for example in the Settings Wi-Fi or Bluetooth where on the right you have your item and on the left a value is displayed.  How can I do this?
Setting.h
@interface Setting : NSObject {

NSString *_settingsID;
NSString *_catalogID;
NSString *_category;
NSString *_facings;
NSString *_quantity;
}

@property (nonatomic, retain) NSString *settingsID;
@property (nonatomic, retain) NSString *catalogID;
@property (nonatomic, retain) NSString *category;
@property (nonatomic, retain) NSString *facings;
@property (nonatomic, retain) NSString *quanity;

- (Setting *)initWithName:(NSString *)settingsID desc:(NSString *)category CategoryID:(NSString *)catalogID Facings:(NSString *)facings Quantity:(NSString *)quantity;

@end

Setting.m
@implementation Setting

@synthesize settingsID = _settingsID;
@synthesize catalogID = _catalogID;
@synthesize category = _category;
@synthesize facings = _facings;
@synthesize quanity = _quantity;

- (Setting *)initWithName:(NSString *)settingsID desc:(NSString *)category CategoryID:(NSString *)catalogID Facings:(NSString *)facings Quantity:(NSString *)quantity {

if ((self = [super init])) {

    self.settingsID = settingsID;
    self.catalogID = catalogID;
    self.category = category;
    self.facings = facings;
    self.quanity = quantity;
}

return self;

}

@end

Next in my connectionDidFinishLoading I have taken the result from the JSON call to my WebAPI and I populate this Setting object....
-(void) connectionDidFinishLoading:(NSURLConnection *)connection {

self.settings = [NSMutableArray array];

NSError *error = nil;

id result = [NSJSONSerialization JSONObjectWithData:receivedData options:kNilOptions error:&error];

if ([result isKindOfClass:[NSArray class]]) {

    for (NSDictionary *item in result) {

        NSString *settingsID = [item objectForKey:@"ID"];
        NSString *category = [item objectForKey:@"Category"];
        NSString *categoryID = [item objectForKey:@"CatalogID"];
        NSString *facings = [item objectForKey:@"Facings"];
        NSString *quantity = [item objectForKey:@"Quantity"];

        Setting *setting = [[Setting alloc] initWithName:settingsID desc:category CategoryID:categoryID Facings:facings Quantity:quantity];

        [self.settings addObject:setting];

    }
}

for (Setting *item in self.settings) {

    NSString *frozen = @"Frozen";
    BOOL res = [frozen isEqualToString:item.category];

    if (res == TRUE) {

        **NSLog(@"Original Value: %@, Bool Value: %@", item.facings, item.facings.boolValue == false ? @"No" : @"Yes");
        NSLog(@"Original Value: %@, Bool Value: %@", item.quantity, item.quantity.boolValue == false ? @"No" : @"Yes");
        // Frozen
        appDelegate.frozen_facing_value = item.facings.boolValue == false ? @"No" : @"Yes";
        appDelegate.frozen_quantity_value = item.quantity.boolValue == false ? @"No" : @"Yes";**
    }

    NSString *fruit = @"Fruit";
    res = [fruit isEqualToString:item.category];

    if (res == TRUE) {

        // Fruit
    }

    NSString *salads = @"Salads";
    res = [salads isEqualToString:item.category];

    if (res == TRUE) {

        // Salads
    }

    NSString *vegetables = @"Vegetables";
    res = [vegetables isEqualToString:item.category];

    if (res == TRUE) {

        // Vegetables
    }
}

NSLog(@"Finished..");
finished = TRUE;
}

I synthesize my selected_value in AppDelegate.h and use this to store the value of the cell the user clicks on.
@interface AppDelegate : UIResponder <UIApplicationDelegate> {
NSString *_selected_value;
**NSString *_frozen_facing_value;**
}

@property (strong, nonatomic) UIWindow *window;

@property (strong, nonatomic) UINavigationController *navigationController;

@property (nonatomic, retain) NSString *selected_value;

**@property (nonatomic, retain) NSString *frozen_facing_value;**

@end

AppDelegate.m
Here is my cellForRowAtIndexPath
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *result = nil;

if ([tableView isEqual:self.myTableView]){

    static NSString *CellIdentifier = @"CellIdentifier";

    result = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if (result == nil){
        result = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
    }

    NSMutableArray *sectionArray = [self.arrayOfSections objectAtIndex:indexPath.section];

    result.textLabel.text = [sectionArray objectAtIndex:indexPath.row];

    NSString *res = (NSString *)result.textLabel.text;

    AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];

    if ([[self tableView:tableView titleForHeaderInSection:indexPath.section] isEqualToString:@"Frozen"]) {

        if ([res isEqualToString:FACINGS]) {

           **result.detailTextLabel.text = appDelegate.frozen_facing_value;**

        } else if ([res isEqualToString:QUANTITY]) {

           result.detailTextLabel.text = @"Yes 2";
        }

    } else if ([[self tableView:tableView titleForHeaderInSection:indexPath.section] isEqualToString:@"Fruit"]) {

        if ([res isEqualToString:FACINGS]) {

            result.detailTextLabel.text = @"No 3";

        } else if ([res isEqualToString:QUANTITY]) {

            result.detailTextLabel.text = @"Yes 4";
        }

    } else if ([[self tableView:tableView titleForHeaderInSection:indexPath.section] isEqualToString:@"Salads"]) {

        if ([res isEqualToString:FACINGS]) {

            result.detailTextLabel.text = @"No 5";

        } else if ([res isEqualToString:QUANTITY]) {

            result.detailTextLabel.text = @"Yes 6";
        }

    } else if ([[self tableView:tableView titleForHeaderInSection:indexPath.section] isEqualToString:@"Vegetables"]) {

        if ([res isEqualToString:FACINGS]) {

            result.detailTextLabel.text = @"No 7";

        } else if ([res isEqualToString:QUANTITY]) {

            result.detailTextLabel.text = @"Yes 8";
        }
    }

    appDelegate.selected_value = result.detailTextLabel.text;

    result.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}

return result;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];

NSMutableArray *sectionArray = [self.arrayOfSections objectAtIndex:indexPath.section];

NSLog(@"Select value: %@", appDelegate.selected_value);

appDelegate.selectedSetting = [[NSString alloc] initWithFormat:@"Select value: %@ for %@, in section: %@", @"Test", [sectionArray objectAtIndex:indexPath.row], [self tableView:tableView titleForHeaderInSection:indexPath.section]];

[tableView deselectRowAtIndexPath:indexPath animated:YES];

SettingsViewController *settings = [[SettingsViewController alloc] initWithNibName:@"Settings" bundle:[NSBundle mainBundle]];

[self.navigationController pushViewController:settings animated:YES];
}

In my log window I see "Select value: Yes 6" unless I scroll down.  The last value rendered to the table is what I end up seeing.  I know there is a better way to do this, I just don't know how.  Ideas/Suggestions?

A: You need to setup your table view cell with a style of UITableViewCellStyleValue1. This is the type used in the Settings app for showing a black title and a blue value.
The title is set for the cell with the titleLabel and the value on the right is set using the detailTextLabel property of the cell.
Look in the docs for UITableViewCell and the initWithStyle:reuseIdentifier: method.


text:
Q: undefined reference to `dlopen' 'dlsym' dlcose' I am using UBUNTU 12.04 and trying to install multicube explorer for Design Space Exploration.
I am new with these makefile and linux internals.
I follow these steps for installation
./configure
make

and then I get error message. Following is the log (command line reformatted for readability).
root@root:/home/snu/Desktop/m3explorer# make
g++ -L. -L/usr/lib/x86_64-linux-gnu -lxml2 -ldl \
    -Wl,--no-as-needed,-export-dynamic -pthread \
    m3_commands.o m3_env.o m3_point.o m3_sim_utils.o \
    m3_database.o m3_grammar.o m3_map.o m3_opt_utils.o \
    m3_pointer_trash.o m3_tokens.o m3_object.o m3_shell.o \
    m3_vector.o m3_driver_utils.o m3_parser.o m3_shell_variables.o \
    m3_list.o m3_object_utils.o m3_arg.o m3_common_utils.o \
    m3_exception.o m3_design_space.o m3_doe_utils.o m3_gen_html.o \
    m3_xdr_api.o m3_rsm.o -o m3explorer
m3_commands.o: In function `prs_command_db_export_xml(std::basic_string<char, std::char_traits<char>, std::allocator<char> >)':
m3_commands.cc:(.text+0x379c): undefined reference to `xmlKeepBlanksDefault'
m3_commands.cc:(.text+0x37a6): undefined reference to `xmlThrDefIndentTreeOutput'
m3_commands.cc:(.text+0x37b0): undefined reference to `xmlThrDefTreeIndentString'
m3_commands.cc:(.text+0x37ba): undefined reference to `xmlNewDoc'
m3_commands.cc:(.text+0x37d0): undefined reference to `xmlNewNode'
m3_commands.cc:(.text+0x37f0): undefined reference to `xmlNewProp'
m3_commands.cc:(.text+0x3809): undefined reference to `xmlNewProp'
m3_commands.cc:(.text+0x3822): undefined reference to `xmlDocSetRootElement'
m3_commands.cc:(.text+0x3a6c): undefined reference to `xmlNewChild'
m3_commands.cc:(.text+0x3a8b): undefined reference to `xmlNewChild'
m3_commands.cc:(.text+0x3aaa): undefined reference to `xmlNewChild'
m3_commands.cc:(.text+0x3aea): undefined reference to `xmlNewChild'
m3_commands.cc:(.text+0x3b19): undefined reference to `xmlNewProp'
m3_commands.cc:(.text+0x3cb2): undefined reference to `xmlNewChild'
m3_commands.cc:(.text+0x3d75): undefined reference to `xmlNewProp'
m3_commands.cc:(.text+0x3d98): undefined reference to `xmlNewProp'
m3_commands.cc:(.text+0x3e94): undefined reference to `xmlNewProp'
m3_commands.cc:(.text+0x3f30): undefined reference to `xmlNewChild'
m3_commands.cc:(.text+0x3f5f): undefined reference to `xmlNewProp'
m3_commands.cc:(.text+0x3fad): undefined reference to `xmlNewProp'
m3_commands.cc:(.text+0x407e): undefined reference to `xmlSaveFileEnc'
m3_opt_utils.o: In function `opt_select_optimizer(m3_env*, std::basic_string<char, std::char_traits<char>, std::allocator<char> >&)':
m3_opt_utils.cc:(.text+0x51): undefined reference to `dlopen'
m3_opt_utils.cc:(.text+0x71): undefined reference to `dlsym'
m3_driver_utils.o: In function `drv_select_driver(m3_env*, std::basic_string<char, std::char_traits<char>, std::allocator<char> >&)':
m3_driver_utils.cc:(.text+0x51): undefined reference to `dlopen'
m3_driver_utils.cc:(.text+0x71): undefined reference to `dlsym'
m3_driver_utils.cc:(.text+0x109): undefined reference to `dlerror'
m3_common_utils.o: In function `m3_look_for_filename_in_search_path(m3_env*, std::basic_string<char, std::char_traits<char>, std::allocator<char> >&, std::basic_string<char, std::char_traits<char>, std::allocator<char> >&)':
m3_common_utils.cc:(.text+0x403): undefined reference to `dlopen'
m3_common_utils.cc:(.text+0x430): undefined reference to `dlclose'
m3_doe_utils.o: In function `doe_select_doe(m3_env*, std::basic_string<char, std::char_traits<char>, std::allocator<char> >&)':
m3_doe_utils.cc:(.text+0x51): undefined reference to `dlopen'
m3_doe_utils.cc:(.text+0x71): undefined reference to `dlsym'
collect2: ld returned 1 exit status
make: *** [m3explorer] Error 1

Following is the makefile contents
# Makefile for Multicube Explorer
#
# (C) Politecnico di Milano and V. Zaccaria

DSTDIR = /home/snu/Desktop/m3explorer
SRCDIR = /home/snu/Desktop/m3explorer/src
INCDIR = /home/snu/Desktop/m3explorer/src
GPLDIR = /home/snu/Desktop/m3explorer/gpl
OTHERCFLAGS =
OTHERCXXFLAGS = -D__M3EXPLORER_VERSION__=\"release_1_1\" -I/usr/include/libxml2
OTHERLINKFLAGS = -L. -L/usr/lib/x86_64-linux-gnu -lxml2
GPLCXXFLAGS =
GPLLINKFLAGS =
IMAGE = /home/snu/Desktop/m3explorer/image
BUILDSHEPARD = no
BUILDSPLINE= no
BUILDNEURAL= nn
BUILDRBF= no
BUILDREGRESSION= no

CXX=g++
AR=ar cr
RANLIB=ranlib
SHLIB_LD=g++ -fPIC
 CFLAGS= $(OTHERCFLAGS) -I$(INCDIR)
#CFLAGS= -Wall -g -I/usr/include/libxml2         commented by Tarun. If you want to uncomment. then comment next line

 CXXFLAGS= $(OTHERCXXFLAGS) -I$(INCDIR)
#CXXFLAGS=-lxml2                                        commented by Tarun. If you want to uncomment. then comment next line

GPLCXXFLAGS += $(OTHERCXXFLAGS)

OS_NAME = $(shell uname -s)

ifeq ("$(OS_NAME)", "SunOS")
CXXFLAGS += -D__SOLARIS__
CXXSOFLAGS = -shared -fPIC
endif

ifeq ("$(OS_NAME)", "Darwin")
CXXFLAGS += -g -D__MAC_OSX__
CXXSOFLAGS = -fno-common -bundle -flat_namespace -undefined suppress
endif

ifeq ("$(OS_NAME)", "Linux")
CXXFLAGS += -pthread
CXXSOFLAGS = -g -shared -fPIC
OTHERLINKFLAGS += -ldl -Wl,--no-as-needed,-export-dynamic -pthread     #--no-as-needed, is added by tarun
endif

#####################################
#     CREATE SYMBOLIC TARGETS       #
#####################################

M3EXPLORER_TARGETS = m3_commands.o m3_env.o m3_point.o m3_sim_utils.o m3_database.o m3_grammar.o m3_map.o m3_opt_utils.o m3_pointer_trash.o m3_tokens.o m3_object.o m3_shell.o m3_vector.o m3_driver_utils.o m3_parser.o m3_shell_variables.o m3_list.o m3_object_utils.o m3_arg.o m3_common_utils.o m3_exception.o m3_design_space.o m3_doe_utils.o m3_gen_html.o m3_xdr_api.o m3_rsm.o

M3EXPLORER_INCLUDES = m3_commands.h m3_driver_utils.h m3_list.h m3_object_utils.h m3_parser.h m3_shell_variables.h m3_database.h m3_env.h m3_map.h m3_opt_utils.h m3_point.h m3_sim_utils.h m3_driver.h m3_object.h m3_optimizer.h m3_pointer_trash.h m3_vector.h m3_arg.h m3_common_utils.h m3_exception.h m3_design_space.h m3_doe.h m3_doe_utils.h drivers/libm3_xml_driver.h m3_gen_html.h m3_xdr_api.h m3_rsm.h

M3EXPLORER_INCDIR_INCLUDES = $(patsubst %.h, $(INCDIR)/%.h, $(M3EXPLORER_INCLUDES))

OPTIMIZERS_SRC = libm3_pareto_doe.cc libm3_aprs.cc libm3_mosa.cc libm3_mopso.cc libm3_nsga_II.cc libm3_linear_scan.cc libm3_femo.cc libm3_semo.cc libm3_gemo.cc
OPTIMIZERS_TARGET = $(patsubst %.cc, %.so, $(OPTIMIZERS_SRC))

DOE_SRC = libm3_full_doe.cc libm3_random_doe.cc libm3_two_level_ff.cc libm3_two_level_ff_extended.cc libm3_scrambled_doe.cc
DOE_TARGET = $(patsubst %.cc, %.so, $(DOE_SRC))

DRIVERS_SRC = libm3_test_driver.cc libm3_xml_driver.cc libm3_dtlz_driver.cc
# libm3_counter_driver.cc
DRIVERS_TARGET = $(patsubst %.cc, %.so, $(DRIVERS_SRC))

# Tells make to search for sources into SRCDIR, SRCDIR/optimizers and SRCDIR/drivers
VPATH=$(SRCDIR):$(SRCDIR)/optimizers:$(SRCDIR)/drivers:$(SRCDIR)/doe:$(SRCDIR)/../gpl:$(SRCDIR)/../gpl/splines:$(SRCDIR)/../gpl/rbf

TARGET = m3explorer

#####################################
#      CREATE RSM TARGETS           #
#####################################

RSM_TARGETS=

ifeq ("$(BUILDSHEPARD)", "yes")
RSM_TARGETS += sh_i
CXXFLAGS += -D__M3_COMPILE_SHEPARD_RSM__
endif

ifeq ("$(BUILDSPLINE)", "yes")
RSM_TARGETS += spline
CXXFLAGS += -D__M3_COMPILE_SPLINE_RSM__
endif

ifeq ("$(BUILDNEURAL)", "yes")
RSM_TARGETS += nn
CXXFLAGS += -D__M3_COMPILE_NEURAL_RSM__
endif

ifeq ("$(BUILDRBF)", "yes")
RSM_TARGETS += rbf_interpolator
CXXFLAGS += -D__M3_COMPILE_RBF_RSM__
endif

ifeq ("$(BUILDREGRESSION)", "yes")
RSM_TARGETS += regressor
CXXFLAGS += -D__M3_COMPILE_REGRESSION_RSM__
endif

#####################################
#     CREATE BUILD TARGETS          #
#####################################

all: $(TARGET) $(OPTIMIZERS_TARGET) $(DRIVERS_TARGET) $(DOE_TARGET) $(RSM_TARGETS)

#############################
#       ENGINE BUILD        #
#############################

m3explorer: $(M3EXPLORER_TARGETS)
    $(CXX) $(OTHERLINKFLAGS) $^ -o $@

%.o: %.cc $(M3EXPLORER_INCDIR_INCLUDES)
    $(CXX) -c  $< -o $@ $(CXXFLAGS)

%.so: %.cc $(M3EXPLORER_INCDIR_INCLUDES)
    $(CXX) $< -o $@ $(CXXSOFLAGS) $(CXXFLAGS)

m3_grammar.o: $(SRCDIR)/m3_grammar.yy
    cp $(SRCDIR)/m3_grammar.yy .
    bison -d $(SRCDIR)/m3_grammar.yy -o bof.cc
    cp bof*h* m3_grammar.h
    cp bof*cc m3_grammar.cc
    $(CXX) -c  m3_grammar.cc -o $@ $(CXXFLAGS)

m3_tokens.o: $(SRCDIR)/m3_tokens.ll
    flex $(SRCDIR)/m3_tokens.ll
    mv lex.yy.c m3_tokens.cc
    $(CXX) -c  m3_tokens.cc -o $@ -I. $(CXXFLAGS)

#############################
#       RSM BUILD       #
#############################

XDR_DEPS= gpl_xdr_api.o gpl_xdr_api.h

gpl_xdr_api.o: gpl_xdr_api.cc gpl_xdr_api.h
    $(CXX) -c  $< -o $@ $(GPLCXXFLAGS) -I$(GPLDIR)

sh_i: sh_i.cc $(XDR_DEPS)
    $(CXX) -o gpl_xdr_api.o $@ $< $(GPLCXXFLAGS) $(GPLLINKFLAGS) -I$(GPLDIR)

nn: cascade.c $(XDR_DEPS)
     $(CXX) -o gpl_xdr_api.o -lpthread $@ $< $(GPLCXXFLAGS) $(GPLLINKFLAGS) -I$(GPLDIR)

SPLINE_OBJ=converter.o parameters.o spline.o r_wrapper.o spline_script.o
SPLINE_INC=r_wrapper.hpp spline_script.hpp converter.hpp parameters.h

$(SPLINE_OBJ): %.o: %.cc $(SPLINE_INC)
    $(CXX) -c $< -o $@ $(GPLCXXFLAGS) -I$(GPLDIR)

spline: $(SPLINE_OBJ) $(XDR_DEPS)
    $(CXX) -o $@ $^ $(GPLCXXFLAGS) $(GPLLINKFLAGS) -I$(GPLDIR)

RBF_OBJ=bvp.o diff_op.o interpolator.o linalg.o utils.o ddm.o error.o func.o rbf.o interpolatorRBF.o
RBF_INC= bvp.hpp  ddm.hpp  diff_op.hpp  error.hpp  func.hpp  interpolator.hpp  linalg.hpp  rbf.hpp  utils.hpp

$(RBF_OBJ): %.o: %.cpp $(RBF_INC)
    $(CXX) -c $< -o $@ $(GPLCXXFLAGS) -I$(GPLDIR)

rbf_interpolator: $(RBF_OBJ) $(XDR_DEPS)
    $(CXX) -o $@ $^ $(GPLCXXFLAGS) $(GPLLINKFLAGS) -I$(GPLDIR)

regressor: regressor.cc $(XDR_DEPS)
    $(CXX) -o gpl_xdr_api.o $@ $< $(GPLCXXFLAGS) $(GPLLINKFLAGS) -I$(GPLDIR)

#############################
#       CLEAN BUILD     #
#############################

clean:
    rm -f *.o $(TARGET) *.cc *.hh *.so *.h *.yy
    rm -rf m3explorer* test*_output tmp

dist-clean:
    rm -f *.o $(TARGET) *.cc *.hh *.so *.scr *.xml *.scr do_tests *.h *.yy doxygen.cfg makefile config.status
    rm -rf m3explorer* test*_output tmp $(RSM_TARGETS)

ifeq ("$(OS_NAME)", "Darwin")
dist:
            tar --directory $(SRCDIR)/../.. -c -v -z -f m3explorer_release_1_1_src.tar.gz m3explorer --exclude "*.svn*" --exclude "build"
endif

ifeq ("$(OS_NAME)", "Linux")
dist:
            tar --exclude="*.svn*" --directory $(SRCDIR)/../.. -c -v -z -f m3explorer_release_1_1_src.tar.gz m3explorer
endif

doc:
            doxygen $(DSTDIR)/doxygen.cfg

ifeq ("$(OS_NAME)", "Linux")
bin-dist: install doc
            tar --exclude="*.svn*" --directory $(IMAGE)/.. -c -v -z -f m3explorer_release_1_1_linux_$(shell uname -r)_bin.tar.gz $(shell cd $(IMAGE) && pwd | xargs basename)
endif

ifeq ("$(OS_NAME)", "Linux")
doc-dist: install doc
            tar --exclude="*.svn*" --directory $(IMAGE) -c -v -z -f m3explorer_release_1_1_docs.tar.gz $(shell cd $(IMAGE)/doc && pwd | xargs basename)
endif

#############################
#      INSTALL BUILD        #
#############################

# Note add: install -m 744 $(SRCDIR)/../tests/*.ref $(IMAGE)/tests
# install -m 744 $(SRCDIR)/../tests/stub_test.py $(IMAGE)/tests

install: all
    @mkdir -p $(IMAGE)
    @mkdir -p $(IMAGE)/bin
    @mkdir -p $(IMAGE)/lib
    @mkdir -p $(IMAGE)/schemas
    @mkdir -p $(IMAGE)/scripts
    @mkdir -p $(IMAGE)/examples
    @mkdir -p $(IMAGE)/examples/simple_sim
    @mkdir -p $(IMAGE)/examples/beverage_can
    @mkdir -p $(IMAGE)/examples/mpeg
    @mkdir -p $(IMAGE)/rsm
    @mkdir -p $(IMAGE)/tests
    @mkdir -p $(IMAGE)/html
    @mkdir -p $(IMAGE)/latex
    @mkdir -p $(IMAGE)/html/template_results_page_files
    install -m 744 $(DSTDIR)/*.so $(IMAGE)/lib
    install -m 744 $(DSTDIR)/multicube_design_space_test*.xml $(IMAGE)/tests
    install -m 744 $(DSTDIR)/debug_*scr $(IMAGE)/tests
    install -m 744 $(DSTDIR)/create_*scr $(IMAGE)/tests
    install -m 744 $(DSTDIR)/do_tests $(IMAGE)/tests
    install -m 744 $(SRCDIR)/../html/*.html $(IMAGE)/html
    install -m 744 $(SRCDIR)/../latex/*.tex $(IMAGE)/latex
    install -m 744 $(SRCDIR)/../html/template_results_page_files/* $(IMAGE)/html/template_results_page_files
    install -m 744 $(SRCDIR)/../schemas/*.xsd $(IMAGE)/schemas
    install -m 744 $(SRCDIR)/../scripts/*.scr $(IMAGE)/scripts
    install -m 744 $(SRCDIR)/../scripts/*.xml $(IMAGE)/examples/mpeg
    install -m 744 $(SRCDIR)/../scripts/full_*.gz $(IMAGE)/examples/mpeg
    install -m 744 $(SRCDIR)/../scripts/*mpeg* $(IMAGE)/examples/mpeg
    install -m 744 $(SRCDIR)/../tests/test*output.ref $(IMAGE)/tests
    install -m 744 $(SRCDIR)/../tests/db7.xml.ref $(IMAGE)/tests
    install -m 744 $(SRCDIR)/../tests/test_xml*.scr $(IMAGE)/tests
    install -m 744 $(SRCDIR)/../tests/test_ff*.scr $(IMAGE)/tests
    install -m 744 $(SRCDIR)/../tests/mpeg_dse.scr $(IMAGE)/tests
    install -m 744 $(SRCDIR)/../tests/mpeg_export_xml.scr $(IMAGE)/tests
    install -m 744 $(SRCDIR)/../tests/pareto_mpeg4.db $(IMAGE)/tests
    install -m 744 $(SRCDIR)/../tests/stub_*.py $(IMAGE)/tests
    install -m 744 $(SRCDIR)/../tests/simple_sim/simple_sim.py $(IMAGE)/examples/simple_sim
    install -m 744 $(SRCDIR)/../tests/simple_sim/simple_sim_scr.scr $(IMAGE)/examples/simple_sim
    install -m 744 $(DSTDIR)/simple_sim_ds.xml $(IMAGE)/examples/simple_sim
    install -m 744 $(SRCDIR)/../tests/beverage_can/beverage_can.py $(IMAGE)/examples/beverage_can
    install -m 744 $(SRCDIR)/../tests/beverage_can/beverage_can_scr.scr $(IMAGE)/examples/beverage_can
    install -m 744 $(DSTDIR)/beverage_can_ds.xml $(IMAGE)/examples/beverage_can
    install -m 744 $(SRCDIR)/../gpl/*xdr* $(IMAGE)/rsm
    @mkdir -p $(IMAGE)/include
    install -m 744 $(DSTDIR)/m3explorer $(IMAGE)/bin
    @for hdr in $(INCDIR)/*.h ; do \
          if cmp -s $$hdr $(IMAGE)/include/`basename $$hdr`; then : ; else \
            echo "Installing $$hdr to $(IMAGE)/include"; \
            install -m 644 $$hdr $(IMAGE)/include; \
          fi; \
        done
    if [ -e $(DSTDIR)/sh_i ] ; then \
         install -m 744 $(DSTDIR)/sh_i $(IMAGE)/rsm; \
    fi ; \
    if [ -e $(DSTDIR)/nn ] ; then \
         install -m 744 $(DSTDIR)/nn $(IMAGE)/rsm; \
    fi ; \
    if [ -e $(DSTDIR)/spline ] ; then \
         install -m 744 $(DSTDIR)/spline $(IMAGE)/rsm; \
    fi ; \
    if [ -e $(DSTDIR)/rbf_interpolator ] ; then \
         install -m 744 $(DSTDIR)/rbf_interpolator $(IMAGE)/rsm; \
    fi ; \
    if [ -e $(DSTDIR)/regressor ] ; then \
         install -m 744 $(DSTDIR)/regressor $(IMAGE)/rsm; \
    fi ; \
    chmod a+x $(IMAGE)/bin/*
    chmod a+x $(IMAGE)/lib/*
    chmod a+x $(IMAGE)/rsm/*
    chmod a+x $(IMAGE)/tests/do_tests

install-doc: install doc

What can be the possible cause of error and how to solve it? I have checked with many earlier posts from blog. But couldn't solve it.

A: List libraries after the object files, not before them.  Rewrite the build rule which is currently:
m3explorer: $(M3EXPLORER_TARGETS)
    $(CXX) $(OTHERLINKFLAGS) $^ -o $@

as:
m3explorer: $(M3EXPLORER_TARGETS)
    $(CXX) -o $@ $^ $(OTHERLINKFLAGS)

Personally, I'd include $(CXXFLAGS) in the link line too:
m3explorer: $(M3EXPLORER_TARGETS)
    $(CXX) $(CXXFLAGS) -o $@ $^ $(OTHERLINKFLAGS)


text:
Q: same space vertically and horizontally between columns Im using bootstap grid and in small devices I have two columns with a default bootstrap space between. Do you know how to give the same space to margin-bottom so the columns have the same space between both vertically and horizontally?
Below this is the example, without margin-bottom, do you know how to give a margin-bottom or top equal to the horizontal margin between the columns?
https://jsfiddle.net/wa1cjfn6/
html:

      text

      text

      Text

css:
.content{
  border:1px solid red;
  margin-top:15px;
}

A: @JonD, Bootstrap 4 has spacing utility classes that you can apply to your markup that will help with adding margins and padding to you markup, without having to write any CSS in most cases. Here's a link to the spacing utility classes for more information. In this case you can use the mt-5 class on the last div with your content class. to get your desired result. See this codeply project for it's implementation.

A: Bootstrap columns are styled with padding-left: 15px; padding-right: 15px. Therefore, between two columns you have 30px.
In the forked demo of your fiddle you will see I added padding-bottom: 30px; to the .col-sm-6 class such that the space on the bottom equals the space between the two columns.
As long as the columns have equal height, you will have an evenly spaced layout.


text:
Q: Increase speed of PowerShell Get-ChildItem large directory I have a script that references a .csv document of filenames and then runs a Get-ChildItem over a large directory to find the file and pull the 'owner'. Finally the info outputs into another .csv document. We use this to find who created files. Additionally I have it create .txt files with filename and timestamp to see how fast the script is finding the data. The code is as follows:
    Get-ChildItem -Path $serverPath -Filter $properFilename -Recurse -ErrorAction 'SilentlyContinue' |
        Where-Object {$_.LastWriteTime -lt (get-date).AddDays(30) -and
                      $_.Extension -eq ".jpg"} |
        Select-Object -Property @{
            Name='Owner'
            Expression={(Get-Acl -Path $_.FullName).Owner}
          },'*' |
        Export-Csv -Path "$desktopPath\Owner_Reports\Owners.csv" -NoTypeInformation -Append
        $time = (get-date -f 'hhmm')
        out-file "$desktopPath\Owner_Reports\${fileName}_$time.txt"
}

This script serves it's purpose but is extremely slow based on the large size of the parent directory. Currently it takes 12 minutes per filename. We query approx 150 files at a time and this long wait time is hindering production.
Does anyone have better logic that could increase the speed? I assume that each time the script runs Get-ChildItem it recreates the index of the parent directory, but I am not sure. Is there a way we can create the index one time instead of for each filename?
I am open to any and all suggestions! If more data is required (such as the variable naming etc) I will provide upon request.
Thanks!


text:
Q: PHP to convert string to slug What is the best way to convert a string of text to a slug? Meaning:

*

*alpha allowed, convert to lowercase

*numbers are allowed

*spaces should be eliminated, not converted to dash ("-")

*accented characters replaced by equivalent standard alpha

*no other characters allowed, should be stripped out

I have found plenty of code online, but it all tends to convert spaces to dashes, which I do not want to do.
I am also interested optionally in varying the conversion, wherein:

*

*ampersand ("&") should be replaced by the string "and"

And also a variant wherein:

*

*Don't bother converting accented characters to equivalent standard alpha

A: Previous one is good solution. But unfortunately it cuts off specific letters like ć or ż.
If you want to keep them, then:
public static function createSlug($str, $delimiter = '-'){

    $unwanted_array = ['ś'=>'s', 'ą' => 'a', 'ć' => 'c', 'ç' => 'c', 'ę' => 'e', 'ł' => 'l', 'ń' => 'n', 'ó' => 'o', 'ź' => 'z', 'ż' => 'z',
        'Ś'=>'s', 'Ą' => 'a', 'Ć' => 'c', 'Ç' => 'c', 'Ę' => 'e', 'Ł' => 'l', 'Ń' => 'n', 'Ó' => 'o', 'Ź' => 'z', 'Ż' => 'z']; // Polish letters for example
    $str = strtr( $str, $unwanted_array );

    $slug = strtolower(trim(preg_replace('/[\s-]+/', $delimiter, preg_replace('/[^A-Za-z0-9-]+/', $delimiter, preg_replace('/[&]/', 'and', preg_replace('/[\']/', '', iconv('UTF-8', 'ASCII//TRANSLIT', $str))))), $delimiter));
    return $slug;
}

A: Here is a modified function that I originally found here (http://cubiq.org/the-perfect-php-clean-url-generator). you can pass '' as the delimiter to not use '-'.
public static function createSlug($str, $delimiter = '-'){

    $slug = strtolower(trim(preg_replace('/[\s-]+/', $delimiter, preg_replace('/[^A-Za-z0-9-]+/', $delimiter, preg_replace('/[&]/', 'and', preg_replace('/[\']/', '', iconv('UTF-8', 'ASCII//TRANSLIT', $str))))), $delimiter));
    return $slug;

}

A: <?php
function createSlug($str,$length,$delimiter = '-'){
    $slug = strtolower(trim(preg_replace('/[\s-]+/', $delimiter, preg_replace('/[^A-Za-z0-9-]+/', $delimiter, preg_replace('/[&]/', 'and', preg_replace('/[\']/', '', iconv('UTF-8', 'ASCII//TRANSLIT', $str))))), $delimiter));
    $slug = substr($slug, 0, $length);
    return $slug;
}
$myString = "Lorem ipsum dolor sit amet consectetur adipiscing elit neque eleifend semper, lectus faucibus velit senectus risus felis malesuada habitant. Sollicitudin malesuada mus scelerisque eros primis dictum ultricies sagittis";
print createSlug($myString,50); // here 50 = 50 character length slug generate; you can change it 100/50/25 or etc
?>

Output: lorem-ipsum-dolor-sit-amet-consectetur-adipiscing-lorem-ipsum-dolor-sit-amet-consectetur-adipiscing

A: <?php
function createSlug($str) {

     $url = strtolower($title);

     $replacements = ['@'=> "at", '#' => "hash", '$' => "dollar", '%' => "percentage", '&' => "and", '.' => "dot",
                '+' => "plus", '-' => "minus", '*' => "multiply", '/' => "devide", '=' => "equal to",
                '<' => "less than", '<=' => "less than or equal to", '>' => "greater than", '<=' => "greater than or equal to",
    ];

     $title = strtr($title, $replacements);
     return $urlKey = preg_replace('#[^0-9a-z]+#i', '-', $title);
}

createSlug("BLUE DIAMOND ALMONDS HONEY ROASTED @ 100 which is < 154")

// output :- blue-diamond-almonds-honey-roasted-at-100-which-is-less-than-154

for performance test case see this answer


text:
Q: Regression with skewed/half-normal distribution - should I transform, undersample, or something else? I'm trying to create a regression model using data that are heavily skewed, almost like a half-normal distribution with a mode at zero. The lower scores are over-represented due to sampling technique - my outcome of interest (the x-axis in the histogram, the y-axis in the scatter plot) is only present in the minority of this population. I'm trying to use this model to predict outcomes in a different population which will not be skewed in the same manner. Ideally it would be great if I could drop some of the low scores in order to normalize the distribution somehow, but I can't find a validated approach to undersampling a continuous distribution. It would also be nice to be able to transform the data somehow, but that just doesn't seem to make sense because the low scores will still be overrepresented and would still drive the model.
Here's a histogram:

So the zeros (and other low values) end up driving my model (see below). In the real world, I think that the relationship is only relevant when y>1.

Just for fun, I tried dropping all of the data with y<1, and it worked beautifully well for predicting outcomes in two independent validation datasets.   Of course, I can't just drop half the data without some sort of strong statistical justification. If I don't drop any data, I can still predict outcomes in one of my validation datasets, but it doesn't quite work in the other one (p=0.1). I tried using various transforms (log, beta, log-beta, rank, square root, and Box-Cox), and they all give me the same issue - the histogram looks less skewed after transformation, but the effect is still driven by the over-represented low values.
Any suggestions for how I could approach this?
Some side notes that may or may not be relevant:
*I also have a handful of covariates which have a small impact on the results, but I didn't include them in the above info because I'm not sure if that's relevant here.
*I'll be using MATLAB to repeat the analysis across thousands of predictors and then use a permutation test (thousands of permutations) to confirm significance, so it would be nice if any proposed solution could be implemented in MATLAB. If that's not possible, that's OK - I can figure out a way to switch back and forth.
EDIT: I understand that I could undersample the over-represented part of the distribution. The problem is that my outcome is continuous, so I can't just "undersample the major variable" without arbitrarily choosing a cutoff between the "major" and "minor" variables. This would introduce bias, since I'm choosing a cutoff after looking at the data. I was hoping I could find a validated algorithm that automatically chooses which parts of the distribution to undersample.

A: Never remove legitimate data.
Use a distribution-free method that allows for arbitrary clumping at zero: a semiparametric ordinal model such as the proportional odds ordinal logistic model.  A detailed case study for ordinal model analysis of continuous Y may be found in RMS and background information on the proportional odds model and its relation to nonparametric tests may be found in BBR.

A: Hi so if rephrase the question, its How to do modelling on an unbalanced data right.
There are multiple approchrs to these kind of problem.

*

*Under sample the Major variable to drop down total distribution inline with lowest

*Oversample lowest distribution to match it in line with highest available destribution.

*Synthetically induce data

But if you are dealing with bussiness sensitive data. I would never recommend inducing artifial data with either of the sampling method. The data we recived is untampered, the skewed destribution is a part of it, and you are suppose to analyse that of the data.
So how to proceed in these kind of situvations are

*

*Confirm the skewness with client, ask for his opinion like should we keep this skewness, wether thats the natural observed pattern or shall i induce artifical data to balance the data.

*Random sample the data, run two different algos one is sensitive towards outliers and skness and one not. Present both results.

*For fun you are always drop skeweed data.
and have fun.
May the code be with you.


text:
Q: Multiple sum columns in single select query and group by id PatientId   PatientName CashAmount  CreditAmount    CreditCardAmount
--------------------------------------------------------------------
1           AMALRAJ A        0               0            0
1           AMALRAJ A        0             100            0
1           AMALRAJ A        0            1500            0
1           AMALRAJ A     1459               0            0

I need result like this:
PatientId   PatientName   CashAmount    CreditAmount    CreditCardAmount
-------------------------------------------------------------------------
1           AMALRAJ A        1459           1600                0

A: SELECT
    PatientId,
    PatientName,
    SUM(CashAmount) AS CashAmount,
    SUM(CreditAmount) AS CreditAmount,
    SUM(CreditCardAmount) AS CreditCardAmount
FROM table_with_patients
GROUP BY PatientId, PatientName

A: Other way is without group by cluase :
SELECT DISTINCT
       PatientId,
       PatientName,
       SUM(CashAmount) OVER(PARTITION BY PatientId,
                                         PatientName) CashAmount,
       SUM(CreditAmount) OVER(PARTITION BY PatientId,
                                           PatientName) CreditAmount,
       SUM(CreditCardAmount) OVER(PARTITION BY PatientId,
                                               PatientName) CreditCardAmount
FROM table;

Result :
PatientId   PatientName CashAmount  CreditAmount    CreditCardAmount
1            AMALRAJ A  1459        1600             0


text:
Q: error CS0246: The type or namespace name 'SteamVR_Trackedobject' could not be found (are you missing a using directive or an assembly reference?) I had a error in playmode option in unity
Can u plz help me


text:
Q: How to use a static color for Chart.js bar chart's legend, when using an array of background colors I have a Chart.js bar chart that has its backgroundColor set as an array.
Example:
{
  type: 'bar',
  label: "...",
  data: [...],
  borderColor: '...',
  backgroundColor: ["var_color1", "var_color2", ..., "var_color3"],
  yAxisID: 'y',
}

The legend above the chart always takes the first color in the backgroundColor array, but I want it to be a static color that I can set manually.
For instance, to always be green here and not the first color in the array that is orange:

Could anyone please provide a solution for this case?
Please note that I am using react-chartjs-2.


text:
Q: After completing the square. After completing the square, what are the solutions to the quadratic equation below?
$$x^2 + 2x = 25$$

Honstely I think it's B. But I'm not sure.

A: $$25=x^2+2x=(x+1)^2-1\implies (x+1)^2=26\implies x+1=\pm\sqrt{26}$$

A: One can got through the process of completing the square (as in "Timbuc"'s posted answer).  But one could also check by substitution.  So suppose it is proposed that $x=-1+\sqrt{26}$ is a solution.  We would then have
\begin{align}
x^2 + 2x & = (-1+\sqrt{26})^2 + 2(-1+\sqrt{26}) \\[10pt]
& = (1-2\sqrt{26}+26) + 2(-1+\sqrt{26}) \\[10pt]
& = (1+26)-2 \\[10pt]
& = 25,
\end{align}
so that is indeed a solution.  And the same thing works with $-1-\sqrt{26}$.

A: For the quadratic equation $x^2+bx+c=0$, the sum of the roots is $-b$ and the product is $c$.  So for $x^2+2x-25=0$, the $2$ roots sum to $-2$, which eliminates A and B.  The product is $-25$.  The product of the roots for D is clearly $-24$, which eliminates this answer, leaving C.  And it can be quickly verified
$$(-1+\sqrt{26})(-1-\sqrt{26})=(-1)^2-\sqrt{26}^2=-25$$

A: You can verify your answrt using this.
The solution to general quadratic equation $ax^2+bx+c=0$ is given by the formula $\frac {-b+\sqrt {b^2-4ac}}{2a}, \frac {-b-\sqrt {b^2-4ac}}{2a}$
The given equation is $x^2-2x-25=0$
There fore after applying this formula you will get option c as your answer.


text:
Q: How to perform an update with optional columns using Scala quill? I'm working on a legacy system that uses Scala Quill. I want to have a generic update function in my DAO and only update the columns that are passed. For example:
override def updateStatus(
    personId: Int,
    name: Option[String] = None,
    address: Option[String] = None): Long = ctx.run(
      query[Person]
      .filter(_.id == lift(personId))
      .update(
        p => if (name.isDefined) p.name -> lift(name.get) else p.name -> p.name,
        p => if (address.isDefined) p.address -> lift(address.get) else p.address = p.address
      )
    )

The example above, although compilable, incurs in the following runtime exception:
org.postgresql.util.PSQLException: ERROR: column "unused" of relation "person" does not exist
  Position: 99

Any suggestion?

A: Quill just translates your code to sql, so every part of code should be wrapeed in lift.
You will see translated sql code when you compile your scala code.
the if (name.isDefined) p.name -> lift(name.get) else p.name -> p.name cant be translated to sql.
And your code has some typo. such as p.address = p.address
BTW, it's not recommend to use .get in Option value. When we forget check the value, None.get will throw NoSuchElementException.
Try this
def updateStatus(
    personId: Int,
    name: Option[String] = None,
    address: Option[String] = None
  ) = ctx.run {
    query[Person]
      .filter(_.id == lift(personId))
      .update(
        p => p.name -> lift(name.getOrElse(p.name)),
        p => p.address -> lift(address.getOrElse(p.address))
      )

  }

it will be translate to sql like following
UPDATE person SET name = ?, address = ? WHERE id = ?


text:
Q: Valid conditional comments to target non-IE browsers and specific IE versions How do you use conditional comments to target

*

*Internet Explorer only

*Certain IE versions

*Certain IE versions and all other browsers

*No IE, just other browsers
in a way that validates? (validator.w3.org/)

A: I tested these and they're valid HTML.
IMPORTANT: Only IE 5 through 9 support conditional comments.
<!-- 1. IE 5-9 only: -->

<!--<![if IE]>
    <link rel="stylesheet" type="text/css" href="ie-5-through-9.css">
<![endif]>-->

<!-- 2. Some IE versions -->

<!--<![if gte IE 8]>
    <link rel="stylesheet" type="text/css" href="ie-8-and-9.css">
<![endif]>-->

<!-- 3. Some IE versions, plus all non-IE browsers -->

<!--[if gte IE 8]>-->
    <link rel="stylesheet" type="text/css" href="ie-gte8-and-non-ie.css">
<!--<![endif]-->

<!-- 4. All browsers except IE 5-9 -->

<!--[if !IE]>-->
    <link rel="stylesheet" type="text/css" href="modern-ie-and-non-ie.css">
<!--<![endif]-->


text:
Q: Game development - how to? I am creating a game and I have assigned three image views of (balls) at the top of my screen and code an animation for them. The balls are going down to the bottom from the top, but I want the balls from the top of the screen to not show at the start of the animation... any advice?
Here is the relevant Activity code:
protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ball1 = (ImageView) findViewById(R.id.ball1);
        ball2 = (ImageView) findViewById(R.id.ball2);
        ball3 = (ImageView) findViewById(R.id.ball3);

    }

private void startBallAnimation() {
    final TranslateAnimation animation = new TranslateAnimation(
            TranslateAnimation.RELATIVE_TO_PARENT, 0.0f,
            TranslateAnimation.RELATIVE_TO_PARENT, 0.0f,
            TranslateAnimation.RELATIVE_TO_PARENT, 0.0f,
            TranslateAnimation.RELATIVE_TO_PARENT, 0.86f
    );

    animation.setAnimationListener(new Animation.AnimationListener() {
        @Override
        public void onAnimationStart(Animation animation) {
            mhandle.post(new Runnable() {
                @Override
                public void run() {
                    setBallColors();
                }
            });
        }

        @Override
        public void onAnimationRepeat(Animation animation) {}

        @Override
        public void onAnimationEnd(final Animation animation) {}

    }
}

Here is my XML:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#FFFFFF"
    tools:context="com.example.hp.colorspoof.MainActivity">

    <!-- ball imageviews -->
    <ImageView
        android:id="@+id/ball1"
        android:layout_width="30dp"
        android:layout_height="30dp"
        android:layout_gravity="left"
        android:layout_marginLeft="40dp"
        app:srcCompat="@drawable/ball_0" />

    <ImageView
        android:id="@+id/ball2"
        android:layout_width="30dp"
        android:layout_height="30dp"
        android:layout_gravity="center_horizontal"
        app:srcCompat="@drawable/row2_2" />

    <ImageView
        android:id="@+id/ball3"
        android:layout_width="30dp"
        android:layout_height="30dp"
        android:layout_gravity="right"
        android:layout_marginRight="40dp"
        app:srcCompat="@drawable/row3_1" />
</FrameLayout>

A: Below is a simple untested implementation of what you want to do. I unfortunately no longer have an environment for programming Android setup, so I can't test the code for you, but this should work.
Please note that I made use of negative margins because that is the easiest way to implement it, but it isn't necessarily the best way to achieve it.  See here for more: Is it a bad practice to use negative margins in Android?
To provide a summary of the changes in the XML below from what you provided:

*

*I provided a RelativeLayout to contain your playfield.  It's generally a good practice to include a FrameLayout at the top level and then use a RelativeLayout or LinearLayout below it to contain the views that will need to be manipulated. RelativeLayout and LinearLayout provide good means of placing views in relation to each other. There is also a newer type of Layout called the ConstraintLayout that I'm not personally familiar with but you may want to look at instead of RelativeLayout. See more here: What are the differences between LinearLayout, RelativeLayout, and AbsoluteLayout?

*I removed the android:layout_gravity statements. You don't need those with a RelativeLayout.

*I utilized android:layout_alignParentTop and android:layout_marginTop to place the balls above the top of your layout by exactly the size of the ball.

*I utilized android:layout_marginLeft, android:layout_centerHorizontal, and android:layout_marginRight to place the balls horizontally on the screen as you did.

XML below:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#FFFFFF"
    tools:context="com.example.hp.colorspoof.MainActivity">

    <RelativeLayout
        android:id="@+id/play_area"
        android:layout_width="match_parent"
        android:layout_height"match_parent">

        <!-- ball imageviews -->
        <ImageView
            android:id="@+id/ball1"
            android:layout_width="30dp"
            android:layout_height="30dp"
            android:layout_alignParentTop="true"
            android:layout_marginTop="-30dp"
            android:layout_marginLeft="40dp"
            app:srcCompat="@drawable/ball_0" />

        <ImageView
            android:id="@+id/ball2"
            android:layout_width="30dp"
            android:layout_height="30dp"
            android:layout_alignParentTop="true"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="-30dp"
            app:srcCompat="@drawable/row2_2" />

        <ImageView
            android:id="@+id/ball3"
            android:layout_width="30dp"
            android:layout_height="30dp"
            android:layout_alignParentTop="true"
            android:layout_alignParentRight="true"
            android:layout_marginTop="-30dp"
            android:layout_marginRight="40dp"
            app:srcCompat="@drawable/row3_1" />

    </RelativeLayout>

</FrameLayout>


text:
Q: How to select rows that have a maximum value for a column I'm doing this challenge on Hackerrank:
https://www.hackerrank.com/challenges/weather-observation-station-5
I'm a beginner on SQL and I'm trying to query all the rows that have a maximum value for a column, maximum that I can only obtain via MAX(). So I'm trying this:
SELECT CITY, LENGTH(CITY) AS citylength
FROM STATION
WHERE LENGTH(CITY) = (SELECT MIN(CITY) FROM STATION)

and I get errors.
I've looked up on google about sub-queries but I'm not accustomed enough to know exactly how it works, so I need your help guys.Thanks.
So to sum up, I need a query that can get the rows on a table that has a maximum value obtained via MAX() clause.

A: You are requested to find two different results:

*

*The city with maximum length (and the first in the alphabet in case of a tie)

*The city with minimum length (and the first in the alphabet in case of a tie)

This means two different queries, which you glue together with UNION ALL.
(
  select concat(city, ' ', length(city))
  from station
  order by length(city), city limit 1
)
union all
(
  select concat(city, ' ', length(city))
  from station
  order by length(city) desc, city limit 1
);

As Strawberry pointed out: You need the parentheses in order to place two ORDER BY clauses, one per query part. (Otherwise you can only place one ORDER BY clause at the end for the whole query.)
In your query you are comparing LENGTH(CITY), i.e. an integer holding the name's length and MIN(CITY), i.e. the city name itself, which cannot work of course. You would have to compare with MIN(LENGTH(CITY)). Then do the same for the maximum and then use UNION ALL. This doesn't solve the problem with ties, however, which the LIMIT query does.

A: This works without sub-queries
SELECT CITY, LENGTH(CITY)
FROM STATION
ORDER BY 2,1
LIMIT 1

A: This works :
SELECT CITY,LENGTH(CITY)
FROM STATION
WHERE LENGTH(CITY) = (SELECT MIN(LENGTH(CITY)) M FROM STATION);

A: This works correctly:
select city, length(city)
from station
where length(city) = (select min(length(city)) as m from station)
order by city ASC
limit 1;

A: (SELECT CONCAT(city,' ',LENGTH(city)) city, 'shortest' category FROM stations ORDER BY LENGTH(city),city LIMIT 1)
UNION ALL
(SELECT CONCAT(city,' ',LENGTH(city)), 'longest' FROM stations ORDER BY LENGTH(city) DESC,city LIMIT 1);

A: select TOP 1 concat(city, ' ' , len(city)) from station where len(city) = (select min(len(city)) from station) order by city asc;

select TOP 1 concat(city, ' ' , len(city)) from station where len(city) = (select max(len(city)) from station) order by city desc;

A: SELECT * FROM
    (SELECT City, LENGTH(City) FROM STATION
    ORDER BY LENGTH(City),city ASC)
WHERE ROWNUM <= 1
UNION ALL
SELECT * FROM
    (SELECT City, LENGTH(City) FROM STATION
    ORDER BY LENGTH(City) DESC)
WHERE ROWNUM <= 1;


text:
Q: Search for Property Types I have to convert property types from String to Long.
Now I want to search with XPath, QueryBuilder,... all properties "prop1" with type String to convert them into Long.
All queries I tried are giving only all nodes where "prop1" exists.
/jcr:root/content/dam/images//element(*,dam:Asset)[jcr:content/metadata/tiff:ImageLength]

Is there a possibility to do that? Because e.g. on http://docs.jboss.org/exojcr/1.12.13-GA/developer/en-US/html/ch-jcr-query-usecases.html I haven't found anything which helps me.
Greetings
Sören

A: The only function related to property types offered by the JCR queries is the CAST(), but it doesn't allow you to filter the results. Therefore, you can't find nodes with given property type using XPath, SQL or SQL2. Filter the results manually, using JCR API and the Property#getType() method.


text:
Q: Gradle-Scala Project Error - Could not load Main Class I have created a gradle/scala project in intellij.
This is my project structure
build
gradle
      - wrapper
META-INF
out
src
   - main
          -resources
          -scala
   - test
         -resources
         -scala
build.gradle
gradlew
gradlew.bat
settings.gradle

These are the contents of my build.gradle file
plugins {
    id 'scala'
}
group 'org.example'
version '1.0-SNAPSHOT'
repositories {
    mavenLocal()
    maven {
        url = uri('<artifactory location>')
    }
}
jar {
    manifest {
        attributes(
                'Class-Path': configurations.compile.collect { it.getName() }.join(' '),
                'Main-Class': 'org.example.Hello'
        )
    }
}
sourceCompatibility = '12'
dependencies {
    implementation 'org.scala-lang:scala-library:2.12.14'
    testImplementation 'org.scalatest:scalatest_2.12:3.0.5'
    testRuntimeOnly 'org.scala-lang.modules:scala-xml_2.12:1.1.1'
}
test {
    useJUnitPlatform()
}

Main Class Content
package org.example
object Hello extends App {
   println("hello!")
}

When I try to build the jar and execute it , it gives an error
Could not find or load main class org.example.Hello . What might be the mistake here?

A: I was able to resolve the issue by adding the following in the settings.gradle
rootProject.name = 'gradle-scala'
include('gradle-scala')

Basically , the include tag is used to specify the directory where the code resides .

A: I see out directory, can you check the gradle settings
ensure below are ticked


text:
Q: I am running a win form app in RDP and the focus to next text box is not set when I press tab I have a win form application with login screen which runs fine with no issues when run on any machine locally.
But when I RDP to a remote system and run the app in remote system through RDP, I face following focus related issue.
Steps to generate the issue:
I run the app and that shows login screen with cursor focused on Username field.
I enter the Username and the login screen looks like:

Now when I press Tab key, the cursor stays in Username field and does not move to the password field.
Even though the focus is not on Password field, I key in the password. After inserting the password the login screen still looks as depicted in above screen.
Now when I click on the app icon in taskbar, the login screen suddenly has the password available in Password field which I inserted in previous step and it looks as below: (So I think when I press **Tab** key in Username field the cursor does move to password field and the password that I type in is also being written to the field but those are not reflected in UI until I press the app icon in taskbar)

Similar behavior occurs in password field that I have in user screen which allows user to change their password.
If anyone has came across above behavior, please share the cause and solution of the issue.
Thank you for going through the issue.


text:
Q: MySQL statement in Project Voldemort site I've just entered  Project Voldemort (a NoSQL key-value datastore) site, and saw something interesting:

"Unlike MySQL replication, both reads and writes scale horizontally"

Well, seems like this statement tries to compare Valdemort with a MySQL traditional RDBMS. Yet, MySQL Cluster is also part of the MySQL solution family. It can scale writes and reads horizontally.

*

*Wasn't this statement a little bit unfair to MySQL?

*Can MySQL Cluster scale well at all?

A: AFAIK MySQL Cluster has the ability to scale, but it is really a manual process to do so. In fact, it takes more planning and more hardware to do such scaling. Here is why:
MySQL Cluster
According to "Guide to Scaling Web Databases with MySQL Cluster" (October 2011 Whitepaper), page 5 paragraphs 4,5 under the subheading 'Auto-Sharding':

MySQL Cluster is implemented as an active/active, multi-master database ensuring updates made by any application or SQL node are
instantly available to all of the other nodes accessing the cluster.
Tables are automatically sharded across a pool of low cost commodity data nodes, enabling the database to scale horizontally to
serve read and write-intensive workloads, accessed both from SQL and
directly via NoSQL APIs. Up to 255 nodes are supported, of which 48
can be data nodes ... MySQL Cluster excels at both aggregate and
per-node performance, eliminating the requirement to provision and
manage racks of poorly utilized hardware.

Scaling can be automatic, but within the confines of the MySQL Cluster architecture.
MongoDB
MongoDB can autoshard by means of running a routing program called mongos in front of shards. The router knows where data is located, so applications can connect to it and issue requests normally. There is no apparent limitations on the amount of servers to store data and communicate requests.
Conclusion
Just comparing MySQL Cluster to MongoDB, you find auto-sharding available in both. The major difference is that you are limited to 48 data nodes, even though a maximum of 255 servers can be configured for MySQL Cluster infrastructure (The remaining 207 maximum nodes make up SQL nodes [providing mysqld process and other APIs] and management nodes [providing ndb_mgmd process]). MongoDB does not have such an architectural limitation. MySQL Cluster can, by design, run out of elbow room.
Saying that" read and writes scale horizontally" would quickly apply to products that internally perform this. Using MySQL Replication, this statement holds true. Why? MySQL Replication is asynchronous (even MySQL 5.5 is Semisynchronous, at best), whereas MySQL Cluster and MongoDB (as well as other NoSQL Databases) are synchronous with the backing of ACID-compliance.

A: Disclosure: I'm part of the MySQL Cluster product team
The 255 node limit is for a single cluster. You could have multiples of these supporting your application, with replication between them.
It is also important to consider per-node performance - in recent tests, MySQL Cluster achieved 6.8m QPS across 8 x physical Intel servers, configured with 2 sockets and 24GB of RAM (ie low cost, commodity):
http://mysql.com/why-mysql/benchmarks/mysql-cluster/
Sharding in MySQL Cluster is automatic - it happens at the database layer and is based on hashing the primary key by default. This tends to give better shard distribution than alternative auto-sharding mechanisms using range-based partitioning
There is a decent answer here that compared application to database level sharding, and the benefits of the latter:
MySQL Sharding vs MySQL Cluster


text:
Q: How to build HTML to contain the output during a foreach loop I have a foreach loop that I need to modify so that after a count of 10 it closes the html structure it's looping in and opens a new structure in order to add 10 more counts and so on until there are no more elements in the array.
<?php
// open the ul
$location_lists .= '
 'location',
'showposts' => -1
));

foreach ($locations as $location) {
  $address = some code here;
  $location_lists .= '
';
  $location_lists .= ''. ($address) .'';
  $location_lists .= '
';
};

// after 10 loops close the ul
$location_lists .= '
';

// open a new ul to hold 10 more li's etc...
$location_lists .= '

So, if there are 24 elements in the array, I need 2 ul's containing 10 li's each and the 3rd ul will contain the 4 remaining li's.

A:     $location_lists='';
$locations = get_posts(array(
'post_type' => 'location',
'showposts' => -1
));
$i=0;
foreach ($locations as $location) {
  if($i==0){$location_lists .= '
';}
  $address = some code here;
  $location_lists .= '
';
  $location_lists .= ''. ($address) .'';
  $location_lists .= '
';
  $i++;
 if($i==10){$location_lists .= '
';$i=0}
};
if($i!=0){$location_lists .= '
';}

A: $location_lists .= '
';
$i=0;
foreach ($locations as $location) {
  $i++;
  $address = some code here;
  $location_lists .= '
';
  $location_lists .= ''. ($address) .'';
  $location_lists .= '
';

  if (($i % 10) == 0) {
       $location_lists .= '

';
  }
};
$location_lists .= '
';


text:
Q: Reg exp javascript validation for name,(),% being removed from name field I need to validate name field in javascript using reg exp where error message needs to be given if number and special character like ~` are entered. I have used the below code :
jQuery.validator.addMethod("ll", function(ll, element) {
   if (ll == null) {return false;}
   return this.optional(element) || ll.match(/^[^0-9~`^|]*$/);
}, "name  invalid");

Above code work fines but when we enter ll()ss%% in the name field it automatically removes () and % and takes only llss when form is submitted. We are using jquery and ui-dform-text  for the element.


text:
Q: Adding a command to the right-click menu of the file explorer in python MyScript.py:
from tkinter import *
from tkinter import filedialog
import sys

root = Tk()

def open_file(file_to_open):
    if file_to_open != "":
        file = open(file_to_open , 'r')
        text.delete('1.0' , END)
        text.insert('1.0' , file.read())
        file.close()

text = Text(root , width = 65 , height = 20 , font = "consolas 14")
text.pack()

open_button = Button(root , text = "Open" , command = lambda: open_file(filedialog.askopenfilename()))
open_button.pack()

if len(sys.argv) > 1:
    open_file(sys.argv[1])

mainloop()

launcher.bat:
@echo off
python MyScript.py %1

Here, I would like to add a command/sub-menu to the right click menu of the windows explorer, and whenever that sub-menu is clicked, I would like to run the launcher.bat file.
I mean, I want to add a command like this to the right click menu:

Is there any way to achieve this in python?
It would be great if anyone could help me out.


text:
Q: Extending default shader in three.js I would like to extend the default lambert material shader of three.js.
I basically would like to add some custom code at the end of the default fragment shader so the last line will apply my color transformations.
It's there any simple way to do that? Or should I rewrite a completely new one adding the default code on it?

A: I've created a custom ShaderMaterial using the predefined blocks from the default materials.


text:
Q: μ-Law algorithm implementation Here is Mu-Law encoder taken from NAudio. The question is how is this formula same with the code? I can understand that MuLawCompressTable is actually the Log but I dont get the thing about mantissa why it is taken as is.

    private const int cBias = 0x84;
            private const int cClip = 32635;

            private static readonly byte[] MuLawCompressTable = new byte[256]
            {
                 0,0,1,1,2,2,2,2,3,3,3,3,3,3,3,3,
                 4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,
                 5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,
                 5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,
                 6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,
                 6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,
                 6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,
                 6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,
                 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
                 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
                 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
                 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
                 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
                 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
                 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
                 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7
            };

 public static byte LinearToMuLawSample(short sample)
        {
            //We get the sign
            int sign = (sample >> 8) & 0x80;
            if (sign != 0)
                sample = (short)-sample;
            if (sample > cClip)
                sample = cClip;

            sample = (short)(sample + cBias);

            int exponent = (int)MuLawCompressTable[(sample >> 7) & 0xFF];
            int mantissa = (sample >> (exponent + 3)) & 0x0F;
            int compressedByte = ~(sign | (exponent << 4) | mantissa);

            return (byte)compressedByte;
        }

A: They are different.  See the Wikipedia page on mu-law, http://en.wikipedia.org/wiki/Mulaw

There are two forms of this algorithm—an analog version, and a quantized digital version.

You quote the formula for the "analog" version - a compressive mapping from -1..1 to -1..1, which emphasizes the basic idea of mu-law, i.e. that the quantized value encodes more detail (uses a smaller quantization step) for smaller values, so the introduced quantization error is roughly proportional to the overall amplitude of the signal.
The "digital" version is a piecewise-linear approximation to this basic idea, with some additional shifts to further simplify processing.
Here's a plot comparing the two.  You can see the stairsteps in the green line (mu_digital) corresponding to the discrete 7-bit values, and you also spot the different linear sections approximating the smooth blue line.


text:
Q: How to update dynamic text using innerHtml with Angular 5 and Material Design I have a list with dynamic data and I want to update a specific text when the user clicks on a button :
<mat-list>
    <mat-list-item *ngFor="let id of ids">
      <mat-radio-group>
        <mat-radio-button name="car" value="honda" id="honda{{id}}" (change)="onChangeCar(id,honda)">Honda</mat-radio-button>
        <mat-radio-button name="car" value="toyota" id="toyota{{id}}" (change)="onChangeCar(id,toyota)">Toyota</mat-radio-button>
      </mat-radio-group>
   </mat-list-item>
Text to update
</mat-list>

How to update the text dynamically in an Angular way? I know how to do it with the old fashion way but it's not suggested :
onChangeCar(id) {
  (<HTMLInputElement>document.getElementById(id)).innerHTML = "new text at a
  specific Id";
}

A: replace
Text to update

with
{{newVal}}

and in your component create a variable to bind with newVal

A: Late reply, but you can simply add a content modifier to your element, such as:

And in your code have update a class variable such as this:
public carName: string;

onChangeCar(newName) {
   this.carName = newName;
}

This way, the text of the element will become whatever you set the variable carName has been set to.


text:
Q: emit event from slot to grandparen i have the following scenario:
var grandParend = new Vue({
  components:[parent,child]
  el: '#app',
  template:
    <parent>
      <child v-on:my-event="eventHandler"><child>
    <parent>
  data: {
    message: 'Hello Vue!'
  },
   methods:{
     eventHandler(){
            // event handler
     }

})

and for child
 Vue.component('child', {
 template: '<button @click="onClick">emit event</button>',
   methods:{
     onClick(){
       this.$emit('my-event')
     }

})

how to emit event form child to direct parent?
how to emit event form child to grand parent?
thank you

A: You can simply use events to emit events from your child components and handle them in your (grand)-parent.
I made a fiddle to demonstrate with your example: https://jsfiddle.net/oLojabhg/2/
<div id="app">
</div>

var child = Vue.component('child', {
 template: '<button @click="onClick">emit event from child</button>',
   methods:{
     onClick(){
       this.$emit('my-event')
     }
   }
})

var grandParend = new Vue({
  components: { parent: parent, child: child },
  el: '#app',
  template: '<parent><child v-on:my-event="eventHandler"></child></parent>',
   methods:{
     eventHandler(){
        console.log('event handled!')
     }
   }
})

Note that you can't actually add listeners to slots, but in most usecases this shouldn't be a problem. More information can be found here:

*

*https://github.com/vuejs/vue/issues/4332

*https://github.com/vuejs/vue/issues/4781


text:
Q: How to get routes for a bus of low weight that doesn't qualify for tollroads but is heigh enough to collide with viaducts? I am using routing api in version 7.2 and trying to get routes by following request:
https://route.api.here.com/routing/7.2/calculateroute.json?waypoint0=52.32122157270602,4.567701386612513&waypoint1=52.939151549621045,17.300288086614863&mode=fastest;truck;tollroad:-3&app_id=MY_APP_ID&app_code=MY_APP_CODE&alternatives=2&height=3.2

but I get response  NoRouteFound.
The vehicle that is travelling by this route is a bus. The height of this bus is 3,2 meter.
To avoid collision with any viaducts I passed parameter "truck" so that I can use parameter "height" and set it to 3,2. The request doesn't find any viable routes because it avoids tollroads with strict weight. In practice the driver does not have to pay for this road because the vehicle is not that heavy so the request should return some routes.
Is there any more parameters that I can specify so that I find routes matching my criteria or do you have any other idea how to solve my problem?

A: If the driver does not have to pay for this road because the vehicle is not that heavy then why you calculate avoids tollroads with strict weight?
When you shouldn't to pay for toll roads however you can use toll roads for a  driving without payment.
But Router show you that the combination of restrictions "avoid strictly toll" + "high <= 3.2m" is impossible.
BTW
Please use this router playground calculator https://demo.routing.ext.here.com/ - there you can see that for given origin and destination any way you should to pay toll (at least in Poland country) for even transport mode "car" although weight is light.


text:
Q: Replace HDD with SSD, / I.D. & auto-mount I have a System 76 NUC/Meercat i7, with a Samsung 950PRO 512GB PCIe NVMe boot drive, and a secondary 2TB HDD. (Ubuntu 16.04 is located on the boot drive)
I had instant remorse, and bought a 2TB 850EVO SSD to replace the existing 2TB HDD (both drives are empty). However, upon boot it did not recognize the 2TB SSD. I assume I need to I.D & auto-mount the drive. I'm not going to partition the drive, It's for bulk storage.
Also, will I need to take steps to insure AHCI has been activated for this drive (instead of IDE)?
Would appreciate any help you can offer, at beginner's level please!


text:
Q: Transform a list + list of lists into a list of maps How can I transform this:
List(a,b,c)
List(List(1,2,3), List(2,3,1), List(3,2,1))

Into this:
List(a -> List(1,2,3), b -> List(2,3,1), c -> List(3,2,1))

A: val list1 = List("a","b","c")

val list2 = List(List(1,2,3), List(2,3,1), List(3,2,1))

val res = list1 zip list2 // List((a,List(1, 2, 3)), (b,List(2, 3, 1)), (c,List(3, 2, 1)))

A: var list_a = List("a","b","c");
var list_b = List(List(1,2,3), List(2,3,1), List(3,2,1));
var new_list = collection.mutable.Map[String, List[Int]]();
for( i <- 0 to list_a.length-1){
    new_list += (list_a(i) -> list_b(i));
}

First we define both lists based on the example provided in the answer.
Second, we define the new list we"re trying to generate.
In the for loop, we"re adding new items to the array, based on the definition provided above.


text:
Q: Flipping (orthographic) camera axes It seems possible to flip an axes of an orthographic camera in three, e.g. by the following code:
var tmp = camera.right;
camera.right = camera.left;
camera.left = tmp;
camera.updateProjectionMatrix();

However, this screws up the lighting, so it seems to not be supported (at least not with built in materials). Is this so? Is there another way to achieve this?
The use case I currently have is a scientific scene (loads of spheres and lines) that can be seen from either positive or negative Z direction. The requirement is that the X and Y axis point the same direction (e.g. right and up) no matter which Z-direction you are looking in. Is there an alternative solution if flipping left/right is not the way to go?
For an example of what I am talking about, see this fiddle: https://jsfiddle.net/mt0bpwcz/1/  Try double clicking the scene to switch the camera. Afterwards the lighting will be very strange (especially visible in the specular highlights).


text:
Q: MySql create a link between 1 or 2 tables
Does there is a cleaner way to do this ?
The Products table is linked to the sub_categories table, but if there is no sub_categories for a category, I make a link between the Products table and table categories ?

A: There are a number of ways to achieve this.  Depending on the depth level of categories and also what your preferred implementation can implement using either of the following approaches.
Adjacency List model
A single categories table with a self referencing parent_id column that is populated for each sub category.
Nested Set model
A single categories table with "lft" and "rgt" columns to denote the position within the set. "lft" and "rgt" mean Left and Right respectively as "LEFT" and "RIGHT" are reserved words in SQL.
There is a fantastic full blog post with examples and diagrams explaining in great detail how both these approaches work - here.
I would also recommend looking at libraries, in your chosen language, that may take some of the work out what you want to achieve.


text:
Q: Solving for unknown exponent I'trying to make a function creates a list of exponentially increasing numbers where the sum of the numbers is equal to some maximum.
For example:
/*
* What do I have to raise N by in order for the sum to be 40
*/

(1**x + 2**x + 3**x + 4**x + 5**x) === 40;

/*
* Wolframalpha tells me: x = 1.76445
* But how can I solve with JS.
*/

function listOfNumbers(n, maxSum) {
  // implementation
}

var result = listOfNumbers(5, 40);
/*
 * result === [1, 3.397..., 6.947..., 11.542...,  17.111...]
 *
*/

result.reduce((acc, n) => acc += n) === 40

A: try https://en.wikipedia.org/wiki/Bisection_method

TOLERANCE = 1e-5;

let f = x => (1 ** x + 2 ** x + 3 ** x + 4 ** x + 5 ** x - 40);

let
    min = 0,
    max = 1,
    x = 0;

// roughly locate the upper bound

while (f(max) < 0)
    max *= 2;

// repeatedly bisect the interval [min, max]

while (1) {
    x = (min + max) / 2;
    let r = f(x);

    if (Math.abs(r) < TOLERANCE)
        break;

    if (r > 0) {
        max = x
    } else {
        min = x
    }
}

// now, x is a "good enough" approximation of the root

console.log(x);


text:
Q: UIGraphicsGetImageFromCurrentImageContext gives poor quality / low resolution image, how do I get better? Ok so I am taking a screen shot of a photo I took with my camera on the iPhone. I put the camera photo into UIImageView and grab a screenshot of it using this sort of code (this is from http://www.skylarcantu.com/blog/2009/10/16/saving-a-view-as-an-image/)...
 - (void)takeScreenshot {

    UIWindow *theScreen = [[UIApplication sharedApplication].windows objectAtIndex:0];
    UIGraphicsBeginImageContext(theScreen.frame.size);
    [[theScreen layer] renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *screenshot = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    [self doSomethingWith:screenshot];
}

I have it working as I want but the image quality of the screenshot is much worse than the image I take with my camera. Is there a way to overcome this? I guess it is because this takes a screenshot which captures the resolution of the iPhone screen rather than the resolution of the camera - maybe?!
Any suggestions would be great :-)

A: You're exactly right.   The resolution of the screen (320 x 480) is much less than the camera (1200 x 1600 on 3G, 1536 x 2048 on the 3GS) so your UIImageView must be 320x480, and it automatically downsamples your image to fit.   This seems convoluted, though -- you already have the photo as a UIImage at the higher resolution -- are you trying to overlay things onto it or something?


text:
Q: Issue with jquery #find on partial postback I have a third party component. It is a calendar control. I have a clientside event on it which fires javascript to show a popup menu. I do everything client side so I can use MVC.

dd
   function MouseDown(oDayView, oEvent, element) {

    try {

        e = oEvent.event;

        var rightClick = (e.button == 2);
        if (rightClick)
        {
            var menu = $find("2_menuSharedCalPopUp");
            menu.showAt(200, 200, e);
        }

    }
    catch (err) {
        alert("MouseDown() err: " + err.description);
    }

}

The javascript fires perfectly withe $find intially.
I have another clientside method which updates the calendar via a partial postback. Once I have done this all subsequent MouseDowns( rightclicks) which use the $find statment error with 'null'.
All similar problems people have out there seem to be around calling javascript after a postback - with solutions being re-registering an event using PageRequestManager or registering a clientside function on the server - et cetera.
However, the event is firing, and the javascript working - it's the reference in the DOM that seems an issue.
Any ideas?

A: I will try to shed some light on this problem:

*

*$find is not a jQuery method although it may look like one. It comes from ASP.NET Ajax and is used to find ASP.NET Ajax components on the client side. It's correct use is without "#" - it needs the ID of the component which is the ClientID server property in most cases.

*I think that you are perhaps using a 3rd party component library which is based on ASP.NET Ajax. It is quite possible that this library does not support the MVC way of doing Ajax. MVC Ajax does not work as ASP.NET Ajax - it does not act as an UpdatePanel and does not execute the scripts tags in the partial view. As a result the calendar component is never initialized and $find correctly returns null.

What gives? I suggest you try using jQuery ajax for loading partial views. It correctly executes any embedded JavaScript code and may lead to better results.

A: Do you mean menu = $('#2_menuSharedCalPopUp'); ?
$find is not declared in your function at all.
use of .find() in jQuery is

$('#parent').find('.child'); // useful for cached jQuery objects

A: Have you checked the name and id when you return from your partial view call?  it may be the id has changed.
if this is the case then give the control a class name of say "MyCalendar" and then use $find(".MyCalendar");

A: jquery needs to rebind events on partial page postback
This will help u..


text:
Q: iPhone/iPad rotation How can I detect the start of a rotation and the end of the rotation on these devices?
EDIT:
So after your answers, how can I detect the begining and ending of the orientation change.

A: You can implement the following two methods in your UIViewController.
To detect a start of a rotation, implement willRotateToInterfaceOrientation:duration: and to detect the end implment didRotateFromInterfaceOrientation: .
i.e.
- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration {
    NSLog(@"I am starting to rotate");
}

- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
    NSLog(@"I have finished rotating");
}

A: You can use the UIAccelerometer api for this
EDIT to match question clarification:
Use the UIAccelerometer api for this. There is a good sample application called AccelerometerGraph that displays the 3 acceleration vectors on a graph. This should give you a good indication on how a shift in orientation will look like.

A: You can't detect rotation on either of these devices. The accelerometer only detects changes in velocity.
You can get a crude measure of orientation from the CLLocationManager class, which reports a heading. This value is slow to update, which limits its usefulness.


text:
Q: How does memory use work in C# when adding the same object to different lists? I am developing a game where 2 players each have many objects from a class called UnitObject, each of which can be on a different Army.
Right now, the player class has a List of UnitObjects and at the same time, each Army has its own List  for storing units that belong to it. I am new to c# and I am wondering if, when having hundreds of units, it would be better to have the player have a Dictionary<int, UnitObject> with the int being the id of said unit, so that other classes can have just a List of integers for reference. Do the UnitObjects in the Army duplicate the memory use of the ones in the Player or is it just a reference?
My code could be (very) simplified to:
UnitObject unit =  new UnitObject();
army.units.Add(unit)
player.units.Add(unit)

This is an over simplification, my classes have other classes they belong to and is not as simple as to make the player have a list of armies or so. I am just wondering if by doing this, i am using double memory for each object.

A: UnitObject is a reference type, unlike s struct or [most] primitive objects such as int, which are value types.
Reference objects are allocated independently, either on the the stack or the heap (depending). They are passed by reference: when you add an instance of a reference type (such as an instance of your UnitObject) to a collection, what it added is a reference to the actual object itself. A reference is a single processor word (32- or 64-bit, depending on processor architecture). It's not a pointer, more like a pointer to a pointer, to allow the allocated object to be moved by the garbage collector if need be.
You when you add an instance of your UnitObject to two different collections, they both point to the same instance of UnitType.
And if you pass a reference type to a method, it is passed by reference: any changes made to the passed object by the called function persist once control returns to the caller.
Value types, are passed by value, näturlich, so adding something like an int to a collection means the collection receives a copy of the value. Ditto for passing value types to method: the method receive a copy of the value.


text:
Q: Sorting rows in a Grid column of String type based on corresponding integer values I have the following structure for a Grid and wanted to know how to sort a column based on the Integer values of the Strings. The data provider is not flexible to change, so I have to sort with some kind of intermediary step:
Grid<String[]> grid = new Grid<>();
...

grid.addColumn(str -> str[columnIndex]).setHeader("sample").setKey("integercolumn").setSortable(true);

...

GridSortOrder<String> order = new GridSortOrder<>(grid.getColumnByKey("integercolumn"), SortDirection.DESCENDING);

grid.sort(Arrays.asList(order));

This sorts two digit numbers properly but not one digit or 3+.

A: You can define a custom comparator on the column that is used for sorting its values. In your case the comparator needs to extract the column-specific value from the array, and then convert it to an int:
        grid.addColumn(row -> row[columnIndex])
                .setHeader("sample")
                .setKey("integercolumn")
                .setSortable(true)
                .setComparator(row -> Integer.parseInt(row[columnIndex]));

See https://vaadin.com/docs/latest/components/grid/#specifying-the-sort-property.


text:
Q: Can I dynamically link without giving read permission to the libraries? I have some dynamically linked libraries that I would like to protect from unauthorized users. I cannot use groups / ACLs to do this. I have a list of the licensed users and can get a yes/no at runtime as to whether a given uid is authorized. Linux and GCC/Clang, if it matters.

A: It takes a bit of extra work but it's doable and would still be considered dynamic:

*

*Make your main program setuid-root (or grant the CAP_DAC_OVERRIDE capability to your program -- see capabilities(7))

*When your program is executed, do your runtime authorization check

*If the user is authorized, use dlopen (along with the root/DAC_OVERRIDE) to load the libraries. You would then need to use dlsym to find/resolve the symbols you need from the library.

*Drop the capability and/or revert UID for best security.
(All that being said, using a group ID is much simpler. You can simply grant group membership to those users who are considered authorized.)


text:
Q: How to fix a mod_rewrite RewriteRule in HTACCESS I'm writing a few RewriteRules, and my most basic rewrite returns a 404 error. Here's my code:
Options +FollowSymLinks
RewriteEngine on

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule s/(.*)/(.*)/$ /page.php?s=$2 [NC,L]
RewriteRule ^submit/$ submit.php [R,L]

# Options All -Indexes

<files .htaccess>
order allow,deny
deny from all
</files>

RewriteRule ^submit/$ submit.php [R,L] is where I'm having trouble.
When I visit domain.com/submit/, my server returns a 404 error saying, "The requested URL /submit/ was not found on this server." It's like the server did not even look at my HTACCESS file. The other RewriteRules work perfectly.
Am I missing something?

A: You may try this:
Options +FollowSymlinks -MultiViews
RewriteEngine On
RewriteBase /

RewriteCond %{REQUEST_URI} !page\.php    [NC]
RewriteRule ^s/(.*)/(.*)/$ /page.php?s=$2 [NC,L]

RewriteCond %{REQUEST_URI} !submit\.php  [NC]
RewriteRule ^submit   submit.php         [R,L,NC]

That's it according to the information in the question.
Can't guess what's the first rule for as there are no URL examples to determine the pattern to be matched by the regex or the location of the script.
Something similar happens with the second rule because there is no way to confirm where the script (submit.php) is located as, again, there are no URL examples in the question.


text:
Q: Wallpaper fit image to screen size I spent hours on an issue that doesn't seem complicated, but despite all the existing messages on this topic, I still don't find a solution...
I'm using a viewpager and in the adapter I have a button and a imageview. I want to set the picture from the imageview as wallpaper when the button is clicked by using myWallpaperManager.setBitmap(image). Before that I resize the picture to fit in screen size. The wallpaper is changed but the picture stays zoomed and cropped. I would like to set the wallpaper with the whole picture.
I have the same values for width and height of getDefaultDisplay() and width and height of  myWallpaperManager.getDesiredMinimumHeight/Width().
I tried many different ways that didn't work. I don't know what else to do ! Thanks for a lot for your answer.
Here is the code :
 Button ButWallpaper = (Button) viewLayout.findViewById(R.id.ButWallpaper);

      ButWallpaper.setOnClickListener(new Button.OnClickListener(){
            @Override
            public void onClick(View arg0) {
               Bitmap image;
               Bitmap imagelarge = ((BitmapDrawable)imageView2.getDrawable()).getBitmap();

              int Measuredwidth = 0;
              int Measuredheight = 0;
              Point size = new Point();
              WindowManager w = _activity.getWindowManager();

             if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)    {
                 w.getDefaultDisplay().getSize(size);
                 Measuredwidth = size.x;
                 Measuredheight = size.y;
             }else{
                 Display d = w.getDefaultDisplay();
                 Measuredwidth = d.getWidth();
                 Measuredheight = d.getHeight();
             }

             Log.i("TAG", String.valueOf(Measuredwidth));
             Log.i("TAG", String.valueOf(Measuredheight));

            image =  Bitmap.createScaledBitmap(imagelarge, Measuredwidth, Measuredheight,true);

               // TODO Auto-generated method stub
            WallpaperManager myWallpaperManager
            = WallpaperManager.getInstance(_activity.getApplicationContext());
            try {
                myWallpaperManager.setBitmap(image);
                 myWallpaperManager.suggestDesiredDimensions(Measuredwidth, Measuredheight);

                 Log.i("TAG", String.valueOf(myWallpaperManager.getDesiredMinimumHeight()));
                 Log.i("TAG", String.valueOf(myWallpaperManager.getDesiredMinimumWidth()));

                 Toast.makeText(_activity.getApplicationContext(), "Wallpaper changed", toast.LENGTH_LONG).show();

            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }});

A: You can try my code :
try{
            DisplayMetrics metrics = new DisplayMetrics();
            WindowManager windowManager = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
            windowManager.getDefaultDisplay().getMetrics(metrics);
            int height = metrics.heightPixels;
            int width = metrics.widthPixels;
            Bitmap tempbitMap = BitmapFactory.decodeFile(path);
            Bitmap bitmap = Bitmap.createScaledBitmap(tempbitMap,width,height, true);
            WallpaperManager wallpaperManager = WallpaperManager.getInstance(mContext);
            wallpaperManager.setWallpaperOffsetSteps(1, 1);
            wallpaperManager.suggestDesiredDimensions(width, height);
            try {
              wallpaperManager.setBitmap(bitmap);
              Toast.makeText(mContext, "Set wallpaper success", Toast.LENGTH_SHORT).show();
              } catch (IOException e) {
              e.printStackTrace();
            }
        }catch(Exception e){
        Log.e("DATA", "Cannot set image as wallpaper", e);
        }

it's ok!
And you add permission:
 <uses-permission android:name="android.permission.SET_WALLPAPER" />
 <uses-permission android:name="android.permission.SET_WALLPAPER_HINTS" />

A: See if this helps:
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
int height = metrics.heightPixels;
int width = metrics.widthPixels;
Bitmap bitmap = Bitmap.createScaledBitmap(yourimagebitmap, width, height, true);
WallpaperManager.getInstance(MyActivity.this).setBitmap(bitmap);

Source: Android setting wallpaper gone wrong