text:
Q: Saving object to be accessible anywhere I have a condition hereby let's say a user has logged in by calling an API. And the response contain's user's details. Is there anyway we can save the details of the user as an object and be accessible globally? Below is how I used ObjectMapper to call the api
For the model class:
import ObjectMapper

class User: Mappable {

var id: Int?
var userId: Int?
var orgId: Int?
var type: Int?
var email: String?
var lang: String?
var nickname: String?
var status: Int?
var token: String?

required init(map: Map) {
    mapping(map: map)
}

func mapping(map: Map) {
    id <- map["id"]
    userId <- map["userId"]
    orgId <- map["orgId"]
    type <- map["type"]
    failedAttempt <- map["failedAttempt"]
    email <- map["email"]
    lang <- map["lang"]
    nickname <- map["nickname"]
    status <- map["status"]
    token <- map["token"]
}

}
And from my Networking file,
    func postLogin(params: [String: Any], controller: UIViewController, completion: @escaping (User) -> Void) {
    alamofire("/login", method: .post, token: false, params: params, controller: controller) { result in
        if let userDetails = Mapper<User>().map(JSON: result as! [String: Any]) {
            DispatchQueue.main.async {
                completion(userDetails)
            }
        }
    }
}

Some solutions may be using UserDefaults but it's just not practical to be using 9 UserDefaults to save the 9 keys that we got from this response. What are the suggested ways of approach we can go about this where user logged in, we save these details as an object globally and even when after closing the app, the details are not reseted? Thank you all

A: I agree that saving 9 individual keys in UserDefaults is not practical.  But why not encode the whole thing as JSON and save the resulting Data?
extension User: Codable { }

// Assuming user is an instance of User
guard let userJSON = try? JSONEncoder().encode(user) else {
    // handle encoding failure
}

let userDefaultsKeyForUser = "com.yourdomain.snazzyapp.userInfo"

UserDefaults.standard.set(userJSON, forKey: userDefaultsKeyForUser)

I think Swift will automatically synthesize Codable conformance for your User class, but you might need to make it final.  Or implement Codable explicitly.
To retrieve it
guard let userJSON = UserDefaults.standard.data(forKey: userDefaultsKeyForUser) else {
    // Handle missing data (first run maybe?)
}

guard let user = try? JSONDecoder().decode(User.self, from: userJSON) else {
   // Handle decoding failure
}

Alternative encoding/decoding methods
Although conforming to Codable would be the preferred way to do this, that can sometimes be a problem for classes, particularly when inheritance is involved.  In particular Codable is a combination of Encodable and Decodable.  Decodable is the one that is sometimes a problem for classes.  The issue has to do with the required init(from decoder: Decoder) throws having to be declared directly in the class, not in an extension, and then you might have trouble with encoding the super.   If your class is the base class that shouldn't be a problem.  This is mainly a problem when you inherit from AppKit/UIKit classes.
If for some reason User can't conform to Codable, you can use NSCoding instead.  It works a little differently.
In the worst case you could implement methods where you manually encode/decode each property explicitly to data.  You could even store them as binary, but you'll probably need to do something like store byte counts for the strings so you know where each one starts and ends, and you'll need to come up with a scheme to indicate when they are nil in the encoding.  It's not as flexible as JSON, which is why it's a last resort... although I will note that it is much faster.  That wouldn't matter much for your User class, but I wrote a neural network library where I wanted to save the model at checkpoints during training, which meant encoding many layers of very large matrices.  Millions of parameters. Reading and writing the model was about 20x faster with my own binary encoding than letting Codable handle it, even when I had Codable saving it as a binary plist.
A third option would be to re-work your User class.  Either make it a struct, or use a struct internally to store its properties and use computed properties to get and set them in your class.  All of your class's properties already conform to Codable, so Swift can definitely synthesize Codable conformance for a struct with those properties.   If you still wrap the struct inside of a class, then you just have an initializer that takes a Data, and do the same decoding I showed above, to set the wrapped struct, and an encode method (or even a computed var) that encodes the struct as above and returns the Data.
I don't think you'll need these alternate solutions, but I mention them just in case I'm wrong, and because they're useful to know about for future situations.

A: You have to ask yourself how you would like to access this object with compilator autocompletion from different places in your app. Secondly, what is the life span of the object? The object should be accessible during login / logout, app session or app life time?
Let's start with the object life span.

*

*login / logout, the object can be stored in memory

*app session, the object can be stored in memory

*app install / delete, the object should be stored in UserDefaults, Database or a file.

Autocompletion Driven Development aka ADD:
Deciding where to store userDetails object and how to access it
Let's say that you have a logic in a view controller which hide or unhide a view in a initial configuration defined in viewDidLoad. Write some prototype code to decide how you would like to access the 'userDetails' object from different places of the app.
func viewDidLoad() {
   super.viewDidLoad()

   if userDetails.status {
     //userDetails is a global instance of a user object
   }

   if session.userDetails.status {
     //session is a global instance of a Session object which has a property which stores a User instance in userDetails
   }

   if Session.current.userDetails.status {
     // Session is a type and 'current' is a singleton of that type which has a userDetails property which stores an instance of User type
   }

   if User.userDetails.status {
     // User is your type which can have a static property 'userDetails' which stores a User instance
   }

}


text:
Q: MySql join statements returning duplicate data I have a fully normalised database and am running queries through mySql. One of the queries required is to return materials required as well as any associated with a job. I need a result of the following 2 queries combined into one select statement(each in a separate row and ideally making use of joins). This is explained better below:
SELECT m.Material_Name
FROM project_materials pm,materials m
WHERE pm.Fitting_ID =  m.Fitting_ID
AND pm.Project_ID = '2';

Which gives me:
Timber
Bricks

And this:
SELECT sjt.Job_Name
FROM project_staff ps, staff_job_type sjt
WHERE ps.Staff_job_ID = sjt.Staff_job_ID
AND ps.Project_ID = '2';
;

Which gives me:
Brick Layer
Project manager

I tried  to combine them together into one here:
SELECT DISTINCT m.Material_Name, sjt.Job_Name
FROM project_materials pm, materials m, project_staff ps, staff_job_type sjt, projects p
WHERE p.Project_ID = ps.Project_ID
AND p.Project_ID = pm.Project_ID
AND pm.Fitting_ID =  m.Fitting_ID
AND ps.Staff_job_ID = sjt.Staff_job_ID
AND pm.Project_ID = '2';

Which didn't work out well at all since I am getting values which are repeating. I.E. the reply from the database is as follows:
Timber, Brick Layer
Timber, Project manager
Bricks, Brick Layer
Bricks, Project manager

Which results in a reply which keeps getting worse as the data grows!
I also tried using JOIN but got the same result. Here's the code I tried:
SELECT Material_Name, Job_Name
FROM projects INNER JOIN project_staff ON projects.Project_ID = project_staff.Project_ID
              INNER JOIN project_materials ON project_materials.Project_ID = projects.Project_ID
              INNER JOIN materials ON materials.Fitting_ID = project_materials.Fitting_ID
              INNER JOIN staff_job_type ON staff_job_type.Staff_job_ID = project_staff.Staff_job_ID
WHERE project_materials.Project_ID = '2'
;

Inner, left,right or no text in front of the join doesn't make a difference.
Thanks in advance and sorry for the long post
EDIT
I want something like this:
SELECT m.Material_Name
FROM project_materials pm,materials m
WHERE pm.Fitting_ID =  m.Fitting_ID
AND pm.Project_ID = '2'
UNION
SELECT sjt.Job_Name
FROM project_staff ps, staff_job_type sjt
WHERE ps.Staff_job_ID = sjt.Staff_job_ID
AND ps.Project_ID = '2';
;

But instead of union, I want it in a separate column

A: have you tried this:
select m.Material_Name, s.JobName
    from project_materials pm
    join materials m on pm.Fitting_ID = m.Fitting_ID
        and pm.Project_ID = m.Project_ID
    join project_staff ps on pm.Project_ID = ps.Project_ID
    join staff_job_type sjt on ps.Staff_job_ID = sjt.Staff_job_ID
where pm.Project_ID = '2'

The above query is unusable, since materials has no Project_ID. Even if the columns is available in materials, the result is still double, not as expected. Please ignore it.
I think we need a column that relate a record on materials to record on staff_job_type, something like foreign key. Without that column, we will ended up in all-to-all relationship. Project_ID alone will not enough, because it is not unique for materials and staff_job_type. Column staff_job_id will relate staff_job_type with project_staff and column Fitting_ID will relate materials with project_material. No column relate materials with staff_job_type.
material_name job_name        sjt.staff_job_id ps.staff_job_id m.fitting_id pm.fitting_id
------------- --------------- ---------------- --------------- ------------ -------------
Timber        Brick Layer     1                1               1            1
Bricks        Brick Layer     1                1               2            2
Timber        Project Manager 2                2               1            1
Bricks        Project Manager 2                2               2            2

I suggest you to create a table to relate/map materials to staff_job_type. The table should be something like this:
create table material_job (
  fitting_id int,
  staff_job_id int
);

And the table is containing materials and staff_job_type relation:
fitting_id  staff_job_id
----------- ------------
1           1
2           2

with assumption that materials is like:
fitting_id  material_name
----------- --------------------------------------------------
1           Timber
2           Bricks

and staff_job_type is like
staff_job_id job_name
------------ --------------------------------------------------
1            Brick Layer
2            Project Manager

project_materials like
project_id  fitting_id  amount
----------- ----------- -----------
2           1           500
2           2           600

project_staff like
project_id  staff_job_id amount
----------- ------------ -----------
2           1            100
2           2            200

we can use query
select m.material_name, sjt.job_name from material_job mj
    join materials m on mj.fitting_id = m.fitting_id
    join staff_job_type sjt on mj.staff_job_id = sjt.staff_job_id;

resulting
material_name job_name
------------- ---------------
Timber        Brick Layer
Bricks        Project Manager

if you need project_staff and project_material record as well, we can use sql:
select m.material_name, sjt.job_name from material_job mj
    join materials m on mj.fitting_id = m.fitting_id
    join staff_job_type sjt on mj.staff_job_id = sjt.staff_job_id
    join project_materials pm on m.fitting_id = pm.fitting_id
    join project_staff ps on sjt.staff_job_id = ps.staff_job_id;

resulting
material_name job_name        pm_amount ps_amount
------------- --------------- --------- ---------
Timber        Brick Layer     500       100
Bricks        Project Manager 600       200

redpajama_set_name: RedPajamaStackExchange


text:
Q: /admin area and /api in not loading after adding react on my .net core web application My react website routing is cached in the browser and all the website requests are processed by this cached routing.
All requests to /admin area and /api are are not working (redirecting to react web site home page) until I do a hard refresh (CTRL + F5).
I am using ASP.NET Core 2.2 with React.
/admin area is a standard ASP.NET Core MVC.


text:
Q: How can I extract columns of data from a CSV file and define them as x and y variables, then plot them in python using pylab? I've got a CSV file with data such as
350, -0.042447984
349, -0.041671798
348, -0.04158416
347, -0.041811798
346, -0.041716855

Though I've got a lot more data. What I am trying to do is have the first column (350, 349, etc.) be defined as my x-values, and the second column (-0.042447984, -0.041671798, etc.) be defined as my y-values. This is my code so far:
import pylab
x=[350, 349, 348, 347, 346]
y=[-0.042447984, -0.041671798, -0.04158416, -0.041811798, -0.041716855]
pylab.plot(x, y)
pylab.show()

However, instead of manually entering the numbers I'm trying to write a program that will extract column 1 from my CSV file as the x-values and column 2 as the y-values. It's probably something much simpler than I'm trying to make it. I'm new at python, so bear with me!

