text:
Q: Register ApplicationUserManager using Simple Injector How will I fix the error below when trying to run the project.

The constructor of type ApplicationUserManager contains the parameter
  with name 'store' and type IUserStore<ApplicationUser> that is not
  registered. Please ensure IUserStore<ApplicationUser> is registered,
  or change the constructor of ApplicationUserManager.

Below is my Identity Config
// Configure the user management application used in this application.
// UserManager defined in ASP.NET Identity and is used in the application.
public class ApplicationUserManager : UserManager<ApplicationUser>
{
    public ApplicationUserManager(IUserStore<ApplicationUser> store)
        : base(store)
    {
    }

    public static ApplicationUserManager Create(
        IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context)
    {
        var manager = new ApplicationUserManager(
            new UserStore<ApplicationUser>(context.Get<ApplicationDbContext>()));
        // Set the validation logic usernames
        manager.UserValidator = new UserValidator<ApplicationUser>(manager)
        {
            AllowOnlyAlphanumericUserNames = false,
            RequireUniqueEmail = true,
        };

        // Set the password validation logic
        manager.PasswordValidator = new PasswordValidator
        {
            RequiredLength = 6,
            RequireNonLetterOrDigit = true,
            RequireDigit = true,
            RequireLowercase = true,
            RequireUppercase = true,
        };

        // Set default values for user lock
        manager.UserLockoutEnabledByDefault = true;
        manager.DefaultAccountLockoutTimeSpan = TimeSpan.FromMinutes(5);
        manager.MaxFailedAccessAttemptsBeforeLockout = 5;

        // Record authentication providers in two phases.
        // This application uses the steps Phone & Email to receive a code
        // to check the user
        // You can write your own provider and connect here .
        manager.RegisterTwoFactorProvider("phone code", new PhoneNumberTokenProvider<ApplicationUser>
        {
            MessageFormat = "Your security code is {0}"
        });
        manager.RegisterTwoFactorProvider("Email Code", new EmailTokenProvider<ApplicationUser>
        {
            Subject = "Security code",
            BodyFormat = "Your security code is {0}"
        });
        manager.EmailService = new EmailService();
        manager.SmsService = new SmsService();
        var dataProtectionProvider = options.DataProtectionProvider;
        if (dataProtectionProvider != null)
        {
            manager.UserTokenProvider =
                new DataProtectorTokenProvider<ApplicationUser>(
                    dataProtectionProvider.Create("ASP.NET Identity"));
        }
        return manager;
    }
}

and below is my Account controller with its corresponding constructor parameters. I've also removed the empty constructor since multiple constructor is not supported in simple injector and said to be anti pattern.
public class AccountController : Controller
{
    private ApplicationSignInManager _signInManager;
    private ApplicationUserManager _userManager;

    //public AccountController()
    //{
    //}

    public AccountController(ApplicationUserManager userManager, ApplicationSignInManager signInManager)
    {
        UserManager = userManager;
        SignInManager = signInManager;
    }

    public ApplicationSignInManager SignInManager
    {
        get
        {
            return _signInManager ?? HttpContext.GetOwinContext().Get<ApplicationSignInManager>();
        }
        private set
        {
            _signInManager = value;
        }
    }

    public ApplicationUserManager UserManager
    {
        get
        {
            return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
        }
        private set
        {
            _userManager = value;
        }
    }

    //
    // GET: /Account/Login
    [AllowAnonymous]
    public ActionResult Login(string returnUrl)
    {
        ViewBag.ReturnUrl = returnUrl;
        return View();
    }

    //
    // POST: /Account/Login
    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
    {
        if (!ModelState.IsValid)
        {
            return View(model);
        }

        // No errors account login for the account lockout
        // To allow password errors trigger lock the account , switch to shouldLockout : true
        var result = await SignInManager.PasswordSignInAsync(model.Username, model.Password, model.RememberMe, shouldLockout: false);
        switch (result)
        {
            case SignInStatus.Success:
                return RedirectToLocal(returnUrl);
            case SignInStatus.LockedOut:
                return View("Lockout");
            case SignInStatus.RequiresVerification:
                return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
            case SignInStatus.Failure:
            default:
                ModelState.AddModelError("", "Invalid username/password");
                return View(model);
        }
    }

    //
    // GET: /Account/Register
    [AllowAnonymous]
    public ActionResult Register()
    {
        return View();
    }

    //
    // POST: /Account/Register
    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Register(RegisterViewModel model)
    {
        if (ModelState.IsValid)
        {
            var user = new ApplicationUser
            {
                UserName = model.Email, Email = model.Email,
                Profile = new Profile
                {
                    EmployeeID = model.EmployeeID,
                    FirstName = model.FirstName,
                    LastName = model.LastName,
                    MiddleName = model.MiddleName
                }
            };

            var result = await UserManager.CreateAsync(user, model.Password);
            if (result.Succeeded)
            {
                await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);

                // For more information about enabling confirmation and account password reset , visit http://go.microsoft.com/fwlink/?LinkID=320771
                // Send email with this link
                // String code = await UserManager.GenerateEmailConfirmationTokenAsync ( user.Id ) ;
                // Var callbackUrl = Url.Action ( " Confirmemail " , "Account ", new { userId = user.Id , code = code} , protocol : Request.Url.Scheme ) ;
                // Await UserManager.SendEmailAsync ( user.Id , "Confirm Account" , " To confirm the account, click <a href=\"" + callbackUrl + "\"> here </a> ");

                return RedirectToAction("Index", "Home");
            }
            AddErrors(result);
        }

        // If we reach this point , it is that it was an error and re- display the form
        return View(model);
    }

    private void AddErrors(IdentityResult result)
    {
        foreach (var error in result.Errors)
        {
            ModelState.AddModelError("", error);
        }
    }

    private ActionResult RedirectToLocal(string returnUrl)
    {
        if (Url.IsLocalUrl(returnUrl))
        {
            return Redirect(returnUrl);
        }
        return RedirectToAction("Index", "Home");
    }
}

Below is my SimpleInjector config
// Create the container as usual.
var container = new Container();
container.Options.DefaultScopedLifestyle = new WebRequestLifestyle();

// Register services
Config.RegisterContainer(container);

// This is an extension method from the integration package.
container.RegisterMvcControllers(Assembly.GetExecutingAssembly());

// This is an extension method from the integration package as well.
container.RegisterMvcIntegratedFilterProvider();

// This will register services
Config.RegisterContainer(container);

container.Verify();

DependencyResolver.SetResolver(new SimpleInjectorDependencyResolver(container));


text:
Q: Swift UITest - No match found for textField with accessibility identifier Trying to create a UITest for entering an email address/password into text fields and then hitting a login button. Using Xcode.
I watch the UITest navigate to the proper page, but it does not detect the text fields. I made sure that both text fields have the "Accessibility" box checked, and I've given them identifiers.
I'm getting this error:

UI Testing Failure - No matches found for text field

func testExample() {
    let app = XCUIApplication()

    //Test login page
    app.buttons["loginButton"].tap()

    //Here it navigates to the desired page
    let emailField = app.textFields["email"]
    emailField.tap()
    emailField.typeText("xxx.xx.edu")

    let passwordField = app.textFields["password"]
    passwordField.tap()
    passwordField.typeText("xxx")

    app.buttons["loginButton"].tap()

   // let loginAlert = app.alerts["alertVC"]

   // XCTAssertEqual(loginAlert.title, "Error")
}

The accessibility indicators are "email" and "password" respectively. Logging in works fine when I run the simulator myself.
EDIT: Apparently there are no text fields at all (count = 0) even though I see them and use them on the page...
Image of storyboard with text fields:

A: I was having the same problem and I solved by unchecking the "accessibility enabled" box for the "views" of ViewControllers

A: If UITextFiled set SecureTextEntry true, you should use:
let passwordField = app.secureTextFields["password"]

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to pass bearer token API in Azure Data Factory I have an API which has Authorization has bearer token. I tested in post man and it's working. However, it's not working when I used web activity in the ADF.

I am passing the url in the URL section. Created new header, typed Authorization and gave value "Bearer token"
Getting below error
Error
Troubleshoot activity failures
{
    "errorCode": "2108",
    "message": "{\"error\":{\"type\":\"invalid_request_error\",\"message\":\"Request forbidden by administrative rules. Please make sure your request has an acceptable User-Agent header.\",\"documentation_url\":\"https://developer.dentally.co\"}}",
    "failureType": "UserError",
    "target": "Web1",
    "details": []
}

Can anyone please advise?

A: I reproduced the same in my environment. I successfully generated a bearer Token with  Postman.
To solve the above error code:2200. Please follow the below approach.

*

*I used the same URL with web Activity and generated a bearer Token in the Azure data factory.

*Generate bearer Token as shown below:

*

*Connect Web activity 2 with newly created Web1 activity

*

*Add dynamic expression : Bearer @{activity('Web2').output.data.Token}

Output:

Reference:
Sample Rest API URL for testing with authentication by Ashok Patel


text:
Q: removing unnecessary line breaks using regex When I view the source of html page, i find many instances of new line/line breaks and one such example is:

Q
239 OF
1999

Ideally it should be

Q 239 OF 1999

As a result of this when I do pattern search the search and replace fails.
I tried following
/[\n\r]/

but this didn't do anything.
How can this be fixed using preg_replace?
Thanks.

A: Can you include the code you're using?
The following appears to work:
preg_replace("/[\n\r]/", "", $input);


text:
Q: Split data directory into training and test directory with sub directory structure preserved I am interested in using ImageDataGenerator in Keras for data augmentation. But it requires that training and validation directories with sub directories for classes be fed in separately as below (this is from Keras documentation). I have a single directory with 2 subdirectories for 2 classes (Data/Class1 and Data/Class2). How do I randomly split this into training and validation directories
    train_datagen = ImageDataGenerator(
    rescale=1./255,
    shear_range=0.2,
    zoom_range=0.2,
    horizontal_flip=True)

    test_datagen = ImageDataGenerator(rescale=1./255)

    train_generator = train_datagen.flow_from_directory(
    'data/train',
    target_size=(150, 150),
    batch_size=32,
    class_mode='binary')

   validation_generator = test_datagen.flow_from_directory(
    'data/validation',
    target_size=(150, 150),
    batch_size=32,
    class_mode='binary')

   model.fit_generator(
    train_generator,
    steps_per_epoch=2000,
    epochs=50,
    validation_data=validation_generator,
    validation_steps=800)

I am interested in re-running my algorithm  multiple times with random training and validation data splits.

A: https://stackoverflow.com/a/52372042/10111155 provided the easiest way: ImageDataGenerator now supports splitting into train/test from a single directory with subdirectories directly.
This is copied directly from that answer with no changes. I take no credit. I tried it and it worked perfectly.
Note that train_data_dir is the same in the train_generator and validation_generator. If you want a three-way split (train/test/valid) using ImageDataGenerator, the source code will need to be modified --- there are nice instructions here.
train_datagen = ImageDataGenerator(rescale=1./255,
    shear_range=0.2,
    zoom_range=0.2,
    horizontal_flip=True,
    validation_split=0.2) # set validation split

train_generator = train_datagen.flow_from_directory(
    train_data_dir,
    target_size=(img_width, img_height),
    batch_size=batch_size,
    class_mode='binary',
    subset='training') # set as training data

