texts: Determine the third octet of an IP address based on user entered site number

texts:
I am trying to create a function for a larger script to determine the third octet of a site IP address based off a user entered site number. I have actually come up with the function, but was hoping that someone could help me come up with something that is simpler and more elegant, instead of the multitude of nested if statements that I came up with. Here are the rules:

For sites numbered 0001 - 0255, the third octet is the last 3 digits of the site number, less any zeroes preceding a real number (e.g. Site 0007 = 10.10.7.xxx)
For sites numbered 0256 - 0399 and 0500 - 1999 (except 1202), the third octet is the last 2 digits of the site number less any zeroes preceding a real number (e.g. site 0315 = 10.22.15.xxx)
For sites numbered 401 - 499, the third octet is the last two digits of the site number +100 (e.g. 0401 = 10.20.101.xxx)
Site 1202 is an exception to the above rule, where the third octet is the last 3 digits (.202)
For sites 5000 and above (5000 - 9999), the first digit is dropped, and then the rules above are followed. (e.g. 8248 = 10.12.48.xxx)

Here is what I have come up with. It is not very elegant, but it seems to work. Note that the first three lines will be in another function in the script, but are here for testing purposes.

$global:site = Read-Host 'What is the 4 digit site number?' #must include leading zeros
[int]$global:sitecheck=$site #need for comparasion operators
[string]$global:sitestring=$site

if ($sitecheck -le 255)
    {
    if ($sitestring.substring(0,3) -eq '000') #(i.e. 0001 - 0009)
        {
        $global:thirdoct = $sitestring.substring(3,1) #(i.e. 1-9)
        }
        elseif ($sitestring.substring(0,2) -eq '00') #(i.e. 0010 - 0099)
            {
            $global:thirdoct = $sitestring.substring(2,2) #(i.e. 10 - 99)
            }
            elseif ($sitestring.substring(0,1) -eq '0') #(i.e. 0100 - 0255)
            {
            $global:thirdoct = $sitestring.substring(1,3) #(i.e. 100 - 255)
            }
}
elseif ($sitecheck -ge 256 -and $sitecheck -le 399 )
    {
    if ($sitestring.substring(2,1) -eq '0')
        {
        $global:thirdoct = $sitestring.substring(3,1)
        }
        else
        {
        $global:thirdoct = $sitestring.substring(2,2)
        }
}
elseif ($sitecheck -ge 401 -and $sitecheck -le 499)
    {
    $global:thirdoct = 100+$sitestring.substring(2,2)
    }
elseif ($sitecheck -ge 501 -and $sitecheck -le 799)
    {
    if ($sitestring.substring(2,1) -eq '0')
        {
        $global:thirdoct = $sitestring.substring(3,1)
        }
        else
        {
        $global:thirdoct = $sitestring.substring(2,2)
        }
    }
elseif ($sitecheck -eq 1202)
    {
    $global:thirdoct = $sitestring.substring(1,3)
    }
elseif ($sitecheck -ge 5000 -and $sitecheck -le 9999)
    {
    $site5000 = [int]$sitestring.substring(1,3)
    if ($site5000 -le 255)
       {
       if ($sitestring.substring(1,2) -eq '00')
           {
           $global:thirdoct = $sitestring.substring(3,1)
           }
                elseif ($sitestring.substring(1,1) -eq '0')
                {
                $global:thirdoct = $sitestring.substring(2,2)
                }
                    else
                    {
                    $global:thirdoct = $sitestring.substring(1,3)
                    }
    }
    elseif (($site5000 -ge 256 -and $site5000 -le 399) -or ($site5000 -ge 501 -and $site5000 -le 999))
        {
        $global:thirdoct = $sitestring.substring(2,2)
        }
    elseif ($site5000 -ge 401 -and $site5000 -le 499)
        {
        $global:thirdoct = 100+$sitestring.substring(2,2)
        }
    }


texts:
Following is a function that takes a long matrix of states and corresponding values (every row is a state), and collects optimal solutions given those values from an interpolating function (getV()) of a grid that contains the optimal solutions (V).

I'm looking for suggestions to clean up the code, but most importantly for efficiency - this part of my script us running for 12 hours already. I suppose one starting point is to preallocate the correct length in results - not sure how much performance gets lost there.

#V has shape (Value(a, m, e, p))
#@return : (a1, m2, a2, m2, a3, m3, e, V1, V2, V3)
def periodValues(states, V, Param, Grid):
    results = np.empty((0, 11))

    for i,z in enumerate(states):
        if np.isnan(z.any()):
            continue
        a1, m1, a2, m2, a3, m3, e = z
        p = Grid.P2[i]
        v1 = getV(a1, m1, e, p, V, Grid)
        v2 = getV(a2, m2, e, p, V, Grid)
        v3 = getV(a3, m3, e, p, V, Grid)
        result = np.array([[a1, m1, a2, m2, a3, m3, e, v1, v2, v3, p]])
        results = np.append(results, result, axis=0)
    return results

def getV(a1, m1, e, p, V2, Grid):
    from scipy import ndimage
    coords = np.array([[a1 - Grid.aGrid[0], m1 - Grid.mGrid[0], e - Grid.eGrid[0], p - Grid.pGrid[0]]])
    # gives policy as a grid index
    choice = ndimage.map_coordinates(V2, coords.T, order=2, mode='nearest')
    return choice


texts: Android Canvas - Draw a line graph with a gradient whose color depends on the y value

texts:
I'm looking mostly for feedback on a solution of mine. I want to create a pretty line graph where the color of the line is dependent on the Y value, and a change in color at y=0. A loose example of such a graph is:

I was wondering how this can be accomplished on Android using Canvas, Paths, etc. I'm currently using MPAndroidChart to handle most of the dirty work. My solution for the coloring part is shown below.

I'm wondering if there is either a simpler way to do this or more efficient method. The reason why I ask is because this code does live in the onDraw method which should be as lightweight as possible and I am creating a new LinearGradient on every draw which I feel like is very expensive. The reason why I do these calculations on every draw is because I allow the user to zoom in on the graph and scroll it, which means the screen coordinates can always change.

protected void drawCubicBezier(ILineDataSet dataSet) {
    ...
    // Get screen coordinates for min Y value
    MPPointD pixelForValues = trans.getPixelForValues(0, minDy);
    minDy = (float) pixelForValues.y;
    MPPointD.recycleInstance(pixelForValues);

    // Get screen coordinates for max Y value
    pixelForValues = trans.getPixelForValues(0, maxDy);
    maxDy = (float) pixelForValues.y;
    MPPointD.recycleInstance(pixelForValues);

    // Get screen coordinates for 0 value
    pixelForValues = trans.getPixelForValues(0, 0);
    float zeroDy = (float) pixelForValues.y;
    MPPointD.recycleInstance(pixelForValues);

    float range = minDy - maxDy;
    float zeroPointNormalized = Math.max((zeroDy - maxDy) / range, 0);

    linearGradient = new LinearGradient(
            0, maxDy, 0, minDy,
            new int[]{Color.RED, Color.RED, Color.BLUE, Color.BLUE},
            new float[]{0, zeroPointNormalized, zeroPointNormalized, 1f},
            Shader.TileMode.REPEAT);
    paint.setShader(linearGradient);
    ...
    mBitmapCanvas.drawPath(cubicPath, paint);
}


texts:
Given the CSV data:

,fan1,fan2,foil1,foil2
0,0.0,0.0,0.0,0.125
1,0.0625,0.0,0.0625,0.125
2,0.0625,0.0,0.0,0.3125

Which I want to turn into a kind of annotated pivot-table which can be plotted as a bar-plot:

,Err,PairType,StimType
0,0.0,Target,1
1,0.0625,Target,1
2,0.0625,Target,1
0,0.0,Target,2
1,0.0,Target,2
2,0.0,Target,2
0,0.0,RPFoil,1
1,0.0625,RPFoil,1
2,0.0,RPFoil,1
0,0.125,RPFoil,2
1,0.125,RPFoil,2
2,0.3125,RPFoil,2

I currently accomplish this with the following code:

import numpy as np
import pandas as pd

def df_plotable(model_err: pd.DataFrame):
    t_len = len(model_err.fan1)
    cols = ("Err", "PairType", "StimType")

    fan1_df = pd.DataFrame(np.array([model_err.fan1, ["Fan"]*t_len, [1]*t_len]).T,
                           columns=cols)
    fan2_df = pd.DataFrame(np.array([model_err.fan2, ["Fan"]*t_len, [2]*t_len]).T,
                           columns=cols)
    foil1_df = pd.DataFrame(np.array([model_err.foil1, ["Foil"]*t_len, [1]*t_len]).T,
                            columns=cols)
    foil2_df = pd.DataFrame(np.array([model_err.foil2, ["Foil"]*t_len, [2]*t_len]).T,
                            columns=cols)

    new_model_err = pd.concat((fan1_df, fan2_df, foil1_df, foil2_df))
    new_model_err["Err"] = new_model_err["Err"].astype(float)
    new_model_err["StimType"] = new_model_err["StimType"].astype(int)

    return new_model_err

Such that:

df = pd.read_csv("in.csv", "r", delimiter=",", index_col=0)
df_plotable(df).to_csv("out.csv")

Is there a way to do this more cleanly?


texts: Unit test for class converting between DTOs and entities

texts:
Is this correctly written test? Tested class is responsible for converting from dto to entity class and i wanted to test it. Are these tests useful and well designed? I have a problem understanding how should look such classes.

Tested class:

@Service
public class ConverterRegisterUserDto extends Converter<RegisterUserDto,User> {

  private final PasswordEncoder passwordEncoder;

  @Autowired
  public ConverterRegisterUserDto(PasswordEncoder passwordEncoder, ModelMapper modelMapper) {
    super(modelMapper);
    this.passwordEncoder = passwordEncoder;
  }

  @Override
  public User convert(RegisterUserDto dto) {
    User user = modelMapper.map(dto, User.class);
    user.setPassword(encodePassword(dto.getPassword()));
    return user;
  }

  private String encodePassword(String password){
    return passwordEncoder.encode(password);
  }
}

Test:

class ConverterRegisterUserDtoTest {

    private PasswordEncoder passwordEncoder;
    private ConverterRegisterUserDto converterRegisterUserDto;
    private RegisterUserDto registerUserDto;

    @BeforeEach
    void init(){
        ModelMapper modelMapper = new ModelMapper();
        passwordEncoder = new BCryptPasswordEncoder();
        converterRegisterUserDto = new ConverterRegisterUserDto(passwordEncoder, modelMapper);
        registerUserDto = getSampleRegisterUserDto();
    }

    private RegisterUserDto getSampleRegisterUserDto(){
        RegisterUserDto registerUserDto = new RegisterUserDto();
        registerUserDto.setUsername("t_username");
        registerUserDto.setPassword("t_password");
        registerUserDto.setEmail("t_email");
        registerUserDto.setClientVerifyAccountUrl("t_url");
        return registerUserDto;
    }

    @Test
    void encodePassword_correctly(){
        //WHEN
        User user = converterRegisterUserDto.convert(registerUserDto);

        //THEN
        assertNotEquals(registerUserDto.getPassword(), user.getPassword());
        assertTrue(passwordEncoder.matches(registerUserDto.getPassword(), user.getPassword()));
    }