A: Assuming that your csv file is in the format you've described, I'd probably use loadtxt.
>>> d = numpy.loadtxt("plot1.csv", delimiter=",")
>>> d
array([[  3.50000000e+02,  -4.24479840e-02],
       [  3.49000000e+02,  -4.16717980e-02],
       [  3.48000000e+02,  -4.15841600e-02],
       [  3.47000000e+02,  -4.18117980e-02],
       [  3.46000000e+02,  -4.17168550e-02]])

and there are lots of ways to get x and y from this:
>>> x,y = numpy.loadtxt("plot1.csv", delimiter=",", unpack=True)
>>> x
array([ 350.,  349.,  348.,  347.,  346.])
>>> y
array([-0.04244798, -0.0416718 , -0.04158416, -0.0418118 , -0.04171685])

or x,y = d.T or d[:,0], d[:,1], etc.
The more complicated the format, the better off you are to work with the csv module directly.  Although loadtxt has lots of options, often you need finer control than it gives.

A: This will get you started:
import csv

with open('data.txt') as inf:
    x = []
    y = []
    for line in csv.reader(inf):
        tx, ty = line
        x.append(int(tx))
        y.append(float(ty))

lists x, and y will respectively contain:
[350, 349, 348, 347, 346]
[-0.042447984, -0.041671798, -0.04158416, -0.041811798, -0.041716855]

Notes:
Using with to open the file will take care of closing it when we're done with it or an exception is encountered. The csv module will read the input data line by line and split each line into a list based on the comma separator. The first item is converted to int, the second to float before being appended to the respective lists.
File data.txt contains your sample data.

A: I know this post is rather dated; however, for someone needing to get csv data plotted quickly, the following script will provide a good solution.
It shows how to import the data from the csv file and how to make a plot with matplotlib which will make a png and plot it.
Using the data of Lake Huron without headers, you get a nice plot.
import csv
import matplotlib.pyplot as plt
from numpy import arange

#####################################
# instatiation of variables

filehandle = "lake_huron.csv"
x_data = []                         # makes a list
y_data = []                         # makes a list
png_filename = 'LakeData.png'

#####################################
# opening csv file and reading

my_file = open(filehandle, "rb")    # opens file for reading
data = csv.reader(my_file)          # saves file to variable "data"

#####################################
# saves csv data to x_data and y_data

for row in data:
    x_data.append(eval(row[1]))     # selects data from the ith row
    y_data.append(eval(row[2]))     # selects data from the ith row

#####################################
# closes csv file
my_file.close()                     # closes file

#####################################
# makes plot (show) and saves png

fig = plt.figure()                  # calls a variable for the png info

# defines plot's information (more options can be seen on matplotlib website)
plt.title("Level of Lake Huron from 1875 to 1972")      # plot name
plt.xlabel('Year')                                      # x axis label
plt.ylabel('Lake Level (in feet)')                      # y axis label
plt.xticks(arange(1875,1973,10))                        # x axis tick marks
plt.axis([1875,1973,573,584])                           # x and y ranges

# defines png size
fig.set_size_inches(10.5,5.5)                           # png size in inches

# plots the data from the csv above
plt.plot(x_data,y_data)

#saves png with specific resolution and shows plot
fig.savefig(png_filename ,dpi=600, bbox_inches='tight')     # saves png
plt.show()                                                  # shows plot

plt.close()                                                 # closes pylab


text:
Q: Auth($this->auth->login()) return false in cakephp 2.5.6 $this->auth->login() always returns false.
I must use model PintiplanAutore model
in my view correctly displays the sql query
SELECT PintiplanAutore.idautor, PintiplanAutore.idfacebook, PintiplanAutore.nombre, PintiplanAutore.correo, PintiplanAutore.password, PintiplanAutore.token, PintiplanAutore.imagen, PintiplanAutore.rol FROM pintiplan.pintiplan_autores AS PintiplanAutore WHERE PintiplanAutore.correo = 'aa@aa.com' LIMIT 1
<?php
    echo $this->Form->create('PintiplanAutore',array('action'=>'login'));
    echo $this->Form->input('correo');
    echo $this->Form->input('password');
    echo $this->Form->end('Login');

?>
<?php echo $this->Session->flash('auth'); ?>
<?php echo $this->element('sql_dump'); ?>