validation_generator = train_datagen.flow_from_directory(
    train_data_dir, # same directory as training data
    target_size=(img_width, img_height),
    batch_size=batch_size,
    class_mode='binary'
    subset='validation') # set as validation data

model.fit_generator(
    train_generator,
    steps_per_epoch = train_generator.samples // batch_size,
    validation_data = validation_generator,
    validation_steps = validation_generator.samples // batch_size,
    epochs = nb_epochs)

A: If you only want to split the image data without applying any transformations to the images, use the following code.
from keras.preprocessing.image import ImageDataGenerator

train_datagen = ImageDataGenerator(
        validation_split=0.4)

train_generator = train_datagen.flow_from_directory(
        'path_to_data_directory',
        subset='training')

validation_generator = train_datagen.flow_from_directory(
        'path_to_data_directory', #same as in train generator
        subset='validation')

This takes the given 'path_to_data_directory' and takes images from the sub-folders from that directory and assigns the respective sub-folder name as class-name of the image.
Sample output
Found 43771 images belonging to 9385 classes.
Found 22490 images belonging to 9385 classes.

You can use model.fit_generator to load this data to your model.
Refer to https://keras.io/preprocessing/image/ for details.

A: Thank you guys! I was able to write my own function to create training and test data sets. Here's the code for anyone who's looking.
import os
source1 = "/source_dir"
dest11 = "/dest_dir"
files = os.listdir(source1)
import shutil
import numpy as np
for f in files:
    if np.random.rand(1) < 0.2:
        shutil.move(source1 + '/'+ f, dest11 + '/'+ f)

A: Unfortunately, it's impossible for the current implementation of keras.preprocessing.image.ImageDataGenerator (as for October 14th, 2017) but as it's a really requested feature I expect it to be added in the nearest future.
But you could do this using standard Python os operations. Depending on the size of your dataset you could also try to first load all images to RAM and then use a classical fit method which could split your data randomly.

A: You will need to either manually copy out some of your training data and paste it into a validation directory, or create a program to randomly move data from your training directory to your validation directory. With either of these options, you will need to pass in the validation directory to your validation ImageDataGenerator().flow_from_directory() as the path.
Details for organizing your data in  the directory structure are covered in this video.

A: Here's my approach:
# Create temporary validation set.
with TemporaryDirectory(dir=train_image_folder) as valid_image_folder, TemporaryDirectory(dir=train_label_folder) as valid_label_folder:
    train_images = os.listdir(train_image_folder)
    train_labels = os.listdir(train_label_folder)

    for img_name in train_images:
        single_name, ext = os.path.splitext(img_name)
        label_name = single_name + '.png'
        if label_name not in train_labels:
            continue
        if random.uniform(0, 1) <= train_val_split:
            # Move the files.
            shutil.move(os.path.join(train_image_folder, img_name), os.path.join(valid_image_folder, img_name))
            shutil.move(os.path.join(train_label_folder, label_name), os.path.join(valid_label_folder, img_name))

Don't forget to move everything back.

A: You solution worked, thanks.
   import os
   import shutil
   import numpy as np

   sourceN = base_dir + "\\train\\NORMAL\\"
   destN = base_dir + "\\val\\NORMAL"
   sourceP = base_dir + "\\train\\PNEUMONIA"
   destP = base_dir + "\\val\\PNEUMONIA"

   filesN = os.listdir(sourceN)
   filesP = os.listdir(sourceP)

   for f in filesN:
       if np.random.rand(1) < 0.2:
       shutil.move(sourceN + '\\'+ f, destN + '\\'+ f)

   for i in filesP:
       if np.random.rand(1) < 0.2:
       shutil.move(sourceP + '\\'+ i, destP + '\\'+ i)

   print(len(os.listdir(sourceN)))
   print(len(os.listdir(sourceP)))
   print(len(os.listdir(destN)))
   print(len(os.listdir(destP)))


text:
Q: Ferramenta de design que exporta para .xib ou .storyboard Gostaria de saber se existe alguma ferramenta que pode ser usada para desenvolver o design do app (como o programa Prototyper da Justinmind ) e depois exportar para o formato xib ou storyboard.

A: não acho que existe, e não vejo nenhuma razão de existir algo desse tipo. O storyboard não é uma ferramenta de design como photoshop, ou uma extensão como jpg. Ele faz parte de uma arquitetura chamada MVC.
https://developer.apple.com/library/ios/documentation/general/conceptual/devpedia-cocoacore/MVC.html
O XIB/Storyboard como a "VIEW" do MVC, possui várias responsabilidades como: criar vínculo entre view e controller, oferecer formas de deixar a sua view adaptavel a portrait e landscape usando Auto Layout, vc pode inserir coisas na sua view através de código, e no XCode 6, vc possui apenas 1 storyboard para phone, tablet e desktop.
Montar a view da sua aplicação não é algo que pode ser gerado, deve ser desenvolvido.

A: Que converte não tem, mas tem o Sympli que ajuda a criar o layout do Sketch para o xcode


text:
Q: How to change hover color using onclick button I want to switch multiple colors in a page like theme change. I successfully changed text color, text background color, shapes color, button color etc. But I also want to change hover color.
This is the html code:-

RED

GREEN

BLUE

This code works:-

But this dont work:-

Please help me. I dont know how to solve it.

A:

    #red:hover
    {
    background-color:"color"
    }

For all id(red,green,blue) you can do this in css

A: using variable and hover() you could do the job: (you cant modify css style with :hover)

var red = {'background-color': 'red'};
var redhover = {'background-color': 'yellow'};
$('#red').click(function() {
  $('.sidebar button').css(red);
  $('.text-color').css(red);
  $('.shape-left').css(red);
  redhover = {'background-color': 'pink'};
});

$(".sidebar button").hover(function() {
    $(this).css(redhover);
  },function() {
    $(this).css("background-color", "");
  });

RED

GREEN

BLUE

A: Here is a solution using CSS variables changed through Javascript. I'll recommend you read the documentation to better understand what is happening here.

let themes = {
  red: {
    '--sidebar-bg': '#FFAEBE',
    '--sidebar-a-color': '#88001B',
    '--sidebar-a-hover-color': '#FF0033',
  },
  green: {
    '--sidebar-bg': '#BBFFAE',
    '--sidebar-a-color': '#148800',
    '--sidebar-a-hover-color': '#3DFF00',
  },
  blue: {
    '--sidebar-bg': '#AEEFFF',
    '--sidebar-a-color': '#006E88',
    '--sidebar-a-hover-color': '#00CEFF',
  },
};

$('.color-changer').on('click', 'a', (e) => {
  e.preventDefault();
  let theme = $(e.target).data('theme');
  setSidebarTheme(theme);
});

function setSidebarTheme(theme) {
  let sidebar = $('#sidebar')[0]; // Get the raw Element, not jQuery
  for(let [prop, value] of Object.entries(themes[theme])) {
    // set value to the CSS variable
    sidebar.style.setProperty(prop, value);
  }
}

// initial theme
setSidebarTheme('blue');
#sidebar { padding: 20px; }

#sidebar {
  background: var(--sidebar-bg);
}

#sidebar a {
  color: var(--sidebar-a-color);
}

#sidebar a:hover {
  color: var(--sidebar-a-hover-color);
}

RED

GREEN

BLUE


text:
Q: Onclick event in Java import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Prg_38 extends JFrame{

    JTextArea area = new JTextArea(5,10);                   // 5 rows and 10 colums
    JButton btn1 = new JButton("TextArea");             // name of JBUtton is TextArea
    JButton btn2 = new JButton("TextField");            // name of JButton is TextField
    JRadioButton bold,italic,plain,bold_italic;         // radio buttons
    JTextField fld = new JTextField(15);                // jtextfield is 15 characters long

    Font bf = new Font("Serif",Font.BOLD, 14);
    Font itf = new Font("Serif",Font.ITALIC, 14);
    Font itbf = new Font("Serif",Font.BOLD + Font.ITALIC, 14);

    GridBagConstraints gc = new GridBagConstraints();       // used to place components on GUI

    public Prg_38() {

        super("Interface");                                 // title of Dialog box
        setLayout(new GridBagLayout());

        gc.insets = new Insets(0,0,2,2);                        // margin between components of GUI (top,left,right,bottom)

        // textarea
        area.setText("textarea");          // default text in textarea
        addComponent(area,0,0);            // method to place components on GUI

        // jbutton

        addComponent(btn1,1,0);            // textare
        addComponent(btn2,2,0);            // textfield

After adding the components to the interface, I'm adding action listeners to every component so that when text area button is clicked, focus changes to text area and when text field button is clicked, focus changes to text field.
        //radio buttons

        bold = new JRadioButton("Bold",false);              // name of radio button is Bold
        addComponent(bold,1,1);

        italic = new JRadioButton("Italic",false);          // name of radio button is Italic
        addComponent(italic,2,1);

        plain = new JRadioButton("Plain",false);                // name of radio button is Plain
        addComponent(plain,1,2);

        bold_italic = new JRadioButton("Bold and Italic",true);     // // name of radio button is Bold and Italic
        addComponent(bold_italic, 2, 2);

        ButtonGroup group = new ButtonGroup();              // it makes sure that only 1 radiobutton is enabled at a time
        group.add(bold);
        group.add(bold_italic);
        group.add(italic);
        group.add(plain);

        // when radio buttons are added to a group, only one radio button can be selected at a time.

        // jtextfield

        fld.setText("enter your name");                 // default text
        addComponent(fld,0,3);

        // action listeners

        thehandler handler = new thehandler();          // action listener class

        btn1.addActionListener(handler);                // textarea action listener
        btn2.addActionListener(handler);                // textfield

        bold.addItemListener(new handler1(bf));
        italic.addItemListener(new handler1(itf));

        setVisible(true);               // making GUI visible
        setSize(400,400);               // pixels (x * y)
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);             // Frame quits when X is clicked on top right corner

    }

    public class thehandler implements ActionListener{

        public void actionPerformed(ActionEvent e) {

            if(e.getSource() == btn1) {

                // change focus to textarea named area

                area.requestFocusInWindow();

            }

            if(e.getSource() == btn2) {

                fld.requestFocusInWindow();
            }

        }

    }

Now i want is that if bold radio button is clicked, whichever component is selected(textarea and textfield), the text of that component changes to bold text
    public class handler1 implements ItemListener{

        Font font;

        public handler1(Font f) {

            font = f;
        }

        public void itemStateChanged(ItemEvent event) {

            if((area.isFocusOwner() == true) && (event.getSource() == bold)) {

                area.setFont(font);
            }

        }
    }

    public void addComponent(Component c, int px, int py) {

        gc.gridx = px;                      // column
        gc.gridy = py;                      // row

        add(c, gc);             // add components(textarea, radio button and all other stuff) to GUI
    }

    public static void main(String[] args) {

        new Prg_38();

    }

}

A: For any JComponent such as a JTextField, use JComponent.requestFocusInWindow(). For the AWT based TextArea, change it to the Swing based JTextArea and do the same thing.
So:
TextArea area = new TextArea(5,10);

Becomes:
JTextArea area = new JTextArea(5,10);

And:
public void actionPerformed(ActionEvent e) {
    if(e.getSource() == btn1) {
        // change cursor to textarea named area
    }
    if(e.getSource() == btn2) {
         // change cursor to textfield if btn2 is clicked
    }
}