    @Test
    void convert_fromRegisterUserDto_toUserDtoClass(){
        //WHEN
        User user = converterRegisterUserDto.convert(registerUserDto);

        //THEN
        assertEquals(User.class, user.getClass());
    }

    @Test
    void convert_fromRegisterUserDto_isMappingCorrectly(){
        //WHEN
        User user = converterRegisterUserDto.convert(registerUserDto);

        //THEN
        assertEquals(registerUserDto.getUsername(), user.getUsername());
        assertEquals(registerUserDto.getEmail(), user.getEmail());
    }
}

I am trying to understand how to write good tests. Is that a good way? Or am I totally missing an idea of testing?


texts: Is it ok to break long html elements down into multiple lines?

texts:
I often see very long code lines like this:

<input type="email" name="email" autocomplete="email" id="email_address" value="<?= $block->escapeHtmlAttr($block->getFormData()->getEmail()) ?>" title="<?= $block->escapeHtmlAttr(__('Email')) ?>" class="input-text" data-mage-init='{"mage/trim-input":{}}' data-validate="{required:true, 'validate-email':true}">

Is it ok to break them down like:

<input type="email"
       name="email"
       autocomplete="email"
       id="email_address"
       value="<?= $block->escapeHtmlAttr($block->getFormData()->getEmail()) ?>"
       title="<?= $block->escapeHtmlAttr(__('Email')) ?>"
       class="input-text"
       data-mage-init='{"mage/trim-input":{}}'
       data-validate="{required:true, 'validate-email':true}"
>

Because this makes it much clearer and easier to read in my opinion.

I usually do this if there are more than about 80-100 chars.

Validation with https://validator.w3.org/


texts:
I have a small function which checks if the given String has all 0's. This method would be used quite often and want to know if it's effectively written. Any help would be greatly appreciated.

 /*
 * Input parameters: Employee Number
 * Returns true if sum of employee number is greater than 0,
 * else false.
 */
private boolean employeeNumberCheck(String employeeNumber){
    try{
        if(employeeNumber.length()==0){
            return false;
        }
        int counter=0;
        for(int i=0;i<employeeNumber.length();i++){
            counter=counter+Integer.parseInt(String.valueOf(employeeNumber.charAt(i)));
        }
        if(counter==0)
            return false;
        return true;
    } catch (Exception someException){
        logger.info("Error from method employeeNumberCheck.\n"+someException);
        return false;
    }
}


texts: Solution to Chef and Squares challenge, timing out in Java but not in C++

texts:
I was solving a problem on codechef (online judge and contest organizer). I was writing my code in Java and was getting TLE at last testcase where as I wrote the same code in C++ and it was accepted. Now I know C++ is faster then java but If anyone could help me optimize my Java code ?

Here is the question

  Chef has finished his freshman year in college. As a present, his
  parents gave him a new problem to solve: Chef has to fill a K x K
  square grid of integers in a certain way. Let us say that such a grid
  is valid if:

  Each cell contains an integer from 1 and K (inclusive).
  No integer appears twice in the same row or the same column.

  Let F(K) be maximum possible distance between the center of the square and the closest
  cell that contains 1, among all possible squares with the side length
  K.

  Here, we use the following notions:

  The distance between cell (x, y) and (i, j) is equal to |x-i|+|y-j|.
  The center of a K × K square is cell ((K+1)/2, (K+1)/2) for odd K.

  Input

  The first line of input contains a single integer T denoting the
  number of test cases. Each test case consists of a single line
  containing a single odd integer K.

  Output

  For each test case, print K lines each consisting of K space separated
  integers giving some square grid where the distance from the center of
  the grid to the nearest 1 is exactly F(K). If there's more than 1
  possible answer output any of them.

  Constraints

  Ki is odd.

  Subtask #1 (10 points):

  1 ≤ T ≤ 50
  1 ≤ Ki ≤ 5

  Subtask #1 (90 points):

  1 ≤ T ≤ 10
  1 ≤ Ki < 400

  Example

  Input:

2
1
3

  Output:

1
3 2 1
1 3 2
2 1 3

Here is my code in Java

import java.util.*;
import java.io.*;

public class Main {
    public static void main(String[] args) throws IOException{
        BufferedReader sc = new BufferedReader(new InputStreamReader(System.in));
        int t = Integer.parseInt(sc.readLine());
        while(t-- > 0){
            int n = Integer.parseInt(sc.readLine());
            int center = (n + 1)/2 ;
            for(int i = 0; i < n; i++){
                int temp = center;
                for(int j = 0; j < n; j++){
                    System.out.print(temp+" ");
                    temp++;
                    if(temp > n)
                        temp = 1;
                }
                center--;
                if(center < 1)
                    center = n;
                System.out.printf("%n");
            }
        }
    }
}

Here is my code in c++

#include <iostream>
using namespace std;

int main(void){
    int t;
    cin>> t;
    while(t--){
        int n;
        cin>>n;
        int center = (n + 1)/2 ;
        for(int i = 0; i < n; i++){
            int temp = center;
            for(int j = 0; j < n; j++){
                cout<<temp<<" ";
                temp++;
                if(temp > n)
                    temp = 1;
            }
            center--;
            if(center < 1)
                center = n;
            cout<<"\n";
        }
   }
   return 0;
}


texts: Return table value based on a primitive "priority queue"

texts:
I have 2 function in Lua, one to look if a key is present inside a provided table and if true then return the value, else return false. This lookup function is called by another function with a "priority queue". It is not a queue per definition but I don't have a better name for it.

function inTable(tbl, item)
    for key, value in pairs(tbl) do
        if key == item then
          return value
        end
    end
    return false
end

function ReturnString()
local valid = {}

valid[22] = "string1"
valid[13] = "string2"
valid[25] = "string3"
...

  if inTable(valid, "22") then
    return inTable(valid, "22")
  elseif inTable(valid, "13") then
    return inTable(valid, "13")
  elseif inTable(valid, "25") then
    return inTable(valid, "25")
  else
    print("nope not found")
  end
end

Usage:

print(ReturnString())

valid is filled with a lot of different key-value pairs, unordered. My goal is to return the value based on a priority I determine using my nested if-elseif-else construct. If there is a key 22 then return string1, else check if there is a key 13 and so on. I know that there are more real implementation of a priority queue like this but I prefer something simple. What improvement can I do without implementing a complex priority queue?


texts: Disable button when required inputs are not filled in

texts:
Currently I'm having a big form, with steps and a lot of complex fields. To make sure the user fills the required inputs and don't make them crazy pushing down the button submit when one required field on step 3 of 6 is no filled in, I decided to disable the button so they can see fast something is not right and check the form back.

My version is working but I'm not satisfied with the result because I'm sure it can be much better.

I simplify my form and I make a fiddle with my code to show the functionality:

You can check my code there.

HTML

  <form action="#myForm">
         Name * <input name="name1" placeholder="required" required>

         Surname * <input name="surname" placeholder="required" required>

         Age <input name="surname" placeholder="not-required">

         <button id="submitBtn" type="submit">Submit</button>
  </form>

Javascript + jQuery

   //This is the first load of is valid, just in case the user gets back again with old inputs
   //if all the required inputs are filled enable the button
   var isValid = true;
     $('input,textarea,select').filter('[required]:visible').each(function() {
      if ( $(this).val() === '' )
         isValid = false;
    });
    if( isValid ) {
       $('#submitBtn').prop('disabled', false);
    } else {
       $('#submitBtn').prop('disabled', true);
    };
    $('#submitBtn').click(function() {
        var isValid = true;
         $('input,textarea,select').filter('[required]:visible').each(function() {
          if ( $(this).val() === '' )
             isValid = false;
        });
        if( isValid ) {
           $("#myForm")[0].submit();
       };

    });

    //When a input is changed check all the inputs and if all are filled, enable the button
     $('input,textarea,select').change(function() {
        var isValid = true;
         $('input,textarea,select').filter('[required]:visible').each(function() {
          if ( $(this).val() === '' )
             isValid = false;
        });
        if( isValid ) {
           $('#submitBtn').prop('disabled', false);
        } else {
           $('#submitBtn').prop('disabled', true);
        };
    });

    //In case the user edits the button with firebug and removes disabled, check
    $('#submitBtn').click(function() {
         var isValid = true;
         $('input,textarea,select').filter('[required]:visible').each(function() {
          if ( $(this).val() === '' )
             isValid = false;
        });
        if( isValid ) {
           $("#myForm")[0].submit();
       };
    });


texts: Data structure for inserting and replacing data in list

texts:
I have a list of key value pairs, that is used as an intermediate store for building URL parameters or JSON data. Currently this is done with a linked list:

struct _kvp {
    char *key;
    struct _v *value; /* the implementation of _v does not matter right now */
    unsigned char is_array;
    struct _kvp *next;
};

struct _kvp_store {
    t_object x_ob;
    struct _kvp *first_data;
    struct _kvp *last_data;
};

Now I want to be able to do several things with the key value pairs:

Add a value identified with a key, that is not an array member: If an item with the same key already exists, I will replace that. If that item is currently an array, all array members have to be deleted first. Otherwise, append the data to the list.
Add an array member to the linked list: if an item with the same key exists and is not an array member, then replace that with the new key value pair, else if an item with the same key already exists and is an array member, add the new key value pair after all other items with the same key, otherwise append to the list.

This means, that for every added or replaced item, the whole list has to be scanned, running it in O(n) for each item or O(n²) for building a list from scratch. Is there a better data structure in C to use for that, that is just as simple to implement?

static void kvp_replace_single(
        struct _kvp *const item,
        struct _v *const value,
        const unsigned char is_array) {
    kvp_val_free(item->value);
    item->value = value;
    item->is_array = is_array;
}

static void kvp_replace_array(
        struct _kvp *const item,
        const char *const key,
        struct _v *const value) {
    struct _kvp *to_free;

    kvp_val_free(item->value);
    item->value = value;
    item->is_array = 0;
    while (item->next != NULL && strcmp(item->next->key, key) == 0) {
        to_free = item->next;
        item->next = to_free->next;
        kvp_free(to_free);
    }
}

static void kvp_add_array(
        struct _kvp_store *const store,
        struct _kvp *const item,
        char *const key,
        struct _v *const value) {
    struct _kvp *it = item;
    struct _kvp *new;

    while (it->next != NULL && strcmp(it->next->key, key) == 0) {
        it = it->next;
    }
    new = kvp_create(key, value, 1);
    kvp_insert(store, it, new);
}

static void kvp_add(
        struct _kvp_store *const store,
        char *const key,
        struct _v *const value,
        const unsigned char is_array) {
    struct _kvp *it = store->first_data;
    unsigned char found = 0;

    while (it != NULL) {
        if (strcmp(it->key, key) == 0) {
            found = 1;
            if (!it->is_array) {
                kvp_replace_single(it, value, is_array);
            } else if (!is_array) {
                kvp_replace_array(it, key, value);
            } else {
                kvp_add_array(store, it, key, value);
            }
            break;
        }
        it = it->next;
    }

    if (!found) {
        struct _kvp *new = kvp_create(key, value, is_array);
        kvp_insert(store, store->last_data, new);
    }
}


texts:
I am making a C library that abstracts window creation with support for the new Vulkan API under a unified API;
I have a github repository that you can check out.

main.c

#include "vkwf.h"