appController.php
<?php App::uses('Controller', 'Controller');
class AppController extends Controller {
public $components=array(
'Session',
'Auth' => array(

        'authenticate'=>array(
            'Form'=>array(
                'userModel'=>'PintiplanAutore',
                'fields' => array(
                    'username' => 'correo',
                    'passwordHasher' => 'Blowfish'
                    )
                )
            )

        )
);

public function beforeFilter(){
    $this->Auth->allow('index','verSitio','sitiosPublicos','verSitiosPlan','planesPublicos');
    $this->Auth->loginAction = array('controller' => 'PintiplanAutores','action'=>'login');
    $this->Auth->loginRedirect = array('controller' => 'Nosotros', 'action' => 'index');
}

}
PintiplanAutoresController.php
<?php
   App::uses('AppController', 'Controller');
   class PintiplanAutoresController extends AppController {
      public $components = array('Paginator', 'Session');
      public function beforeFilter() {
        parent::beforeFilter();
        // Allow users to register and logout.
        $this->Auth->allow('add','logout','login');
    }

public function add() {
    if ($this->request->is('post')) {
        $this->PintiplanAutore->create();
        if ($this->PintiplanAutore->save($this->request->data)) {
            $this->Session->setFlash(__('The pintiplan autore has been saved.'));
            return $this->redirect(array('action' => 'index'));
        } else {
            $this->Session->setFlash(__('The pintiplan autore could not be saved. Please, try again.'));
        }
    }
}
public function login(){

        if ($this->request->is('post')){
            //echo debug($this->request->data['PintiplanAutore']['password']);
            debug($this->Auth->login()); die();

        if ($this->Auth->login()) {
            return $this->redirect(array('controller' => 'Nosotros', 'action' => 'index'));
            //return $this->redirect($this->Auth->redirectUrl());
        }

        $this->Session->setFlash(__('Invalid username or password, try again'));

        }
    }
 ?>

Model PintiplanAutore:
<?php
   App::uses('AppModel', 'Model');
   App::uses('BlowfishPasswordHasher', 'Controller/Component/Auth');
   class PintiplanAutore extends AppModel {
     public $primaryKey = 'idautor';
       public $validate = array(
       'nombre' => array(
           'required' => array(
               'rule' => array('notEmpty'),
               'message' => 'A username is required'
           )
       ),
        'correo' => array(
           'required' => array(
               'rule' => array('notEmpty'),
               'message' => 'A correo is required'
           )
       ),
       'password' => array(
           'required' => array(
               'rule' => array('notEmpty'),
               'message' => 'A password is required'
           )
       ),
       'rol' => array(
           'valid' => array(
               'rule' => array('inList', array('admin', 'author')),
               'message' => 'Please enter a valid role',
               'allowEmpty' => false
           )
       )
   );
    public function beforeSave($options = array()) {
    if (isset($this->data[$this->alias]['password'])) {
        $passwordHasher = new BlowfishPasswordHasher();
        $this->data[$this->alias]['password'] = $passwordHasher->hash(
            $this->data[$this->alias]['password']
        );
    }
    return true;
    }
   }

put my user with the action add
I hope someone can help me

A: try with it
$user=$this->PintiplanAutore->findByCorreoAndPassword($yourCorreo_field_getting_from_form);

if($this->Auth->login($user)){

}

A: This works for me without making a query:
if($this->Auth->login($this->request->data)) { ... }


text:
Q: get property from data variable in ajax jQuery I try to get value of the variable what lay in response object(data  variable). Here is what I get when console.log whole data:
 {"comment_id":7,"view": ......

But when I try this to get  comment_id I getting undefined:
console.log(data['comment_id']); // undefined
console.log(data.comment_id); // undefined

What I am doing wrong?

A: You have to parse the JSON string you received in a JSON Object..
see $.parseJSON (if you have jQuery)
or else in pure JS
var mjsn = JSON.parse( your_json );
console.log(mjsn['key']);
// or
console.log(mjsn.key);

A: If it is from an ajax request your content type should be application/json to make that code work
if not parse it

var json = JSON.parse(data);
console.log(json.comment_id);


text:
Q: java application to access amazon simpledb domains I need to make an application in java which would be able to access the domains in simpledb. I have created the account and generated access keys. the tools - sdb explorer, scratchpad, and the sdb tool for firefox are not working. how should I start.

A: You need to specify the correct region and endpoint to which your domain belongs. Amazon SimpleDB supports 8 region end points.
Here is the link :
http://docs.aws.amazon.com/general/latest/gr/rande.html#sdb_region
Here is sample code:
AmazonSimpleDBConfig theConfig = new AmazonSimpleDBConfig();
theConfig.ServiceURL = myEndpoint;  //where myEndPoint is the region endpoint you are interested in
AmazonSimpleDBClient simpleDbClient= new AmazonSimpleDBClient(myKey, mySecretKey, theConfig);
String selectExpression = "select * from LogTable";
SelectRequest selectRequestAction = new SelectRequest();
selectRequestAction.SelectExpression = selectExpression;
selectRequestAction.NextToken = null;
SelectResponse selectResponse = simpleDbClient.Select(selectRequestAction);
SelectResult selectResult = selectResponse.SelectResult;
List<Item> itemList = selectResult.Item;

The same thing is applicable to your third party tool. If you are using SDB Explorer then after successfully logged-in you should see the list of regions and endpoints at left-hand side corner. You should explore the correct region end point in which you can find your created domain.


text:
Q: How to use custom projection in Folium I think Folium uses EPSG3857 by default, but I have a custom .prj file that I need to use. Is there a way to load that in? I'm not reading in the projection file at all right now.
This is my current code:
gdf = gpd.read_file('test.shp')
# gdf_wgs84 = gdf.to_crs({'init': 'epsg:4326'})
gj = json.loads(gdf.to_json())
m = folium.Map(location=[36.6, -119.6], zoom_start=9, tiles=basemap)
folium.GeoJson(gj, style_function=lambda feature: {
    # 'fillColor': feature['properties']['RGBA'],
    # 'color' : feature['properties']['RGBA'],
    'weight' : 1,
    'fillOpacity' : 0,
}).add_to(m)

folium.LayerControl().add_to(m)

# Save map
m.save(save_name("name", ".html"))

A: You can use this solution to convert you .prj file to proj4 string and then use this string to convert your coordinates to lat-lon before plotting with Folium:
import folium
import pandas as pd
import pyproj

#create dataset
data = {'y':[67480.7, 67500.7, 67520.5],
        'x':[220850.6, 220868.4, 220888.7]}

df = pd.DataFrame(data)

# proj4 string
p = pyproj.Proj("+proj=lcc +lat_1=51.16666723333333 +lat_2=49.8333339 +lat_0=90 +lon_0=4.367486666666666 +x_0=150000.013 +y_0=5400088.438 +ellps=intl +towgs84=-99.059,53.322,-112.486,0.419,-0.830,1.885,-1")

def convert_to_LatLon(df, p):
    lon, lat = p(df['x'], df['y'], inverse=True)
    df['lat'] = lat
    df['lon'] = lon
    return df

df = df.apply(convert_to_LatLon, p=p, axis=1)
df.head()

# change location and zoom accordingly
m =folium.Map(location=[49.914623, 5.355284], zoom_start=16, max_zoom=25)
for index, row in df.iterrows():
    lat, lon = row[['lat', 'lon']]
    folium.CircleMarker(
        radius=5,
        location=[lat, lon],
        popup=index,
        color='crimson',
        fill=False,
    ).add_to(m)
m


text:
Q: What is an Enterprise architecture? I am a web developer, I want to become software architect, and I learn everyday about it, but when I am learning software architecture I see TOGAF framework for enterprise architecture, I want to get solid understand in an enterprise architecture.

A: Overview
Enterprise architecture focuses on the future state solution for : Current business problem , business strategy , business process improvement (BPI), business process re-engineering and business adventures. If you ask one enterprise architect what they are working on, most likely you are going to find out that they are working on one of these areas, unless they have a more specialized domain, which we cover later in this article.
"The What"
Enterprise Architecture does not prescribe the "how" only the what,
Deliverables
Depending on your company solution lifecycle standards and templates, your deliverable may be called "solution architecture", "Enterprise Architecture blueprint" or some other name.
Architecture layers
It is a good practice to include in your deliverable minimum six architecture layers:

*

*Security: End to end view of your solution from security perspective, this captures authentication and access management, data in transit and at rest protection.

*Application: A view  of your solution from the application perspective, includes domain specific programming language, and application design patterns and decisions for your font end, back-end and middle tier.

*Infrastructure: This layer shows a view of your running platform, it may include cloud, containerization and virtualization.

*Information: This captures your entire information lifecycle management from data modeling to acquisition, classification, and retirement.

*Network: This architecture layer depicts the network end points and their paths.

*Integration: This layer shows your data transportation and systems conversations, for example it shows your separations of data transportation from orchestration.

While these layers are not the only layers hat you can add to your architecture, you can add more as needed for example "business continuity" and "devops", but all depends on the  type of your organization and objectives.
The Enterprise Architect role
Being an Enterprise Architect (EA) entails command in multiple domains ,  however most of us in this industry started our careers in one domain such as development, networking, DBA, etc,  an architect usually have expertise in at least one of the following and experience in the rest.

*

*Expertise in one programming language (expert level means very familiar with the language and design patterns specific to the language).

*Expertise in one database vendor ( Oracle, MSSql, DB2) expert level means  -  - Expertise in SQL , SQL:2016 being the latest standard in addition to server side language (PLSQL, TSQL)

*Experience in networking basic concepts of networking and knowledge of new trends such as software defined networks (SDN).

*Experience in integration patterns

*Experience in infrastructure such as cloud , virtualization and containerization

*Experience in information security: Identity and access management , Data in transit and data at rest protection.

In addition basic knowledge in : Data modeling, data warehousing, big data, Web UI frameworks, major cloud providers, compliance (ie: PCI, HIPPA), IPV4, IPV6, SOA.
And also helps if you have your own vision of the future landscape (ie: server-less , self-rendering services )
Architecture frameworks
There are multiple frameworks that depending on the situation may fit in your deliverables, these frameworks try to address the common architecture patterns in a prescriptive way.

*

*TOGAF

*Zachman

*DoDAF

To answer your question " what s the difference between system architecture, application, software architecture":
Application architecture is one of the layers in your architecture.
System architecture, software architecture, solution architecture can be used interchangeably. Just don't lose your the big picture .

Some of the inputs for the architecture are

*

*business strategy.

*use cases

*business cases.

*Business continuity strategy

*Compliance
Some of the outputs are

*High level designs
A vertical partition) of your architecture layers.

*Software specifications
A prescriptive and technology oriented specifications of your solution.

A: I have presented on Enterprise Architecture a few times over the past couple of years. One of the quotes (from myself) that I use in my talks is: "Just because I am an Enterprise Architect, that does not mean that I am an Enterprise Architect". That might seem like a strange quote but it's basically just a fun way to say that enterprise architecture can mean different things to different organizations and people.
Enterprise architects tend to work across a broad domain of concerns, occasionally focusing on specific aspects of a specific technology and/or business process. Some organizations (they tend to be the ones with a more mature EA practice) will have architects that work across all domains within the organization (or, enterprise - hence enterprise architect). Some organizations will have specific types of architects (e.g. applications architect, solutions architect, data architect, network/systems architect, business architect, etc.) that focus on a particular area. Having various types of architects within an organization is one way to "ease" yourself into the architecture space.
For example, the organization I work for has the role, Lead Developer. Each development team has a lead developer and they essentially act as applications architects (even if that is not their specific title). For someone new to that role, they focus on learning the business domain their team is typically responsible for. They also provide the overall architectural vision and design for the apps their team produces. And, they also work closely with the enterprise architects to ensure they are working within the parameters of the organization as a whole (i.e. not reinventing the wheel or making use of a technology or approach that does not fit within the enterprise architecture as a whole).
Starting out as a lead developer is one way to get your foot in the door, so to speak. There are other ways. For example, if you're interested in data architecture, then joining a BI team would be a great way to learn more about data architecture at scale. Joining a network team would go a long way toward gaining knowledge that could be applied as a network/systems architect.
You mention TOGAF in your question above but there are many architectural frameworks out there (TOGAF, Zachman, DoDAF, etc.). Depending upon your specific situation, a "canned" framework might make sense for your organization and it might not. However, becoming familiar with some of the available frameworks will give you insights into some of the common challenges faced by enterprise architects. In the end, however, you will want to do what is right for your organization. You might take bits and pieces from multiple frameworks and wrap them all up into your own framework. As with many challenges, do what works for you.
Along with everything else, keep in mind that enterprise architects tend to think strategically and keep a focus on the future. That does not mean that they do not think tactically or are not concerned with the "here and now". They just tend to have strengths when it comes to strategy and vision.
While this is a bit of a wordy answer, the reality is that nothing beats experience. If you want to become an enterprise architect then you should try to apply architectural practices to your everyday tasks. The more you work and act like an enterprise architect the more ready you will be when an opportunity presents itself.
Hope this helps!

A: If you want to be a software architect - aka Application Architect, then TOGAF is useful to know, but not necessary for you. Enterprise architects deal with things that impact the entire organisation, particularly things like Strategy & Planning. Organisational modelling, etc.
They can be sometimes involved as a governance role to ensure alignment with organisational design standards, or security standards. They can also sometimes be involved in setting organisational policy.
Either way - too many people assuming taking the "most senior looking" title will get them the best pay and the best life - this is not always true and an EA role is very very different to a software architect - even though they are both "Architects"
Now getting a solid understanding of Enterprise Archtiecture will be a challenge - because 1. its kind of undefined right now - or more accurately - there is around 460+ different models of what an Enterprise Architecture is - TOGAF only being one of them. 2. Most EAs like to get completely OCD around model definitions, and each one has a different OCD point of view exactly what they are - I should know, I'm one of them :)
One of the best general models I have found is DoDAF, but it sure isn't light bedtime reading. Wikipedia has a reasonably light definition though and it might be worth starting there if you haven't already

A: Enterprise Architecture (EA) entails the whole organization and possibly beyond. It includes Business Architecture, Information Architecture, Technology Architecture & Application Architecture. EA is strategic and thus it is "What" needs to be done.


text:
Q: Automize array object display from array database I have an array containing 10 objects. Each contains a question string, a correctAnswer string, and an object with 4 answer strings:
const DB = [
{
  question: "some question",
  answers: ["a", "variety", "of", "choices"],
  correctAnswer: "variety"
}, ...

I have a function which captures the user's answer via radio button input, and saves it in a variable:
function feedbackPage(){
  $('.js-quizform-questions').on('click', '.js-button-next', function(event){
    event.preventDefault()
    let yourAnswer = getFeedback()
    $('.js-feedback-page').show().html(evalCorrectAnswer(DB))
  })
}

You see that evalCorrectAnswer reaches out to the above database for validation. At the moment i am only able to display and validate the hardcoded first answer, which is dynamically generated like this:
function generateQuestionElement(item) {
  return `

${item[0].question}

    <form id='form'>
        <fieldset>

                <input id='answer1' type='radio' name='answer' required>
                ${item[0].answers[0]}

                <input id='answer2' type='radio' name='answer' required>
                ${item[0].answers[1]}

I need a way to automatically choose the first question, to include its answers and display it via generateQuestionItem. Then I need to take that question (& its answers) out of the pool and display the next question once i click on a Next button on the eval page. I have a hard time implementing this feature in an object-oriented way.
Codepen

A: Construct a variable of
let questionNumber = 0

Then update the following line inside renderQuestion:
${DB[questionNumber].answers[0]}

Later create a function that updates questionNumber at each appropriate point.


text:
Q: Combining ArrayList without duplicates import java.util.ArrayList;
import java.util.Collections;

public class SmartCombining {
    public static void main(String[] args) {
        ArrayList<Integer> list1 = new ArrayList<Integer>();
        ArrayList<Integer> list2 = new ArrayList<Integer>();

        Collections.addAll(list1, 4, 3);
        Collections.addAll(list2, 5, 10, 4, 3, 7);

        smartCombine(list1, list2);
        System.out.println(list1);
        System.out.println(list2);
    }

    public static void smartCombine(ArrayList<Integer> first,
            ArrayList<Integer> second) {
        first.addAll(second);
    }
}

So, I want to combine two lists into one, but if the second list contains a number from the first it won't be added. So far my method adds them all together.

A: Well, one way to do it is to iterate through the second list while checking if each element exists in the first list. If it doesn't, add it.
public static void smartCombine(ArrayList<Integer> first, ArrayList<Integer> second) {
     for(Integer num : second) {      // iterate through the second list
         if(!first.contains(num)) {   // if first list doesn't contain current element
             first.add(num);          // add it to the first list
         }
     }
}

Another way would be for you to hold your values inside a set (like HashSet) which doesn't allow any duplicates. Then you can combine them like:
first.addAll(second);

One more way you could do it is to first remove all elements from the first list that exist in the second list (the ones that would be duplicated). Then you add all elements of the second list to the first list.
public static void smartCombine(ArrayList<Integer> first, ArrayList<Integer> second) {
    first.removeAll(second); // remove elements that would be duplicated
    first.addAll(second);    // add elements from second list
}

A: The simple, no brains solution:
Set<Integer> joinedSet = new HashSet<Integer>();
joinedSet.addAll(list1);
joinedSet.addAll(list2);

A: Remove duplicates, then merge both lists:
list1.remove(list2);
list1.addAll(list2);

If you dont want to alter the original list, then first create a backup:
list1BP = new ArrayList(list1);

Another approach is to use HashSet, see other answers.

A: Use Set, it has been created for that purpose. A Set cannot contain 2 identical elements, based on the equals method.
Set<Integer> list1 = new HashSet<Integer>();
Set<Integer> list2 = new HashSet<Integer>();

Using a combination of ArrayList and contains method is an antipattern here.

A: There are two easy way you can combine two Lists and duplicate will be removed.
1) First and very easiest way you can get your output, by creating equivalent HashSet object of your ArrayList. Since HashSet does not allow duplicates.
public static void main(String[] args) {
    ArrayList<Integer> list1 = new ArrayList<Integer>();
    ArrayList<Integer> list2 = new ArrayList<Integer>();

    Collections.addAll(list1, 4, 3);
    Collections.addAll(list2, 5, 10, 4, 3, 7);
    System.out.println(smartCombine(list1, list2));
}
public static HashSet<Integer> smartCombine(ArrayList<Integer> first, ArrayList<Integer> second) {
    first.addAll(second);
    HashSet<Integer> hs = new HashSet<Integer>(first);
    return hs;

2) There is another way using advanced for loop. Iterate the second list  and check if the current element is not in first list and then add the current element.
public static void main(String[] args) {
    ArrayList<Integer> list1 = new ArrayList<Integer>();
    ArrayList<Integer> list2 = new ArrayList<Integer>();
    Collections.addAll(list1, 4, 3);
    Collections.addAll(list2, 5, 10, 4, 3, 7);
    smartCombine(list1, list2);
    System.out.println(list1);
}
public static void smartCombine(ArrayList<Integer> first, ArrayList<Integer> second) {
    for (Integer num : second) {
        if (!first.contains(num)) {
            first.add(num);
        }
    }
}

Note: The second way will work fine only if first list has no duplicates.

A: use contains(Object) method in ArrayList
public static void smartCombine(ArrayList<Integer> first,
        ArrayList<Integer> second) {
    for(Integer i :second){
       if(!first.contains(i)) { // if first list doesn't contain this item, add item to the first list.
          first.add(i);
       }
    }
}

A: Have you tried ArrayList.addAll()
Look at this java doc
As pointer out this would not handle duplicates which can easily be removed using a Set


text:
Q: How to stop Starling and re-initiate for a book reading app? I have two classes named Startup.as & RacTest.as
Here Startup.as is the main class, where i initiated the starling.
this.starling = new Starling(RacTest, stage, new Rectangle(xOffset, yOffset, adjustedScreenWidth, adjustedScreenHeight));

RacTest.as serves as the engine for the app and reads a particular book for which i gave a specific path.
It works perfectly. Now i need to press back button to quit the engine and re-initiate the RacTest.as to read the another book.
NativeApplication.nativeApplication.addEventListener(KeyboardEvent.KEY_DOWN, onKeyDown, false, 0, true);

public function onKeyDown(event:KeyboardEvent):void
        {
            if(event.keyCode == Keyboard.BACK )
            {
                event.preventDefault();
                event.stopImmediatePropagation();
RacTest.gameInstance.removeChild(RacTestApp.gameInstance.imageContainer);
                RacTest.gameInstance.bgSoundChannel.stop();
                RacTest.gameInstance.sceneIntSoundChannel.stop();
                RacTest.gameInstance.sceneLoadSoundChannel.stop();
                Starling.current.stop()
            }
        }

Thanks in advance..

A: Just use these following codes to dispose starling completely.
this.starling.stop();
this.starling.dispose();
this.starling = null;


text:
Q: What years does "The Peripheral" take place in? I recently read The Peripheral by William Gibson, and I had fun trying to keep track of when it could have taken place (similarly to Neuromancer, it's vague). I have some guesses, but does anyone have the definite years it takes place (possibly something I missed in the book, or possible to work out)? If not, what are the possible year-ranges the book could take place in?

A: 2096 - 2138(ish)
In the book, there is a passing reference to the protagonist's receiving a souvenir from Clanton's bicentennial when she was 8 years old.

She found herself looking at the plastic tray propped on the
  mantelpiece, the one with the aerial-view cartoon map from Clanton's
  bicentennial year. Her mother had driven the three of them over for
  the celebrations, when she was eight. She remembered it, but it seemed
  like somebody else's life.

Assuming she's in her 30's, this places the lower bound in the late 2090s.

There was the mantelpiece, the one with the commemorative plastic tray whose duplicate he'd seen in Clovis Fearing's shop in Portobello Road, a pale oblong propped against the wall. He rolled forward, the camera bobbing annoyingly, until he could make out "Clanton Bicentennial," and the dates. And seventy-some years on from the year of celebration, he sat at Lev's grandfather's desk in the Gobiwagen

This places the upper bound in the 2130s.

A: 2132 in the parent timeline (the "big stub," Wilf's timeline).
Now that Agency is out, the dates are much clearer.  Agency takes place in 21361 and, according to Conner Penske, 4 years have passed2 since the events of The Peripheral.  Hence The Peripheral happens in 2132 in Wilf's timeline.
(Note that it's established several times that time passes at the same rate in the "big stub" as all the other stubs.  Examples: "a fixed ratio of duration with their continuum: one to one."3 and "a one-to-one temporal ratio"4)
2061 in Flynne's timeline ("the county").
Wilf refers to Flynne's timeline as "seventy-some years earlier"5 and "seventy-some years before"6 and when Flynne relates her briefing by Wilf and Ash to Burton he asks "Just over seventy years?"7  But we can be more accurate than that.  In Agency, Ash says Conner is staying in Washington with Leon: "This is Leon's first year in office, so it's helpful for him to have someone from home."8   That places the date in the year following a U.S. election year.  U.S. election years around 70 years previous to 2132 are 2052, 2056, 2060, 2064; a year after those election years are 2053, 2057, 2061 and 2065, differences of 79, 75, 71 and 67 years.  Only 1 of those numbers, 71, would be "just over seventy."
However, there are a few inconsistencies in the story, primarily the ages of Lowbeer and Clovis Fearing.  In The Peripheral when we meet Clovis and Griff in Flynne's stub, they are respectively "a little older"9 than and "not quite as old"10 as she.  But in Agency they are both "a hundred and twenty-something,"11 which would make Flynne 50-plus, given a 71-year difference between the timelines, which she obviously is not.  (Note that this is the only inconsistency with their ages; in Agency Lowbeer is said to be "a child" in 2017,11 which fits with an age of 120-something in 2136.)
There is also some confusion about the timing of the jackpot.  Wilf regularly refers to Flynne's timeline as "pre-jackpot" or "the far side of the jackpot"6 but there are also references to the jackpot starting earlier than 2061: "midcentury, just as the jackpot really got going"12 and elsewhere being underway by the 2040s.
The date of the Clanton Bicentennial (presumably 2068, since there is only 1 Clanton listed in my gazetteer) is also problematic; if Flynne were 8 at that time,13 she would be 27 (her most probable age14) around 2088, only 44 years distant from Wilf's time.  This date can't be right, since that would be deep into the jackpot and the devastation would have had a major and obvious effect on Flynne's timeline by then.  (Even the fact that Wilf thinks it's "seventy-some years on from the year of celebration"15 is either an error on his part or the editor's, since it directly contradicts the 70-year span given by multiple characters.  But it works if it should have been "ninety-some.")
1 Agency ch. 53 "Over London"
2 Agency ch. 61 "Continental Breakfast"
3 The Peripheral ch. 24 "Anathema"
4 Agency ch. 63 "Users"
5 The Peripheral ch. 20 "Polt"
6 The Peripheral ch. 12 "Archaism"
7 The Peripheral ch. 45 "Up There"
8 Agency ch. 63 "Users"
9 The Peripheral ch. 81 "Alamo"
10 The Peripheral ch. 87 "The Antidote for Party Time"
11 Agency ch. 73 "Singularity"
12 The Peripheral ch. 12 "Thylacine"
13 The Peripheral ch. 59 "Adventure Capitalists"
14 The Peripheral ch. 13 "Easy Ice"
15 The Peripheral ch. 98 "Bicentennial"


text:
Q: For loop not working properly in batch file I am trying to get the current operating system using this batch file. It is:
@echo off
for /f "skip=1 tokens=1* delims= " %%a in ('wmic path win32_operatingsystem get caption') do set _os=%%a %%b %%c %%d
echo You are running %_os%.
goto :eof

My operating system is windows 7 so I expected it will return:
You are running Microsoft Windows 7 Ultimate.

But it returns you are running %c %d.
Why I am getting this result?

A: There are a few ways, one already posted by Mofi in the above comment which already demonstrates the main change using /value. You can also use the caption itself as variable name with its value:
@echo off
for /f "delims=" %%a in ('wmic path win32_operatingsystem get caption /value') do set %%a>nul 2>&1
echo %caption%


text:
Q: SpriteKit Two Objects bouncing. So, I have a game in SpriteKit that involves to circular objects, and one is controlled by the player.
Problem:
When the player taps or drags along the screen, the first object is moved along with it.
 The second object is not controlled by the player or computer, but is to be a physics object that can be bounced around. However, Enabling the physics bodies only lets me push it around, but it won't bounce. I have set the restitution of both bodies to 1.0, and the friction to 0.0. There is no gravity. The way I am moving the player object is by calling the runAction on a move action when the player taps or drags, and that seems to let the second object be pushed around. I feel like I'm missing something, probably obvious.

A: Using SKAction move will only make your node move to a specific point. If you want your player node to be moved in the direction of the touchPoint, then you need to use applyImpulse. Here's how you can achieve that:
Look up the shooting projectiles section in the tutorial by Ray Wenderlich here:
http://www.raywenderlich.com/42699/spritekit-tutorial-for-beginners
Copy the rwAdd, rwSub, rwMult, rwLength and the rwNormalize methods from the tutorial.
Then, in your -touchesEnded method:
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {

    // 1 - Choose one of the touches to work with
    UITouch * touch = [touches anyObject];
    CGPoint location = [touch locationInNode:self];

    // 2 - Set up initial location of projectile
    SKSpriteNode * projectile = [self childNodeWithName:@"desirednode"];
    //make projectile variable point to your desired node.

    // 3- Determine offset of location to projectile
    CGPoint offset = rwSub(location, projectile.position);

    // 4 - Get the direction of where to shoot
    CGPoint direction = rwNormalize(offset);

    // 5 - Make it shoot far enough to be guaranteed off screen
    float forceValue = 200; //Edit this value to get the desired force.
    CGPoint shootAmount = rwMult(direction, forceValue);

    //6 - Convert the point to a vector
    CGVector impulseVector = CGVectorMake(shootAmount.x, shootAmount.y);
    //This vector is the impulse you are looking for.

    //7 - Make the node ignore it's previous velocity (ignore if not required)
    projectile.physicsBody.velocity = CGVectorMake(0.0, 0.0);

    //9 - Apply impulse to node.
    [projectile.physicsBody applyImpulse:impulseVector];

}

The projectile object in the code represents your node. Also, you will need to edit the forceValue to get the desired impulse.


text:
Q: using getdate() in sql server to get date as "27Aug13"? Query to get the below as output is required.
How can I get ouput as 27AUG13 in SQL SEVER?
Please suggest

A: The following will have spaces:
SELECT CONVERT(VARCHAR,GETDATE(),6)

You can replace spaces:
SELECT REPLACE(CONVERT(VARCHAR,GETDATE(),6),' ','')

A: It's a bit of a hack, but the following works:
  SELECT replace(convert(varchar(10), getdate(), 6), ' ', '')

The internal convert(varchar, getdate(), 6) returns (at least, today) "28 Aug 13", with the replace then removing the spaces.

A: Perhaps (works also in SQL-Server 2005 without DATE):
SELECT CONVERT(VARCHAR(12), GETDATE(),6) AS [TodaysDate]

DEMO 28 Aug 13


text:
Q: myParticleEmitter weirdness (creates artifact at 0.0) while drawing from point A to point B A little weirdness here, I have a particle emitter added to an SKShapeNode
(the particles should follow the line)
yet when it does it also has a bit of particle system sitting at 0,0
Ive moved it up a little so you can see it better
Any thoughts to how this might be happening?,
I'll post the code below, but still I cant find anything, I have tested with other textures setting setStrokeTexture -  incase the line is making some sort of sneaky extra part - but no it seems fine....and creates a line between the sprites...
in LinkWithNumberClass //SKSpriteNode SKPhysicsContactDelegate
if (isUsingParticles == YES) {

    //create new line
    SKShapeNode*lineNode02 = [SKShapeNode node];
    lineNode02.lineWidth = 10;
    lineNode02.name = @"lineNode";

    //clear line of colour
    lineNode02.fillColor = [SKColor clearColor];
    lineNode02.strokeColor = [SKColor clearColor];

    //create the path the line follows (line joins two sprites)
    CGMutablePathRef pathToDraw = CGPathCreateMutable();
    CGPathMoveToPoint(pathToDraw, NULL, spriteA.position.x, spriteA.position.y);
    CGPathAddLineToPoint(pathToDraw, NULL, spriteB.position.x, spriteB.position.y);
    lineNode02.path = pathToDraw;
    [self addChild:lineNode02];

    //Add Particles
    myParticlePath = [[NSBundle mainBundle] pathForResource:_parName ofType:@"sks"];
    myParticleEmitter = [NSKeyedUnarchiver unarchiveObjectWithFile:myParticlePath];
    [self addChild:myParticleEmitter];

     CGFloat distancebtween = SDistanceBetweenPoints(spriteA.position, spriteB.position);
    myParticleEmitter.particlePositionRange = CGVectorMake( particleLength,0 );
    myParticleEmitter.position = CGPointMake(distancebtween/2, +10);
    self->myParticleEmitter.targetNode = self.scene;

    int particleTime = 3;
     SKAction *followTrack =
     [SKAction followPath:pathToDraw
     asOffset:YES
     orientToPath:YES
     duration:particleTime];

     SKAction *forever = [SKAction repeatActionForever:followTrack];
     self->myParticleEmitter.particleAction = forever;
}

In Game Layer
    -(void)addStaticLinkedSpriteWithParticles
{
    twoSpritesWithParticlesBridge =
    [[LinkWithNumber alloc]initWithlinkSpriteA:@"Object"
                                       spriteB:@"Object"
                             andPlistAnimation:@"Aniamtions"
                                   distbetween:100
                                  hasParticles:YES
                                ParticlesNamed:@"Fire"];
      [self addChild:self->twoSpritesWithParticlesBridge];
}

With thanks :)
Natalie.

A: In the end I go it to work not needing to draw a line at all.

*

*Create particle system Position on SpriteA

*find distance between
the two sprites (to get length for particles)

*Adjust length of the particles in emitter properties

*reposition the
particles so they are centered between the two sprites
    if (isUsingParticles == YES) {

//create particles
myParticlePath = [[NSBundle mainBundle] pathForResource:_parName ofType:@"sks"];
myParticleEmitter = [NSKeyedUnarchiver unarchiveObjectWithFile:myParticlePath];
[self addChild:myParticleEmitter];//try moving it to the line node

//find length needed for particles
 CGFloat distancebtween = SDistanceBetweenPoints(spriteA.position, spriteB.position);

//Adjust length of particles
myParticleEmitter.particlePositionRange = CGVectorMake( particleLength,0 );

//center particles between the two sprites
myParticleEmitter.position = CGPointMake(spriteA.position.x+distancebetween/2, spriteA.position.y);
myParticleEmitter.targetNode = self.scene;

}
Hope it helps someone else :)


text:
Q: Is there a tool to easily convert text files to JSONL documents? I have several fairly large .txt files that I need to convert to JSONL documents so that I can prepare training data and upload files into an OpenAI environment.
I searched for various free web-based sites and conversion tools and could not find anything that actually worked.


text:
Q: Copy all rows from each sheet I need help with the code. I want to merge all rows from few sheets except header in one sheet in Excel.
Here is the code:
Dim ws As Worksheet
Dim sh As Worksheet
Set sh = Sheets("P&L_consolidation")

For Each ws In Sheets
    If ws.Name <> "Zero's" Then
       ws.Range("A2", ws.Range("U"& Rows.Count).End(xlUp)).Copy sh.Range("A"& Rows.Count).ENd(xlUp)(2)
    End if
Next ws

This code works if the sheet has some data in it, but the problem is if some sheet contains only header then this code copy that header and paste it to the merged sheet. In that case I just want to skip that sheet.
Please, can somebody help me?

A: Something like this should work for you:
Sub tgr()

    Dim wb As Workbook
    Dim ws As Worksheet
    Dim wsDest As Worksheet

    Set wb = ActiveWorkbook
    Set wsDest = wb.Worksheets("P&L_consolidation")

    For Each ws In wb.Worksheets
        If ws.Name <> "Zero's" Then
            With ws.Range("A2", ws.Cells(ws.Rows.Count, "U").End(xlUp))
                If .Row >= 2 Then .Copy wsDest.Cells(ws.Rows.Count, "A").End(xlUp).Offset(1)
            End With
        End If
    Next ws

End Sub


text:
Q: Negative Binomial distribution as a Gamma mixture distribution Let $f(x;\theta)$ be the poisson frequency function with mean $\lambda$. and $p(\lambda)$ the Gamma distribution with mean $\mu$,  and variance $\mu^2/\alpha$.
I have to show that $g(x)=\frac{\Gamma(x+\alpha)}{x!\Gamma(\alpha)}\left(\frac{\alpha}{\alpha+\mu}\right)^{\alpha}\left(\frac{\mu}{\alpha+\mu}\right)^{x}$.
However, from my calculations:
$\displaystyle g(x)=\int f(x;\theta)p(\lambda) d\lambda=\int\frac{e^{-\lambda}\lambda^x}{x!}\cdot\frac{\mu^{\alpha}\lambda^{\alpha-1}}{\Gamma(\alpha)}e^{-\mu\lambda}d\lambda
= \frac{\Gamma(\alpha+x)}{x!\Gamma(\alpha)}\left(1/(\mu+1\right))^{x+\alpha}\mu^{\alpha}$, where the last equality is obtained by doing a coordinate change to $z=\lambda(\mu+1)$
So where did I go wrong?
Any help will be appreciated.

A: First make sure your parameters for the Gamma distribution are correct:
$G(a,b)$ has mean $ab$ and variance $ab^2$. Hence you have:
$$
ab = \mu \\
ab^2 = \mu^2/\alpha
$$
Solve to get:
$$
a = \alpha \\
b = \mu/\alpha
$$
Hence your integral should be:
$$
\int_0^\infty \frac{e^{-\lambda} \lambda^x}{x!} \frac{\lambda^{\alpha-1}e^{-\frac{\alpha\lambda}{\mu}}}{(\mu/\alpha)^\alpha \Gamma(\alpha)} d\lambda
$$
Try to solve this from here.


text:
Q: How to catch c3p0 and JPA exceptions? I got this app where the user must connect the DB manually, I do that with this line
EntityManagerFactory emf = Persistence.createEntityManagerFactory("persistenceUnit", connectionProperties);

when the user/password is incorrect or the host timeouts due to wrong url C3P0 breaks the connection
then I get these in console
com.mchange.v2.resourcepool.BasicResourcePool$AcquireTask, 1853 - A RESOURCE POOL IS PERMANENTLY BROKEN! [com.mchange.v2.resourcepool.BasicResourcePool$AcquireTask@18e3f02a]

THE PROBLEM: I can't capture that exception so I can translate it to a user friendly message on screen, it is like emf is always created and I got no way to tell when is broken or not
UPDATE: I found on Hibernate http://docs.jboss.org/hibernate/entitymanager/3.5/reference/en/html/transactions.html#transactions-demarcation-exceptions
But I surrounded my emf with EVERY single try catch possible and still can't catch a thing

A: The JPA spec says that Persistence.createEntityManagerFactory will return null if a persistence-unit can't be instantiated (and states nothing about possible exceptions). Consequently it's as much use as a chocolate teapot for detecting the reason programmatically. Complain to the people who wrote the JPA spec.

A: I know this is an old thread.
But I was trying to do exactly the same as you.
I did a big search and could not find the answer, even you posted this a long time ago and got no answer.
Well.. what happens is that most Hibernate code catches exceptions and put it into a local exception list.
For example, take a look at org.hibernate.tool.hbm2ddl.SchemaUpdate.execute() where it catches all jdbc exceptions and put them on exceptions list.
Unfortunately, the code that uses this class lose track of these exceptions since the objects are not referenced anymore.
All exceptions are logged though.. but I find this behavior really annoying since I'm a control freak. The idea of putting exceptions on a list is very good for a framework. But if the other end can't use it.. it's just code bloat and it makes you wast time analyzing why you can't get the God damn exception (For those who never give up).
What I do is perform some basic start up operations on the database and when I get a query exception, then I know something is wrong. The error page in the servlet is more generic but doesn't give the user the impression that the system has lots of bugs (hehe, this sounded wrong).
Ah.. just a remark. It's not a JPA specification problem (like DataNucleus said) since if you use hibernate's native initialization, it's the same. Although I really think JPA lacks of initialization exceptions.


text:
Q: Printing out an array I am printing out an array to a .txt file. I have not discussed the array definition/formulation here, because its complex.
To give a background, its a 2D array and I wish to write the data from the array to another file on my computer. I am using the following code. The problem is I am unable to compile the code and the error points to this section of the code. Could anyone please point out what is wrong in the data implementation with this?
   ofstream outFile;
   outFile.open("matrix.txt");

   for (int i=0; i<6; i++){
    for (int j=0; j<3; j++){
    ofstream << matrix[i][j];
    }}
   outFile.close();


text:
Q: XML reading child nodes I have an XML document and I am trying to get the childnodes of an element called Unit
My XML Doc is layed out like so:
<Unit>
    <id>3</id>
    <name>System Information</name>
    <description>null</description>
    ... other ...
</Unit>

This is the code I am using to try and read them.
public void Load()
{
    FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
    XmlDocument xmldoc = new XmlDocument();
    XmlNodeList xmlnode;

    xmldoc.Load(fs);
    xmlnode = xmldoc.GetElementsByTagName("Units");

    for (int i = 0; i < xmlnode.Count; i++)
    {
        string str = string.Format("ID: {0}\r\nName:{0}", xmlnode[i].ChildNodes.Item(0).InnerText, xmlnode[i].ChildNodes.Item(1).InnerText);
        MessageBox.Show(str);
    }
}

But the problem is, when I try and get them, instead of getting item 0 or item 1, it displays all the items and not the items i have selected.

A: With Linq to Xml you can easily parse your xml into (anonymous) strongly typed objects:
public void Load()
{
    FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);

    var xdoc = XDocument.Load(fs);
    var units = from u in xdoc.Descendants("Unit")
                select new {
                   Id = (int)u.Element("id"),
                   Name = (string)u.Element("name")
                };

    foreach(var unit in units)
    {
       // thanks God for IntelliSense!
       MessageBox.Show(String.Format("ID:{0}\r\nName:{1}", unit.Id, unit.Name));
    }
}

Well, actually if you only need to show those values in message box, you can even write all code in one line. But I prefer first approach, when retrieving data and displaying them are separated (ideally in separate methods):
XDocument.Load(filePath)
         .Descendants("Unit")
         .Select(u => String.Format("Id:{0}\nName:{1}", (int)u.Element("id"), (string)u.Element("name"))
         .ToList()
         .ForEach(MessageBox.Show);

A: You have a typo in element name: should be Unit instead of Units.
However, have you tried using LINQ to XML instead of XmlDocument?
public void Load()
{
    var doc = XDocument.Load(filePath);

    foreach(var unit in doc.Descendants("Unit"))
    {
        string str = string.Format("ID: {0}\r\nName:{0}", unit.Element("id").Value, unit.Element("name").Value);
        MessageBox.Show(str);
    }
}

A: As I can see from your xml and code. You have error in line:
 xmlnode = xmldoc.GetElementsByTagName("Units");

change it on:
 xmlnode = xmldoc.GetElementsByTagName("Unit");


text:
Q: Firefox can't connect to a local site, but Chrome can I have a web server running locally that's mapped to project.name.localhost:3011 on a MacOSX box.  My /etc/hosts defines:
127.0.0.1  project.name.localhost
I need to browse to this server in Chrome and Firefox.  Chrome works great when I visit http://project.name.localhost:3011/.  Firefox gives an "Unable to connect" connect error.  I can see in my local server's console that no connection attempt was even sent to the server when I try from FF.
This is on FF version 59.0.2 (64-bit).  FF has no problem with public internet sites like this one, and google.
I've already tried all of the steps suggested here:
https://support.mozilla.org/en-US/kb/firefox-cant-load-websites-other-browsers-can
In summary, those steps are:

*

*Check proxy settings, verify proxy is turned off

*Set network.dns.disableIPv6 to true in about:config

*Set network.dns.disablePrefetch to true in about:config

*Cleared all history, including cookies and cache

Also tried disabling HSTS as described here:
https://support.mozilla.org/en-US/questions/1204380
ping project.name.localhost

works just fine also.  There is no local DNS issue.
http://127.0.0.1:3011/ gives me the exact same error as using the hostname.  However, I need to access the server via a hostname.  It is not and should not be configured to respond on a direct IP.
How can I get FF to hit my local web server via a hostname?
EDIT:  Two co-workers experienced what they describe as the same problem when they setup their systems, but they both said "it just went away on its own" after a day or two.  My problem has persisted across weeks and reboots.

Console output from request:
GET http://global.appen.localhost:3011/invoice_groups

Request headers (398 B)
Accept
text/html,application/xhtml+xm…plication/xml;q=0.9,*/*;q=0.8
Accept-Encoding
gzip, deflate
Accept-Language
en-US,en;q=0.5
Cache-Control
no-cache
Connection
keep-alive
Host
global.appen.localhost:3011
Pragma
no-cache
Upgrade-Insecure-Requests
1
User-Agent
Mozilla/5.0 (Macintosh; Intel …) Gecko/20100101 Firefox/59.0

Network Timing:
Blocked:          → 1 ms
DNS resolution:                  → 1 ms

A: You probably just have to clear your FF browser cache. Sometimes you have to clear it all, not just for the site you are working on. Have you done this yet? Old caches can create very mysterious problems like this.

A: Firefox gave special treatment to ".localhost" which seems to have caused to problems.  When I change my hosts file from project.name.localhost to project.name.devl it started working.

A: I had an issue with Firefox, where it opened localhost:1234, but couldn't connect and load any resources from static.localhost:1234.
This only happened on sub-domain with a port specified. Thus, static.localhost worked fine.
Adding
127.0.0.1  static.localhost
to hosts file (located in C:\Windows\System32\drivers\etc) solved the problem for me.

A: Edit: Not working [seems internate stops working in firefox with this]
in firefox type
about:config
search localhost in it and make below flag true
network.dns.native-is-localhost

Edited
Sorry Its Not reliable solution

A: I would suggest a couple of things:

*

*In the hosts file, add the name www.project.name.localhost, in case Firefox is adding www to it. It would look like this:
127.0.0.1 project.name.localhost www.project.name.localhost

*Use an HTTP Header analyzer such as Fiddler to monitor the connections Firefox and Chrome are making when you're using http://project.name.localhost:3011/. That will tell you if there's a problem resolving the IP or if there's a difference with the requests made by Chrome.

*When pinging, use /4 to check the IPv4 and /6 for IPv6 to make sure it's resolving properly.

A: You might also try running from the command line:
nbtstat -R
That will flush your windows name cache.
I don't really think this will solve this though because the name works in one browser, just not FF.
Just to be sure, when you're clearing the FF cache, go to Options -> Privacy & Security.  From there you want to clear "Cached Web Content" and "Site Data".  You're getting both of those?
If it still won't work, you may have found a FF bug, although that seems highly unlikely. Specifying a host and port number is very standard and it seems highly unlikely that FF could somehow not be able to do that in this case.
You might also break the problem down.  What happens when you just call the host without the port number?  You might want to make your server serve up a test page on port 80 and see if that part of the call is working.  That at least would narrow it down to the port number.  Or, perhaps narrow it down to the fact that it's not calling the server correctly.

A: Try to create another endpoint, like localhost:3011/test, see if works, firefox could check your url and your suffix or prefix might consider incomplete and automatically add some prefixes, in location bar type about:config then Search: fixup and double-click browser.fixup.alternate.enabled so it becomes false. See if that helps.

A: I'm using a simple machine name or alias, I solved this issue with this setting:

browser.fixup.dns_first_for_single_words = true

Although the right solution is to use name.localhost instead of just name.

A: It is not about your configuration in machine. Firefox adds 'www' prefix when you visit subdomain of localhost and Chrome does not.


text:
Q: Sobolev space on closed surfaces I was wondering if anybody here knows how the Sobolev space $H^2(\mathbb{S}^2)$ is defined? I.e. I want to integrate on this space with respect to the surface measure, but since this not the canonical case, I could not find a proper definition of this space.

A: The most consistent way that I've seen $L^{2}$ Sobolev spaces handled on (relatively)compact manifolds without boundary--and keep in mind that I'm way out of my element when dealing with manifolds--is through domains of powers of the Laplacian or through some similar elliptic PDE. The first Sobolev space, for example, would come from the form domain, which is the closure of $\mathcal{C}^{\infty}$ under the form
$$
                    \|\phi\|^{2}_{H^{1}}=(-\Delta \phi,\phi)+(\phi,\phi).
$$
This assumes that $-\Delta$ is essentially selfadjoint on the manifold, meaning that the closure of the graph is a selfadjoint operator $A=-\Delta^{c}$ (c for closure.) Then $H^{n}(M)=\mathcal{D}(A^{n/2})$ is defined in terms of the domain of powers of $A$. For a positive unbounded selfadjoint $A$,
$$
                 A = \int_{0}^{\infty}\lambda dE(\lambda)
$$
where $E$ is the spectral measure of $A$. Of course for the sphere $E$ is atomic, which reduces everything to a sum:
$$
                    A = \sum_{n}\lambda_{n}E_{n}
$$
In this case, $\lambda_{n}$ are the eigenvalues of the Laplacian on the sphere, and $E_{n}$ is the projection operator on the Spherical Harmonics with the common eigenvalue $\lambda_{n}$. Domains are easily characterized by the spectral theorem. $f \in L^{2}(M)$ is in the domain of $A$ iff
$$
                             \int \lambda^{2}d\|E(\lambda)f\|^{2} < \infty.
$$
Similarly, $f \in \mathcal{D}(A^{1/2})=H^{1}(M)$ iff $\int \lambda d\|E(\lambda)f\|^{2} < \infty$. (No absolute value is required on $\lambda$ because $\sigma(A)\subseteq [0,\infty)$.) More generally $f \in \mathcal{D}(A^{n/2})$ iff $\int \lambda^{n} d\|E(\lambda)f\|^{2} < \infty$. Using the spherical harmonics,
$$
            f \in H^{n}(\mathbb{S}^{2}) \iff \sum_{l,m}\lambda_{l}^{n}|(f,Y_{l,m})|^{2} <\infty
$$
This may seem odd or like cheating, but really this is the same as the common cases.
To relate this to the classical case on $\mathbb{R}^{n}$, note that $-\Delta$ is essentially selfadjoint and the closure $A$ from the domain of $\mathcal{C}^{\infty}_{0}$ is a positive operator. The Fourier transform gives the spectral representation for $A$:
$$
                        Af = \mathcal{F}^{-1}(\lambda^{2}\mathcal{F}f)
$$
Now assume you start with $f \in L^{2}$. Then $f \in\mathcal{D}(A^{n/2})$ iff
$$
          \int_{\mathbb{R}^{n}}|\mathcal{F}f(s)|^{2}|s|^{2n}\,ds < \infty.
$$
And this is correct in the strictest Functional Analysis sense.
Rather than the separate check that $f \in L^{2}$, it is standard to require $(1+|s|)^{n}\mathcal{F}f(s) \in L^{2}$, and this becomes an equivalent norm. (And there are various equivalent expressions such as $(1+|s|^{2})^{n/2}$.) Notice that if such a condition is met, then it is automatically met for all lower $n$ as well, which is one of the odd qualities of Sobolev spaces. Even the mixed terms are finite for $n=2$ because $2|s_j s_k| \le s_j^{2}+s_k^{2} \le |s|^{2}$, which is another peculiarity of the Laplacian. The Laplacian shares this property with other elliptic operators.
Anyway, the abstraction to manifolds seems to work well when dealing with the problem as a spectral problem for a positive elliptic operator of some kind. This makes sense, too, because the typical reason for using such spaces is to study differential operators. So why not study them on the native spectral spaces of the Laplacian in the classical manner of $\mathbb{R}^{n}$.
Reference for Abstract Sobolev Spaces on Manifolds


text:
Q: How to avoid old value flashed after view updated in Angular? In my angular app, there is an main app component which have a event listener:
...
$scope.$on('page::change', function(e, value) {
  self.navList = value;
});
...

And a navigation component inside app component, it has only one varible which bind to navList inside app component:
app.component('navBar', {
  bindings: {
    list: '<',
  },
  templateUrl: 'templates/e/navBar.html',
  ...
});

Inside navBar.html, I use ng-repeat to display the data of 'list':

Whenever I change the value of navList inside the app, or I emit an event of 'page::change', the view of data will flash in webpage like:
Original:
OldValue

And then flash:
NewValue OldValue

Then finally:
NewValue

How should I fix this? The version of anuglar is 1.5.8

A: You could try this:
$scope.$watch('modelName' ,  function ( newValue, oldValue )  {
  // access new and old value here
  console.log("Your former modelName was "+oldValue+", your current modelName value "+newValue+".");
});

A: I had the same problem sometimes and my solution was to put an element around to avoid to many bindings to one element:

       {{key}}

I don't know whether this could help you in your situation, but i might be a try.


text:
Q: Images distorted using pygame Trying to build my first pygame project and wanted to import the following map. Used image:

My code is:
import pygame
pygame.init()
size = (1300, 700)
screen = pygame.display.set_mode(size)
pygame.display.set_caption("My Game")
done = False
clock = pygame.time.Clock()
map = pygame.image.load('map.jpg')
map = map.convert()
map = pygame.transform.scale(map, (466,700))
while not done:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True
    screen.fill((255,255,255))
    screen.blit(map, (430, 0))
    pygame.display.flip()
    clock.tick(60)
pygame.quit()

and the output looks like:

I have also tried converting the jpg to a bmp but still the same results. I cannot figure out what is distorting the image, trying with other images it appears that the outputted images is slightly wider than the original. I suspect that pygame is just reading the width wrong and then putting the pixels into an array with that width.
Any advice on fixing this would be much appreciated.

A: There is a bug in SDL_image (which Pygame is based on) that corrupts images in OS X 10.11.
https://bugzilla.libsdl.org/show_bug.cgi?id=3154
Currently, the only known workaround is to downgrade to SDL_image 1.2.10, but I have not been able to confirm.


text:
Q: Formatting (date)time string with LINQ-to-Entity I have troubles formatting two datetime (actually, it's just the time part) values in my LINQ query. The values for time I'm getting in my gridview (gvDaily) have the following format: "HH:mm:ss-HH:mm:ss". What I'd like to have is to have "HH:mm-HH:mm" time format, but I'm not sure how to accomplish it. Needless to mention that it's the Time part of the query that I have problems with.
var dailyList = (from d in db.Daily
                         select d).ToList();

gvDaily.DataSource = from d in dailyList
                     orderby d.Datum
                     select new { d.idDaily, d.Biljeske, d.Datum, d.EfektivnoSati, Tvrtka = d.Ticket.Firma.Naziv, DailyManager = d.Kontakt.Ime + " " + d.Kontakt.Prezime, Ticket = d.Ticket.Opis, Time= d.TimeFrom+ "-" + d.TimeTo, d.TimeFrom, d.TimeTo, d.Opis, d.Ticket.Zatvoren, d.Ticket.IzdanRacun, TicketNumber = d.Ticket.idTicket + "-" + d.Ticket.RedniBroj, d.Dolazak };

Thank you in advance!
P.S. Custom formatting doesn't work so I'm trying to find some other ideas.

A: I don't know whether LINQ to Entities supports custom formatting, but you could try
Time= d.TimeFrom.ToString("HH:mm") + "-" + d.TimeTo.ToString("HH:mm")

However, I'd personally keep the values as DateTime values in the LINQ to Entities part, and only transform to text in the .NET code. In particular, different cultures have different preferred ways of representing times, so you should probably respect that. Separate "fetching the data" from "presenting the data".


text:
Q: How to convert a object arraylist into a hashmap where key and value are the objects attributes I have a object arraylist like below
List<Model> list= new ArrayList<Model>();

The Model object has two attributes where both are integers.

*

*id

*count

Now I want to convert this arraylist into a Hash Map where id is the key and count is the value:
Map<Integer,Integer> convertedmap=new  HashMap<Integer,Integer>();

Any help is appreciated?

A: Iterate on the list and add a new element in the map for each iterated Model object :
Map<Integer,Integer> convertedmap = new  HashMap<Integer,Integer>();
for (Model model : list){
   convertedmap.put(model.getId(), model.getCount());
}

Beware : If list has Model instances with as id field the same value,  the last instance in the List with the same id will overwrite the previous instance(s) in the created map.
You could do a check about it.
Otherwise, you can also perform the job by using the  Collectors.toMap() method of Java 8 :
Map<Integer, Integer> convertedmap = list.stream().collect(
                Collectors.toMap(Model::getId, Model::getCount));

It has an advantage over the classic loop iteration.
If the id value that is used as key in the map has duplicated values in the list, it will rise IllegalStateException : Duplicate key... rather than overwriting silently the map.

A: You can do this with for loop.
List<Model> list= new ArrayList<Model>();
Map<Integer,Integer> convertedmap=new  HashMap<Integer,Integer>();

for(int i=0;i<list.size();i++){
Model model = list.get(i);

convertedmap.put(model.getId(),model.getCount());
}

A: First of all complete your POJO class Model with proper setters/getters then
you can iterate the whole ArrayList list and put the values in Map convertedmap like :
Map<Integer,Integer> convertedmap=new  HashMap<Integer,Integer>();

for (Model md : list) {
   convertedmap.put(md.getId(), md.getCount());
}


text:
Q: How do write a template which can decide which constructor to call? I'd like to be able to construct an A or B without having to think about the number of constructor arguments.
The second constructor is not legal C++ but I wrote it like this as an attempt to express what I want.
Is there an enable_if trick to selectively enable one of the constructors?
(e.g. depending on the number of constructor arguments of A and B.)
I need this to test about 15 classes with 1, 2 or 3 constructor arguments.
struct A
{
    A(int x)
    {
    }
};

struct B
{
    B(int x, int y)
    {
    }
};

template<typename T>
struct Adaptor // second constructor is illegal C++.
{
    T t;

    Adaptor(int x, int y)
        : t(x)
    {
    }

    Adaptor(int x, int y) // error: cannot be overloaded
        : t(x, y)
    {
    }
};

int main()
{
    Adaptor<A> a(1,2);
    Adaptor<B> b(1,2);

    return 0;
}

A: A variant of @Aaron's approach:
#include <type_traits>
#include <utility>

enum EArity { EZero = 0, EOne, ETwo, EThree, Error };

template <typename T, typename A1, typename A2, typename A3> struct getArity
{
    static const EArity arity =
       std::is_constructible<T>::value             ? EZero  :
       std::is_constructible<T, A1>::value         ? EOne   :
       std::is_constructible<T, A1, A2>::value     ? ETwo   :
       std::is_constructible<T, A1, A2, A3>::value ? EThree : Error;
};

template <typename T, EArity A> struct Construct;

template <typename T> struct Construct<T, EZero>
{
    T t;

    template <typename A1, typename A2, typename A3>
    Construct(A1 && a1, A2 && a2, A3 && a3) : t() { }
};

template <typename T> struct Construct<T, EOne>
{
    T t;

    template <typename A1, typename A2, typename A3>
    Construct(A1 && a1, A2 && a2, A3 && a3) : t(std::forward<A1>(a1)) { }
};

// ...

template <typename T>
struct AdapterIntIntInt : Construct<T, getArity<T, int, int, int>::arity>
{
    Adapter(int a, int b, int c)
    : Construct<T, getArity<T, int, int, int>::arity>(a, b, c) { }
};

template <typename T, typename A1, typename A2, typename A3>
struct Adapter : Construct<T, getArity<T, A1, A2, A3>::arity>
{
    Adapter(A1 && a1, A2 && a2, A3 && a3)
    : Construct<T, getArity<T, A1, A2, A3>::arity>
      (std::forward<A1>(a1), std::forward<A2>(a2), std::forward<A3>(a3))
    { }
};

A: Another variant:
#include <boost/utility/enable_if.hpp>

struct A {
    A(int) {}
};

struct B {
    B(int, int) {}
};

template <class T>
struct arg_count {
};

template <>
struct arg_count<A> {
    const static int count = 1;
};

template <>
struct arg_count<B> {
    const static int count = 2;
};

template <class T>
struct Adaptor : public T {
    template <class A1, class A2>
    Adaptor(A1 a1, A2 a2, typename boost::enable_if_c<arg_count<T>::count == 1, A1>::type* = 0) : T(a1) {}

    template <class A1, class A2>
    Adaptor(A1 a1, A2 a2, typename boost::enable_if_c<arg_count<T>::count == 2, A2>::type* = 0) : T(a1, a2) {}
};

int main() {
    Adaptor<A> a(1, 2);
    Adaptor<B> b(1, 2);
}

A: Use template specialization. The first Adaptor is the 'default' template, but the latter will be used only for Adaptor<A>.
template<typename T>
struct Adaptor
{
    T t;

    Adaptor(int x, int y)
        : t(x,y)
    {
    }

};

template<>
struct Adaptor<A> {
    A t;
    Adaptor(int x, int y)
        : t(x)
    {
    }
};


text:
Q: structKeyExists with XML Data Does Not Work I am working with the below XML feed and am using structKeyExists and CFLoop to display the data it contains.
<cfoutput>
<cfxml variable="eating">
<catalog>
<results>10    </results>
<food id="bk101">
<initials type="thefirst" name="BK"/>
<initials type="thesecond" name="KB"/>
<keywords>Burger King, pie, hamburgers, fries, milkshakes    </keywords>
</food>
<food id="bk102">
<initials type="thefirst" name="TB"/>
<initials type="thesecond" name="BT"/>
<keywords>Taco Bell, tacos, churros, burrito, gorditas    </keywords>
</food>
<food id="bk103">
<keywords>Pizza Hut, pizza, cheese, garlic bread    </keywords>
</food>
<food id="bk104">
<initials type="thefirst" name="CFA"/>
<initials type="thesecond" name="AFC"/>
<keywords>Chick-Fil-A, chicken, chicken wrap, sauce, Bananas Pudding Milkshake    </keywords>
</food>
<food id="bk105">
<initials type="thefirst" name="PE"/>
<initials type="thesecond" name="EP"/>
<keywords>Panda Express, rice, egg rolls, general tso    </keywords>
</food>
<food id="bk106">
<initials type="thefirst" name="SJ"/>
<initials type="thesecond" name="JS"/>
<keywords>Sakura Japan, rice, spring rolls, bento    </keywords>
</food>
<food id="bk107">
<initials type="thefirst" name="FG"/>
<keywords>Five Guys, fries, burgers, hot dogs    </keywords>
</food>
<food id="bk108">
<initials type="thefirst" name="TN"/>
<initials type="thesecond" name="NT"/>
<keywords>Tandoori Nights, biryani, chicken, egg rolls    </keywords>
</food>
<food id="bk109">
<initials type="thefirst" name="HoK"/>
<keywords>House of Kabob, rice, bread, beef kabaob, chicken kabob    </keywords>
</food>
<food id="bk110">
<initials type="thefirst" name="BF"/>
<initials type="thesecond" name="FB"/>
<keywords>Baja Fresh, quesadilla, soft taco, chili con queso    </keywords>
</food>
</catalog>
</cfxml>
</cfoutput>

<cfset data = queryNew("id,initials,initials2,keywords","integer,varchar,varchar,varchar")>

<cfloop index="x" from="1" to="#eating.catalog.results.xmlText#">
    <cfif structKeyExists(eating.catalog.food[x],"initials")>
        <cfset queryAddRow(data)>
        <cfset querySetCell(data,"id",x)>
        <cfset querySetCell(data,"initials", eating.catalog.food[x].initials[1].xmlattributes.name )>
        <cfset querySetCell(data,"initials2", eating.catalog.food[x].initials[2].xmlattributes.name )>
        <cfset querySetCell(data,"keywords", eating.catalog.food[x].keywords )>
     </cfif>

</cfloop>

<cfoutput query="data">
#id# - #initials# :: #initials2# :: #keywords#

</cfoutput>

You will notice there is one initial tag missing for Element 3 and two that are missing for Elements 7 and 9 in the XML feed . If the initials tags are added to the XML for Elements 3,7,9, the code works beautifully. However since they are missing, this causes an error to be thrown out an error.
What I would like to do is omit Element 3 (and all other entries which cause an error) from my results and prevent any errors from showing so the application result shows up like so:
1 - BK :: KB :: Burger King, pie, hamburgers, fries, milkshakes
2 - TB :: BT :: Taco Bell, tacos, churros, burrito, gorditas
4 - CFA :: AFC :: Chick-Fil-A, chicken, chicken wrap, sauce, Bananas Pudding Milkshake
5 - PE :: EP :: Panda Express, rice, egg rolls, general tso
6 - SJ :: JS :: Sakura Japan, rice, spring rolls, bento
8 - TN :: NT :: Tandoori Nights, biryani, chicken, egg rolls
10 - BF :: FB :: Baja Fresh, quesadilla, soft taco, chili con queso
Note my example is simplified, in actuality I am working with an XML feed with hundreds of elements. With that in mind, what am I doing wrong and how can I get the above to display correctly?

A: StructKeyExists() works just fine, but you need to check to ensure the second initials exists too. Adding ArrayLen(eating.catalog.food[x].initials) GT 1 (or EQ 2, if you know it'll always be 2) will solve it.
<cfif structKeyExists(eating.catalog.food[x],"initials") AND ArrayLen(eating.catalog.food[x].initials) GT 1>

With this fix, the example you gave outputs 1, 2, 4, 5, 6, 8, and 10. If you want to print 7 and 9, just move the check to here:
<cfif structKeyExists(eating.catalog.food[x],"initials")>
    <cfset queryAddRow(data)>
    <cfset querySetCell(data,"id",x)>
    <cfset querySetCell(data,"initials", eating.catalog.food[x].initials[1].xmlattributes.name )>
    <cfif ArrayLen(eating.catalog.food[x].initials) GT 1>
        <cfset querySetCell(data,"initials2", eating.catalog.food[x].initials[2].xmlattributes.name )>
    </cfif>
    <cfset querySetCell(data,"keywords", eating.catalog.food[x].keywords )>
 </cfif>


text:
Q: Can a function be discontinuous outside its domain of definition? Define a function $f$ by:
$f(x)=\ln(x), x>0$
It says that $0$ is a point of (infinite) discontinuity of $f$. But $0$ doesn't even belong to the domain of definition of $f$!

A: It's a common abuse of language to imply that if the domain were expanded it would be discontinuous despite zero not being in it's domain. Domains in particular are commonly abused this way.

A: Calculus books and mathematicians tend to disagree on exactly this point.

A: In general if we have a continuous function $f$ defined on some open interval $(a,b)$ we could hope to extend $f$ to a continuous function on [a,b]. For example, f(x)=x^2 on (0,1) can be extended with no problems to [0,1].
We always need to consider the behavior on the boundary of the domain of our function.
In your case what happens if you consider the limit for $x \to 0$?


text:
Q: Java Script File Reader class is not reading the contents properly I am using readAsText method in FileReader class (java script) with encoding type as "UTF-8" to read a file from client.  It works well for all kind of characters with ascii values ranging from 1 to 65000. The only problem I have is, when I read chunk by chunk from the file, any char has ascii value after 3000 sometimes not read properly, After the investigation, I found that it is happening only when I do this reading for big files and the particular char is accidently sitting as first letter of a chunk. And I tested with multiple chunks of a file. This problem is not happening for all the chunks, happening one or 2 chunks out of 10. This is weird and strange. Am I missing something here? and do we have any other options to read local file in Java script? Any help will be much appreciated.

A: this might be one solution

new Blob(['hi']).text().then(console.log)

Here is another, not so cross browser friendly... but this could work...

new Blob(['foo']) // or new File(['foo'], 'test.txt')
  .stream()
  .pipeThrough(new TextDecoderStream('utf-8'))
  .pipeTo(new WritableStream({
    write(part) {
      console.log(part)
    }
  }))

Another lower level solution that don't depend on WritableStream or TextDecoderStream would be to use regular TextDecoder with stream option by doing
var res = ''
const decoder = new TextDecoder()
res += decoder.decode(chunk1, { stream: true })
res += decoder.decode(chunk2, { stream: true })
res += decoder.decode(chunk3, { stream: true })
res += decoder.decode() // flush the end

how u get each chunk could be by using new Response(blob).body or by blob.stream() or simply slicing the blob using blob.slice(start, end) and use FileReader.prototype.readAsArrayBuffer()


text:
Q: Tool for managing large numbers of SSL certificates My organisation has a lot of SSL certificates and managing them is a pain: we need to keep backups of private keys and certificates, keep them secure, deal with certificate renewals (we use different CAs, some of which require a new CSR each time) and occasionally generating new keys, either because we add a new server or because we need to increase the key size.
I suppose it would be possible to write a tool to automate all of the above, but before we commit to doing so, can anyone recommend a tool that does this already? Ideally it'd run on Linux via a command line or web interface.

A: I only know of tools that exist for the entire life cycle of a CA for example Windows Certification Services.
If however you are using a third party CA and simply want to keep good record from Linux, I would highly recommend you simply organise your current system.
When working with certificates I do something along the following:
Folder called CSR - keeps the requests
Folder called Public - keeps the public keys
Folder called Private - Keeps the private keys
all files called xxxxxx.crt / xxxxxx.pem etc, where x is the next available number - keep them the same so 000001.crt is the public certificate to 000001.pem's private key.
Keep an up to date spreadsheet / database in the root folder that simply has the number in one column and details, expiry and any other relevant information in the next.
For a spreadsheet, this shouldn't take more than a few minutes to set up, but If you were to use a small database, you can probably build a little (but nice) DB in less than an hour that can do nice reports such as expiry warnings etc.
I think that this system could work out well for you.

A: With no other tool than google, here are some possibilities:
Venafi Digital Certificate Management & Encryption Key Management
Trustwave Certificate Lifecycle Manager
Both these products handle discovery, analysis, alerting and management.


text:
Q: How can I create a type that uses fluent chaining syntax without requiring parenthesis? I'm trying to make an assertions library for testing in Rust. Currently, I have statements like:
expect(value).to().be().equal_to(4);

It would be really nice to drop the parens on filler to and be functions to make it something like:
expect(value).to.be.equal_to(4);

I think this requires the to and be to be fields on struct returned by expect (Expectation). It currently looks like this:
struct Expectation<V: Debug> {
    value: V,
}

Is it possible to make it something like this:
struct Expectation<V: Debug> {
    value: V,
    to: Box<Expectation<V>>,
    be: Box<Expectation<V>>,
}

where to and be point to the struct they're in?
I've tried, but it's a tricky one to construct. I'm not even sure it is safe if the object is moved (maybe that can be prevented via Pin?).
I'm looking for any solution to allow the expect(value).to.be syntax above.

A:
I'm looking for any solution to allow the expect(value).to.be syntax above.

Keep it simple then:
fn main() {
    expect(4).to.be.equal_to(3);
}

fn expect<T>(actual: T) -> To<T> {
    let be = Be {
        be: Expectation(actual),
    };
    To { to: be }
}

struct To<T> {
    pub to: Be<T>,
}

struct Be<T> {
    pub be: Expectation<T>,
}

struct Expectation<T>(T);

impl<T> Expectation<T> {
    fn equal_to<U>(&self, expected: U)
    where
        U: PartialEq<T>,
    {
        if expected != self.0 {
            panic!("Report error")
        }
    }
}

optionally want to skip [to and be]

use std::{ops::Deref, rc::Rc};

fn main() {
    expect(4).to.be.equal_to(3);
    expect(4).to.equal_to(3);
    expect(4).equal_to(3);
}

fn expect<T>(actual: T) -> Expectation<T> {
    let core = Core(Rc::new(actual));

    let be = Be { core: core.clone() };

    let to = To {
        be,
        core: core.clone(),
    };

    Expectation {
        to,
        core: core.clone(),
    }
}

struct Expectation<T> {
    pub to: To<T>,
    core: Core<T>,
}

impl<T> Deref for Expectation<T> {
    type Target = Core<T>;
    fn deref(&self) -> &Core<T> {
        &self.core
    }
}

struct To<T> {
    pub be: Be<T>,
    core: Core<T>,
}

impl<T> Deref for To<T> {
    type Target = Core<T>;
    fn deref(&self) -> &Core<T> {
        &self.core
    }
}

struct Be<T> {
    core: Core<T>,
}

impl<T> Deref for Be<T> {
    type Target = Core<T>;
    fn deref(&self) -> &Core<T> {
        &self.core
    }
}

struct Core<T>(Rc<T>);

impl<T> Clone for Core<T> {
    fn clone(&self) -> Self {
        Core(self.0.clone())
    }
}

impl<T> Core<T> {
    fn equal_to<U>(&self, expected: U)
    where
        U: PartialEq<T>,
    {
        if expected != *self.0 {
            panic!("Report error")
        }
    }
}

Some macros would reduce duplication, but I was too lazy to actually show that ;-)
When in Rome...
I would try to play to Rust's strengths when designing a test assertions library. To me, this means using traits to allow people to easily add custom assertions.
use crate::testlib::prelude::*;

fn main() {
    expect(4).to(be.equal_to(3));
    expect(4).to(equal_to(3));
}

mod testlib {
    // Shorthand variants that will always be imported.
    // Minimize what's in here to avoid name collisions
    pub mod prelude {
        use super::*;

        pub fn expect<A>(actual: A) -> Expectation<A> {
            Expectation::new(actual)
        }

        #[allow(non_upper_case_globals)]
        pub static be: Be = Be;

        pub fn equal_to<E>(expected: E) -> EqualTo<E> {
            EqualTo::new(expected)
        }

    }

    // All the meat of the implementation. Can be divided up nicely.

    pub trait Assertion<A> {
        fn assert(&self, actual: &A);
    }

    pub struct Expectation<A>(A);
    impl<A> Expectation<A> {
        pub fn new(actual: A) -> Self {
            Expectation(actual)
        }

        pub fn to(&self, a: impl Assertion<A>) {
            a.assert(&self.0)
        }
    }

    pub struct Be;

    impl Be {
        pub fn equal_to<E>(&self, expected: E) -> EqualTo<E> {
            EqualTo::new(expected)
        }
    }

    pub struct EqualTo<E>(E);

    impl<E> EqualTo<E> {
        pub fn new(expected: E) -> Self {
            EqualTo(expected)
        }
    }

    impl<A, E> Assertion<A> for EqualTo<E>
    where
        A: PartialEq<E>,
    {
        fn assert(&self, actual: &A) {
            if *actual != self.0 {
                panic!("report an error")
            }
        }
    }
}

Next steps I'd look into:

*

*An assertion should probably report failures to some passed-in struct, not panic.

*Add a to_not and/or not_to negative matcher.

*Add composition of assertions.

A: I've had some success with lazily generating the to and be using the thunk crate:
struct Expectation<V: Debug> {
    value: Rc<V>,
    to: Thunk<Box<Expectation<V>>>,
    be: Thunk<Box<Expectation<V>>>,
}

fn expect<V: Debug>(value: V) -> Expectation<V> {
    expect_rc(Rc::new(value))
}

fn expect_rc<V: Debug>(value: Rc<V>) -> Expectation<V> {
    let to_cloned = value.clone();
    let be_cloned = value.clone();
    Expectation {
        value,
        to: Thunk::defer(|| Box::new(expect_rc(to_cloned))),
        be: Thunk::defer(|| Box::new(expect_rc(be_cloned))),
    }
}

impl<V: PartialEq + Debug> Expectation<V> {
    fn equals<R: Debug>(&self, expected: R)
    where
        V: PartialEq<R> + Clone,
    {
        assert_eq!(self.value.deref().clone(), expected);
    }
}

This works as I'd expect, thanks to magic of Deref + Deref conversion:
expect(4).to.be.equal_to(3);

A: For designing a custom syntax, I'd just use a macro:
macro_rules! expect {
    ($subject:expr, to, $($attr:tt)*) => {
        expect!($subject, $($attr)*)
    };
    ($subject:expr, be, $($attr:tt)*) => {
        expect!($subject, $($attr)*)
    };
    ($subject:expr, equal_to $object:expr) => {
        assert_eq!($subject, $object)
    };
}

expect!(1, to, be, equal_to 1);

Deploying boxes and self-referential structs just to get a particular syntax is overkill.
Link to playground


text:
Q: Python cloudant query "_id" by regex I am new to ibm cloudant and I am using the python API for cloudant for my web application.
Is there any way I can retrieve documents from my couch database hosted on IBM cloudant instance using regex on "_id"?
I've read the python-cloudant documentation but I couldn't find anything.
Please help.
Thank you.

A: If you consider the underlying API, you can use the $regex operator in Cloudant Query. However, it won't use an index, so performance will be pretty dire, as it will scan the whole database. If possible, try arrange your ids such that you can find the subset you need with a range query instead. Given a db that looks like so:
% curl https://skruger.cloudant.com/aaa/_all_docs
{"total_rows":4,"offset":0,"rows":[
{"id":"aaron","key":"aaron","value":{"rev":"1-..."}},
{"id":"adam","key":"adam","value":{"rev":"1-..."}},
{"id":"ben","key":"ben","value":{"rev":"1-..."}},
{"id":"charlie","key":"charlie","value":{"rev":"1-..."}}
]}

we can retrieve all docs with id starting with "a" only,
% curl 'https://skruger.cloudant.com/aaa/_all_docs?startkey="a"&endkey="b"'
{"total_rows":4,"offset":0,"rows":[
{"id":"aaron","key":"aaron","value":{"rev":"1-..."}},
{"id":"adam","key":"adam","value":{"rev":"1-..."}}
]}