Becomes:
public void actionPerformed(ActionEvent e) {
    if(e.getSource() == btn1) {
        area.requestFocusInWindow();
    }
    if(e.getSource() == btn2) {
         fld.requestFocusInWindow();
    }
}


text:
Q: Data merge on-the-fly with natural balanced merge sort I have implemented (external) natural balanced two-way merge sort for sorting text files (text files contain strings separated by new line character). The algorithm works as expected but there is part of it that I would like to improve. First, the algorithm is separated into two parts: first part distributes the input data, the second part merges it. The first part of the algorithm works good but the second part is not implemented in the right way. The problem here is that the length of next runs is read in advance from both temp files with the help of getNextStringRunLength function.
For example:
int n = getNextStringRunLength(temp_file_1)
int m = getNextStringRunLength(temp_file_2)

The algorithm merges data until (n+m) values are merged into a new run of a length (n+m). The idea here is to merge data on the fly without reading runs lengths before that. The main question here is how to implement merge procedure on the fly?
Sample of the input.txt
Car
Motor
Bike
Book
John
Carl
Sample of the output.txt
Bike
Book
Car
Carl
John
Motor
Please see code below and thanks for the answers!
/**
* Sorts input text file of strings using natural merge procedure with a help of two auxiliary files.
* In the first part it uses these files to distribute input data and then merges them in the second part.
* Input data is distributed using writeNextStringRun method which writes next string run
* to auxiliary file. When it merges runs to a length of (m+n) it uses functiongetNextStringRunLength
* which returns length of a next string run found in auxiliary files and thus helping to merge run of length m
* and run of length n into a single run of length (m+n).
*

* Distribute and merge procedure repeat until all the data is sorted in ascending order. The algorithm
* produces a brand new output file which contains sorted data and thus retains input file unchanged.
* Since the algorithm is balanced it changes the role of input/output files after merge part ends. At the
* end of algorithm all empty auxiliary files are deleted from the local file system, the auxiliary file which
* contains sorted data becomes output file of the algorithm.
*

* @param temp_files         number of auxiliary files used for data distribution and merging.
* @param working_dir        path to local directory where all the sorting takes place.
* @param main_string_file   local text file which contains all input data separated by new a line character.
* @throws IOException       if an input or output exception occurred during file operations.
*/

public static void naturalBalancedTwoWayMergeSortStrings(int temp_files, String working_dir, File main_string_file) throws IOException
{
    long data_read = 0;
    String last_string_runs = new String[temp_files];

    int i,j;
    int n,m;
    int rw_switch = 0;
    int run_counter = 0;
    String line_1 = null;
    String line_2 = null;
    int file_write_pointer;
    long output_file_length = 0;
    String file_extension = ".txt";

    File input_files[] = new File[temp_files];
    File output_files[] = new File[temp_files];
    String input_file_name = "input_string_file_";
    String output_file_name = "output_string_file_";
    File sorted_file = new File(working_dir + "/main_string_sorted" + file_extension);

    BufferedWriter input_file_writers[] = new BufferedWriter[temp_files];
    BufferedReader input_file_readers[] = new BufferedReader[temp_files];
    BufferedReader run_length_readers[] = new BufferedReader[temp_files];
    BufferedWriter output_file_writers[] = new BufferedWriter[temp_files];
    BufferedReader main_file_reader = new BufferedReader(new FileReader(main_string_file));

    for(int p=0; p<temp_files; p++)
    {
        input_files[p] = new File(working_dir + input_file_name + (p+1) + file_extension);
        output_files[p] = new File(working_dir + output_file_name + (p+1) + file_extension);
        input_file_writers[p] = new BufferedWriter(new FileWriter(input_files[p],true));
        run_length_readers[p] = new BufferedReader(new FileReader(input_files[p]));
    }

    /* START - initial run distribution */
    long main_file_length = main_string_file.length();

    while(data_read < main_file_length)
    {
        writeNextStringRun(main_file_reader,input_file_writers[run_counter%2]);
        run_counter++;
    }

    main_file_reader.close();
    input_file_writers[0].close();
    input_file_writers[1].close();
    /* END - initial run distribution. */

    /* START - merge all runs. */
    do
    {
        for(int r=0; r<temp_files; r++)
        {
            input_file_readers[r] = new BufferedReader(new FileReader(input_files[r]));
            run_length_readers[r] = new BufferedReader(new FileReader(input_files[r]));
            output_file_writers[r] = new BufferedWriter(new FileWriter(output_files[r],true));
        }

        /* >>> This is not the righ approach <<< */
        n = getNextStringRunLength(run_length_readers[0],0);
        m = getNextStringRunLength(run_length_readers[1],1);

        try
        {
            line_1 = input_file_readers[0].readLine();
        }
        catch(Exception e){}

        try
        {
            line_2 = input_file_readers[1].readLine();
        }
        catch(Exception e){}

        file_write_pointer = 0;

        while(n > 0 || m > 0)
        {
            i = 1;
            j = 1;

            while((line_1 != null && i <= n) && (line_2 != null && j <= m))
            {
                if(line_1.compareTo(line_2) < 0)
                {
                    output_file_writers[file_write_pointer%2].write(line_1 + "\n");

                    try
                    {
                        line_1 = input_file_readers[0].readLine();
                    }
                    catch(Exception e){}

                    i++;
                }

                else
                {
                    output_file_writers[file_write_pointer%2].write(line_2 + "\n");

                    try
                    {
                        line_2 = input_file_readers[1].readLine();
                    }
                    catch(Exception e){}

                    j++;
                }
            }

            while(line_1 != null && i <= n)
            {
                output_file_writers[file_write_pointer%2].write(line_1 + "\n");

                try
                {
                    line_1 = input_file_readers[0].readLine();
                }
                catch(Exception e){}

                i++;
            }

            while(line_2 != null && j <= m)
            {
                output_file_writers[file_write_pointer%2].write(line_2 + "\n");

                try
                {
                    line_2 = input_file_readers[1].readLine();
                }
                catch(Exception e){}

                j++;
            }

            file_write_pointer++;

            /* >>> This is not the righ approach <<< */
            n = getNextStringRunLength(run_length_readers[0],0);
            m = getNextStringRunLength(run_length_readers[1],1);
        }
        /* END - merge all runs. */

        for(int k=0; k<temp_files; k++)
        {
            input_file_readers[k].close();
            run_length_readers[k].close();
            output_file_writers[k].close();
        }

        /* START - swap io files. */
        File temp_store[] = new File[temp_files];

        switch(rw_switch % 2)
        {
            case 0:
            output_file_length = output_files[0].length();
            for(int k=0; k<temp_files; k++)
            {
                input_file_writers[k] = new BufferedWriter(new FileWriter(input_files[k]));
                temp_store[k] = input_files[k];
                input_files[k] = output_files[k];
                output_files[k] = temp_store[k];
            }
            break;

            case 1:
            output_file_length = output_files[0].length();
            for(int k=0; k<temp_files; k++)
            {
                temp_store[k] = output_files[k];
                output_files[k] = input_files[k];
                input_files[k] = temp_store[k];
                output_file_writers[k] = new BufferedWriter(new FileWriter(output_files[k]));
            }
            break;
        }
        /* END - swap io files. */

        rw_switch++;
    }
    while(main_file_length > output_file_length);
    /* END - merge all runs. */
}

/**
* Writes next string run to auxiliary file.
*
* @param  input_file_reader a reader which reads strings from input text file.
* @param  input_writer      a writer which writes next string run to a auxiliary file.
* @throws IOException       if an input or output exception occurred during file operations.
*/
private static void writeNextStringRun(BufferedReader input_file_reader, BufferedWriter input_writer) throws IOException
{
    try
    {
        if(last_string_run != null)
        {
            input_writer.write(last_string_run + "\n");
            last_string_run = null;
        }

        String min_value = "";
        String current_line = input_file_reader.readLine();

        while(current_line !=  null)
           {
            if(current_line.compareTo(min_value) >= 0)
            {
                input_writer.write(current_line + "\n");

                data_read += current_line.length() + 1;
                min_value = current_line;

                current_line = input_file_reader.readLine();
            }

            else
            {
                last_string_run = current_line;
                return;
            }
        }
    }
    catch(Exception e){}
}

/**
* Returns length of next string run in auxiliary string file.
*
* @param  input_file_reader a reader which reads strings from auxiliary input file.
* @param  input_file_index  an index of auxiliary file from which it reads next string run length.
*         This parameter is used in last_string_runs array which contains last runs read from
*         a file with this parameter (index).
* @return next string run length found in auxiliary string file.
* @throws IOException if an input or output exception occurred during file operations.
*/

private static int getNextStringRunLength(BufferedReader input_file_reader, int input_file_index) throws IOException
{
    int run_length = 0;

    try
    {
        if(last_string_runs[input_file_index] != null)
        {
            run_length++;
        }

        String min_value = "";
        String current_line = input_file_reader.readLine();

        if(run_length > 0)
        {
            min_value = last_string_runs[input_file_index];
        }

        while(current_line !=  null)
           {
            if(current_line.compareTo(min_value) >= 0)
            {
                run_length++;
                min_value = current_line;
                current_line = input_file_reader.readLine();
            }

            else
            {
                last_string_runs[input_file_index] = current_line;
                return run_length;
            }
        }
    }
    catch(Exception e){}

    last_string_runs[input_file_index] = null;

    return run_length;
}


text:
Q: Where can I find a comprehensive reference for CSS and its syntax? I'm trying to build a purely CSS navigation menu which I know can be done. I've seen it. I could copy other people's but I'd rather understand what is happening myself than just copy/paste all the time.
In an effort to understand the CSS I'm running into questions I cannot manage to find anywhere on the internet and w3schools has nothing on the subject.
It took me a while to figure out what the difference was between #nav ul {...} and #nav ul ul{...} because w3schools assumes you'll never need to do anything other than the absolute basics.
My current problems:
What is .sf-sub-indicator ? Sounds self explanatory but I'd like to know exactly what that's doing.
What is sfHover as seen in #nav li.sfHover {...}
and lastly, what is the significance of using > in the CSS Class IDs? EX:
#nav li:hover>ul

as opposed to
#nav li:hover ul {...}

or
#nav li:hover > a {...}

I don't see any sort of explanation for these issues on w3schools and I don't know where else to look?

A: The best resource for learning about CSS selectors is the World Wide Web Consortium's CSS Selectors page: http://www.w3.org/TR/CSS2/selector.html (The Selectors Level 3 entry is the updated version, found here: http://www.w3.org/TR/css3-selectors/).
Read this and then it's easier to Google for additional information, since you'll have, at least, an understanding of what you're searching for.

A: Everything you ever wanted about CSS, JavaScript, and HTML... instantly: http://dochub.io/#css/


text:
Q: I am getting syntax error while using foreach in javascipt. I am trying to create a function to increase and decrease the text size on my page This is the code I am trying to use to create a function to increase/ decrease text size on my page:
this is the error i get: "main.js (65,19) Syntax error"
function changeFontsize(type)
{
    let ids = ["#h3", "#p" ];

    ids.forEach( id => {

        let el = document.querySelector(id);

        let fontSize = window.getComputedStyle(el, null).getPropertyValue("font-size");

        fontSize = parseFloat.(fontSize);

        if(type === "increase")
        {
            el.style.fontSize = (fontSize + 5) + "px" ;

        }
        else
        {
           el.style.fontSize = (fontSize - 5) +"px";

        }

    });
}