int main()
{
    VKWFWindow* window = VKWFCreateWindow("Test Window", 800, 600);

    while (!VKWFWindowShouldClose(window))
    {
        VKWFWindowUpdate(window);
    }

    free(window);

    return 0;
}

The way I am handling this is creating a general vkwf.h file, that includes a list of functions, like this:

vkwf.h

#pragma once

#ifdef __cplusplus
extern "C" {
#endif

#ifdef VKWF_PLATFORM_WINDOWS
#include "win32_window.h"
#elif VKWF_PLATFORM_MACOS
#include "macos_window.h"
#elif VKWF_PLATFORM_LINUX
#include "linux_window.h"
#endif

VKWFWindow* VKWFCreateWindow(const char* title, int width, int height)
{
    return VKWFPlatformCreateWindow(title, width, height);
}

VKWFBool VKWFWindowShouldClose(VKWFWindow* window)
{
    return VKWFPlatformWindowShouldClose(window);
}

void VKWFWindowUpdate(VKWFWindow* window)
{
    VKWFPlatformUpdate(window);
}

void VKWFDestroyWindow(VKWFWindow* window)
{
    VKWFPlatformDestroyWindow(window);
}

#ifdef __cplusplus
}
#endif

All VKWFPlatformX() functions are functions that get defined by the platform_window.h files, like this:

win32_window.h (short)

#define VKWFPlatformCreateWindow(title,width,height) VKWFWin32CreateWindow(title,width,height)
#define VKWFPlatformWindowShouldClose(window) VKWFWin32WindowShouldClose(window)
#define VKWFPlatformUpdate(window) VKWFWin32Update(window)
#define VKWFPlatformDestroyWindow(window) VKWFWin32DestroyWindow(window)

Does this look like a good approach?
Are there any drawbacks, or things that i could improve?


texts:
I am making a Cryptography application and I noticed that the encrypted file is approximately 2 times bigger because I am encoding the files in base64. Are there any file encodings that take less space? Here is the code that converts files into byte arrays:

Console.Write("Enter File Path: ");
docPath = Console.ReadLine();
extension = docPath.Substring(docPath.IndexOf(".")).Trim();
byte[] binarydata = File.ReadAllBytes(docPath);
text = System.Convert.ToBase64String(binarydata, 0, binarydata.Length);
var Encrypted = AESCryptography.Encrypt(text, m.ToString(), extension);
using (FileStream fs = File.Create(docPath.Substring(0,docPath.IndexOf(".")) + ".aent"))
{
    Byte[] info = new UTF8Encoding(true).GetBytes(Encrypted);
    // Add some information to the file.
    fs.Write(info, 0, info.Length);
}

and here is the Encryption class that does the actual encryption:

public static class AESCryptography
{
    private const int keysize = 256;
    public static string Encrypt(string plainText, string passPhrase, string extention)
    {
        byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);
        using (PasswordDeriveBytes password = new PasswordDeriveBytes(passPhrase, null))
        {
            byte[] keyBytes = password.GetBytes(keysize / 8);
            using (RijndaelManaged symmetricKey = new RijndaelManaged())
            {
                symmetricKey.GenerateIV();
                symmetricKey.Mode = CipherMode.CBC;
                using (ICryptoTransform encryptor = symmetricKey.CreateEncryptor(keyBytes, symmetricKey.IV))
                {
                    using (MemoryStream memoryStream = new MemoryStream())
                    {
                        using (CryptoStream cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
                        {
                            cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
                            cryptoStream.FlushFinalBlock();
                            byte[] cipherTextBytes = memoryStream.ToArray();
                            return Convert.ToBase64String(cipherTextBytes) + "\n" + Convert.ToBase64String(symmetricKey.IV) + "\n" + extention;
                        }
                    }
                }
            }
        }
    }

    public static string Decrypt(string cipherText, string passPhrase, string initVector)
    {
        byte[] initVectorBytes = Convert.FromBase64String(initVector);
        byte[] cipherTextBytes = Convert.FromBase64String(cipherText);
        using (PasswordDeriveBytes password = new PasswordDeriveBytes(passPhrase, null))
        {
            byte[] keyBytes = password.GetBytes(keysize / 8);
            using (RijndaelManaged symmetricKey = new RijndaelManaged())
            {
                symmetricKey.Mode = CipherMode.CBC;
                using (ICryptoTransform decryptor = symmetricKey.CreateDecryptor(keyBytes, initVectorBytes))
                {
                    using (MemoryStream memoryStream = new MemoryStream(cipherTextBytes))
                    {
                        using (CryptoStream cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read))
                        {
                            byte[] plainTextBytes = new byte[cipherTextBytes.Length];
                            int decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
                            return Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount);
                        }
                    }
                }
            }
        }
    }
}


texts: Confirm regex for validating password policy

texts:
I have the following password policy:

At least 8 characters in length
At least one digit
At least one special* character

*I consider any character that is not a letter, digit or space to be a special character.

I've come up with the following regex for enforcing this policy, and it seems to be working.

^(?=.*?[0-9])(?=.*?[^a-zA-Z0-9 ]).{8,}$

Are there any drawbacks or pitfalls with my regex?


texts: Using Mockito to verify that an object is saved

texts:
We've been reviewing some legacy code and have found differences in the preferred approach to how to write tests using Mockito.

Both the following tests pass but which one is better and why?

@Test
public void verifyObjectSaved() throws PersistQueueException {
    final UserTokenVo userTokenVo = new UserTokenVo();

    String token = vodafoneSubscriptionService.processTokenRequest(userTokenVo);

    Mockito.verify(userTokenDao).savePayload(isA(String.class), eq(userTokenVo));

    assertTrue(StringUtils.isNotBlank(token));
}

and

@Test
public void verifyObjectSaved() throws PersistQueueException {
    final UserTokenVo userTokenVo = new UserTokenVo();

    doAnswer(new Answer() {
        public Object answer(InvocationOnMock invocation) {
            return "completed";
        }
    }).when(userTokenDao).savePayload(any(String.class), eq(userTokenVo));

    String token = vodafoneSubscriptionService.processTokenRequest(userTokenVo);

    assertTrue(StringUtils.isNotBlank(token));

    verify(userTokenDao, times(1)).savePayload(any(String.class), eq(userTokenVo));
}

Here's the production code it tests — it's not very complicated:

public String processTokenRequest(UserTokenVo userTokenVo) {
    String token;

    try {
        token = new String(TokenFactory.getToken());
        if (token != null) {
            userTokenDao.savePayload(token, userTokenVo);
        }
    } catch (Exception e) {
        LOGGER.error("failed to save token");
        token = null;
    }
    return token;
}


texts: Guessing a unique 4 random digits number

texts:
I've created a simple game, in which the user needs to guess 4 digits number between 0-9, generated randomly using Random() Each of the 4 digits are different from each other, with no repeated digits.  The user has 5 attempts to guess, and each failed (almost correct) guess will tell the user in which part they got it correct.

Do you think this is too hard, or too easy for the user to guess?  I also need some review of this code.  Perhaps some of it can be simplified?

import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;

public class Game {

    public static void main(String[] args) {
        System.out.println("The computer has generate a unique 4 digit number.\n"
                + "You can try to guess the 4 digits number in 5 attempts.\n");
        System.out.println("_______________________________________________________\n");
        int[] random=numberGenerator();
        int maxTry=5;
        int indexMatch=0;
        int match=0;
        while(maxTry>0 && indexMatch!=4){
            int[] guess=getGuess();
            indexMatch=0;
            match=0;
            for(int i=0;i<guess.length;i++){
                if(guess[i]==random[i]){
                    indexMatch++;
                }
                else if(guess[i]==random[0] || guess[i]==random[1] || guess[i]==random[2] || guess[i]==random[3]){
                    match++;
                }
            }
            if(indexMatch==4){
                System.out.print("Well done! Your guess is Correct! The number is: ");
                for(int i=0;i<guess.length;i++){
                    System.out.print(guess[i]);
                }
            }
            else{
                maxTry--;
                if(maxTry>1){
                    System.out.println("You have guess "+indexMatch+" correct number in correct position,"+
                    " and "+match+" correct number in incorrect position. \n"+maxTry+" attempt remaining.");
                }
                else if(maxTry==1){
                    System.out.println("You have guess "+indexMatch+" correct number in correct position,"+
                    " and "+match+" correct number in incorrect position. \nLast attempt!. Good luck");
                }
                else{
                    System.out.println("Sorry, you failed to guess the number in 5 attempts.");
                    System.out.print("The number is: ");
                    for(int i=0;i<random.length;i++){
                        System.out.print(random[i]);
                }
            }
        }
    }
}

public static int[] getGuess(){
    Scanner keyboard = new Scanner(System.in);
    System.out.println("Please enter your guess: ");
    String input = keyboard.nextLine();
        if(input.length()!=4 || input.replaceAll("\\D","").length()!=4){
            System.out.println("Invalid number. You must enter 4 digits between 0-9 only.");
            return getGuess();
    }
    int[] guess = new int[4];
    for (int i = 0; i < 4; i++) {
        guess[i] = Integer.parseInt(String.valueOf(input.charAt(i)));
    }
    return guess;
}

public static int[] numberGenerator() {
    Random randy = new Random();
    int[] randArray = {10,10,10,10};

    for(int i=0;i<randArray.length;i++){
        int temp = randy.nextInt(9);
        while(temp == randArray[0] || temp == randArray[1] || temp == randArray[2] || temp == randArray[3]){
            temp=randy.nextInt(9);
        }
        randArray[i]=temp;
    }
    return randArray;
}
}


texts: Get the length of data within a buffer (by getting the position of the last byte with data)

texts:
Background. I start out with a completely empty byte[4096]. As data streams into my application, the byte[4096] gets filled with data starting from first position.

This results in a byte array that is partially filled, but mostly empty, like so...

                0  1  2  3  4  5  6  7  8                       4096
byte[4096] --> [+][+][+][+][+][+][+][+][+][ ][ ][ ][ ][ ][ ] ... [ ]

[+] = Data
[ ] = Empty

I am trying to quickly obtain the position of the last byte with data.

My Question for Code Review

I'm looking for feedback for performance and possibly any correctness in unanticipated cases of this code block:

/// <summary>
/// Get the position of the last byte with data
/// </summary>
public static int GetPositionOfLastByteWithData(this byte[] array)
{
    int i = array.Length - 1;
    // find the end of the buffer by iterating backwards
    while (array[i] == 0) --i;

    return i;
}

Note: This method will throw an exception in the event that the byte[] passed in is totally blank/empty. In the actual use, I do validate that there is data in the byte array before it gets to this method. This method is aimed squarely for high performance.


texts:
I want to create a class ClientSocket with PHP, which is an adapter of the fsockopen, fread, and fwrite.

Class ClientSocket extends SenderAdapterAbstract
{
    private $s = null;

    public function __construct($host, $port)
    {
        $this->s = fsockopen($host, $port);
    }

    // Abstract method concrete implementation
    public function send($message)
    {
        fwrite($this->s, $message);

        $result = fgets($this->s);
        fclose($this->s);
    }
}

Should I test this class?  A unit test is not really one if it talks to the network.

Here is some rules about unit testing (I totally agree with them):

A test is not a unit test if:

It talks to the database
It communicates across the network
It touches the file system
It can't run at the same time as any of your other unit tests
You have to do special things to your environment (such as editing config files) to run it.