A: Syntax error is in this line:
parseFloat.(fontSize)

Remove .:
parseFloat(fontSize)


text:
Q: Why is Polymorphism is needed when we have the keyword "auto" in C++ Correct me if i'm wrong, but the keyword "auto" can solve all the problems that polymorphism was invented to solve.
instead of declaring of virtual function func of class A, when we have Class B inheriting from it, we can just say that the function func is receiving auto param, and it will know what case to trigger.
What do i miss?

A: No, auto cannot solve any of those problems.
auto is a compile-time utility to deduce the type of a thing from the code that's around it. It is more closely related to templates (indeed, the auto in the parameter list of a lambda is implemented by a template!).
It has no knowledge of runtime states and cannot be used to perform virtual dispatch.
These are completely different concepts and your best bet would be to re-study what each one means.


text:
Q: Random variable representing distance of first random point I came across the following question in a probability book by A. Papoulis.
We place at random 200 points in the interval (0, 100). The distance from 0 to the first random point is a random variable $z$. Find the cdf $F_z(z)$.
My approach was following.
Probability of a point belonging the $(0, z)$ i.e.
P(A) = $\frac{z}{100}$
Then probability that the first point is $z$ distance away from 0 is
$f_z(z)$ = P({zero points fall in interval (0, $z$)} $\cap$ {99 points fall in interval ($z$, 100)})
i.e. $f_z(z) = \left(1-\frac{z}{100}\right)^{n-1}$
Can you help me understand what I am doing wrong?

A: You did nothing wrong but you need to continue with your expression. What is missing is just the normalization.
Let more generally
$$f(z,n,k) = \frac{1}{A} (1-\frac{z}{n})^k$$
Here $A$ is a nomalization constant.
In your case we have $n=100$, $k=200$.
In order for $f$ being a probability distribution the sum must be equal to unity, i.e. we must have
$$A = \sum_{z=0}^n  (1-\frac{z}{n})^k$$
The sum can be done in closed form using special functions with the result
$$A = 1+\left(-\frac{1}{n}\right)^k \left(\zeta (-k,1-n)-\zeta (-k)\right)$$
Here $\zeta(x,y)$ the the Hurwitz zeta function and  $\zeta(x)$ the Riemann zeta function.
With $n=100$ and $k=200$ we find numerically $A \simeq 1.15415$, and the first few numerical values of the distribution function (in the format $(z,f)$) are
$$((0, 0.866436), (1, 0.116085), (2, 0.0152388), (3, 0.00195922), (4,
  0.000246594), (5, 0.0000303709))$$
The expectation value is $E(z)\simeq 0.153604$
Original post
I have misunderstood the Problem of the OP. Hence the following decribes the solution to a different problem which might be of interest as well.
§1. The discrete case
There are $\binom{n}{k}$ possibilities to place $k$ points in $n$ different positions $1,2,3, ..., n$.
If you fix one point closest to $0$ at position $m$, you can place the remaining $(k-1)$ points in the remaining $n-m$ positions from $m+1$ to n in $\binom{n-m}{k-1}$ manners.
Hence the probability that the position of the point closest to $0$ is $m$ is gven by
$$p_m = \binom{n-m}{k-1}/\binom{n}{k}\tag{1}$$
The expectation of $m$ is
$$E(m) = \sum_{m=1}^n m p_m = \frac{n+1}{k+1}$$
that of $m^2$
$$E(m^2) = \sum_{m=1}^n m^2 p_m = \frac{n+1}{k+1}=\frac{(n+1) (2 n-k+2)}{(k+1) (k+2)}$$
And the central second moment is
$$\sigma^2 = E(m^2)-E(m)^2 = \frac{k (n+1) (n-k)}{(k+1)^2 (k+2)}$$
2. The continuous case
This case consists in finding the distribution function (pdf) of the minimum of $k$ independent random varables $x_{i}, i=1,...,k$ distributed according to $U(0,1)$.
Due to a lack of time at the moment I provide just the result
$$f(k,w)  = k (1 - w)^{k - 1}\tag{2}$$
The first two moments of the minimum $w$ are
$$E_c(w) = \int_{0}^1 w f(k,w)\,dw = \frac{1}{k+1}$$
$$E_c(w^2) = \int_{0}^1 w^2 f(k,w)\,dw = \frac{2}{(k+1) (k+2)}$$
And the central second moment is
$$\sigma_{c}^2=E(w^2)-E(w)^2 = \frac{k}{(k+1)^2 (k+2)}$$
§3. Discussion
The moments for the continous case are the limits for $n\to \infty$ of those of the discrete case:
$$ E_c(w) = \lim_{n\to \infty} \frac{1}{n} E(m) $$
$$ E_c(w^2) = \lim_{n\to \infty} \frac{1}{n^2} E(m^2) $$
$$ \sigma_{c}^2 = \lim_{n\to \infty} \frac{1}{n^2} \sigma^2 $$

A: The distance to the first point is less than z if and only if there is at least one point in the interval (0,z].
If x is the distance to the first point x < z => there is at least one point in the interval (0,z]
Let n(x,z) be the number of points in the interval (x,z], then
$F_{Z}(z) =P(x \leq z) = P(n(0,z) > 0) = 1 - P(n(0,z) = 0)$
$= 1-(1-\frac{z}{100})^{200}$


text:
Q: What's the word (or phrase) for the phenomenon that something suddenly works when you try to show an error As the title describes, I'm looking for a word or phrase that describes the phenomenon that a bug/error/etc. disappears when you want to show it to someone.
Example:
Your Internet connection does not work properly. You try everything to fix it, but it won't work.
You call an expert but then when you want to show the issue to them, your Internet connection seems to be fine. Obviously, once your expert left, your Internet connection is broken again. Bad luck.
So, what would you call it?


text:
Q: Clustered Nodejs server and CAS server: CORS issue I have a Nodejs based server, which uses a middleware which basically redirects the user to a CAS to manage authentication. The CAS server responds with a ticket, and finally my Nodejs server trades the ticket for an user object with the CAS and stores it in a session.
This process works perfectly fine without cluster.
Today i wanted to clusterize my Nodejs server, using https://nodejs.org/api/cluster.html (thing that i've already done without any problem).
So instead of having:
let server = http.createServer(app);
server.listen(PORT, HOST, () => {
  // Keep a track that the server has been launched
  logger.log(`Server running at http://${HOST}:${PORT}/`);
});

Where everything was working fine, I now have:
if(cluster.isMaster) {

// This is the mother process

  // Let's create the threads
  for(let i=0; i < NB_WORKERS; i++) {
    cluster.fork();
  }

  // When a child crash... Restart it
  cluster.on('exit', (worker, code, signal) => {
    logger.log("info", "A child died (PID: %s). It was killed by code or signal %s. Restarting...", worker.process.pid, dode || signal);
    cluster.fork();
  });
} else {
  // This is a child

  // Create the server, based on http
  let server = http.createServer(app);
  server.listen(PORT, HOST, () => {
    // Keep a track that the server has been launched
    logger.log(`Server running at http://${HOST}:${PORT}/`);
  });
}

When i launch the server, it actually starts the server on NB_WORKERS threads, as expected. But when i want to access the app delivered by my Node server with my browser, i have the following error:

which says if you can't see:
XMLHttpRequest cannot load https://localhost:8443/cas/login?
service=http://localhost:3000. No 'Access-Control-Allow-Origin' header is
present on the requested resource. Origin 'http://localhost:3000' is
therefore not allowed access

https://localhost:8443 is were my CAS server is running, and http://localhost:3000 is where my Node server is running.
Note that if i set NB_WORKERS to 1, everything works fine again.
I understand that setting 'Access-Control-Allow-Origin' header in my CAS server config would probably make everything works fine, but i don't understand why it's working with one thread and not with two or more.
What am i missing ?

A: I finally managed to make it work, so i post here in case someone come across a similar issue.
About Node session
As I said, my Nodejs server stores datas into a session. In this case, it was a simple express-session with the default MemoryStore since i'm still in development.
When clustering, express-session default store is NOT shared between threads. This means that requests supposed identified by the session were sometimes not, depending of which thread handled the request. This caused the authentication middleware to ask the CAS server again.
To make it work, i had to use a persistant store for my session, such as Redis.
About the CORS issue
I'm not really sure about what caused this strange issue, but here what i thought about:

*

*Since my CAS server uses HTTPS protocol, some handshakes were made between both servers due to TSL (Hello, Certificate exchange, Key exchange). Maybe these were broken if not only one thread tried to do it (One makes the Hello, then the response is sent to another thread => this can't work).
Still it's very strange, because it's very low-level, and almost none cluster Node app would work if this was not managed internally.

*In order to make the previous handshakes work, i guess that each thread must be identified somehow. A likely way to do it is to assign a custom port to each thread: the process still run on port 3000, but each thread use a custom one to communicate.
Maybe this was causing my issue, but I can't really tell precisely.

So, i just had to manage correctly my session store to make it work. But please let me know if i was wrong somewhere about the CORS issue.


text:
Q: Regex: Separated by nested parentheses and semicolon My strings look like the following (each row is one exemplrary string):

Smith, Anna (Univ Cambridge); Doe, Jane (Univ Vienna (Austria)); Doe, John (Univ Tokyo; MIT)

Mueller, Hans (FU Berlin (Germany)); Schmid, Julia (); Doe, John (CalTech); Boe, Jane (TU Wien)

Kim, Lee (Nazarbayev Univ (Kazakhstan); Univ Oxford)

In other words, the pattern comprises Surname, Name (Affiliation); (or without the ; if no other person follows), whereby the parentheses may be optionally nested ( () ) or contain a ; or be empty ().
I want to extract each name and affiliation, as in:

Smith, Anna (Univ Cambridge)
Doe, Jane (Univ Vienna (Austria))
Doe, John (Univ Tokyo; MIT)
Mueller, Hans (FU Berlin (Germany))
Schmid, Julia ()
Doe, John (CalTech)
Boe, Jane (TU Wien)
Kim, Lee (Nazarbayev Univ (Kazakhstan); Univ Oxford)

What would be the correct RegEx to do this?
My attempt with (?<=\()(?:[^()]+|\([^)]+\))+ did not work well...

A: Since your expected matches can only have one nested parentheses level, you can use
\w+,\s*\w+\s*\([^()]*(?:\([^()]*\)[^()]*)*\);?

See the regex demo.
Depending on whether or not your regex library supports recursion, or balanced constructs, this can be further enhanced to match parenthetical phrases of any depth.
Details:

*

*\w+ - one or more word chars

*, - a comma

*\s* - zero or more whitespaces

*\w+\s* - one or more word and then zero or more whitespace chars

*\( - a ( char

*[^()]* - zero or more chars other than ( and )

*(?:\([^()]*\)[^()]*)* - zero or more sequences of (...) substrings with no ( and ) in between and then zero or more chars other than ( and )

*\);? - a ) and then an optional ;.


text:
Q: Safari Javascript is conflicting JSON item with keyword I have the following JSON data:
{"data":{
            "default":"some data"
         }
}

Whenever I try to access data.default, Safari generates sytax error because the keyword default. Other web browsers seem to work.
What is the work around for this type of issue?
note: I can't change the JSON data. It is out of my control.

A: data["default"]

works exactly the same, but takes a string

A: Use data["default"] instead. The word default, normally used within switch statements, is contained within a string, so the JavaScript parser does not complain about an "unexpected keyword."

A: This should work:
var js = {"data":{
        "default":"some data"
     }
};
alert(js.data["default"]);


text:
Q: How to extract secrets from running node app via debugger I'm trying to hack my own node app and extract secrets from it by attaching a debugger to the running process. It's a NestJS / Express app.
So there is a compiled main.ts file of the same form as here running.
I am attaching a debugger via node inspect -p $PID. I can now go into a repl, but from there I don't know how to access the instantiated NestJS objects...
There is a ConfigService class from which I would like to retrieve the variables.
How would I continue here?


text:
Q: destructuring assignment on array `process.argv` return Cannot read property 'next on nodejs I am using nodejs when using destructuring assignment on array process.argv I get error Cannot read property 'next' of undefined.
How to fix this issue? Why is that?
Notes: I am using node v6.9.1
let fileIn, fileOut;
let getNodeArguments = () => {
    // this is ok
    process.argv.forEach((val, index) => {
         console.log(`${index}: ${val}`);
    });
    // this is ok
    var hasFileInOutArgs = process.argv.length === 4;
    if (!hasFileInOutArgs) {
        throw ('arguments for file-in and file-out must be provided');
    }
    // issue
    var [, , argUrlIn, argUrlOut] = process.argv;  // error exception here <<<
    fileIn = argUrlIn;
    fileOut = argUrlOut;
};
getNodeArguments();

More infos:
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#Nested_object_and_array_destructuring


text:
Q: Delete Objects in Realm using cascade Relationship I have a Class "Person":RLMObject. Now this Class has a property "Dog":RLMObject.
When i delete "Person" object from Realm, it doesn't automatically delete the "Dog" associated with it.
Is there any delete rule in Realm like in Core Data? Help me to resolve this issue.
Thanks!

A: We are actually working on that feature as we speak, but until it is finally released, you would have to  manually delete the Dog before you delete the Person.
Cheers,


text:
Q: Navigation bar fill the parent div 100% with padding Below is the code which produces the following navigation:

Nav 1

Nav 2

Nav 3

How can I get the lighter red colour navigation completely fill the parent div with the extra 3% padding? The padding needs to be a percentage to allow the content to be responsive. I'm trying to achieve the following:

Thanks in advance.

A: You can make the nav position absolute:

body {
  background-color: #b40404;
}

#wrapper {
  margin: auto;
  text-align: center;
  background-color: white;
  max-width: 750px;
  padding-top:45px;
  padding-left: 1.5%;
  padding-right: 1.5%;
  margin-top: 30px;
  border-radius: 10px;
  position:relative;
}

ul {
  position:absolute;
  top:0;
  right:0;
  left:0;
  list-style-type: none;
  padding: 0px;
  margin:0;
  overflow: hidden;
  background-color: #dc4b4b;
  border-top-right-radius: 10px;
  border-top-left-radius: 10px;
}

li {
  float: left;
}

li a {
  display: block;
  color: white;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
}
.content {
  background:pink;
  padding:50px;
}

Nav 1

Nav 2

Nav 3

    some content here

A: #wrapper {
    margin: auto;
    text-align: center;
    background-color: white;
    max-width: 750px;
    margin-left: 1.5%;
    margin-right: 1.5%;
    margin-top: 30px;
    border-radius: 10px;
}


text:
Q: How to access dictionary key having colon I am having dictionary(JSON i think),
As a response I am getting below value...
{
    "servers": [
        {
            "status": "ACTIVE",
            "updated": "2014-06-12T01:13:47Z",
            "hostId": "e60cf1024aecbddd13805ea01d4702ccfcf2c2de0f67a205b143ca07",
            "OS-EXT-SRV-ATTR:host": "ubi1",

        }
    ]
}

in this how do i access
OS-EXT-SRV-ATTR:host

value but I am getting status and updated keys.
How do i do that?
Thanks.

A: Your dictionary has one key "servers" who's value is a list of dictionaries.  Those internal dictionaries have to be accessed either in a loop or by index.
data =  {
"servers":
 [
    {
        "status": "ACTIVE",
        "updated": "2014-06-12T01:13:47Z",
        "hostId": "e60cf1024aecbddd13805ea01d4702ccfcf2c2de0f67a205b143ca07",
        "OS-EXT-SRV-ATTR:host": "ubi1",
    },
 ],
 }

Example of in a loop
 for server in data['servers']:
     print(server['OS-EXT-SRV-ATTR:host'])

 >>>> ubi1

or direct index
 print(data['servers'][0]['OS-EXT-SRV-ATTR:host'])
 >>>> ubi1

A: variable_that_holds_dictionary['servers'][0]['OS-EXT-SRV-ATTR:host']

A: This will print the value
data = {
    "servers": [
        {
            "status": "ACTIVE",
            "updated": "2014-06-12T01:13:47Z",
            "hostId": "e60cf1024aecbddd13805ea01d4702ccfcf2c2de0f67a205b143ca07",
            "OS-EXT-SRV-ATTR:host": "ubi1",
        }
    ]
}

host = data["servers"][0]["OS-EXT-SRV-ATTR:host"]
print host # for python 3, you use print(host) instead

>>> ubi1

To get the value, first you need to access the "servers" in the data with data["servers"] then to get the dictionary in that list you use [0] because its the first and only element and after that you get the value of "OS-EXT-SRV-ATTR:host" with ["OS-EXT-SRV-ATTR:host"]

A: there Few steps :

*

*first thing is your saying JSON i think  so first clearify what it is

*if it is json  then using json.loads(<ur json string>) this converts in to python object(i.e, dictionary)

*then call directly data["servers"][0]["OS-EXT-SRV-ATTR:host"] to get value

or if it Dictionary then directly u can call data["servers"][0]["OS-EXT-SRV-ATTR:host"]


text:
Q: ¿como realizar una operacion matematica en un mismo input, usando javaserver faces? Código xhtml

<html xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://xmlns.jcp.org/jsf/html" xmlns:p="http://primefaces.org/ui">
<h:head>
  <title></title>
</h:head>
<h:body>
  <p:layoutUnit position="center">
    <h:form>
      <h:panelGrid columns="3" cellpadding="5">
        <h:outputText value="Numero:" />
        <p:inputText id="surname" value="#{operacion.numero}">
          <p:ajax event="blur" update="out2" listener="#{operacion.resolver()}" />
        </p:inputText>
        <h:outputText id="out2" value="#{operacion.respuestaEntera}" />
      </h:panelGrid>
    </h:form>
  </p:layoutUnit>
  <br />
</h:body>

</html>

Managed bean que permite llamar a la funcion en el xhtml
public class Operacion {

    private String numero;
    private String respuesta;
    private int respuestaEntera;

    public Operacion() {
    }

    public int getRespuestaEntera() {
        return respuestaEntera;
    }

    public void setRespuestaEntera(int respuestaEntera) {
        this.respuestaEntera = respuestaEntera;
    }

    public String getNumero() {
        return numero;
    }

    public void setNumero(String numero) {
        this.numero = numero;
    }

    public String getRespuesta() {
        return respuesta;
    }

    public void setRespuesta(String respuesta) {
        this.respuesta = respuesta;
    }

    public void resuelveOperacion() {
        String num1 = "";
        String num2 = "";
        int numero2 = Integer.parseInt(this.numero);
        for (int x = 0; x < numero.length(); x++) {
            if (numero.charAt(1) == '+') {
                if (numero == null) {
                    num1 = numero;
                } else {
                    num2 = numero;
                }
            }
            int suma = Integer.parseInt(num1) + Integer.parseInt(num2);
            respuestaEntera = suma;
        }
    }
}

A: En principio tu vista es correcta, mostrará y recogerá la información tal y como lo tienes planteado.
Solo recordarte que es recomendable en primefaces utilizar la etiqueta p siempre que quieras hacer uso de un componente de primefaces ejemplo:
<p:outputLabel for="@next" value="Numero:" /> <!-- @next o surname lo que prefieras-->
<p:inputText id="surname" value... /> <!-- surname supongo que sean numero -->