texts: Detecting a cycle in a directed graph via an adjacency list implementation and a recursive DFS

texts:
Here's my attempt. I iterate through each vertex in the graph and do a DFS to see if I reach back on a vertex I already visited in this vertex's iteration. It seems to work but I am not satisfied with how I short-circuit my code when it found a cycle using if clauses, could not think of a better way to do that.
public boolean isCyclic(Map<T, List<T>> adjacencyList) {

    for (T node: adjacencyList.keySet()) {
        Set<T> visited = new HashSet<>();
        visited.add(node);
        if (isCyclic(visited, node) == true)
            return true;
    }

    return false;
}

private boolean isCyclic(Set<T> visited, T node) {
    boolean retval;
    for (T connectedNode: map.get(node)) {
        if (visited.contains(connectedNode)) {
            // We've reached back to a vertex, i.e. a back-edge
            return true;
        } else {
            visited.add(connectedNode);
            if (isCyclic(visited, connectedNode) == true)
                return true;
        }
    }

    return false;
}


texts:
This program tests whether a string is a palindrome or not.
Can there be any improvements or shortcuts that can be used in the program. You can give any type of string as input. The program finds does it work.

#include <stdio.h>
#include <string.h>

/*
A palindrome is a string that is same in both forward and backward reading.
Example:
   "madam"
   "racecar"
   "a man a plan a canal panama"
   "radar"
You will write a program that will test if a given string is a palingdrome or not.
Your program will ask the user to input a string and if the string is a palindrome program
will just print "Yes, it is a Palindrome", otherwise will print "No, not a Palindrome".

Please note that:
1. Your you need to check in case-insensitive way, that means: Madam or madam both should be
detected as Palindrome.

2. There can be (any number of ) spaces in between the words.
    "A man a plan a canal panama"
        OR
    "A     man    a   pla n a cana l Panama"
    both the strings must be detected as Palindrome.
3.There can be punctuations in between the words, for this assignments,
we consider only 4 punctuations,   . ?  ! and ,

Your program will just need to ignore them (treat them as space).
    "Cigar? Toss it in a can. It is so tragic."
    Should be detected as palindrome.

 *** For this assignment I will not write any instructions or guidance, you are free
        to implement it with your own way, you can use the string.h functions

    Good luck.

*/

/***********************************************************************

    Created by Shaik Mohammed Zeeshan
    Date - 19 Aug 2018
    Objective - Checks whether a given string is palindrome or not

************************************************************************/

int main()
{
    char string[100];
    char string1[100];//the string without spaces and special characters will be stored in this

    printf("Enter a string: ");
    scanf("%[^\n]", string);

    int isPalindrome = 1;  // assign 0 to this if the string is a NOT palindrome

    // write code to test if string is a palindrome

    int index;
    int index1;//index for the second array

    for(index=0,index1=0;string[index] != '\0'; index++)  //to eliminate spaces, special characters and capital letters from the string
    {
        if( (string[index] < 'A' || string[index] > 'Z' ) && (string[index] < 'a' || string[index] > 'z' ) ) // checks if the element is a special
            continue;                                                                              // character or space and skips the iteration

        if(string[index] >= 'A' && string[index] <= 'Z' )
            string[index] += 32;

        string1[index1] = string[index];
        index1++;
    }
    string1[index1] = '\0'; // assigning the last element with null character

    int i,stringlength = strlen(string1); // storing length after eliminating unecessary characters

    for(i=0;i<=stringlength/2;i++) //starts the loop from first element to the middle element
    {
        if(string1[i] != string1[stringlength-i-1]) //checks if the elements are true
        {
            isPalindrome = 0;   // checks the first  element with the first element from the last and second element with the penultimate element and so on
            break;
        }
    }

    // at the end you need to test
    if (isPalindrome)
        printf("Yes, it is Palindrome!\n");
    else
        printf("No, not a Palindrome\n");

    return 0;
}


texts:
So I made a quick programme in F# to do FizzBuzz, I'm trying to learn more languages, so I figured I'd do something functional for a change. (Haskell is also on the list.)

FizzBuzz is pretty self-explanatory: every third value print Fizz, every fifth print Buzz (possible both if it's a multiple of 3 and 5).

[<EntryPoint>]
let main argv =
    let fizzBuzzSequence = seq {
        for value in 1..100 do
            let valueMod3 = value % 3
            let valueMod5 = value % 5

            if valueMod3 = 0 && valueMod5 = 0 then yield "FizzBuzz"
            else if valueMod3 = 0 && valueMod5 <> 0 then yield "Fizz"
            else if valueMod3 <> 0 && valueMod5 = 0 then yield "Buzz"
            else yield value.ToString()
    }
    for value in fizzBuzzSequence do printfn "%s" value
    0


texts: Calculate and make a database of prime numbers

texts:
I recently created a program for finding a prime number. It's working great and doing it very fast but I was wondering if you can help me make it calculate the prime numbers faster.

    procedure btnCalculateClick(Sender: TObject);
     procedure btnStopClick(Sender: TObject);
     procedure FormActivate(Sender: TObject);
     procedure Timer1Timer(Sender: TObject);
     procedure btnRefreshClick(Sender: TObject);
    private
     iTime, iMin, iHour, iSec, iPrimes : integer;
     iNum,iNumB, iRep, iFakt, iFak : int64;
     bStart : boolean;
    procedure RefreshTime;
    { Private declarations }
    public
    { Public declarations }
     end;

    procedure TfrmPrimeFaktors.btnCalculateClick(Sender: TObject);
    begin
     bStart := true;
     Append(myFile);
     bStop := false;
    repeat
     iRep := 1;
     iFakt := 0;
     while (iFakt <= 1) AND (iRep <= ceil(sqrt(iNum))) do
      begin
        if iNum MOD iRep = 0 then inc(iFakt);
        inc(iRep,1);
      end;

    if iFakt = 1 then
      begin
         sNum := IntToStr(iNum);
         WriteLn(myFile, sNum);
         inc(iPrimes);
      end;

    inc(iNum);
    Application.ProcessMessages;
    until bStop = true;
  CloseFile(myFile);
  label2.Caption := 'Primes found: ' + intToStr(iPrimes);
  label3.Caption := 'Numbers Checked: ' + intToStr(iNum-iNumB);
end;


texts:
For this challenge on HackerRank:

  A valley is a sequence of consecutive steps below sea level, starting with a step down from sea level and ending with a step up to sea level.

  Given Gary's sequence of up and down steps during his last hike, find and print the number of valleys he walked through.

  For example, if Gary's path is s=[DDUUUUDD], he first enters a valley 2 units deep. Then he climbs out and up into a mountain 2 units high. Finally, he returns to sea level and ends the hike.

I reached a solution, but I'm sure it can be optimized:

function countingValleys(n, s) {
    let heightTracker = [];
    let height = 0;
    for (let i = 0; i < s.length; i++) {
        if (s[i] === "D") {
            height--;
            heightTracker.push(height);
        }
        if (s[i] === "U") {
            height++;
            heightTracker.push(height);
        }
    }
    let planeTracker = [];
    for (let j = 0; j < heightTracker.length; j++) {
        if (heightTracker[j] < 0) {
            planeTracker.push("valley");
        }
        if (heightTracker[j] > 0) {
            planeTracker.push("mountain");
        }
        if (heightTracker[j] === 0) {
            planeTracker.push("flat");
        }
    }
    let newArray = [];
    for (let k = 0; k < planeTracker.length; k++) {
        if (planeTracker[k] === planeTracker[k - 1]) {
            continue;
        }
        if (planeTracker[k] !== planeTracker[k - 1]) {
            newArray.push(planeTracker[k]);
        }
    }
    let valleyCount = 0;
    for (let l = 0; l < newArray.length; l++) {
        if (newArray[l] === "valley") {
            valleyCount++;
        }
    }
    return valleyCount;
}

My logic was to keep track of all negative and positive values in s.

If heightTracker[j] is negative, push "valley" into planeTracker
If heightTracker[j] is positive, push "mountain" into planeTracker
Otherwise, push "flat" into planeTracker

So at that point, I'm left with:

[ 'valley', 'valley', 'valley', 'flat', 'valley', 'valley', 'valley', 'valley', 'valley', 'flat', 'mountain', 'flat' ]

And I'm wondering, is there a way to filter out any elements that are the same as the element before them? The goal was to generate the array:

[ 'valley', 'flat', 'valley', 'flat', 'mountain', 'flat'] and then count the number of times the word "valley" appears in that array. As you can see, I did this with a for-loop. But I'm wondering what other suggestions you'd have - maybe the .filter() method?


texts:
I wanted to check and see if this was as efficient as can be. The goal is to get a user's data from a group of documents that contains references to users in Firestore.
ngOnInit
this.links = this.currentUserRef.collection('links', ref => ref.where('pendingRequest', '==', false)).get()
            .pipe(map(querySnap => {
                const ret = [];
                querySnap.forEach(async doc => {
                    const val = await doc.get('otherUser').get().then(async userData => {
                        return {
                            id: userData.id,
                            img: await this.getImage(userData.get('profilepic')),
                            name: userData.get('name'),
                            bio: userData.get('bio')
                        }
                    });
                    ret.push(val);
                });
                return ret;
            }));

HTML
<ion-item *ngFor="let link of links | async">
            <ion-avatar slot="start">

            </ion-avatar>
            <ion-label>

{{link.name}}

{{link.bio}}

            </ion-label>
            <ion-checkbox id="{{link.id}}"></ion-checkbox>
        </ion-item>


texts:
I implemented a search function like this:

private static void GetResults(ref ObservableCollection<string> resultTitles, ref string[] query, ref ObservableCollection<int> weight)
{
    int position = -1;

    foreach (string[] r in SearchKeys.Keys)
    {
        position++;
        foreach (string s in query)
        {
            int m = r.Length/2;
            int min = r[m][0] < s[0] ? m : 0;
            int max = r[m][0] <= s[0] ? r.Length : m+1;

            for (int i = min; i < max; i++)
            {
                weight.Add(0);

                if (r[i] == s)
                {
                    if (weight[position] == 0)
                    {
                        resultTitles.Add(r[0]);
                    }
                    weight[position]++;

                }   // end if
            }   // end foreach(s)
        }   // end foreach(t)
    }   // end foreach(r)
}

In the main program, the use inputs a query, the program splits the query at the spaces, and passes the query and two empty ObservableCollections to this function.

SearchKeys.Keys is implemented like this:

public static string[][] Keys = { Array1, Array2, Array3 };

The arrays are implemented like this:

private static string[] Array1 = { "Title", "val1", "val2", "val3", "val4", "val5", "val6" };

As always, all comments are welcome; particularly, I am interested in which ways could this code's performance be improved.  The data in SearchKeys is sorted, of course.

This is a previous version of my code, which may also be of interest.  This version should run about twice as slow as the above, according to my estimates:

private void getResults(ref ObservableCollection<string> tmp, ref string[] query, ref ObservableCollection<int> weight)
{
    int position = -1;

    foreach (string[] r in SearchKeys.Keys)
    {
        position++;
        foreach (string t in r)
        {
            weight.Add(0);

            foreach (string s in query)
            {
                if (t == s)
                {
                    if (weight[position] == 0)
                    {
                        tmp.Add(r[0]);
                    }
                    weight[position]++;

                }   // end if
            }   // end foreach(s)
        }   // end foreach(t)
    }   // end foreach(r)
}

This is how I call this function:

static void Main(string[] args)
{
    ObservableCollection<int> weight = new ObservableCollection<int>();
    ObservableCollection<string> resultTitles = new ObservableCollection<string>();
    string[] query = Console.ReadLine().Split(' ');

    GetResults(ref resultTitles, ref query, ref weight);
    StableSort(ref resultTitles, ref weight);

    foreach (string s in resultTitles)
        Console.WriteLine(resultTitles.IndexOf(s)+": "+s);
}

This is StableSort (see Stable Sort in C#):

static void StableSort(ref ObservableCollection<string> values, ref ObservableCollection<int> weights)
{
    while(weights.Contains(0))
    {
        weights.Remove(0);
    }

    if (values == null) { throw new ArgumentNullException("values"); }
    if (weights == null) { throw new ArgumentNullException("weights"); }

    if (values.Count != weights.Count) { throw new ArgumentOutOfRangeException("collections count not equal", (Exception)null); }

    ObservableCollection<string> localValues = new ObservableCollection<string>();
    ObservableCollection<int> localWeights = new ObservableCollection<int>();

    int index = -1;
    var weightsWithIndex = weights.Select(p => new { Value = p, Index = ++index }).OrderByDescending(p => p.Value);

    foreach (var w in weightsWithIndex)
    {
        localWeights.Add(w.Value);
        localValues.Add(values[w.Index]);
    }

    values = localValues;
    weights = localWeights;
}


texts: Asking the user to input a proper email address

texts:
The purpose of this code is to ask the user to input an email address but it must contain "@" and ".co". The code works but it is too long so I would like to know if there is any way to shorten it using functions.

email_address = input("What is your email address? ")
while "@" not in email_address:
    email_address = input("Your email address must have '@' in it\nPlease write your email address again: ")
    if len(email_address) <= 6 :
        email_address = input("Your email address is too short\nPlease write your email address again: ")
    if "." not in email_address:
        email_address = input("Your email address must have '.' in it\nPlease write your email address again: ")
while "." not in email_address:
    email_address = input("Your email address must have '.' in it\nPlease write your email address again: ")
    if len(email_address) <= 6 :
        email_address = input("Your email address is too short\nPlease write your email address again: ")
    if "@" not in email_address:
        email_address = input("Your email address must have '@' in it\nPlease write your email address again: ")


texts:
I used to use the MemoryCache in .Net but recently read about a DB using  using a linked-list, which only had to check the prefix of the list in \$O(1)\$ complexity, to time values out, as opposed to ln N; the heap-based approach that's default for variable timeout, min-heaps.

I'd appreciate a review of this code; in terms of how optimal it is and if there are obvious mistakes in it, that I'm missing. The general idea is that count(R) >>> count(W).

I considered using ReaderWriterLockSlim in upgradeable mode, but I may very well have two threads with read locks trying to acquire a write upgrade simultaneously in this piece of code, so I decided against. The check of the queue head is supposed to be quick enough to avoid contention around this resource.

This code is intended to be used in a low-latency F# API as part of Logibit Hawk.

I'd also like this code to be non-allocating, besides the single int64 that's the Instant (x2) and the allocated-outside string reference. Returning Choice-values (allocating) is intentional however, and will be changed to Result in the future.

module Settings =
  open NodaTime
  open System.Collections.Generic
  open System.Collections.Concurrent

  let private tsem = obj ()
  let private runTimeouts (timeouts: Queue<_>) (cache: ConcurrentDictionary<string, Instant>) (now: Instant) =
    /// Iterate until the head is due later than now. Tail-recursion needed.
    let rec iter () =
      if timeouts.Count = 0 then () else
      let struct (nonce, timeout) = timeouts.Peek()
      if timeout > now then () else
      ignore (timeouts.Dequeue())
      ignore (cache.TryRemove nonce)
      iter ()
    lock tsem iter

  let nonceValidatorMem (clock: IClock) (keepFor: Duration) =
    // We will use a queue, because it's O(1) on dequeue/peek and since the duration is a constant for the
    // life time of this validator, we know the head is due closest in time.
    let timeouts = Queue<_>()
    // The cache stores the nonces and when they were added
    let cache = ConcurrentDictionary<_, _>()

    fun (nonce: string, ts: Instant) ->
      let now = clock.GetCurrentInstant()
      do runTimeouts timeouts cache now
      // https://docs.microsoft.com/en-us/dotnet/api/system.collections.concurrent.concurrentdictionary-2.tryadd?view=netframework-4.7.1
      // returns true if the nonce was successfully added
      if cache.TryAdd (nonce, now) then
        do lock tsem (fun () -> timeouts.Enqueue (struct (nonce, now + keepFor)))
        Choice1Of2 ()
      else
        Choice2Of2 AlreadySeen


texts: Exposing includes to client over webservice for database queries

texts:
I am using a CQRS type patter for querying data in my application. I am currently using entity framework to connect to the database.

public class GetCustomerQuery : IQuery<Customer>
{
     public string CustomerId { get; set; }
}

public class GetCustomerQueryHandler : IQueryHandler<GetCustomerQuery, Customer>
{
    public void Handle(GetCustomerQuery query)
    {
        return _dbContext.Customers.FirstOrDefault(c => c.Id == query.CustomerId);
    }
}

The problem I am having with this design is that the Customer object has relationships with other entities:

public void Customer
{
    public string Id { get; set; }
    public IList<Post> Posts { get; set; }
}

The query handler shown above will not return the list of posts, as this is a one-to-many relationship in the database. The way I was thinking to solve this was to add a BaseQuery object which allowed settings includes:

public abstract class BaseQuery<T> : IQuery<T>
{
    public void AddInclude(Expression<Func<T, object>> include)
    {
      ....
    }
}

Is this considered a leaky abstraction, as it exposes the structure of the database?

Is there a better way around this problem?


texts: Inserting Data in The Database using LINQ TO SQL

texts:
Can this Code be any shorter? because it seems it is very long with just simple insertion of data using LINQ TO SQL

 public void addPatientInformation() {

            using(DbClassesDataContext myDb = new DbClassesDataContext()){

                PatientInfo patientInfo = new PatientInfo();

                patientInfo.Phy_ID = physcianID;
                patientInfo.Pat_First_Name = txtFirstName.Text;
                patientInfo.Pat_Middle_Init = txtMiddleName.Text;
                patientInfo.Pat_Last_Name = txtLastName.Text;
                patientInfo.Pat_Gender = cmbGender.Text;
                patientInfo.Pat_Marital_Status = cmbMaritalStatus.Text;
                patientInfo.Pat_Date_Of_Birth = dtpDOB.Value;
                patientInfo.Pat_Home_Add = txtHomeAdd.Text;
                patientInfo.Pat_Home_Num = txtPhone.Text;
                patientInfo.Pat_Work_Add = txtWorkAdd.Text;
                patientInfo.Pat_Work_Num = txtWorkPhone.Text;
                patientInfo.Pat_Prim_Physician = txtPrimPhysician.Text;
                patientInfo.Pat_Ref_Physician = txtRefePhysician.Text;

                myDb.PatientInfos.InsertOnSubmit(patientInfo);
                myDb.SubmitChanges();
        }


texts:
This is Dijkstra's algorithm in PHP. Regarding the data structure, I use a 2-dimensional array $_distArr[m][n]=length to store it. Are there any improvements for this?

$a and $b are the start and the end node, respectively.

<?php
/**
 *  Dijkstra's algorithm in PHP by zairwolf
 *
 *  Demo: http://www.you4be.com/dijkstra_algorithm.php
 *
 *  Source: https://github.com/zairwolf/Algorithms/blob/master/dijkstra_algorithm.php
 *
 *  Author: Hai Zheng @ https://www.linkedin.com/in/zairwolf/
 *
 */

//set the distance array
$_distArr = array();
$_distArr[1][2] = 7;
$_distArr[1][3] = 9;
$_distArr[1][6] = 14;
$_distArr[2][1] = 7;
$_distArr[2][3] = 10;
$_distArr[2][4] = 15;
$_distArr[3][1] = 9;
$_distArr[3][2] = 10;
$_distArr[3][4] = 11;
$_distArr[3][6] = 2;
$_distArr[4][2] = 15;
$_distArr[4][3] = 11;
$_distArr[4][5] = 6;
$_distArr[5][4] = 6;
$_distArr[5][6] = 9;
$_distArr[6][1] = 14;
$_distArr[6][3] = 2;
$_distArr[6][5] = 9;

//the start and the end
$a = 1;
$b = 5;

//initialize the array for storing
$S = array();//the nearest path with its parent and weight
$Q = array();//the left nodes without the nearest path
foreach(array_keys($_distArr) as $val) $Q[$val] = 99999;
$Q[$a] = 0;

//start calculating
while(!empty($Q)){
    $min = array_search(min($Q), $Q);//the most min weight
    if($min == $b) break;
    foreach($_distArr[$min] as $key=>$val) if(!empty($Q[$key]) && $Q[$min] + $val < $Q[$key]) {
        $Q[$key] = $Q[$min] + $val;
        $S[$key] = array($min, $Q[$key]);
    }
    unset($Q[$min]);
}

//list the path
$path = array();
$pos = $b;
while($pos != $a){
    $path[] = $pos;
    $pos = $S[$pos][0];
}
$path[] = $a;
$path = array_reverse($path);

//print result
echo "";
echo "
From $a to $b";
echo "
The length is ".$S[$b][1];
echo "
Path is ".implode('->', $path);


texts: Positioning a tooltip relative to various kinds of elements

texts:
I am trying to simplify the following massive conditional statement but have no idea how to. Does anyone have suggestions for it?

//regular elements use the normal position variables.
var tooltipXPos = xPos;
var tooltipYPos = yPos-$tooltipElement.height()-YOffset;

//individual elements position shifting...
//for sub_link on top
if ($element.is('#uilder') || $element.is('#options')) {
    tooltipYPos = yPos + 35;
}

//expend button after do search in Search page
if ($element.is('#extend')) {
    tooltipXPos = xPos - 240;
}
if ($element.is('#lis')) {
     tooltipXPos = xPos - 295;
     tooltipYPos = yPos - 80;
}

if ($element.is('#count')) {
    tooltipXPos = xPos + 180;
    tooltipYPos = yPos - 90;
}
if ($element.is('label')) {
    tooltipXPos = xPos + 80;
    tooltipYPos = yPos - 90;
}

if ($element.is('#add')) {
    tooltipXPos = xPos -280;
    tooltipYPos = yPos -120;
}

if ($element.is('title_label')) {
    tooltipXPos = xPos + 35;
    tooltipYPos = yPos -75;
}

//assign homework by class button under homework tab..
if ($element.is('#control')) {
    tooltipXPos = xPos -270;
}

//place the tutorial window
$tooltipElement.css({
    position: 'absolute',
    top: tooltipYPos,
    left: tooltipXPos,
    'z-index': 9999
})


texts: Iterating through nested array of objects

texts:
I have the following JSON list of objects, and I'm able to find the required object, and pass it back to the caller, given the id. Everything works fine, I'm just wondering if there's a better (more efficient) way to return the node. I'm open to using a 3rd party tool like lodash.

JSON payload:

{
  "_expanded": true,
  "_canDrop": false,
  "_id": "-1",
  "_name": "root",
  "_children": [
    {
      "_expanded": true,
      "_canDrop": false,
      "_id": "1",
      "_name": "Child 1",
      "_children": [
        {
          "_expanded": true,
          "_canDrop": false,
          "_id": "1-1",
          "_name": "Child 1-1",
          "_children": [
            {
              "_expanded": false,
              "_canDrop": false,
              "_id": "1-1-1",
              "_name": "Child 1-1-1",
              "_children": []
            }
          ]
        },
        {
          "_expanded": false,
          "_canDrop": false,
          "_id": "1-2",
          "_name": "Child 1-2",
          "_children": []
        },
        {
          "_expanded": false,
          "_canDrop": false,
          "_id": "1-3",
          "_name": "Child 1-3",
          "_children": []
        }
      ]
    },
    {
      "_expanded": true,
      "_canDrop": false,
      "_id": "2",
      "_name": "Child 2",
      "_children": [
        {
          "_expanded": false,
          "_canDrop": false,
          "_id": "2-2",
          "_name": "Child 2-2",
          "_children": []
        }
      ]
    }
  ]
}

Find method:

public findNode = (id: any): TreeNode => {
    let result = null;
    if (this._id === id) {
      result = this;
    } else {
      if (this._children.length > 0) {
        for (let index = 0; index <= this._children.length - 1; index++) {
          result = this._children[index].findNode(id);
          if (result) {
            break;
          }
        }
      }
    }
    return result;
  }


texts: Display content if form field is filled - Do not display if field is empty

texts:
I am using the following code within the footer of my test site. I am using WordPress and Advanced Custom Fields

The intention is:

To display the HTML container .social-media--icons if any of the fields contain content within the CMS.
Then, within the container .social-media--icons, display the relevant icon and href if that field is filled.

I have included strlen(trim($twitter)) > 0 as I understand this will detect if the field only has spaces.

I appear to have this working locally and performing the above tasks. I am looking to find out if there is a clearer, optmisied method of performing these tasks

  <img src="<?php echo get_template_directory_uri(); ?>/svg/arrow.svg" alt="Up Arrow">

&copy;
    <?php echo date('Y'); ?>

  <?php

    $facebook = get_field('facebook', 'option');
    $twitter = get_field('twitter', 'option');
    $instagram = get_field('instagram', 'option');
?>

  <?php if(isset($facebook) && strlen(trim($facebook)) > 0 || isset($twitter) && strlen(trim($twitter)) > 0 || isset($instagram) && strlen(trim($instagram)) > 0): ?>

    <?php if(isset($facebook) && strlen(trim($facebook)) > 0): ?>
    <a class="social-link ie9" href="<?php echo $facebook; ?>" target="_blank" rel="noopener">
        <img src="<?php echo get_template_directory_uri(); ?>/svg/facebook.svg" alt="Facebook Icon">

    <?php endif; ?>

    <?php if(isset($twitter) && strlen(trim($twitter)) > 0): ?>
    <a class="social-link ie9" href="<?php echo $twitter; ?>" target="_blank" rel="noopener">
        <img src="<?php echo get_template_directory_uri(); ?>/svg/twitter.svg" alt="Twitter Icon">

    <?php endif; ?>

    <?php if(isset($instagram) && strlen(trim($instagram)) > 0): ?>
    <a class="social-link ie9" href="<?php echo $instagram; ?>" target="_blank" rel="noopener">
        <img src="<?php echo get_template_directory_uri(); ?>/svg/instagram.svg" alt="Instagram Icon">

    <?php endif; ?>

  <?php endif; ?>


texts:
When looking at people you may know on LinkedIn (requires you to be logged in) there are sometimes some annoying boxes that are for people who are email contacts but not on LinkedIn.  I don't want to see these.  If I wanted to connect with them and invite them to LinkedIn, I would have.  So I wrote a userscript!  I wrote a few versions, because I wasn't sure about all of these things.  I've never written a userscript before, so let me know if any of this is weird, or not idiomatic, or something

This version uses jQuery!  That seems like overkill though...

// ==UserScript==
// @name Hide invites
// @namespace http://dannnno.github.io/
// @description Hides those "Invite to network boxes" on LinkedIn
// @include https://www.linkedin.com/people/pymk/hub/*
// @require https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js
// @grant GM_log
// ==/UserScript==

$(document).on('scroll', function (event) {
    $('li.card.guest').hide();
});

This version uses jQuery in a Chrome compatible way:

// ==UserScript==
// @name Hide invites - Chrome compatible
// @namespace http://dannnno.github.io/
// @description Hides those "Invite to network boxes" on LinkedIn in a Chrome compatible way
// @include https://www.linkedin.com/people/pymk/hub/*
// @require https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js
// @grant GM_log
// ==/UserScript==

var version = "2.1.4";

// Code adapted from http://stackoverflow.com/a/12751531/3076272
if (typeof jQuery !== "function") {
    add_jQuery(version);
}

function add_jQuery (jqVersion) {
    var jqVersion = jqVersion || version;
    var targ = document.getElementsByTagName('head')[0] || document.body || document.documentElement;
    var scriptNode = document.createElement('script');
    scriptNode.src = 'http://ajax.googleapis.com/ajax/libs/jquery/' + jqVersion + '/jquery.min.js';
    scriptNode.addEventListener("load", function () {
        var scriptNode = document.createElement("script");
        scriptNode.textContent = 'jQuery.noConflict(true);';
        targ.appendChild(scriptNode);
    }, false);
    targ.appendChild(scriptNode);
}

jQuery(document).on('scroll', function (event) {
    jQuery('li.card.guest').hide();
});

And this version does it without jQuery:

// ==UserScript==
// @name Hide invites - no jQuery!
// @namespace http://dannnno.github.io/
// @description Hides those "Invite to network boxes" on LinkedIn without jQuery
// @include https://www.linkedin.com/people/pymk/hub/*
// ==/UserScript==

// Throttling adapted from https://developer.mozilla.org/en-US/docs/Web/Events/scroll
(function() {
    var throttle = function(type, name, obj) {
        var obj = obj || window;
        var running = false;
        var func = function() {
            if (running) { return; }
            running = true;
            requestAnimationFrame(function() {
                obj.dispatchEvent(new CustomEvent(name));
                running = false;
            });
        };
        obj.addEventListener(type, func);
    };

    throttle("scroll", "optimizedScroll");
})();

// handle event
window.addEventListener("optimizedScroll", function() {
    var results = document.querySelectorAll('li.card.guest:not([style*="display:none"]):not([style*="display: none"])';
    for (var i = 0; i < results.length; ++i) {
        results[i].style.display = "none";
    }
});

Some bits of these were adapted from other sources (there are code comments to that effect).  Feel free to review those as much or as little as you'd like.


texts: Another dynamic array implementation in C

texts:
I saw quite a few posts about making a dynamic array so I tried making my own for learning purposes.
Here it is:
#ifndef VECTOR_H
#define VECTOR_H

#include <stdlib.h>
#include <stdbool.h>
#include <string.h>

#ifndef VECTOR_RESERVE_SIZE
#define VECTOR_RESERVE_SIZE 4
#endif

//Declaration

typedef struct
{
        int size_of_each;
        int reserved;
        int used;
        void* data;
} vector_t;

bool vector_init(vector_t *, int);
void vector_append(vector_t *, void *);
void* vector_get(vector_t *, int );
void vector_set(vector_t *, int, void *);
void vector_free(vector_t *);

//Implementation

bool vector_init(vector_t *p, int s)
{
        p->size_of_each = s;
        p->reserved = VECTOR_RESERVE_SIZE;
        p->used = 0;
        p->data = malloc(VECTOR_RESERVE_SIZE * p->size_of_each);

        if (p->data != NULL) { return false; }
        else { return true; }
}

void vector_append(vector_t *p, void *d)
{
        if (p->used == p->reserved)
        {
                p->data = realloc(p->data, VECTOR_RESERVE_SIZE);
                //printf("reallocated \n");
                p->reserved += VECTOR_RESERVE_SIZE;
        }
        memcpy((void*)((char*)p->data + p->size_of_each * p->used),  // copy to back of the vector
                        d, p->size_of_each);

        p->used += 1;
}

void* vector_get(vector_t *p, int i)
{
        if (!(i > p->used))
        {
                return (void*)((char*)p->data + p->size_of_each * i);
        }
        else { return NULL; }
}

void vector_set(vector_t *p, int i, void *d)
{
        if (!(i > p->used))
        {
                memcpy((void*)((char*)p->data + p->size_of_each * i), d, p->size_of_each);
        }
}

void vector_free(vector_t *p)
{
        free(p->data);
}

#endif

Here is an example of its usage:
#include <stdio.h>

#define VECTOR_RESERVE_SIZE 3
#include "vector.h"

int main()
{
        int a = 321;
        int b = 45;
        int c = 21;
        int d = 31;
        int e = 71;

        vector_t v;
        vector_init(&v, sizeof (int));

        vector_append(&v, &a);
        vector_append(&v, &b);
        vector_append(&v, &c);
        vector_append(&v, &d);
        vector_append(&v, &e);

        printf("1st element is  %d \n", *(int*)vector_get(&v, 0));
        printf("2nd element is  %d \n", *(int*)vector_get(&v, 1));
        printf("3th element is  %d \n", *(int*)vector_get(&v, 2));
        printf("4th element is  %d \n", *(int*)vector_get(&v, 3));
        printf("5th element is  %d \n\n", *(int*)vector_get(&v, 4));

        vector_set(&v, 4, &a);
        printf("4th element after setting is  %d \n\n", *(int*)vector_get(&v, 4));

        //contiguous
        printf("size of int is: %d \n", sizeof (int));
        printf("address of 1st element: %p \n", vector_get(&v, 0));
        printf("address of 2nd element: %p \n", vector_get(&v, 1));
        printf("address of 3rd element: %p \n", vector_get(&v, 2));
        printf("address of 4th element: %p \n", vector_get(&v, 3));
        printf("address of 5th element: %p \n", vector_get(&v, 4));

        vector_free(&v);
}

I've written some C++ before and this was one of my first few projects in C.
I'd like to know overall how good my code is and whether I'm using good practices / conventions.
Edit:
this:
p->data = realloc(p->data, VECTOR_RESERVE_SIZE);
should be this:
p->data = realloc(p->data, (p->reserved  + VECTOR_RSERVE_SIZE) * P->size_of_each);
Edit: Maybe it's too late but, if people are still reviewing this I would really like to know how does this approach compare to std::vector.


texts:
At work they use a format similar to JSON but without quotes that looks like this:

{foo:{qux:1,quux:0}, bar:{}}

The reason they don't just use json is because the C# package Newtonsoft.Json can deserialize this like if it was regular json and it works. I need to use it in Php but json_decode is not as forgiving.

So here's my attempt at a simple parser:

<?php

namespace Foo\Bar;

class NotJsonParser
{
    const STEP_NAME = 0;
    const STEP_VALUE = 1;

    /**
     * @param $string
     * @return array
     */
    public static function parseNotJSON($string)
    {
        $generator = self::stringIterator($string);
        $data = self::parser($generator);
        return $data[''];
    }

    /**
     * @param \Generator $generator
     * @return array
     */
    private static function parser(\Generator $generator)
    {
        $data = [];
        $step = self::STEP_NAME;
        $name = '';
        $value = '';

        while ($generator->valid()) {
            $i = $generator->current();
            switch ($i) {
                case ' ':
                case "\n":
                    continue;
                case '{':
                    $generator->next();
                    $value = self::parser($generator);
                    $data[$name] = $value;
                    $step = self::STEP_NAME;
                    $name = '';
                    $value = '';
                    break;
                case '}':
                    if ($name) {
                        $data[$name] = $value;
                    }
                    return $data;
                case ',':
                    if ($name) {
                        $data[$name] = $value;
                    }
                    $step = self::STEP_NAME;
                    $name = '';
                    $value = '';
                    break;
                case ':':
                    $step = self::STEP_VALUE;
                    break;
                default:
                    if ($step === self::STEP_NAME) {
                        $name .= $i;
                    } else {
                        $value .= $i;
                    }
            }
            $generator->next();
        }
        return $data;
    }

    /**
     * @param string $str
     * @return \Generator
     */
    private static function stringIterator($str)
    {
        for ($i = 0; $i < strlen($str); $i++) {
            yield $str[$i];
        }
    }
}

And here's the usage:

>>> $result = \Foo\Bar\NotJsonParser::parseNotJSON("{foo:{qux:1,quux:0}, bar:{}}");
=> [
     "foo" => [
       "qux" => "1",
       "quux" => "0",
     ],
     "bar" => [],
   ]

How could I improve this? I know it really lacks error handling. I don't mind that the numbers stay as strings. Also the format never goes more than 2 levels deep. Whitespace between tokens is non important but there shouldn't be whitespace inside the keys (e.g.: {foo bar: baz} should be an error).

Also how should I encode it back from an array to a string? I was thinking just using json_encode and then removing the quote characters.


texts:
I'm writing a custom JavaScript converter to deserialize some JSON. Here's a few lines I'm writing:

public override object Deserialize(IDictionary<string, object> dictionary, Type type,
      JavaScriptSerializer serializer)
  {
    int NoteID;
    NotesModel TheObject = new NotesModel();

    if (dictionary.ContainsKey("NoteID"))
    {
      if (int.TryParse(serializer.ConvertToType<string>(dictionary["NoteID"]),
          out NoteID))
      {
         TheObject.NoteID = serializer.ConvertToType<int>(dictionary["NoteID"]);
      }
    }

How can this be improved?


texts: Returning a list of the values from the binary tree

texts:
I want to return a list of the values from the binary tree.  Is there a shorter and more efficient way to write the method for numbers?

class BTNode(object):
    """A node in a binary tree."""

    def __init__(self, item, left=None, right=None):
        """(BTNode, object, BTNode, BTNode) -> NoneType
        Initialize this node to store item and have children left and right,
        as well as depth 0.
        """
        self.item = item
        self.left = left
        self.right = right
        self.depth = 0  # the depth of this node in a tree

    def number(self: 'BTNode') -> list:
        lst = []

        if self.right is None and self.left is None:
            lst.append(self.item)
        else:
            lst.append(self.item)
        if self.left:
            left = self.left.number()
            lst.extend(left)
        if self.right:
            right = self.right.number()
            lst.extend(right)
        return lst


texts: Finding an object in a nested object/array structure

texts:
I have an app with a bunch of questions defined in a yaml file. For various reasons I would like the data to be divided into sections (section_0, section_1, section_2 etc.). When I load this file into my js app I get an object that looks like this:

const questionData = {
  "section_0": {
    "items": [
      {
        "key": "0.0",
        "title": "Question one",
        "type": "integer"
      },
      {
        "key": "0.1",
        "title": "Question 0.1",
        "type": "integer"
      }
    ]
  },
  "section_1": {
    "items": [
      {
        "key": "1.0",
        "title": "Some title",
        "type": "integer",
        "options": {
          "1": "one",
          "2": "two",
          "3": "other option"
        }
      },
      {
        "key": "1.1",
        "title": "Question 1.1",
        "description": "Longer description text",
        "type": "string"
      },
      {
        "key": "1.2",
        "title": "Question 1.2",
        "type": "integer",
        "options": {
          "0": "option zero",
          "1": "option one",
          "2": "option two"
        }
      },
      {
        "key": "1.3",
        "title": "Q 1.2",
        "type": "boolean",
        "options": {
          "true": "Yes",
          "false": "No"
        }
      },
      {
        "key": "1.4",
        "title": "Question 1.4",
        "type": "string"
      },
      {
        "key": "1.5",
        "title": "Question 1.5",
        "type": "integer"
      },
      {
        "key": "1.6",
        "title": "Question 1.6",
        "type": "integer"
      },
      {
        "key": "1.7",
        "title": "Q1.7",
        "type": "integer"
      }
    ]
  }
}

(a lot more questions and sections in the actual app)

Now I would like to be able to query for a question by the key. I found/figured out two ways to do this. One is sort of home made and the other flattens the array using lodash.

Traversing the object:

function findByKey(data, key){
    if (data.hasOwnProperty('key') && data['key'] === key) {
      return data;
    }

    for (let i = 0; i < Object.keys(data).length; i++) {
      if (typeof data[Object.keys(data)[i]] === 'object') {
        let obj = findByKey(data[Object.keys(data)[i]], key);
        if (obj != null) {
          return obj;
        }
      }
    }

    return null;
}

findByKey(questionData, "0.1")
// => returns the object with the key "0.1"

Using lodash to create a flat array of objects:

const questionsArray = _.flatten(_.map(_.keys(questionData), function(val) {
  return questionData[val].items;
}));

_.find(questionsArray, function(obj) { return obj.key === "0.1" })
// => returns the object with the key "0.1"

Do I need to transform the questionData object like this just to be able to query for an object somewhere in the tree or am I missing some simpler solution (other than not creating the nested structure in the first place)?


texts:
I implements big reactive form on angular5. This form get data from JSON. I use formBuilder and several nested formGroups.

Every field have default value before rendering form. In console output form values after submit form.

CSS design is very simple.

Live demo here.

js:

  formData = {
    'Информация из КХД': {
      Марка: {
        type: 'input',
        value: 'qwerty',
      },
    'Модель': {
        type: 'select',
        value: ['wqeqwewq', 'sadasdasdda', 'xcvxcxcvxcv',],
        selected: 1,
      },
      'Год выпуска': {
        type: 'input',
        value: '',
      },
    },
    'Общая информация': {
      'ПТС': {
        type: 'input',
        value: 'qwerty',
      },
      'Пробег': {
        type: 'select',
        value: ['tgtrgrt', 'fdvdfvdf', 'csdcscsc',],
        selected: 2,
      },
      'Тип кузова': {
        type: 'select',
        value: ['sdv', '544564564', 'yjyujuyj',],
        selected: 0,
      },
    },
    // and more, more, more...
  }

  form: FormGroup;

  constructor(private fb: FormBuilder) { }

  ngOnInit() {
    this.form = this.fb.group(
      this.createForm(Object.keys(this.formData))
    );
  }

  createForm(fields) {
    const result = {};
    fields.forEach(field => {
      const fields = Object.keys(this.formData[field])
      result[field] = this.fb.group(this.createSubForm(field, fields));
    });
    return result;
  }

  createSubForm(field, fields) {
    const result = {};
    fields.forEach(f => {
      let fd = this.formData[field][f];
      if (fd.type === 'select') {
        result[f] = new FormControl(fd.value[fd.selected]);
      } else if (fd.type === 'input') {
        result[f] = new FormControl(fd.value);
      }
    });
    return result;
  }

  getKeys() {
    return Object.keys(this.form.controls);
  }

  getSubKeys(key) {
    const subControls = this.form.get(key).value;
    return Object.keys(subControls);
  }

  onSubmit() {
    console.log('form submitted', this.form.value);
  }

html:

<form class="form" [formGroup]="form" (ngSubmit)="onSubmit()">

{{key}}

      {{subKey}}

      <input type="text" [formControlName]="subKey" *ngIf="formData[key][subKey].type === 'input'">

      <select [formControlName]="subKey" *ngIf="formData[key][subKey].type === 'select'">
        <option
          *ngFor="let item of formData[key][subKey].value; let i = index"
          [value]="item">
          {{ item }}
        </option>
      </select>

  <button class="submit" type="submit">Submit</button>
</form>

scss:

.head {
    font-weight: bold;
    text-decoration: underline;
    width: 100%;
    margin-bottom: 20px;
}

.key {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 30px;

    .subKey {
        width: 47%;
        display: block;
        margin-bottom: 15px;

        >* {
            width: 100%;
        }
    }
}


texts: Which is a better implementation of a stack data structure (based on an array)?

texts:
This is a version I made:

#include <stdio.h>
#include <stdbool.h>

#define MAX_STACK_SIZE 255

typedef struct
{
    int array[MAX_STACK_SIZE];
    unsigned int count;
    unsigned int max;
} Stack;

void initialize(Stack*);
void push(Stack*, int value);
int* pop(Stack*);
bool isEmpty(Stack*);
bool isFull(Stack*);

int main()
{
    Stack s1;
    initialize(&s1);
    for(int i = 0; i < 7; i++)
    {
        push(&s1, i);
    }
    pop(&s1);
    push(&s1, 88);
    push(&s1, 6);
    int *top;
    while((top = pop(&s1)) != NULL)
    {
        printf("Popping %d from the top of the stack.\n", *top);
    }
    return 0;
}

void initialize(Stack *p)
{
    p->count = 0;
    p->max = MAX_STACK_SIZE;
}

void push(Stack *p, int value)
{
    if(!isFull(p))
    {
        p->array[p->count] = value;
        p->count++;
    }
}

int* pop(Stack *p)
{
    if (!isEmpty(p))
    {
        p->count--;
        return p->array + p->count;
    }
    return NULL;
}

bool isEmpty(Stack *p)
{
    return p->count == 0;
}

bool isFull(Stack *p)
{
    return p->count == p->max;
}

This is a version of how it was done from the source I'm learning from:

#include <stdio.h>

#define MAX_STACK_SIZE 255
#define true 1
#define false 0
#define bool unsigned short int

struct stack
{
    int *topOfStack;
    int *pointer;
    int count;
    int max;
    int theStack[MAX_STACK_SIZE];
};

void initStack(struct stack *stackStruct)
{
    stackStruct->topOfStack = stackStruct->theStack;
    stackStruct->pointer = stackStruct->theStack;
    stackStruct->max = MAX_STACK_SIZE;
    stackStruct->count = 0;
}
bool pushStack(struct stack *stackStruct, int inputValue)
{
    if(stackStruct->count < stackStruct->max)
    {
        *stackStruct->pointer = inputValue;
        stackStruct->count++;
        stackStruct->pointer++;
        return true;
    }
    else
        return false;
}
int* popStack(struct stack *stackStruct)
{
    if(stackStruct->count > 0)
    {
        stackStruct->pointer--;
        stackStruct->count--;
        return stackStruct->pointer;
    }
    return NULL;
}

I think there's not so much of a difference between theb, but I just wanted to be sure.  In their version, they've used 2 additional pointers in their Stack struct and I removed them because I thought it was not necessary because we could use the array address + count to get the pointer address in their example.  I think they used it for convenience reasons.  More differences are that I included <stdbool.h> instead of using macros (not really important).

On top of that, I've implemented isEmpty() and isFull() methods just for convenience, but don't take it into account when comparing the two implementations since I'm sure they could do the same.  I just chose to show the 2 main functions that could be used on a stack.

Other than that, since it's an array-based implementation of a stack, I think it was possible to not include the max field in the struct since we define in a macro the stack maximum size, but I added it as well to my implementation for the heck of it.

Is there any differences between our implementations? Since I chose to do my own implementation I just want to make sure I that I did implemented it correctly and efficiently.


texts:
I am working through UPenn CIS 194: Introduction to Haskell (Spring 2013). Since I am not able to take the course for real I am asking for CR (feedback) as it could be from teacher in that course.

HW3 - Code golf - Full description

module Golf where

import Data.List

-- ["apple","orange","plum"] example
-- ... [("apple",0),("orange",1),("plum",2)] added indexes
-- ... [("apple",0),("orange",1),("plum",2)] filtered by predicate: index `mod` 1 == 0
-- [["apple","orange","plum"]] ++ ... [("orange",0),("plum",1)] added indexes
-- [["apple","orange","plum"]] ++ ... [("orange",0)] filtered by predicate: index `mod` 2 == 0
-- [["apple","orange","plum"]] ++ [["orange"]] ++ ... [[("plum",0)]] added index
-- [["apple","orange","plum"]] ++ [["orange"]] ++ ... [[("plum",0)]] filtered by predicate: 0 `mod` 3 == 0
-- [["apple","orange","plum"]] ++ [["orange"]] ++ [["plum"]]
-- [["apple","orange","plum"],["orange"],["plum"]]
skips :: [a] -> [[a]]
skips = skips' 1

skips' :: Integer -> [a] -> [[a]]
skips' _ [] = []
skips' n root@(_:xs) = [fst $ unzip $ filter devidedByIndex $ zip root [0..]] ++ skips' (n + 1) xs
  where
    devidedByIndex x = (snd x) `mod` n == 0

-- [1,2,9,3]
-- 2 > 1 && 2 > 9 = False
-- localMaxima [2,9,3]
-- 9 > 2 && 9 > 3 = [9] ++ localMaxima [3]
-- [9] ++ []
-- [9]
localMaxima :: [Integer] -> [Integer]
localMaxima [] = []
localMaxima (x:[]) = []
localMaxima (x:y:[]) = []
localMaxima (x:y:z:xz)
  | y > x && y > z = [y] ++ localMaxima (z:xz)
  | otherwise      = localMaxima (y:z:xz)

-- putStr (histogram [1,2,2,3,3,3,4,4,4,4,5,5,5,5,5,6,6,6,6,7,7,7,8,8,9])
--      *
--     ***
--    *****
--   *******
--  *********
-- ==========
-- 0123456789
histogram :: [Integer] -> String
histogram m = transform (maximum n) n
  where
    n = countElements m

transform :: Int -> [Int] -> String
transform 0 _  = "==========\n0123456789\n"
transform i n  = intercalate "" ((map transform' n) ++ ["\n"]) ++ transform (i - 1) n
  where
    transform' x
      | x >= i    = "*"
      | otherwise = " "

-- count how many times each number appears in array
countElements :: [Integer] -> [Int]
countElements n = map count [0..9]
  where
    count x = length (elemIndices x n)


texts: How to design interface of deep-copy behaving pointer containers?

texts:
I want to make a container which manages big objects. which performs deep copies on copy construction and copy assignment. I also like the interface of the std containers, so I wanted to implement it using public inheritance:

template <class TBigObject>
class Container : public std::vector< std::shared_ptr<TBigObject> >
{
public:
    Container(int nToAllocate){ /* fill with default constructed TBigObjects */}
    Container(const Container& other){ /* deep copy */ }
    Container(Container&&) = default;
    Container& operator = (const Container& population){ /* deep copy */ }
    Container& operator = (Container&&) = default;
};

I heard of the "Thou shalt not inherit from std containers" maxim and the reasons behind it. So I decided to make an alternative:

template <class T>
using Container = std::vector< std::shared_ptr<T> >;

template <class T>
Container<T> defaultAllocate(int nItems);

template <class T>
Container<T> deepCopy(const Container<T>& other);

This looks more expressive, but using the code feels strange and verbose:

class Big;
Container<Big> someContainer = defaultAllocate(12);
Container<Big> copy = deepCopy(someContainer);

instead of:

class Big;
Container<Big> someContainer(12);
Container<Big> copy = someContainer;

I am a beginner programmer and I don't want to make errors early on. I would like to ask your advice on which choice to make. Or even better, if there is a third option.


texts:
I have been doing TDD since I have started my first job out of university (about 5 months ago), most of which is working with legacy code. I started a personal project today and thought I would TDD it. I don't have much "green field" dev experience so I am unsure if this is the correct way of driving interface design. I am testing the interface has the expected methods, is a service contract etc... I get the feeling this is too much?

The code is shown below:

[TestFixture]
public class IPairSessionTests
{
    [TestCase]
    public void Then_IPairSession_is_a_service_contract()
    {
       var iPairSessionType = typeof(IPairSession);
       Assert.That(iPairSessionType.IsDefined(typeof(ServiceContractAttribute),true));

    }
    [TestCase]
    public void Then_IPairSession_has_Insert_Method()
    {
        var iPairSessionType = typeof(IPairSession);
        Assert.That(iPairSessionType.GetMethod("Insert"), Is.Not.Null);
    }

    [TestCase]
    public void Then_IPairsSession_Insert_is_operation_contract()
    {
        var iPairSessionType = typeof(IPairSession);
        var insertMethod = iPairSessionType.GetMethod("Insert");
        Assert.That(insertMethod.IsDefined(typeof(OperationContractAttribute), true));
    }
}


texts:
I wrote a simply parser for Tektronix's internal binary file format .isf. The code is supposed to read in the file and return the header data as well as the actual oszi-data.

Since I mostly code by myself, I would like your opinion on whether my code follows common practice and whether it can be improved.

import numpy as np
import os.path

def read_curve(binaryfile):
    """
    Reads one tektronix .isf file and returns a dictionary containing
    all tags as keys. The actual data is stored in the key "data".
    """
    postfixs = [".isf", ".ISF"]
    if os.path.splitext(binaryfile)[-1] not in postfixs:
        raise ValueError("File type unkown.")

    with open(binaryfile, 'rb') as bfile:

        # read header
        header = {}
        current = 0

        while True:

            current, name = _read_chunk(bfile, " ")

            if name != ":CURVE":
                current, value = _read_chunk(bfile, ";")

                assert name not in header
                header[name] = value
            else:
                # ":CURVE" is the last tag of the header, followed by
                # a '#' and a 7 digit number.
                header[name] = bfile.read(8)
                current = bfile.tell()
                break

        assert header["ENCDG"] == "BINARY"

        # read data as numpy array
        header["data"] = _read_data(bfile, current, header)

    return header

def _read_chunk(headerfile, delimiter):
    """
    Reads one chunk of header data. Based on delimiter, this may be a tag
    (ended by " ") or the value of a tag (ended by ";").
    """
    chunk = []
    while True:
        c = headerfile.read(1)
        if c != delimiter:
            chunk.append(c)
        else:
            return headerfile.tell(), "".join(chunk)

def _read_data(bfile, position, header):
    """
    Reads in the binary data as numpy array.
    Apparently, there are only 1d-signals stored in .isf files, so a 1d-array
    is read.
    Returns a 2d-array with timepoints and datapoints aligned.
    """
    # determine the datatype from header tags
    datatype = ">" if header["BYT_OR"] == "MSB" else "<"
    if header["BN_FMT"] == "RI":
        datatype += "i"
    else:
        datatype += "u"
    datatype += header[":WFMPRE:BYT_NR"]

    bfile.seek(position)
    data = np.fromfile(bfile, datatype)
    assert data.size == int(header["NR_PT"])

    # calculate true values
    data = data * float(header["YMULT"]) + float(header["YZERO"])

    # create timepoints
    t = np.arange(data.size)
    t = t * float(header["XINCR"]) + float(header["XZERO"])

    # create single array
    res = np.concatenate((t[None, :], data[None, :]), axis=0)

    return res

Edit: I posted my revised code here: Parsing oscilloscope data, follow up


texts:
I'm a beginner who has never seen a sorting algorithm's implementation and have decided to try make one on my own (can someone tell me if this has been already used?).

The fact is I have never used iterators, but since I wanted to make this more generic I decided to quickly look them up.

Also, can anyone suggest what to do if someone passes the same iterator twice?

#include <iterator>
#include <algorithm>

template <typename container>
inline void
sort
(typename container::iterator beginning,
 typename container::iterator end       )
{
    typedef typename container::value_type type_contained;
    typename container::iterator beginning_original_state = beginning;
    while (beginning <= end)
    {
        if (*beginning > *(beginning + 1))
        {
            // Gotta change the name to something more meaningful
            auto check_back(beginning);

            while (check_back != beginning_original_state && *check_back < *(check_back - 1))
            {
                std::swap(check_back, --check_back);
            }
        }
        else
        {
            ++beginning;
        }
    }
}


texts: Conversion from Roman to decimal numbers

texts:
My program makes a conversion between Roman and decimal numbers. Can you give me some advice on how to make it look more readable or to improve in general?

Would code extraction of similar-looking logic from switch cases into helper methods do the job? Or can we take some other approach and use recursion, enums or regular expressions to solve the conversion task?

import java.util.Scanner;

public class Romans_to_Decimals
{
    public static void main(String[] args)
    {
    System.out.println("Enter roman number from I to MMMCMXCIX (1 to 3999), q to quit: ");
    Scanner in = new Scanner(System.in);

    boolean done = false;
    while (!done && in.hasNext())
    {
        String number = in.next();
        if (number.equals("q"))
        {
            done = true;
        }
        else
        {
            int result = 0;
            char[] array = number.toCharArray();

            for (int i = number.length() - 1; i >= 0; i--)
            {
                switch (array[i])
                {
                case 'I':
                        result += 1;
                        break;
                case 'X':
                        if (i != 0 && array[i-1] == 'I')    //IX = 9
                        {
                            result += 9;
                            i--;
                        }
                        else
                        {
                            result += 10;
                        }
                        break;
                case 'C':
                        if (i != 0 && array[i-1] == 'X')    //XC = 90
                        {
                            result += 90;
                            i--;
                        }
                        else
                        {
                            result += 100;
                        }
                        break;
                case 'M':
                        if (i != 0 && array[i-1] == 'C')    //CM = 900
                        {
                            result += 900;
                            i--;
                        }
                        else
                        {
                            result += 1000;
                        }
                        break;
                case 'V':
                        if (i != 0 && array[i-1] == 'I')    //IV = 4
                        {
                            result += 4;
                            i--;
                        }
                        else
                        {
                            result += 5;
                        }
                        break;
                case 'L':
                        if (i != 0 && array[i-1] == 'X')    //XL = 40
                        {
                            result += 40;
                            i--;
                        }
                        else
                        {
                            result += 50;
                        }
                        break;
                case 'D':
                        if (i != 0 && array[i-1] == 'C')    //CD = 400
                        {
                            result += 400;
                            i--;
                        }
                        else
                        {
                            result += 500;
                        }
                        break;
                default:
                        System.out.println("Not correct roman number");
                        break;
                }
            }
            System.out.println("Corresponding decimal number is: " + result);
            }
        }
        in.close();
    }
}