Pero lo anterior no es un problema, tu código de vista es correcto.
El problema lo tienes en resuelveOperacion()
En la pregunta no se queda del todo claro que pretendes hacer en este método, pero no va a funcionarte.
1 int numero2 = Integer.parseInt(this.numero);
2 for (int x = 0; x < numero.length(); x++) {

En la línea de codigo 1 tratas a numero como un string al cual transformas a entero, perfecto si escribes "3" -> 3.
En la linea 2 vas a recorrer el String numero para buscar un "+" -> INCORRECTO, o es un número o es una operación, no puede ser los dos.
Suponiendo que sean una operación lo que esperas en la variable número tendrías lo siguiente -> CASO BÁSICO para 2+3 por ejemplo
public void resuelveOperacion() {
int num1 = 0;
int num2 = 0;
String regex = "+"; //Dale un par de vueltas a tu expresión regular

// analyzing the string y suponiendo que se ha entrado "2 + 3" de lo contrario
// para "2 + " daría un error de arrayoutofboundexception
String[] numeros = this.numero.split(regex);
if (numero.contains("+")) {
    num1= Integer.parseInt(numeros[0]);
    num2= Integer.parseInt(numeros[1]);
    return num1 + num2;
}

}
Ahora te toca darle un par de vueltas para hacerlo genérico y poder utilizar operaciones del tipo "3 * 2 + 1" o ya más avanzado 1 + (3 * 2).
Pista: En tu expresión regular "regex", puedes buscar por números y operadores de manera que el array de "String[] numeros" sea [3, *, 2, +, 1] y solo tienes que recorrerlo buscando operadores y haciendo dicha operaciones entre los elementos [x-1] op [x+1] comprobando que tu formula es correcta [x+1] siempre exista "3+" para la posición x=1 -> x[1]=+ [x-1]=3 [x+1]=ERROR. Tienes que capturarlo o no permitir este tipo de situaciones "3+", "+3", ¿"++2"?, ¿"2++"?..
Espero que te sea de utilidad.


text:
Q: Error while run project Error is Like :
Error:Execution failed for task ':app:transformClassesWithJarMergingForDebug'.

com.android.build.api.transform.TransformException: java.util.zip.ZipException: duplicate entry: com/google/android/gms/iid/zzb$zza$zza.class

I get this error..
My build gradle file is..
buildscript {
    repositories {
        maven { url 'https://maven.fabric.io/public' }
    }

    dependencies {
        classpath 'io.fabric.tools:gradle:1.+'
    }
}
apply plugin: 'com.android.application'
apply plugin: 'io.fabric'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.3"

    defaultConfig {
        applicationId "com.example.poonam.chatrbox"
        vectorDrawables.useSupportLibrary= true
        minSdkVersion 15
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
        multiDexEnabled true
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.1.1'
    compile 'com.android.support:support-v4:23.0.0'
    compile 'com.android.support:cardview-v7:23.0.0'
    compile 'com.android.support:design:23.+'
    compile 'com.miguelcatalan:materialsearchview:1.4.0'
    compile 'com.facebook.android:facebook-android-sdk:4.+'
    compile 'com.mcxiaoke.volley:library:1.0.19'
    compile 'com.squareup.picasso:picasso:2.5.2'
    compile 'com.google.code.gson:gson:2.4'
    compile 'com.tumblr:jumblr:0.0.11'
    compile "com.google.android.gms:play-services:8.3.0"
    // compile 'com.facebook.android:facebook-android-sdk:[4,5)'
    compile files('libs/apache-httpcomponents-httpcore.jar')
    compile files('libs/twitter4j-core-android-2.2.6.jar')
    compile 'com.daksh:loglr:1.1.1'
    compile('com.twitter.sdk.android:twitter:2.3.0@aar') {
        transitive = true;
    }
}
repositories {
    maven { url "https://jitpack.io" }
    maven { url 'https://maven.fabric.io/public' }
}
apply plugin: 'com.google.gms.google-services'


text:
Q: Declaring integer: Type Mismatch Error when using sumproduct with countif Can anyone help me with the following:
Dim fundcount as integer

FundCount = Application.WorksheetFunction.SumProduct(1 / Application.CountIf(Range("B12:B28"), Range("B12:B28")))

I am getting a type mismatch error on this script.
The purpose of the script is to count a range of text results and return a unique value that can then be used in a loop later on in the code.
Thanks in advance

A: CountIf does not take a range as its second parameter.  It should be a value like 32 or "Some text".
See: https://msdn.microsoft.com/en-us/vba/excel-vba/articles/worksheetfunction-countif-method-excel?f=255&MSPPError=-2147217396

A: CountIf will count the number of cells that match your criteria. It does not change because you've placed it in SumProduct formula.
If you are counting everything, try using Count instead of CountIf


text:
Q: complex integrating on half-unit circle $\int_{|z| = \frac{1}{2}} \frac{e^{1/z}}{1-z}$
Singularities:
$1-z = 1$ implies $z=1$ is a simple pole. It is not in $|z| = \frac{1}{2}$.
Whereas, $e^{1/z}$ has an essential singularity inside $|z| = \frac{1}{2}$.
Consider $\frac{e^{1/z}}{1-z}= (1+z+z^2+...)(1+\frac{1}{z}+\frac{1}{2!z^2} + ...)$
It seems that the coefficient of $1/z = e-1$.
Therefore, $\int_{|z| = \frac{1}{2}} \frac{e^{1/z}}{1-z} = 2i\pi(e-1)$.
Am I right?

A: We could show ( observe that we take the Cauchy product, i.e. according to powers of $\;z\;$)
$$\frac{e^{1/z}}{1-z}=\sum_{n=0}^\infty z^n\sum_{k=0}^\infty\frac1{k!z^k}=\sum_{m=0}^\infty\frac{z^k}{(m-k)!z^{m-k}}=\sum_{m=0}^\infty\frac{z^{2k-m}}{(m-k)!}$$
we now observe that
$$2k-m=-1\iff m=2k+1\implies\,\text{in the above development, the wanted coefficient is}$$
$$\sum_{m=0}^\infty\frac1{(k+1)!}=\sum_{n=1}^\infty\frac1{n!}=e-1$$


text:
Q: Can not display stacks or Push So I have a project for my C++ class and we are asked to create a library program using Stacks and Doubly Linked Lists. Now we cannot use the stack header file so everything from push, pop, display, etc. has to created by us.
I have the push function working, but the display function I cannot seem to get it to display more than just the lastNode stuct. When it tries to access previousNode, it crashes. Any ideas on what I'm doing wrong?
Also I can not get the pop function to work either. The program crashes as well when it runs.
void pushBook(BookStack *bkStack, BookNode *bkNode)
{
    if(isEmpty(bkStack))
      {
        bkStack->lastNode = bkNode;
        bkStack->lastNode->previousNode = NULL;
      }
    else
    {
        bkStack->lastNode->previousNode = bkStack->lastNode;
        bkStack->lastNode = bkNode;
    }
}
BookNode *popBook(BookStack *bkStack)
{
  BookNode *temp = new BookNode;
  if(isEmpty(bkStack))
  {
    temp = bkStack->lastNode;
    return temp;
  }
  else if(bkStack->lastNode->previousNode == NULL)
  {
    temp = bkStack->lastNode;
    bkStack->lastNode = NULL;
    return temp;
  }else
  {
    temp = bkStack->lastNode->previousNode;
    bkStack->lastNode->previousNode = NULL;
    bkStack->lastNode = temp;
    return temp;
  }
}

void displayStackElements(BookStack *bkStack)
{
  BookNode *nodePtr = new BookNode;

  nodePtr = bkStack->lastNode;

  if(isEmpty(bkStack))
  {
    cout << "Book stack is empty." << endl;
  }
  else
  {
      while(nodePtr != NULL)
        {
          cout << "\nBook Name: " << nodePtr->bk.name << endl;
          cout << "Author Name: " << nodePtr->bk.authorName << endl;
          cout << "Page Numbers: " << nodePtr->bk.pagesNumber << endl;
          cout << "ISBN: " << nodePtr->bk.isbn << endl;
          cout << endl;

          nodePtr = bkStack->lastNode->previousNode;
          }
      }

}
bool isEmpty(BookStack *bkStack)
{
    bool status;

    if(bkStack->lastNode == NULL)
        status = true;
    else
        status = false;

    return status;
}

void addBook(BookStack *bkStack)
{
  BookNode *bkNode = new BookNode;
  cout << "\nEnter the book name: ";
  getline(cin, bkNode->bk.name);
  cout << "Enter the Author's Name: ";
  getline(cin, bkNode->bk.authorName);
  cout << "Enter the ISBN: ";
  cin >> bkNode->bk.isbn;
  cout << "Enter the page numbers: ";
  cin >> bkNode->bk.pagesNumber;
  pushBook(bkStack, bkNode);
}

void removeBook(BookStack *bkStack)
{
  BookNode *removedNode = new BookNode;
  removedNode = popBook(bkStack);

  if(removedNode == NULL)
  {
    cout << "\nNo books to remove." << endl;
  }else
  {
    cout << endl << removedNode->bk.name << " was removed." << endl;
  }
}

(edit) Sorry about that here's the structs from the main header file
    struct Book
        {
            int isbn;
            string name;
            string authorName;
            int pagesNumber;
        };

    struct BookNode
        {
            Book bk;
            BookNode *previousNode;
        };

    struct BookStack
        {
            BookNode *lastNode = NULL;
        };

A: As you don't show the BookNode class definition or its constructor, I can only assume that you forget to clear the nodes previousNode pointer, which means that after you add the second second node then bkStack->lastNode->previousNode will be an uninitialized pointer.
Dereferencing uninitialized pointers leads to undefined behavior.

A: I haven't done c++ in a while so if any of the statement below are wrong, tell me so !
Here what I see :
In displayStackElements:
nodePtr = bkStack->lastNode->previousNode; should be nodePtr = nodePtr->previousNode; otherwise, you will always display the previousnode of lastnode of bkStack in an infinite loop !

I don't know why you do this everywhere:
BookNode *nodePtr = new BookNode;
nodePtr = bkStack->lastNode;

You don't need a new BookNode if you are assigning it right after it ! You are creating a new BookNode in memory and then overwrite the pointer. This is a memory leak. You can simply do this:
BookNode *nodePtr = bkStack->lastNode;

In your pop function, the last else code should be this. You want to pop out the lastnode, not the previous node of the current last node.
temp = bkStack->lastNode->previousNode;
BookNode *lastNode = bkStack->lastNode
bkStack->lastNode->previousNode = NULL;
bkStack->lastNode = temp;
return lastNode;

In your push function, you are setting the previousNode of last node but after that, you were overwriting the lastNode with the node passed in parameter. Your list became broken because the lastNode->previousNode will always be emtpy. The else statement should be this.
bkNode->previousNode = bkStack->lastNode;
bkStack->lastNode = bkNode;


text:
Q: Cannot exclude particular post from loop of custom post type I have a custom post type (from a theme installed by previous developer), and here is the code of loop which retrieve the post and display them.
<?php
// Counter
$post_count = 1;

// Query
$gp_query_args = array(
    'post_type'         => 'event',

    //EXCLUDE Events try by me
    'post__not_in' => array('1646'),
    // exclude event try code block ends

    'meta_key'          => 'gp_event_date',
    'meta_value'        => date('Y/m/d'),
    'meta_compare'      => '>=',
    'orderby'           => 'meta_value',
    'order'             => 'ASC',
    'posts_per_page'    => -1

);
$gp_query = NULL;
$gp_query = new WP_Query($gp_query_args);

I want to exclude certain events (post of custom post type, from loop), and as you can see i tried using 'post__not_in' => array('1646'), where 1646 is the post id i see when i edit the custom post . So i guess this is universal post id, not custom post type specific id.   But No Matter, the post is not being excluded :-(
Am i doing wrong??
Edit1:
I found a [repository on github](links below edit3 )
 that is exactly similar to my theme structure.
I don't know the theme name, so i'm not sure whether that's the same theme on the site i'm working over.
Edit2
So as per the suggestions below
I did, renamed template-event.php (my template file for showing list of events  ) to archive-event.php
And placed the function snippet from here in function.php of my theme.
But i cannot exclude the post with specified ID yet.
Edit3
As asked here is the link of the github repository  that is exactly same as my theme.
Github Links:

*

*template-event.php

*posttype-event.php

A: Something like this should work from your functions file as long as you use the correct conditional tag for your CPT archive:
function exclude_single_post_cpt($query) {
  if (is_post_type_archive('event') && $query->is_main_query() && !is_admin() ) {
    $query->set('post__not_in', array(1646));
  }
}

add_action('pre_get_posts', 'exclude_single_post_cpt');

A: You should rename your file archive-event.php instead of template-event.php as per the WordPress Theme Hierarchy. The template-event.php (template-customposttypename.php) file used for display the content of single events as the single.php working to display the content of post content.
You can use your above code by using any page template also. I hope it will be work.


text:
Q: Best Fit a document in Richtextbox Using C# How can I show a document in richtextbox without scrollbars, But I need like a bestfit mode? I mean what we are seeing like a preview.

A: If you set the Multiline property to true, the contents should word wrap. That will take care of your horizontal scroll bars.


text:
Q: ttk create multiple checkbuttons I'm trying to make a GUI that display lots of checkbuttons, i create them from a list; make a dictionary form the list and assign each checkbutton a variable from the dictionary so i can check it's state later.
Problem is that all the checkbuttons are displayed in an 'alternate' state, even if i set the variable to either 0 or 1, i've also tried changing states, but nothing seems to help.
y = 0
        for x in get_dir_names(r'D:\SKL\test\win10'):
            drv_check[x] = Variable()
            drv_check[x].set(0)
            center_window(150, 500, top_child)
            drv = ttk.Checkbutton(child_frame, text=x, variable=drv_check[x])
            drv.grid(row=y, column=0, sticky=W)
            y += 1

for reference
def get_dir_names(dir_path):
    """Get names only of all directories from a given path (none recursive)"""
    drv_list = [x for x in os.walk(dir_path).__next__()[1]]
    drv_name = dict({})
    for y in drv_list:
        tmp_ver = dir_path + r'\\' + y
        drv_name[y] = (os.walk(tmp_ver).__next__()[1]).pop()
    return drv_name

A: Figured it out, I've made a "toggle all" button and it seemed to fix it, but it's weird that it didn't work before.
here's the function i used:
def toggle_all(*args):
        while True:
            if toggle_all_var.get() == '1':
                for name in drv_check:
                    drv_check[name].set('1')
            elif toggle_all_var.get() == '0':
                for name in drv_check:
                    drv_check[name].set('0')

ttk.Checkbutton(drv_frame, text='Toggle all', variable=toggle_all_var).grid(row=y, column=0, sticky=W)

Also i run the function in a new thread.


text:
Q: Camera Cards and Gimp I have three camera cards: white, 18% gray, and black. These are used to fix the colors of the photos that are taken. I took a picture with all three of these cards at the beginning of the shoot.
My question is: How can I get GIMP to correct the color of the photos based on these cards? Also, how can I apply the transformation to the photos after the one that contains the cards?

A: Here's how you do this:

*

*Load the image with the color cards.

*Go to Image » Color Tools » Levels

*Use the color pickers to choose the cards

*Create a name of the color profile and save it from the Levels dialog

*See how badly your camera picks out colors.

When you have the other photos open, just select the saved profile from the Levels dialog.


text:
Q: How to use Substring function in C#
Possible Duplicate:
How to break a string at each comma?

I want to split this string  in C#.
string str= "ahmad,ehsan,mohmmad,sss";

The result must be as below:
ahmad
ehsan
mohmmad
sss

A: if you want to split it in a list of strings then you can use String.Split function.
string[] splitted = str.Split(',');

A: If you want to split a string, use String.Split.
string str= "ahmad,ehsan,mohmmad,sss";
var result = str.Split(',');

A: You can use split method.
string str= "ahmad,ehsan,mohmmad,sss";
string[] list=str.Split(',');
foreach(string item in list)
Console.WriteLine(item);

A: Use the Split method:
string[] items = str.Split(',');

You could use the Substring method, that would be like this:
List<string> items = new List<string>();
int start = 0, pos;
while ((pos = str.IndexOf(',', start)) != -1) {
  items.Add(str.Substring(start, pos - start));
  start = pos + 1;
}
items.Add(str.Substring(start));

A: Do you want to split the string, or do you want to replace the , with ?
The string class has both a Split method and a Replace method.
string str= "ahmad,ehsan,mohmmad,sss";
var subStrings = str.Split(',');
foreach (var s in subStrings)
{
    Console.WriteLine(s);
}

var newString = str.Replace(","," ");
Console.WriteLine(newString);

A: //use this code

string str= "ahmad,ehsan,mohmmad,sss";
str.Replace(",", " ");

Hope will help you.

A: you the following code,
str = str.Replace(',',' '); /* ans will be "ahmad ehsan mohmmad sss" */

http://msdn.microsoft.com/en-us/library/system.string.replace.aspx
if you just want to split the words and want to have as a string array, you can use
string[] arr = str.Split(',');
/*
   ahmad
   ehsan
   mohmmad
   sss
 */


text:
Q: 'To be on' as 'in charge of' or 'to be working on' I would to know if I could use 'to be on' to mean I'm working on something or I'm in charge of something. For example, could I replace 'I'm working on that issue' or 'I'm in charge of that issue' for 'I'm on that issue'.

A: Not exactly in the way you are using it.  You can say, "I'm on the job" or "I'm on the project," but this means you are a part of the project. We have an English phrase you may be thinking of ..."I'm on it."  This means, "I will take care of it" or "I have everything under control."
For example, your co-worker says, "We still are having a problem with this part of the system."  You can say, I'm on it.  It should be fixed by tomorrow.


text:
Q: Android emulator pinch to zoom anywhere on screen (mac OS) I have already looked at How to pinch zoom on Android emulator? but haven't found specifically how to pinch zoom on any part of the screen via emulator.
I'm on mac OS so I know I can hold Command ⌘ and two dots will apear and I can drag when holding left mouse button to simulate pinch-to-zoom gesture.
However this happens only from the center of the screen. For example iOS emulator allows to move this center anywhere. I would like something similar for Android emulator as well. Is this possible?

A: I'm afraid I'm not using a Mac, but here's my solution on Ubuntu:

*

*Move the mouse cursor to the place you want to center the pinch gesture.

*Press and hold Shift.

*Press CTRL (while holding Shift).

This should display the gesture indicator centered on the mouse cursor.
On Mac, there should be equivalent keys, but I don't use Macs so I don't know.


text:
Q: How to iterate through an array of hashes inside an object with perl I am trying to iterate through an array of hashes stored as the '_skills' attribute of a 'Person' object, and having trouble.
test1.pl
my $person = new Person( "Hubert", "Blu",
    [
       {"name" => "Python", "Weight" => 80, "group","IT SKILLS", "id"=>0002},
       {"name" => "Magic", "Weight" => 100, "group", "MISC SKILLS", "id"=>0001},
       {"name" => "JavaScript","Weight" => 70, "group"=> "IT SKILLS", "id"=>0004},
       {"name" => "Mage","Weight" => 100, "group"=>"JOB TITLE", "id" =>0003},
       {"name" => "Assassin", "Weight" => 85, "group"=>"JOB TITLE"}
    ]
);

and Person.pl
sub new {
    my ($class,$first_name,$last_name,@skills) = @_ ;
    my $self = {};
    $self->{"_first_name"} = $first_name;
    $self->{"_last_name"} = $last_name;
    @{$self->{"_skills"}} = @skills;
    # Print all the values just for clarification.
    print "First Name is $self->{_first_name}\n";
    print "Last Name is $self->{_last_name}\n";
    print "Skills : " . Data::Dumper::Dumper($self->{_skills}) . "\n";

    print"---SKILLS---\n";
    my $i = 1;
    foreach my $skill_set (@{$self->{_skills}}) {
        print "skill ".$i .": \n";
        $i++;
        #print Data::Dumper::Dumper($skill_set) . "\n";
        print "$skill_set->{'_first_name'}";
    };
    bless $self, $class;
    return $self;
}

the first dump shows the array and it looks fine. the second dump inside the loop displays the entire array again, and it only loops through once before finishing with the following error
Not a HASH reference at /home/izoom/PerlTrainingGround/LeeR/lib/Person/Person.pm line 26.

Been stuck for hours any help appreciated as always!

A: You are passing three arguments to new plus the invocant. The last is a reference to an array. That means that @skills ends up with a single element whose value is that reference.
my $person = new Person( "Hubert", "Blu",
    [
       {"name" => "Python", "Weight" => 80, "group","IT SKILLS", "id"=>0002},
       {"name" => "Magic", "Weight" => 100, "group", "MISC SKILLS", "id"=>0001},
       {"name" => "JavaScript","Weight" => 70, "group"=> "IT SKILLS", "id"=>0004},
       {"name" => "Mage","Weight" => 100, "group"=>"JOB TITLE", "id" =>0003},
       {"name" => "Assassin", "Weight" => 85, "group"=>"JOB TITLE"}
    ]
);

should be
my $person = new Person( "Hubert", "Blu",
   {"name" => "Python", "Weight" => 80, "group","IT SKILLS", "id"=>0002},
   {"name" => "Magic", "Weight" => 100, "group", "MISC SKILLS", "id"=>0001},
   {"name" => "JavaScript","Weight" => 70, "group"=> "IT SKILLS", "id"=>0004},
   {"name" => "Mage","Weight" => 100, "group"=>"JOB TITLE", "id" =>0003},
   {"name" => "Assassin", "Weight" => 85, "group"=>"JOB TITLE"}
);

or
    my ($class,$first_name,$last_name,@skills) = @_ ;

    @{$self->{"_skills"}} = @skills;     # Useless shallow array copy
       # -or-
    $self->{"_skills"} = [ @skills ];    # Same[1] but clearer
       # -or-
    $self->{"_skills"} = \@skills;       # No copy of elements

should be
    my ($class,$first_name,$last_name,$skills) = @_ ;

    @{$self->{"_skills"}} = @$skills;    # Shallow array copy
       # -or-
    $self->{"_skills"} = [ @$skills ];   # Same[1] but clearer
       # -or-
    $self->{"_skills"} = $skills;        # No copy of elements

*

*Since $self->{"_skills"} is undef at this point.


text:
Q: In SecItemCopyMatching the &keyRef returns nil i have been using
https://github.com/ideawu/Objective-C-RSA/blob/master/RSA.m
for the RSA encryption but in iOS 9 the kefRef is returned nil,works fine with iOS 8.What change should be made?
    SecKeyRef keyRef = nil;
    status = SecItemCopyMatching((__bridge CFDictionaryRef)privateKey,(CFTypeRef *)&keyRef);
    if(status != noErr){
    return nil;
    }
    return keyRef;

A: The problem was with the public key used.
https://forums.developer.apple.com/thread/15129


text:
Q: Extract sub-matrix based on conditions of specific columns in matlab I want to Select a sub-matrix x7992 based on conditions of Certain columns of original data matrix. Specifically, the original matrix is 23166-by-9, follow a original Gauss code
x7992  =selif(data,data[.,col_coh].==0 .and data[.,col_year].<=1992);

I rewrite this in matlab with
x7992 = data(data(:,col_coh)==0 & data(:,col_year)<=1992);

col_coh,col_year are predefined column number.
However, rather than give me a sub-matrix, the above line of code only give me a single row (23166-by-1),it's not what I want (and not the real result base on this condition).So how to fix it? thank you.
--- Update -----
The data matrix is like (I omit other columns because only first 3 cols are relevant to selection), the first column is id for individuals
1  1979  0
1  1980  0
1  1981  1
1  1982  0
1  1983  1
2  1990  0
2  1991  0
2  1992  0
2  1993  1
3  1985  0
3  1986  0
3  1987  0

Based on the conditions, what I want is a submatrix from data, which excludes those rows with value>1992 in the second column and value=1 in the third one

A: Based on the example that you have given, the following will do this:
data(data(:,2)<=1992 & data(:,3)~=1,:)

which gives this output:
       1   1979   0
       1   1980   0
       1   1982   0
       2   1990   0
       2   1991   0
       2   1992   0
       3   1985   0
       3   1986   0
       3   1987   0

A: You only get a single column vector as output since your condition vector is returned as a single 23166x1 vector.
To get the entire row of values you need to add a colon as a second argument.
I've splitted the example in two lines to make more readable.
condIdx = data(:,col_coh)==0 & data(:,col_year)<=1992;
x7992 = data( condIdx, :);

If you want specific columns in your result matrix, just put the column number in a vector instead of the colon operator.
colsInResult = [1 2 3];
x7992 = data( condIdx, colsInResult);


text:
Q: EntityFunctions.TruncateTime alternative when using EF CTP5 with Sql Server Compact Edition 4.0 I'm using EF CTP5 code-first with Sql CE 4.0. I am trying to perform a time-insensitive date comparison between two DateTime properties.
As linq to entites cannot parse the DateTime.Date property (which would have been nice) the solution is to use EntityFunctions.TruncateTime, however this doesn't appear to work with Sql CE 4.0.
I can manually compare the Year, Month and Day of the two dates, this works but makes the code a lot more verbose than it should be. Ideally I don't want to change my queries to use the long-hand version to make them work with both full sql server and sql ce 4.0.
Therefore does anyone have any clean and clever solutions to this? I think the solution will probably involve expression re-writing but I'm not quite sure where to start.
Any help is greatly appreciated,
Paul

A: Do you have the option of changing the structure of your database?
If so you could add an extra column with just the date part of the datetime, and then use that column in your query.
It will use a little more space in your database, but should run a little faster since you avoid any conversions.


text:
Q: Elastic search query for getting array of values Hi have written a query for getting the avg of values at a position in Elastic search
elastic search payload : "userData": [ { "sub":1234, "value":678,"condition" :"A" },{ "sub":1234, "value":678,"condition" :"B" }]
{
  "aggs": {
    "student_data": {
      "date_histogram": {
        "field":"@timestamp",
        "calendar_interval":"minute"
      },
      "aggs": {
        "user_avg": {
          "avg": {
            "field":"value"
          }
        }
      }
    }
  }
}

What I want is to get the array of elements of which the avg value is returned.
For example, if the avg of values on the basis of condition 'A' is 42 with values as  {20,10,40,60,80}
In the output needed a field which can provide an array of [20,10,40,60,80]

A: I don't think you can obtain an array formatted like [20, 10, 40, 60, 80] in the response of a query. I can't think of a way to obtain it by using aggregations or scripted fields. Nevertheless, you can easily (1) get that information from the same query that specifies the aggregations and the filter logic; then, (2) post-process the query response to collect all the value's values used to calculate the average, by formatting format them in the way you prefer. How you post-process your response depends on the client/script you are using to send queries to Elasticsearch.
For example, you can output the values used to calculate the average as query hits.
{
  "size": 100,           <-- adjust this upper limit to your use case
  "_source": "value",    <-- include only the `value` field in the response
  "query": {
    "match": {
      "condition": "A"
    }
  },
  "aggs": {
    "user_avg": {
      "avg": {
        "field": "value"
      }
    }
  }
}

Or you can output the values used to calculate the average in a more compact way, by using terms aggregations.
{
  "size": 0,
  "_source": "value",
  "query": {
    "match": {
      "condition": "A"
    }
  },
  "aggs": {
    "group_by_values": {
      "terms": {
        "field": "value",
        "size": 100 .       <-- adjust this upper limit to your use case
      }
    },
    "user_avg": {
      "avg": {
        "field": "value"
      }
    }
  }
}

The result of the latter will be something like:
"aggregations" : {
    "array_of_values" : {
      "doc_count_error_upper_bound" : 0,
      "sum_other_doc_count" : 0,
      "buckets" : [
        {
          "key" : 50,
          "doc_count" : 2
        },
        {
          "key" : 60,
          "doc_count" : 1
        },
        {
          "key" : 100,
          "doc_count" : 1
        }
      ]
    },
    "user_avg" : {
      "value" : 65.0
    }
  }


text:
Q: How to parse and match multiple XML files over multiple iterations with Python? I have two XML files. One file contains firewall rules which are defined using objects as opposed to IP addresses, services, etc. The second file contains the definition of those objects, their IP addresses, service types, etc.
I can loop through each XML file and match objects to service definitions very easily using ElementTree and the following code:
import xml.etree.ElementTree as ET
fwPolicy = ET.parse('policy.xml')
services = ET.parse('services.xml')

rules = fwPolicy.findall('./rule')
service = services.findall('./service')

for rule in rules:
    ruleServices = rule.findall('./services/members/reference/Name')
    for ruleService in ruleServices:
            for objService in service:
                    objServiceName = objService.find('./Name').text
                    if ruleService.text == objServiceName:
                            print('Service search Found :', objServiceName)

XML File 1 policy.xml:

<Class_Name>rule_services</Class_Name>
  <members>
    <reference>
        <Name>icmp-requests</Name>

services

    </reference>
    <reference>
        <Name>gre</Name>

services

    </reference>
   </members>
</Class_Name>

XML File 2 services.xml:

<service>
 <Name>icmp-requests</Name>
 <Class_Name>service_group</Class_Name>
<members>
    <reference>
        <Name>echo-request</Name>

services

    </reference>
    <reference>
        <Name>info-req</Name>

services

    </reference>
    <reference>
        <Name>timestamp</Name>

services

    </reference>
    <reference>
        <Name>mask-request</Name>

services

    </reference>
 </members>
</service>

<service>
 <Name>echo-request</Name>
 <Class_Name>icmp_service</Class_Name>
 <icmp_type>8</icmp_type>
</service>

The issue I have is that some of the objects used in policy.xml are "service_groups" which contain the actual services I need to access. In the example XML policy.xml contains "icmp-requests" as the service object which is a "service_group" in services.xml. So when I perform the match I'm matting against the group when I really need to match against all services in the group.
I thought about just adding a code to check if the service object is a service group and then looping though it and pulling all the services. The problem I have is that the service group can contain other service groups. There really is no limit on how far the nesting can occur.
In the end what I need to be able to do is pull all the members from policy.xml and match that to all of the individual members of services.xml.

A: I was able to fix my problem by building the following function:
def resolve_group_members(group_name):
    # Loop through the list of members
    for member in groups[group_name]:
            # If the member is in the groups dict keys
            if member in groups.keys():
                    # recursively loop through the function again passing the member name
                    resolve_group_members(member)
            else:
                    # if the member is not a group now we can do something with it
                    print('\t\tGroup Members: ' +  member)

This way I was able to assign all services to a dictionary and then resolve each group member.


text:
Q: How to wait until a file is available in a Jake build (Node.js)? Is there a way in a Node.js Jake build to wait until a certain file has been copied, and advance to do some operation only after the destination file can be found? I think this question pretty much comes down to "is there a way to copy files synchronously in Node.js/Jake?" (Perhaps something else than writing something from scratch, using the combination of fs.readSync and fs.writeSync.)
Background:
I'm developing a web app that is run on Node.js (with Express) during development, but will be deployed on a Java server in production. (We use Jade and Stylus in the client and Express enables us to run the app without generating all the HTML files etc. and deploying it after every change.)
I use Jake for making the build, i.e. generating HTML files from Jade files and CSS from Stylus files etc. Now I'm also trying to concatenate all of the app's JavaScript files into one minimized file and change all the HTML files to use that instead of all the separate JS files that are used in "raw" form during development.
However, I now have a problem with that last step. My idea was to copy all of my Jade files into a temporary directory for the deployment build and replace the reference (in a Jade file used as a header on all HTML pages) to a list of all separate JS files to the one that has just been generated by concatenating and minimizing the whole bunch. But as I first copy all of the Jade files to another location (which happens asynchronously) and try to edit one of the files, opening the file always fails since the copy operation hasn't really finished yet.
This is what I have now (in a simplified form) in my jakefile:
var fs = require('fs');
var fse = require('fs-extra');
var path = require('path');
var glob = require('glob');
var Snockets = require('snockets');
var snockets = new Snockets();

// generating the minimized JS file
snockets.getConcatenation(baseDir + '/scripts/all.js', { minify: true }, function(err, allJs) {
  if (err) {
    throw err;
  }

  fs.writeFileSync(generatedJsFileName, allJs);
});

// copying all the Jade files to a temp dir
glob.sync('**/*.*', {
  cwd : srcDir
}).forEach(function(file) {
  var loadPath = srcDir + '/' + file;
  var savePath = targetDir + '/' + file;
  fse.mkdirsSync(path.dirname(savePath));
  fse.copy(loadPath, savePath);
});

// trying to read one of the copied files (which fails, since the file cannot be found yet)
fs.readFile(targetDir + '/views/includes/head.jade', 'utf8', function(err, data) {
  ...
});

This might be a stupid question, and a stupid way to try to solve the problem in the first place. So, also suggestions for a better approach are very welcome.
Update:
I also tried using Parseq, putting each operation (creating the JS file, copying the Jade files, reading one file) in its own function, but even that gives me the same error. If I run the script several times without deleting the target directory of the copy operation in between, the file can be found. So e.g. the path is correct and the problem really seems to be about timing.

A: I didn't really find an answer to the main question so I don't know if this helps anyone else facing the same problem. But I did find a way to get around the problem.
I ended using the same original Jade files for the two different conversions, but in the second conversion I use a custom js function to change the script tag reference to point to the minified file.
I.e.
var data = jade.compile(str, { filename: file, pretty: true })({
  css: function(path) {
    return '<link rel="stylesheet" href="/styles/' + path + '.css" />';
  },
  js: function(path) {
    var name = '<script src="/scripts/';

    if (path == 'all') {
      name += generatedJsFileName;
    }
    else {
      name += path + '.js';
    }
    name += '"></script>';

    return name;
  }
});

It might not be the prettiest workaround but it works.


text:
Q: How to compare rows of your datatable? Asuming the table is ordered,
Im looking for a resultset
that gives me the difference of value in row x and value in row (x + 1)
I can make a condition for value_rowx and one for value_rowx+1 then self join those so I actually subtract columns not rows.


text:
Q: NSURL path not functioning as expected despite encoding spaces for fileWithUrlPath: I'm implementing a simple button-sound interface for a toy project.  There are multiple buttons, with individual sounds assigned to each button.  I accomplish this all within the fooViewController.{h,m} with the 'tag' attribute of each UIButton like so:
B0.tag = 0;
B1.tag = 1;
...

I also have an array of sound files, which I hold inside an array of strings, populated as follows:
sounds[0] = [[NSBundle mainBundle] pathForResource:@"foo" ofType:@"caf"];
sounds[1] = [[NSBundle mainBundle] pathForResource:@"bar" ofType:@"caf"];
...

Now when a button Touch Up Inside event is triggered, the following method fires:
-(IBAction)playSoundClip:(id)sender {

    if(sounds[[sender tag]] != nil) {
        NSError *error;
        NSString *temp = [sounds[[sender tag]]   stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        AVAudioPlayer *av = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:temp] error:&error];

        [av play]
    }
}

I always receive a EXC_BAD_ACCESS exception.  When I print out the strings, they are in tact, and as can be expected.. a few spaces, which I thought would be taken care of by the string encoding ^above.

A: You are populating the C array with autoreleased objects. Since you are not taking ownership of the objects, they would have been released soon after assignment.
My recommendation is to use an NSArray instance to hold your paths. It will automatically retain them when you add the path.

A: You need to allocate NSError *error:
NSError *error = [[NSError alloc] init];


text:
Q: Travis CI throwing invalid token/public directory not found errors I am building a static resume website as a fun project.
It is being built with Angular/Firebase/GitHub/TravisCI. I am completely new to the last two.
When pushing changes to my repository through Visual Studio Code, TravisCI was throwing the error "Public Directory Not Found."
I have my Firebase public directory set to "dist" which is what angular cli builds my app into.
This was my initial .travis.yml file
language: node_js
node_js:
  - "10.4"
branches:
  only:
    - master
before_script:
  - npm install -g @angular/cli
script:
  - ng build --prod
install:
  - npm install -g firebase-tools
deploy:
  provider: firebase
  token:
    secure: $FIREBASE_TOKEN
  project: "my-project"

Someone suggested adding
skip_cleanup: true

under the deploy parameter. However this did not fix the issue.
So then I tried adding
- npm install

under the script parameter and it worked! but I have no idea why.
I guess what I am wondering here is why do I need that npm install line under the script parameter? Or DO I need it?
I am pretty new to GitHub/TravisCI, so I apologize if these are very basic questions/I am doing all of this completely wrong.