text:
Q: Delete branch with jgit not working as expected I am trying to delete a branch in my repo using jgit.
DeleteBranchCommand command = git.branchDelete();
command.setBranchNames("myBranch");
command.setForce(true);
try {
    List<String> deletedBranches = new ArrayList<String>();
deletedBranches = command.call();
System.out.println(deletedBranches.toString());
} catch (GitAPIException e) {
throw new MyInternalErrorException("Error while deleting branch [" + branchName + "]", e);
}

The value of deletedBranches will be [myBranch]
If I check if the branch is still in the repo:
git.getRepository().getRef("myBranch");

I will get true.
And this is because cf to jgit javadoc:
getRef(name)

name the name of the ref to lookup. May be a short-hand form, e.g.
  "master" which is is automatically expanded to "refs/heads/master" if
  "refs/heads/master" already exists.

It is checking for "refs/heads/myBranch" instead of "myBranch".
Moreover, if I will run the deleteBranch command the second time, the value for deletedBranches will be [refs/heads/myBranch].
Can someone explain why is this happening and how can I solve this issue?
Thank you.
Update
After debugging inside the jgit code, I've noticed that
String fullName = currentRef.getName();

https://github.com/eclipse/jgit/blob/a76a4acf87952249b94f4be29614565541eb8c46/org.eclipse.jgit/src/org/eclipse/jgit/api/DeleteBranchCommand.java#L133
returns "myBranch" instead of "heads/refs/myBranch" thus it is not executing this piece of code:
                if (fullName.startsWith(Constants.R_HEADS)) {
                    String shortenedName = fullName
                            .substring(Constants.R_HEADS.length());
                    // remove upstream configuration if any
                    final StoredConfig cfg = repo.getConfig();
                    cfg.unsetSection(
                            ConfigConstants.CONFIG_BRANCH_SECTION,
                            shortenedName);
                    cfg.save();
                }

https://github.com/eclipse/jgit/blob/a76a4acf87952249b94f4be29614565541eb8c46/org.eclipse.jgit/src/org/eclipse/jgit/api/DeleteBranchCommand.java#L158-L167

A: It could be similar to git branch -d, which will refuse to delete a branch not fully merged in its upstream branch.
That is why the examples you see in org.eclipse.jgit.test/tst/org/eclipse/jgit/api/BranchCommandTest are using setForce(true) (like a git branch -D):
List<String> deleted = git.branchDelete().setBranchNames("ForDelete")
            .setForce(true).call();


text:
Q: Microsoft RDP 10 File Transfer - Specifically .mtw files in Minitab 17 Does anyone know how to open files from Mac in Microsoft Remote Desktop 10? I'm specifically looking to open .mtw in Minitab 17.
I tried changing the folder to my "Macintosh HD" folder and also tried using the specific folder from "My Documents" but it still doesn't show up when I'm using Windows through RDP.

redpajama_set_name: RedPajamaStackExchange


text:
Q: json enum default value c# I'm trying to serialize a large struct with loads of enums, and when a property in the struct is not set, I would like to get the first enum string value to be serialized in json instead im getting 0 as a default value.
public enum YesNoUnknown
{
    [EnumName(Name = "unknown")]
    Unknown,

    [EnumName(Name = "yes")]
    Yes,

    [EnumName(Name = "no")]
    No
}

[JsonProperty(PropertyName = "property1", ItemConverterType = typeof(EnumAttributeConverter<YesNoUnknown>))]
public YesNoUnknown Property1 { get; set; }

I want the default result to be: property1: "unknown" instead of: property1: 0
Thanks in advance!

A: Turns out the problem was that i should have used the Json EnumString attribute instead of using my custom attribute. So these are the changes I made to make it work:
public enum YesNoUnknown
{
    [EnumString("unknown")]
    Unknown,

    [EnumString("yes")]
    Yes,

    [EnumString("no")]
    No
}

    [JsonProperty(PropertyName = "property1")]
    [JsonConverter(typeof(EnumAttributeConverter<YesNoUnknown>))]
    public YesNoUnknown Property1 { get; set; }


text:
Q: Vertically center h2 and sub-heading I'm working on a website and wanted to see how I could vertically center h2 and the sub-heading with respect to the div that contains the image.
Basically, I have a container with display: flex and flex-direction: column. I have three columns.
The first column contains a profile image along with a header and sub-header. What's the best way to vertically center the .title div?
Here's a link to the jsfiddle

A: give display: flex to class profile-container, then you can align it's child profile image and title class to vertically center like below:
.profile-container{
 display : flex;
 align-items : center;
 height : 200px; //provide wrapper height
}

This should achieve your requirement.

A: Try using absolute positioned, with a -50% transform.

@import url('https://fonts.googleapis.com/css?family=Lato');
html {
  width: 100%;
  height: 100%;
}

body {
  background-color: #fafafa;
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
}

.container {
  background: white;
  width: 1000px;
  height: 600px;
  border: 1px solid rgba(0, 0, 0, .09);
  box-shadow: 0 1px 4px rgba(0, 0, 0, .04);
  display: flex;
  flex-direction: column;
}

/*set up vertical column layouts for the three containers*/

.profile-container,
.work-container,
.social-media-container {
  flex: 1;
  padding: 1.5rem;
}

.profile-container {
  align-self: center;
  position: relative;
  width: 100%;
}

.profile-image {
  display: inline-block;
  background-image: url('https://organicthemes.com/demo/profile/files/2012/12/profile_img.png');
  background-repeat: no-repeat;
  background-position: 0px 0px;
  background-size: 100%;
  height: 200px;
  width: 200px;
  border-radius: 50%;
}

.title {
  display: inline-block;
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  padding-left: 25px;
}

.header-name {
  font-family: 'Lato', sans-serif;
  display: inline-block;
  margin: 0px;
}

Tarang Hirani

Software Engineer

          These are my projects

          Social media link

Link for reference: https://jsfiddle.net/kzj4omo8/3/


text:
Q: DateTime.ParseExact Returns Wrong Value I am trying to add hour and minute into the returning value of a datepicker(wpf). I think there is something wrong with my date format parameter for ParseExact(), but couldnt get where the problem is.
string[] timeAndDate = System.Text.RegularExpressions.Regex.Split(dPicker.SelectedDate.ToString(), " ");
string time = cmbTime.SelectedItem.ToString();
string tempDT = timeAndDate[0] + " " + time;
DateTime queryDT = DateTime.ParseExact(tempDT, "dd.MM.yyyy HH:mm", CultureInfo.InvariantCulture);

It keeps returning minValue 01.01.0001 etc. Its probably about these time dots. I also tried to add seconds but still no luck.
Btw tempDT is kinda "22.12.2016 20:30"
my input string is "22.12.2016 20:30"
method returns {01.01.0001 00:00:00}
I am also doing this to get two dates from datepickers and get two hour variables via two comboboxes, and make two datetime objects to send them to sql.
It seems I didnt put the debug point on the right place, embarrising but anyway, thanks so much!

A: Looks like you don't need to parse the date at all; the date picker exposes the selected date as a System.DateTime already.  You still have to parse the time because it is being held in a combo box instead of a TimePicker for some reason.
Instead of
string[] timeAndDate = System.Text.RegularExpressions.Regex.Split(dPicker.SelectedDate.ToString(), " ");
string time = cmbTime.SelectedItem.ToString();
string tempDT = timeAndDate[0] + " " + time;
DateTime queryDT = DateTime.ParseExact(tempDT, "dd.MM.yyyy HH:mm", CultureInfo.InvariantCulture);

why not write
var ts = TimeSpan.Parse(cmbTime.SelectedItem.ToString());
DateTime queryDT = dPicker.SelectedDate.Add(ts);


text:
Q: How to dynamically set an expression type within a method I have this view model:
    public class BankAccountViewModel : IValidator<BankAccountViewModel>
    {
      public BankAccount BankAccount { get; set; }

public void ConfigureValidation(ValidationConfiguration<StockOnHandViewModel> config)
        {
            config.For(m => m.BankAccount.AccountHolder);

        }
    }

so the class is:
public class BankAccount
{
  public string AccountHolder { get; set; }
  public List<Transfer> Transfers { get; set; }
}

public class Transfer
{
  public int Amount { get; set; }
}

Then I have some extensions for validation
public static class ValidationExtensions
    {
  public static PropertyRuleSet<TModel, TProperty> For<TModel, TProperty>(
            this ValidationConfiguration<TModel> validationConfiguration,
            Expression<Func<TModel, TProperty>> accessor)
        {
            return validationConfiguration.Add(accessor);
        }
}

So I was able to call the For method for AccountHolder config.For(m => m.BankAccount.AccountHolder);
So that's cool. It sends through the expression as expected.
It becomes a little more difficult for the list items Transfers.
In transfers I might want to send through the expression for the amount of each transfer. So if I had two transfers I would want to send:
m => m.BankAccount.Transfers[0].Amount
m => m.BankAccount.Transfers[1].Amount

I know I could do it this way:
for(int i=0; i < BankAccount.Transfers.Count; i++)
            {
                config.For(m => m.BankAccount.Transfers[i].Amount);
            }

However I don't want to be doing this for list items all the time.
I really want to maybe have a different For method for list items that I could some how call and it would do this for me.
I was thinking maybe of something like:
public static PropertyRuleSet<TModel, TProperty> For<TModel, TProperty>(
            this ValidationConfiguration<TModel> validationConfiguration,
            Expression<Func<TModel, TProperty>> accessor, int count)
        {
...
}

where you maybe call it like:
config.For(m => m.BankAccount.Transfers[i].Amount, BankAccount.Transfers.Count);

However this won't work because I'm not sure how to send the expression part without the i and then populate it for each list item later. Also not sure what to do in the method
Anyone know what to do here?

A: Having it return a list seems linqy:
public static PropertyRuleSet<TModel, TProperty> For<TModel, TProperty>(
            this ValidationConfiguration<TModel> validationConfiguration,
            Expression<Func<TModel,IEnumerator<TProperty>>> accessor)
        {
...
}

and then this:
config.For(m => m.BankAccount.Transfers.Select(t => t.Amount));

I have not tested it so it might have a typo.


text:
Q: Sharepoint recover / restore deleted list views Just wondering if it is possible to recover or restore list views that have been deleted. i have a sharepoint list which has several list views. one of these list views was connected to an excel document. this list view was accidentally  deleted and this now directly affects the excel document it had a data connection to. is there any way i can get this list view back i looked in the recycle bin but its not there.
Just to clarify nothing on the list was deleted just one of the views


text:
Q: Why does my jQuery menu disappear before I click a link? I am writing a jQuery dropdown menu.  I hover over a link and a menu is supposed to appear... and does.  The problem is that the menu closes before I get to a menu link.  The menu should not disappear unless the mouse leaves the menu or the top level link.  Should I be doing this differently?
$(function(){
    //Find all ul elements within items in the nav
    $('nav ul li:has(ul)').each(function(){
        //Prevent the links that have submenus from being clicked
        $(this).children('a').on('click', function(e){
            e.preventDefault();
        });
        $(this).children('a').mouseover(function(){
            console.log('hovered');
            $(this).parent().find('ul').css('display', 'inline');
        })
        .mouseout(function(){
            $(this).parent().find('ul').css('display', 'none');
        });
    });
});

Here is a jsFiddle

A: Why jQuery ? When u can do it in pure CSS.
nav ul li:hover ul {
    display:inline;
}

Demo: Fiddler

A: It's because the mouseover id bound to the anchor element, and the ul is not a children of it, so when you move to the submenu it closes.
Change your selector to:
$(this).mouseover(function(){
    console.log('hovered');
    $(this).parent().find('ul').css('display', 'inline');
})
.mouseout(function(){
    $(this).parent().find('ul').css('display', 'none');
});

and will work fine.
Demo: http://jsfiddle.net/IrvinDominin/oypo3vrm/1/

A: $(function(){
    $('nav ul li:has(ul)').each(function(){
        //Prevent the links that have submenus from being clicked
        $(this).children('a').on('click', function(e){
            e.preventDefault();
        });
        //you don't need li in here
        $(this).mouseenter(function(){
            console.log('hovered');
            $(this).parent().find('ul').css('display', 'inline');
        })
        .mouseleave(function(){
            $(this).parent().find('ul').css('display', 'none');
        });
    });
});


text:
Q: Python with solcx don't find evm (vs code) I was following this course on ytb and after making the same code than him I encoutered a problem with solcx. Tanks a lot in advance.
This is the error message (i'm french so the first line is french but i think you'll understand):
Information�: impossible de trouver des fichiers pour le(s) mod�le(s) sp�cifi�(s).
Traceback (most recent call last):
  File "d:\Code\Blockchain\demos\web3_py_simpleStorage\deploy.py", line 34, in <module>
    bytecode = compiled_sol["contracts"]["SimpleStorage.sol"]["SimpleStorage"]["evm"]["bytecode"]["object"]
KeyError: 'evm'

This is my code (exactly the same as in the course):
import json
from solcx import compile_standard, install_solc

with open("SimpleStorage.sol", "r") as file:
    simple_storage_file = file.read()

# compile solidity project
install_solc("0.8.0")
compiled_sol = compile_standard(
    {
        "language": "Solidity",
        "sources": {"SimpleStorage.sol": {"content": simple_storage_file}},
        "settings": {
            "outputSelection": {
                "*": {
                    "*": ["abi", "metadata", "evm.bytecode" "evm.bytecode.sourceMap"]
                }
            }

        },

    },
    solc_version="0.8.0"

)

with open("compiled_code.json", "w") as file:
    json.dump(compiled_sol, file)

# get bytecode
bytecode = compiled_sol["contracts"]["SimpleStorage.sol"]["SimpleStorage"]["evm"]["bytecode"]["object"]

# get abi
abi = compiled_sol["contracts"]["SimpleStorage.sol"]["SimpleStorage"]["abi"]

The solidity code if you need but i think the problem is not here:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

contract SimpleStorage {
    // this will get initialized to 0!
    uint256 favoriteNumber;
    bool favoriteBool;
    struct People {
        uint256 favoriteNumber;
        string name;
    }
    People[] public people;
    mapping(string => uint256) public nameToFavoriteNumber;

    function store(uint256 _favoriteNumber) public {
        favoriteNumber = _favoriteNumber;
    }

    function retrieve() public view returns (uint256) {
        return favoriteNumber;
    }

    function addPerson(string memory _name, uint256 _favoriteNumber) public {
        people.push(People(_favoriteNumber, _name));
        nameToFavoriteNumber[_name] = _favoriteNumber;
    }
}

A: there is a missing "," somehow in between "evm.bytecode" and "evm.bytecode.sourceMap", thus no evm related generate in the compiled_code.json


text:
Q: rake aborted by NotImplementedError when db:create I get NotImplementedError when I run rake db:create --trace, and this is full trace of the command.
rake db:create --trace
rake aborted!
NotImplementedError
C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/railroady-1.1.1/tasks/railroady.rake:34:in `sed'
C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/railroady-1.1.1/tasks/railroady.rake:47:in `block in <top (required)>'
C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/rake-10.1.1/lib/rake/task_manager.rb:196:in `in_namespace'
C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/rake-10.1.1/lib/rake/dsl_definition.rb:104:in `namespace'
C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/railroady-1.1.1/tasks/railroady.rake:41:in `<top (required)>'
C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/activesupport-4.0.0/lib/active_support/dependencies.rb:222:in `load'
C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/activesupport-4.0.0/lib/active_support/dependencies.rb:222:in `block in load'
C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/activesupport-4.0.0/lib/active_support/dependencies.rb:213:in `load_dependency'
C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/activesupport-4.0.0/lib/active_support/dependencies.rb:222:in `load'
C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/railroady-1.1.1/lib/railroady/railtie.rb:8:in `block in <class:Railtie>'
C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/railties-4.0.0/lib/rails/railtie.rb:201:in `instance_exec'
C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/railties-4.0.0/lib/rails/railtie.rb:201:in `block in run_tasks_blocks'
C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/railties-4.0.0/lib/rails/railtie.rb:201:in `each'
C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/railties-4.0.0/lib/rails/railtie.rb:201:in `run_tasks_blocks'
C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/railties-4.0.0/lib/rails/application.rb:243:in `block in run_tasks_blocks'
C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/railties-4.0.0/lib/rails/engine/railties.rb:17:in `each'
C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/railties-4.0.0/lib/rails/engine/railties.rb:17:in `each'
C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/railties-4.0.0/lib/rails/application.rb:243:in `run_tasks_blocks'
C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/railties-4.0.0/lib/rails/engine.rb:446:in `load_tasks'
C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/railties-4.0.0/lib/rails/railtie/configurable.rb:30:in `method_missing'
C:/Users/ironsand/dev/tangocho/Rakefile:6:in `<top (required)>'
C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/rake-10.1.1/lib/rake/rake_module.rb:25:in `load'
C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/rake-10.1.1/lib/rake/rake_module.rb:25:in `load_rakefile'
C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/rake-10.1.1/lib/rake/application.rb:637:in `raw_load_rakefile'
C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/rake-10.1.1/lib/rake/application.rb:94:in `block in load_rakefile'
C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/rake-10.1.1/lib/rake/application.rb:165:in `standard_exception_handling'
C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/rake-10.1.1/lib/rake/application.rb:93:in `load_rakefile'
C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/rake-10.1.1/lib/rake/application.rb:77:in `block in run'
C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/rake-10.1.1/lib/rake/application.rb:165:in `standard_exception_handling'
C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/rake-10.1.1/lib/rake/application.rb:75:in `run'
C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/rake-10.1.1/bin/rake:33:in `<top (required)>'
C:/RailsInstaller/Ruby1.9.3/bin/rake:23:in `load'
C:/RailsInstaller/Ruby1.9.3/bin/rake:23:in `<main>'

To fix the error I reinstall rake by gem uninstall rake, gem install rake.
And I also tried with rake.bat.
I tried same thing also with Railsinstaller3.0(Ruby2.0.0).
But all try didn't work.
If I create a new rails project, then rake db:create works properly.
What can I do to fix this error?

A: I'm afraid I have bad news. The project you are trying to run depends on railroady gem, which heavily depends on system sed command. This command is not available on windows, so I'm afraid there won't be any easy solutions.
There are number of tools which tries to add sed command to windows, you can always try installing one of them (Google 'sed windows') and changing the gem so it knows how to call it (with what options etc).
However the best solution would be to say goodbye to windows and move to linux. With enough googling skills you will never look back.


text:
Q: Defer close on multiple Goroutines? I have the following code:
package main

import (
    "fmt"
    "time"
)

func main() {
    t := time.Now()
    stuff := fanIn(
        generator(4, 5, 6, 7),
        generator(1, 2, 6, 3, 7),
        generator(12, 15, 33, 40, 10),
        generator(18, 13, 20, 40, 15),
        generator(100, 200, 64000, 3121, 1237),
    )

    for v := range stuff {
        fmt.Println(v)
    }

    fmt.Println(t.Sub(time.Now()))
}

func generator(nums ...int) <-chan int {
    out := make(chan int, 10)
    go func() {
        defer close(out)
        for _, v := range nums {
            out <- v
        }
    }()
    return out
}

func fanIn(in ...<-chan int) <-chan int {
    out := make(chan int, 10)

    for _, v := range in {
        go func(ch <-chan int) {
            for val := range ch {
                go func(c int) { out <- c }(val)
            }
        }(v)
    }

    return out
}

It results in a deadlock on line 18:
for v := range stuff {...}

The issue (I think) is that I'm not deferring the close on the fanIn function that returns a read-only channel. I don't know when to defer it since it's got to wait for the end of multiple goroutines to complete.
What's the idiomatic way to solve this deadlock? Is this code even idiomatic?
Thanks!
GoPlay

A: You are correct about the cause of error being un-closed fanIn's channel. You can use a sync.WaitGroup to resolve the issue:
func fanIn(in ...<-chan int) <-chan int {
    // use a WaitGroup here
    var wg sync.WaitGroup
    out := make(chan int, 10)

    for _, v := range in {
        wg.Add(1)
        go func(ch <-chan int) {
            defer wg.Done()
            for val := range ch {
                out <- val
            }
        }(v)
    }

    // wait for wait groups to finish in another goroutine
    go func() {
        wg.Wait()
        close(out)
    }()
    return out
}

Working code.


text:
Q: I can't seem to get Java to read my text document import java.util.Scanner;
public class Average
{
    public void Average()
    {
        Scanner in = (new Scanner("J:\\AP Comptuter Science\\Semester 2\\Exeptions\\13.1\\numbers.txt"));
        try{
            String test = in.nextLine();
        } catch(NullPointerException i) {
            System.out.println("Error: " + i.getMessage());
        }

        int total = 0;
        int counter = 0;

        while(in.hasNextInt()){
            total = total + in.nextInt();
            counter++;
        }
        total = total / counter;
        System.out.println(total);
    }
}

I have a project for my AP Comp class and i did the work according to the notes, but the file "numbers" isn't being read and i get the answer 0 when it should be some huge number.

A: new Scanner("J:\\AP Comptuter Science\\Semester      2\\Exeptions\\13.1\\numbers.txt")

You are calling Scanner(String source), which does not read the file; it scans the string itself.
What you need is probably public Scanner(File source), as follows:
new Scanner(new File("J:\\AP Comptuter Science\\Semester      2\\Exeptions\\13.1\\numbers.txt"))

You also need to check the path, there almost certainly aren't 5 spaces between "Semester" and "2"
Overall I would strongly urge you to step through your code in a debugger instead of just running. If you had done that, you would have seen that after executing
String test = in.nextLine();

The string test contains the name of the file rather than its contents.
There are other improvements possible, consider posting in the codereview stackexchange after you are able to make it work

A: Firstly you should correct your path, and probably put it in the same directory as your class files. And instead of providing a path to the scanner you should also give it a file. It should look something like this.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class Average
   {

        public void printAverage(){
            File file = new File(""J:\\AP Comptuter Science\\Semester 2\\Exeptions\\13.1\\numbers.txt"");
            Scanner scan;

            try {
                scan = new Scanner(file);
                int total = 0, counter = 0;

                while(scan.hasNextInt()){
                    System.out.println("loop");
                    total = total + scan.nextInt();
                    counter++;

                }
                if(counter != 0)
                    total = total/counter;
                System.out.println(total);

            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }

        }

   }

A: As mentioned earlier, the code has several issues:
a) new Scanner(String) reads the string instead of the file
b) path seems to be incorrect
c) handling of DivideByZero and FileNotFound exceptions
Please see the following code:
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.io.File;
public class Average{
    public void average(){
        Scanner in = null;
        try{
            in = (new Scanner(new File("J:\\AP Comptuter Science\\Semester 2\\Exeptions\\13.1\\numbers.txt")));
            String test = in.nextLine();
        }
        catch(NullPointerException | FileNotFoundException i){
            System.out.println("Error: " + i.getMessage());
        }
        int total = 0;
        int counter = 0;
        while(in != null && in.hasNextInt())
        {
            total = total + in.nextInt();
            counter++;
        }
        Float average = null;
        if (counter > 0) { //to avoid divide by zero error
            average = (float)total / counter;
            System.out.println("Average: "+average);
        }
    }

    public static void main(String args[]){
        new Average().average();
    }
}

This works for only numbers.txt which has integers separated by space as required by the nextInt() method of Scanner class.


text:
Q: Customizing  when in focus I'd like to create a customized Lumo theme in Vaadin 14.6, where the buttons (<vaadin-button>) show a double border (css: box-shadow: 0 0 0 1px #fff, 0 0 0 3px var(--some-custom-background-color);) when focussed.
While custom styles for other <vaadin-button> pseudo selectors, such as :hover, :active, etc. work well, I cannot find a way to customize the :focus appearance.

A: Focus styles need to be customized using the focused and focus-ring state attributes, which are applied on the host element.
The focused attribute is applied the button is focused either with a mouse/pointer or keyboard, while focus-ring is only applied when it's focused with the keyboard (corresponds to the native :focus-visible pseudo class).
:host([focused]) {
  ...
}

:host([focus-ring]) {
  ...
}

A: I found that it is actually Firefox which is not showing the :focus related css. Chrome and Safari display the style as desired.
For the sake of completeness, this is the related css, which goes into 'vaadin-button.css' in the 'themes/components' folder of the application:
:host([theme~="primary"]:focus) {
    height: calc(var(--my-button-size) - 6px);
    border-radius: 1px;
    background-color: var(--my-button-primary-background-color-focus);
    box-shadow: 0 0 0 1px #fff, 0 0 0 3px var(--my-button-primary-background-color);
}


text:
Q: SwiftUI Local Notification Delegate I made two classes to manage local notifications, to get more notification functionality I used local notification delegation, but it's doesn't work (the delegation functions) may be because I didn't set it correctly, if there is any way to fix this issue please share it with me.
Notification Manager
internal final class LocalNotificationManager: ObservableObject {

    // MARK: - Properties
    @Published var authorizationState: UNAuthorizationStatus?

    // MARK: - Methods
    func reloadAuthorizationState() {
        UNUserNotificationCenter.current().getNotificationSettings { settings in
            DispatchQueue.main.async {
                self.authorizationState = settings.authorizationStatus
            }
        }
    }

    func requestAuthorization() {

        UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { (granted, error) in
            if granted {
               // Do something if user allowing notifications
                DispatchQueue.main.async {
                    self.authorizationState = .authorized
                }
            } else if !granted {
                // Do something if user do not allow the notifications
                DispatchQueue.main.async {
                    self.authorizationState = .denied
                }
            } else if let error = error {
                // Show some message
                print(error.localizedDescription)
            }
        }
    }

    func schedulNotification(for taskModel: TaskModel) {

        // Set Delegation
        let delegate = LocalNotificationDelegate()
        UNUserNotificationCenter.current().delegate = delegate

        let content = UNMutableNotificationContent()
        content.interruptionLevel = .timeSensitive
        content.title = ""
        content.body = taskModel.text
        content.subtitle = "\(taskModel.priority != .none ? "\(taskModel.priority.rawValue) Priority" : "")"
        content.categoryIdentifier = "Task Actions" // Same Identifier in registerCategories()
        content.sound = UNNotificationSound.default
        let taskIdentifier = taskModel.id.uuidString

        let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)

        let request = UNNotificationRequest(identifier: taskIdentifier, content: content, trigger: trigger)

        registerCategories(for: taskModel)
        UNUserNotificationCenter.current().add(request)

    }

    private func registerCategories(for taskModel: TaskModel) {
        let markAsCompleted = UNNotificationAction(identifier: "MARK_AS_COMPLETED", title: "Mark as Completed", icon: UNNotificationActionIcon(systemImageName: "checkmark.circle"))
        let remindMeInAnHour = UNNotificationAction(identifier: "REMIND_ME_IN_AN_HOUR", title: "Remind Me in an Hour", icon: UNNotificationActionIcon(systemImageName: "clock"))
        let remindMeTomorrow = UNNotificationAction(identifier: "REMIND_ME_TOMORROW", title: "Remind Me Tomorrow", icon: UNNotificationActionIcon(systemImageName: "calendar"))

        let placeholder = "Task"
        let category = UNNotificationCategory(identifier: "Task Actions", actions: [markAsCompleted, remindMeInAnHour, remindMeTomorrow], intentIdentifiers: [], hiddenPreviewsBodyPlaceholder: placeholder) // // Same Identifier in schedulNotification()

        UNUserNotificationCenter.current().setNotificationCategories([category])
    }

Notification Delegat
internal final class LocalNotificationDelegate: NSObject, UNUserNotificationCenterDelegate {

    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification,
       withCompletionHandler completionHandler: (UNNotificationPresentationOptions) -> Void) {
       completionHandler(.banner)
     }

    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {

        switch response.actionIdentifier {

        case UNNotificationDefaultActionIdentifier:
            // the user tapped to unlock
            print("User Tapped to Unlock the App")

        case "MARK_AS_COMPLETED":
            print("MARK_AS_COMPLETED")
            break
        case "REMIND_ME_IN_AN_HOUR":
            print("REMIND_ME_IN_AN_HOUR")
            break
        case "REMIND_ME_TOMORROW":
            print("REMIND_ME_TOMORROW")
            break
        default:
            break
        }
        completionHandler()
    }

}


text:
Q: What is the point of the pull-up resistors for rows on this schematic? I am looking through a schematic of a keyboard. It for some reason has pull-up resistors on row lines. Meantime the firmware it uses suppose to iterate over rows by bringing them up from the ICs own GPIO pins.
Wouldn't having pull-up resistors here defeat that logic by having those lines always high which in turn would cause issues with keyboard?

A: Makes sense to me. The MCU column pin selects the column by driving it LO, and scans the row pins. If a button in the selected column is pressed it connects the row to the column and the row pull up gets overridden by the LO column line. You're saying the firmware doesn't do this?


text:
Q: Getting (key, value) pairs from a HashMap using an iterator I have
private Map<K,Collection<V>> map = new HashMap<>();

I want return the value
public Iterable<Map.Entry<K, V>> allValues() {
}

How could I return the values as Iterable?

A: You can use streams as follows:
Iterable<Map.Entry<K, V>> iterable = map.entrySet().stream()
    .flatMap(e -> e.getValue().stream().map(v-> entry(e.getKey(), v)))
    .collect(toList());

This assumes Java 9 or above (for Map.entry) and the following static imports:
import static java.util.Map.entry;
import static java.util.stream.Collectors.toList;


text:
Q: Trying to get string value from activity1 to fragment of activity 2 but it returns as null. GetArgument always returns as null I am trying to get bundle extras from activity 1 to fragment of activity 2 but getargument() always returns as null.
     //Using this to get string in fragment
     String value = getArguments().getString("abc");

    //activity1 code that i used to get the extras
    Bundle bundle = new Bundle();
    bundle.putString("abc", townextra);
    UserFragment myFrag = new UserFragment();
    myFrag.setArguments(bundle);

A: Your Activity
Bundle bundle = new Bundle();
bundle.putString("params", "Your String data");
// set MyFragment Arguments
MyFragment myObj = new MyFragment();
myObj.setArguments(bundle);

The Fragment.
public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam = getArguments().getString("params");
        }
    }

But will be better if you show the code how you pass data between activities and then use my answer.
And please add your fragment code.

A: There is a problem with logic of passing data.
Correct way would be: Pass data from Activity1 to Activity2, and then from Activity2 to Fragment.

A: all fixed. I added a new function on my activity 2 to create fragment. instead of doing it in oncreat. it all works fine, thanks


text:
Q: How can i convert 0d0a to 0a? I am coding a perl code dos2unix.
This is a simple example code.
$hex =~ s/0d0a/0a/g;

I'm found one problem.
The well was converted to 000a00 if 000d0a00.
The problem is when 00d0a000.
When the conversion is not the case.
So I changed the code.
$hex =~ s/0d0a(?=(..)+$)/0a/g;

Issue has been resolved.
But, speed is too slow.
Is there another way to fix this?

A:
I am coding a perl code dos2unix.

So you want to convert CR LF to LF.
use open IO => ':raw';  # Prevent Perl from doing any implicit
binmode STDIN;          # changes to the input or output.
binmode STDOUT;         #
while (<>) {
   s/\r\n/\n/g;
   print;
}

or
use open IN => ':crlf';  # Have Perl change CR LF to LF when reading,
binmode STDIN, ':crlf';  # and prevent Perl from doing any implicit
binmode STDOUT;          # changes to the output.
print while <>;


text:
Q: How do I combine 2 lines at a time, appending line1 onto line2, pulling only specific parts of each line in Bash? I have millions of short input files. PyLauncher will run on supercomputers, running millions of python scripts in parallel. Each runs a program on each input and copies 2 lines from the output of each, then appends those 2 lines to results.txt. The python script looks like:
for input_file in directory:
 subprocess.run(["script_name input_file | sed -n '22p; 39p' | tee -a results.txt"], shell=True)

results.txt will have 2*num_input_files (millions) of lines like:
Ligand: ./input/ZINC00001677.pdbqt
1       -8.288          0          0
Ligand: ./input/ZINC00001567.pdbqt
1       -10.86          0          0
Ligand: ./input/ZINC00001601.pdbqt
1       -7.721          0          0

I'd like to take this, rearrange, drop the 1, 0, and 0 from line 2, and sort so most negative number comes first so it looks like:
-10.86 ZINC00001567.pdbqt
-8.288 ZINC00001677.pdbqt
-7.721 ZINC00001601.pdbqt

I found this StackOverflow question: How do I sort two lines at a time in bash, using the second line as index?
But I can't quite get the commands to work for my file. Speed of execution is very important, so Bash commands or Python could both work, depending on which is faster.
Thanks in advance!

A: In python I would do something like this:
with open('input.txt', 'r') as f_inp, open('output.txt', 'w') as f_out:
    while True:
        one = f_inp.readline().strip('\n')
        if not one:
            break
        two = f_inp.readline().strip('\n')
        f_out.write(f'{two} - {one}\n')

Then I would leave it to the sort command to do the sort part.

A: If you have enough RAM to store the output file contents then you could do this:
from os.path import basename

INPUTFILE = 'verylargefile.txt'
OUTPUTFILE = 'results.txt'

result = []

with open(INPUTFILE) as data:
    while line := data.readline():
        filename = basename(line.split()[-1])
        v = data.readline().split()[1]
        result.append(f'{v} {filename}\n')

with open(OUTPUTFILE, 'w') as data:
    data.writelines(sorted(result, key=lambda x: float(x.split()[0])))


text:
Q: Center text within textview I have a textview inside of a linear layout. I have the textview set to match_parent, both height and width.
Essentially the textview is the size of the screen. But the text is staying aligned to the top left. Is there a way to have it centered?
I have android:gravity and android:textAlignment set to center.
    <TextView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:text="Large Text"
    android:id="@+id/textView"
    android:layout_gravity="center"
    android:layout_weight="1"
    android:textAlignment="center" />

A: Use
android:gravity="center_vertical|center_horizontal"
or just
android:gravity="center"
to center text in a TexView.
EDIT: try removing android:textAppearance="?android:attr/textAppearanceLarge" or the layout_weight attribute

A: <TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerInParent="true"
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:text="Large Text"
    android:id="@+id/textView"
    android:layout_gravity="center"
    android:layout_weight="1"
    android:textAlignment="center" />

A: <TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="@+id/textView"
android:layout_gravity="center"
android:layout_weight="1"
android:textAlignment="center" />


text:
Q: How to extract usernames from text in python? So I have a message such as "Hey @richard01 what time are we meeting @freddy023?" and I need a function to get it to extract the usernames which are always marked by beginning with an @ symbol.
def get_username(message, position):

So, for example, the following code would output "freddy023"
get_username("Hey @richard01 what time are we meeting @freddy023?", 2)

A: You can use regex:
import re

test_string = "Hey @richard01 what time are we meeting @freddy023?"

usernames = re.findall("\B@\w+", test_string)

print(usernames)
# Prints: ['@richard01', '@freddy023']

Here the regex expression matches the @ symbol followed by 1 or more word characters (including numbers). The \B makes sure the @ doesn't appear halfway through a word (like in an email)
I highly recommend having a play around with regex to fully understand how this works, Regex101 is brilliant for this. You can see this regular expression in action here: https://regex101.com/r/BOwY5z/1


text:
Q: Angular 5 forms creating a model for the form group inputs or leaving it as generic variable with 2 way binding I am new to Angular, I don't understand why most courses or tutorials are using a model or interface for the data that is taken from a form, for me I found it working well (& easier) to use generic variable with 2 way data binding to fill it.
Can someone explain why we should define a model for the form data ?
I mean instead of using
  attorney: any = {
  };

usually the courses use this:
attorney: Attorney = {...}
//where the Attorney is a class defined with many parameters

You can find my working code below for this.
https://stackblitz.com/edit/angular-xkcgng?file=app%2Fapp.component.html

A: Sure you can use any for any variable/field/parameter, the problem is if you do this you will not get any safety from the typescript compiler.
interface Attorney  {
    name: string
}
class Comp {
    attorney: Attorney = {
        Name: 'Test' // compile time error which is good
    }
}

If you use any you can access any field on the object, which can lead to errors,
    attorney: any= {
        Name: 'Test' // compile time error which is good
        age: 10
    }
    console.log(this.name + ' '+this.age.trim('0')) // will be a runtime error instead of a compile time one

A: There is no right or wrong way to do any of this. If you want to use a custom type, use a custom type. If you want to use any, use any.
Just understand that each approach has costs and benefits. @Titan makes a good argument for using a custom type. Let the compiler do all the work for you.
You should use the approach that makes the most sense to you. If you don't see any reason why not to use any for your use case, and it makes your life easier, then use any. When you come to a point where any is not well suited and a custom type would be better, then you can switch.
Or you can try both now and see which one you like better for the particular feature you are building.

That being said, in your StackBlitz example, you are mixing template-driven forms with reactive forms. If you are using the FormBuilder, do not use ngModel to bind to your properties for the same form object values... just use formControlName or something. When you are working with plain objects, then it makes sense to use ngModel because that is the only way you'll get the binding.


text:
Q: How to get action bar show in android public class MainActi`enter code here`vity extends Activity {
@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);`enter code here`
        setContentView(R.layout.activity_main);
        ActionBar actionBar=getActionBar();`enter code here`
        actionBa`.setDisplayShowHomeEnabled(true);
        actionBar.setDisplayShowTitleEnabled(true);
}
}

A: actionBar is deprecated you should use Toolbar...
first create new layout named "app_bar.xml"
and type this codes on it:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
      android:orientation="vertical" android:layout_width="match_parent"
      android:layout_height="150dp"
      android:paddingTop="@dimen/top_padding"
      android:background="@color/colorPrimary">

</android.support.v7.widget.Toolbar>

then in your mainactivity type this :
public class MainActivity extends AppCompatActivity{

    public Toolbar toolbar;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        toolbar = (Toolbar)findViewById(R.id.app_bar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayShowTitleEnabled(false);
        getSupportActionBar().setDisplayShowHomeEnabled(true);

   }}


text:
Q: Making a simple check in C# in Umbraco I want to do a check if something is an integer, so if it is 8, then assign a certain value to a variable, if not, another variable, pretty straightforward, but I get an error on this?
var getColor = umbraco.presentation.nodeFactory.Node.GetCurrent().GetProperty("textColor" + i).Value;
                if (getColor == 8)
                {
                    var color = "black";
                }
                else
                {
                    var color = "white";
                }

Then I want to print out the variable in my HTML as a class like so:
<div class="headline <% color %>">

The whole code looks like:

            <%for(int i = 1; i < 5; i++) { %>
            <%

                var getColor = umbraco.presentation.nodeFactory.Node.GetCurrent().GetProperty("textColor" + i).Value;
                if (getColor == "8")
                {
                    var color = "black";
                }
                else
                {
                    var color = "white";
                }
            %>
                <%if(umbraco.presentation.nodeFactory.Node.GetCurrent().GetProperty("image"+ i).Value != "") {%>
                    <div class="slide" id="slide<%=i%>" onclick="location.href = '<%=umbraco.library.NiceUrl(int.Parse(umbraco.presentation.nodeFactory.Node.GetCurrent().GetProperty("link"+ i).Value))%>';" style="display:<%if(i != 1){%>none<%}%>;" tmpcolor="<%=umbraco.presentation.nodeFactory.Node.GetCurrent().GetProperty("backgroundColor"+ i).Value%>">
                    <div class="image" id="image<%=i%>" style="background: url(<%=umbraco.presentation.nodeFactory.Node.GetCurrent().GetProperty("image"+ i).Value%>) center center;">

                    <div class="headline <%=color%>"><%=umbraco.presentation.nodeFactory.Node.GetCurrent().GetProperty("headline"+ i).Value%>

<%=umbraco.presentation.nodeFactory.Node.GetCurrent().GetProperty("subline"+ i).Value%>

                        <%for(int y = 1; y < 5; y++) { %>
                            <%if(umbraco.presentation.nodeFactory.Node.GetCurrent().GetProperty("menutext"+ y).Value != "") {%><span class="item<%if(i==y){%> selected<%}%>" onmouseover="gotoSlide(<%=y%>);"><a title="<%=umbraco.presentation.nodeFactory.Node.GetCurrent().GetProperty("headline"+ i).Value%>" href='<%=umbraco.library.NiceUrl(int.Parse(umbraco.presentation.nodeFactory.Node.GetCurrent().GetProperty("link"+ y).Value))%>'><%=umbraco.presentation.nodeFactory.Node.GetCurrent().GetProperty("menutext"+ y).Value%>
<%}%>
                        <%}%>

                <%}%>
            <%}%>

Im getting the error that "color in not in the current context"

A: Value returns a string, which is dependent on the datatype you used for the properties on your document type.  As such you can't say "getColor == 8".
Here are some snippets I got working in a test environment of mine on a .master or .aspx page.

<div class="<% =GetColorClass() %>">

Cool It Works!

Now, also notice I am using <% =... versus what you had as <%.
<% %> = inline code (doesn't insert anything into the response, just executes inline code)
<%$ %> = for evaluating expressions with one of the expression builders registered in the web.config
...
<%= %> : short hand for response.write (this is what you want here because it will insert the output into the response where encountered, e.g. like on a class=" attribute.
For a more complete list of these, see the post I took this from, <%$, <%@, <%=, <%# ... what's the deal?
I also used the node factory from a different namespace, the namespace you were accessing it from has been marked obsolete and could be removed from future versions.


text:
Q: Scala - shortening piece of code with higher level methods How can I shorten the following piece of code (the toText method) with higher level methods like map, takeWhile, filter, etc.:
/** Returns the text that is produced by this keypad from the given multi-tap input.
  * For instance, the input `"33 3338881330000"` produces `"HIYAH!"`. The given string
  * is assumed to consist of digits and spaces only.
  */
def toText(keysPressed: String): String = {
 val pieces = keysPressed.split(" ")
 var result = ""                        // gatherer
 for (currentPiece <- pieces) {         // most-recent holder
   var remaining = currentPiece         // gatherer
   while (remaining.nonEmpty) {
     val copyCount = countInitialCopies(remaining) // temporary
     result += charFor(remaining(0), copyCount)
     remaining = remaining.drop(copyCount)
   }
 }
 result
}

where:
/** Returns the character produced by pressing the given number key (from '0' to '9')
  * the given number of times on this keypad. If a key is pressed more times than there
  * are characters assigned to the key, the result "wraps around".
  */
def charFor(keyPressed: Char, timesPressed: Int): Char = {
  val charactersForKeys = Vector(" .,!?", "ABC", "DEF", "GHI", "JKL", "MNO", "PQRS", "TUV", "WXYZ", "ÅÄÖ")
  val key = charactersForKeys(keyPressed.asDigit)
  key((timesPressed-1) % key.length)
}

and:
/** Determines the first letter of the given string, and returns the number of times
  * the letter occurs consecutively at the beginning of the string. The given
  * string must have at least one character.
  */
def countInitialCopies(str: String): Int = str.takeWhile(_ == str(0)).length

I tried to do the following, but it didn't go that far:
def toText(keysPressed: String): String = keysPressed.split(" ").foldLeft("")(charFor(_(0), countInitialCopies(_)))

A: Not sure if it is really shorter but here is one:
def toText(keysPressed: String): String = {
  def split(seq: Seq[Char]): Stream[Seq[Char]] = {
    if (seq.isEmpty)
      Stream.empty
    else {
      val lr = seq.span(ch => ch == seq.head)
      Stream.cons(lr._1, split(lr._2))
    }
  }

  split(keysPressed)
    .filter(s => s.head.isDigit) // filter out spaces between different series of the same digits
    .map(s => charFor(s.head, s.length))
    .mkString("")
}

The idea behind this code is:

*

*first split the keysPressed (treated as Seq[Char] thanks to implicit scala.collection.immutable.StringOps) into a Stream[Seq[Char]] in a way similar to your countInitialCopies (note that cons second argument is a "recursive" (actually delayed) call on the rest of the Seq!)

*then filter out Seq[Char] that come from spaces for explicit groups separation,

*then map that filtered Stream[Seq[Char]] using your charFor

*finally accumulate the result from Stream into a String

A: Here's a slightly different approach to the problem. Uses takeWhile() but not much else.
val charsForKeys = Vector(" .,!?", "ABC", "DEF", "GHI", "JKL", "MNO", "PQRS", "TUV", "WXYZ")

def toText(keysPressed: String): String = {
  if (keysPressed.isEmpty) ""
  else {
    val kpHead = keysPressed.head
    val kpStr  = keysPressed.takeWhile(_ == kpHead)
    val kpLen  = kpStr.length
    if (kpHead.isDigit)
      charsForKeys(kpHead.asDigit)(kpLen-1) + toText(keysPressed.drop(kpLen))
    else
      toText(keysPressed.drop(kpLen))  //not a digit, skip these chars
  }
}

toText("33 3338881330000")  //res0: String = HIYAH!

2nd, shorter, attempt. Uses foldRight() and collect().
def toText(keysPressed: String): String = {
  keysPressed.foldRight(List[String]()){
    case (c, s::ss) => if (c == s.head) c+s :: ss
                       else c.toString :: s :: ss
    case (c, Nil)   => List(c.toString)
  }.collect{
    case s if s.head.isDigit => charsForKeys(s.head.asDigit)(s.length-1)
  }.mkString
}


text:
Q: When using dgram (UDP) with Socket.IO at what speed are the datagrams sent? (node) I am using socket.io and the dgram node library to send UDP messages from one program to a browser via node.
The code looks just like the socket.io example
var dgram = require("dgram");
var dServer = dgram.createSocket("udp4");
dServer.bind(12345, '0.0.0.0');
var io = require('socket.io').listen(80);
io.sockets.on('connection', function (socket) {
  dServer.on("message", function (msg) {
     socket.send('message', msg);
  });
});

My question is at what speed are the datagrams ultimately being sent to the browser? Are they being sent at TCP speeds, web socket speeds (which I understand to be slower) or UDP speeds (which I understand are quicker when it comes to real time communication).
Also, in this example is io perpetually listening on port 80 (meaning it can only receive things at http / tcp speeds) or does it just listen to establish the socket connection and then can stop listening (and let the socket connection take over)

A: The speed of UDP, TCP and WebSockets "Packets" are the same (e.g. wire speed), but they differ in overhead and reliability.

*

*WebSockets are a tunnel within an existing HTTP connection, so in effect TCP with more overhead. But they use existing ways in tunneling through NAT router and firewalls.

*TCP has reliability guarantees, e.g. no packets get lost and no duplicates. TCP needs an initial 3-way handshake, but this is once for a connection and not for each data chunk.

*UDP is fire and forget and you need to implement you own reliability on top if you need it. Apart from that, I'm not sure if the browser will even natively accept your UDP packet, at least outside RTP context (e.g. WebRTC). It might work with Java and Flash.


text:
Q: my appendix title did not goes to top of the page and also my table and fig did not fix to side by side \addcontentsline{toc}{chapter}{Appendices-C}
\setcounter{chapter}{1}
\begin{center}
\textbf{\LARGE Appendices-C}
\end{center}
\section{algorithm}
\begin{table}
\begin{minipage}[b]{1\textwidth}%
        \large
            \begin{tabular}{cc}
    \toprule
    Y     & X   \\
    \midrule

    0.003049 & -165 \\
    17.34357 & -156 \\
    33.01277 & -147 \\
    47.01361 & -138 \\
    59.34909 & -129 \\
    70.02217 & -120 \\
    79.03583 & -111 \\
    86.39305 & -102 \\
    92.09681 & -93 \\
    96.15008 & -84 \\
    98.55585 & -75 \\
    99.31709 & -66 \\
    98.43678 & -57 \\
    95.91789 & -48 \\
    91.7634 & -39 \\
    85.97629 & -30 \\
    78.55954 & -21 \\
    69.51613 & -12 \\
    58.84903 & -3 \\
    46.56122 & 6 \\
    32.65568 & 15 \\
    17.13538 & 24 \\
    0.003302 & 33 \\

\hline
        \end{tabular}
    \label{A}%
    \end{minipage}\hfill
    \begin{minipage}[b]{0.2\textwidth}
        \includegraphics[width=0.2\textwidth]{p1}
        \captionof{figure}{P1}
        \label{ }
    \end{minipage}
        \caption{P1 profile coordinates}
    \end{table}


text:
Q: WCF and DataContract on a complex type containing complex types Searching around, I couldn't find a clear answer on this.
So i have a complex type, which contains two complex types
[DataContract]
public class complextype
{
   [DataMember]
   public Complex1 type1{get;set;}
   [DataMember]
   public Complex2 type2{get;set;}
}

Is this the correct way? Because both Complex1 and Complex2 always come back as null so i'm assuming no.
Edit:Told to add the two compolex types as data contracts as well
[DataContract]
public Complex1
{
   [DataMember]
   string Test1{get; set;}
}

[DataContract]
public Complex2
{
   [DataMember]
   int Test1{get; set;}
}


text:
Q: Strange behaviour using Slerp I am using Quaternion.Slerp to rotate a car when turning. I've noticed that right before a left turn, the car will rotate slightly right before rotating left to make the turn. I am also Lerping the car from one position to the next. Any idea why this happens and how to stop it?
car.transform.position = Vector3.Lerp(car.transform.position, nextPosition, fracJourney);

if (direction != Vector3.zero)
{
    Quaternion lookRotation = Quaternion.LookRotation(direction);
    car.transform.rotation = Quaternion.Slerp(car.transform.rotation, lookRotation, Time.deltaTime * rotationSpeed);
}

A: Quaternion.Slerp uses interpolation and shortest path.  It does not work well with large angles.  And is literally undefined at exactly 180 degrees.  Around that angle you will get something "jerky" from frame to frame.
Two options:
Tween your animation.  That is, effectively, rotating by smaller angles up until you reach the final angle.  Think of key frames or breaking one rotation into smaller chunks.
Or you can do the interpolation while still in Euler Angles space.  And then use Quaternion.Euler after interpolation.


text:
Q: Yii2 Ajax request in yii2 By using kartik select2 plugins in Yii2, I try to make dependence dropdown for country and states.
Form field for country and states:
$url = yii\helpers\Url::toRoute('op-client/lists');

$this->registerJs($this->render('script.js'), \yii\web\VIEW::POS_READY);

$form->field($model, 'country_id')->widget(Select2::classname(), [
                                    'data' => $countryData,
                                    'language' => 'en',
                                    'options' => ['placeholder' => 'Select'],
                                    'pluginOptions' => [
                                        'allowClear' => true,
                                    ],
                                    'pluginEvents' =>
                                    [
                                        'change' => 'function()
                                          {
                                              getstate
                                              (
                                                $("#select2-opclient-country_id-container").val(),
                                                 "'.$url.'"
                                              )
                                          }',
                                    ],
                                ]).'

                                $form->field($model, 'states_id')->widget(Select2::classname(), [
                                    'data' => $statesData,
                                    'language' => 'en',
                                    'options' => ['placeholder' => 'Select'],
                                    'pluginOptions' => [
                                        'allowClear' => true,
                                    ],

                                ]).'

Script.js
function getstate($countryid,url)
{
    //console.log(startdate + enddate);
 var csrfToken = $('meta[name="csrf-token"]').attr("content");

    $.ajax({
        type:"POST",
        cache:false,
        url:url,
        data:{countryid:countryid, _crsf:csrfToken},
        success:function(data){
            $("#select2-opclient-states_id-container").val(data);
        },
    })
}

Controller:
public function actionLists()
    {
        $request = Yii::$app->request;

        $country = $request->post('countryid');

        $countStates = OpStates::find()
                        ->where(['country_id' => $country])
                        ->count();

        $states = OpStates::find()
                        ->where(['country_id' =>$country])
                        ->all();

        if($countStates > 0)
        {
            foreach($states as $state){
                echo "<option value='".$state->id."'>".$state->state_name."</option>";
            }
        }
        else
        {
            echo "<option></option>";
        }
    }

When I run the program, it show error "Uncaught ReferenceError: countryid is not defined".
But I thought i passed the countryid into it already? Where have I done wrong?
Any help/advice will be appreciated. Thankss

A: Please check below code,i think you did little mistake in country_id variable name.
public function actionLists()
    {
        $request = Yii::$app->request;

        $country = $request->post('country_id');

        $countStates = OpStates::find()
                        ->where(['country_id' => $country])
                        ->count();

        $states = OpStates::find()
                        ->where(['country_id' =>$country])
                        ->all();

        if($countStates > 0)
        {
            foreach($states as $state){
                echo "<option value='".$state->id."'>".$state->state_name."</option>";
            }
        }
        else
        {
            echo "<option></option>";
        }
    }

and here
function getstate(countryid,url)
{
    //console.log(startdate + enddate);
 var csrfToken = $('meta[name="csrf-token"]').attr("content");

    $.ajax({
        type:"POST",
        cache:false,
        url:url,
        data:{countryid:countryid, _crsf:csrfToken},
        success:function(data){
            $("#select2-opclient-states_id-container").val(data);
        },
    })
}

It will solve your issue.


text:
Q: Is there a more elegant way to add key/value pairs to a hash? (If key == nil, then assign new key/value, else add value to the existing key) Given a polynomial expression (e.g. 3a+2c-4a), and its array representation foo = [[3,'a'],[2,'c'],[-4,'a']], I am simplifying the expression by creating a hash and adding the coefficients as follows:
foo = [[3,'a'],[2,'c'],[-4,'a']]
foo_hash = {}
foo.each {|el| foo_hash.include?(el[1]) ? foo_hash[el[1]] = el[0] : foo_hash[el[1]] += el[0]}
foo_hash = {'a' => -1, 'c' => 2}

My question: can the conditional hash assignment within the each block be expressed in a more concise form that avoids repetition?

A: You can use Enumerable#inject with Hash#new
foo.inject(Hash.new(0)) {|h, (n,a)| h[a]+= n; h  }
# => {"a" => -1, "c" => 2}

A: This is a good use of a default value in Hash's initailizer:
foo_hash = Hash.new(0)
# => {}
foo_hash["completely_new_key"]
# => 0

So the concise solution becomes:
foo = [[3,'a'],[2,'c'],[-4,'a']]
foo_hash = Hash.new(0)
foo.each{|val, key| foo_hash[key] += val}
foo_hash
#  => {"a"=>-1, "c"=>2}

A: Perhaps merge! with a block:
foo.each.with_object({}) { |p, h| h.merge!([p.reverse].to_h) { |_, x, y| x + y} }
#=> { "a" => -1, "c" => 2 }


text:
Q: Show that $f(z)=\sum_{n= 0}^{+\infty}a_n z^n$ is a polynomial
Let $f(z)=\sum_{n= 0}^{+\infty}a_n z^n$, the radius of convergence $\ge 1$.
For all $n,\quad a_n\in \mathbb{Z}$ and $f$ is bounded the open unit disk.
Show that $f$ is a polynomial.

My attempt:
for  $0< r< R=1$ we have $a_{n}=\frac{1}{2\pi r^{n}}\int_{0}^{2\pi }f(re^{i\theta })e^{-in\theta }d\theta$ : Cauchy formula.
Then
$$
 \left | a_{n} \right |\leq \frac{max_{D}\left | f \right |}{r^{n}}
$$
Then I take the limit as $x \rightarrow 1$, is it correct ?
Thanks
Sorry I deleted : I think it's incorrect.

A: By Parseval's Theorem, you have
$$\int_0^{2\pi} |f(re^{i\theta})|^2\,d\theta = 2\pi(|a_0|^2 + \sum_{n > 0} r^{2n}|a_n|^2) \tag 1$$
(Essentially what is going on here is you are expanding the square, noting that cross terms integrate to zero, then integrating the remaining square terms.)
If infinitely many $a_n$ were nonzero, since they are all integers, taking the limit on the right in $(1)$ gives
$$\lim_{r \rightarrow 1} \int_0^{2\pi} |f(re^{i\theta})|^2\,d\theta = \infty$$
This would not occur if $f(z)$ were bounded inside the unit disk. So only finitely many $a_n$ can be nonzero in this situation; that is, $f(z)$ is a polynomial.


text:
Q: Wordpress Form POST Request In Current Page Got Twice I use wordpress shortcode to create a form and send post request in current page.
But I will get twice post request so my mail will send twice.
Hope someone can help me to fix this problem.
Here is my code :
<?php
   if(isset($_POST['flag']) && $_POST['flag'] == 'true') {
      $message = 'MAIL CONTENT';
      $headers = array('Content-Type: text/html; charset=UTF-8');
      wp_mail(["sender1@xxx.com", "sender2@xxx.com"], 'subject', $message, $headers);
?>

<?php
   }else{
?>

          <form action="" method="post" name="reupload" enctype="multipart/form-data">
                <input type="hidden" name="flag" value="true">
                File
                <input type="file" class="files" name="files" id="file1" accept=".jpg, .jpeg">
                <button id="submit" type="submit" class="button">Submit</button>
          </form>

<?php
   }
?>


text:
Q: convert short jquery to standalone javascript Can you help me getting this:
$(document).ready(function() {
    $("#large").attr("src",bilder[0]);

    $.each(bilder, function(i) {
        $("#gallery .large").append("

");
    });

    $(".small td").mouseover(function(){
        var src = $("img",this).attr("src");
        $("#large").attr("src",src);
    });
});

I started with this:
document.addEventListener('DOMContentLoaded', function() {
    document.getElementById('large').setAttribute('src', bilder[0]);

    for (var i = 0, len = bilder.length; i < len; ++i) {
    //???
    };

});

That's what I have, but appending and mouseover...no idea.
Hope you can help me "converting" this.

A: Ok, phew, this comes a little close. Can you try this ?
for (var i = 0, len = bilder.length; i < len; ++i) {
    var els = document.getElementById("gallery").getElementsByClassName("large");
    for (var j = 0; j < els.length; ++j){
        els[i].innerHTML += "

";
    }
};

...

var smallEls = document.getElementsByClassName("small");
for( var i = 0 ; i < smallEls.length; ++i){
    var tds = smallEls[i].getElementsByTagName("td");
    for( var j = 0 ; i < tds.length; ++j){
        tds[j].onmouseover = function(){
            var imgs = document.getElementsByTagName("img");
            for( var k = 0 ; k < imgs.length; ++k){
                var src = imgs[k].src;
                document.getElementById("large").addAttribute("src", src);
            }
         }
    }
}

A: You can use the property innerHtml of an element te set its content. To append some content, you should use +=
Ex: myElement+= "
A new paragraph
"

A: FYI, solved it like this:
document.addEventListener('DOMContentLoaded', function() {
    document.getElementById('large').setAttribute('src', bilder[0]);

    for (var i = 0, len = bilder.length; i < len; ++i) {
        var els = document.getElementById("gallery").getElementsByClassName("large");
        for (var j = 0; j < els.length; ++j){
            els[j].innerHTML += "

";
        }
    };

});


text:
Q: PHP: atomatic include I am using a lot of include files to include my 191 files of with the collection of functions, classes ect.
A problem for me is I really dislike editing the include files its gets a big mess and sometime i just forget to include something.
Therefore I was wondering, is there a include function for php or own made library that includes all the php files in a folder or even better in its own folder + all its sub-folders.
These things make life much easyer and flexible.

A: If you have a standard between the Class Names and the files you can use the __autoload() function. It will save you a lot of includes.
http://php.net/manual/en/language.oop5.autoload.php

A: You can use the following function i just created:
function load_folder($folder, $ext = '.php') {
    foreach (glob("$folder*$ext") as $file) {
        if (file_exists($file)) {
            require_once($file);
        }
    }
}

START EDIT
This is the new version of the same function. Now it allows you to specify folders as folder or folder/ without crashing. Also now it loads all files in all folders and subfolders.
function load_folder($dir, $ext = '.php') {
    if (substr($dir, -1) != '/') { $dir = "$dir/"; }
    if($dh = opendir($dir)) {
        $files = array();
        $inner_files = array();
        while($file = readdir($dh)) {
            if($file != "." and $file != ".." and $file[0] != '.') {
                if(is_dir($dir . $file)) {
                    $inner_files = load_folder($dir . $file);
                    if(is_array($inner_files)) $files = array_merge($files, $inner_files);
                } else {
                    array_push($files, $dir . $file);
                }
            }
        }
        closedir($dh);
        foreach ($files as $file) {
            if (is_file($file) and file_exists($file)) {
                $lenght = strlen($ext);
                if (substr($file, -$lenght) == $ext) { require_once($file); }
            }
        }
    }
}

END EDIT
You can also specify a specific extension if you want to load for example only .txt files in a folder you can execute is like this: load_folder('folder/', '.txt');.
Remember that someone think that this is somehow insecure. Before using this function inside a business site, look for more opinion about the topic.
Notice also that if some of your files are regarding classes you could use the __autoload() PHP native function to let PHP call the class where it is really needed (lazy loading).
References:

*

*Autoloading classes

A: You could just have a 'meta-include' file which has the individual include statements, and then you only include that one single file in your scripts.
Of course, the auto-loading versions in the other answers here would be more efficient. While PHP's pretty fast at loading/parsing, 191 individual files to load for every request would add up pretty quick.

A: I usually require as first application_top.php with this:
...

function requireAll($folder){
    // open the folder
    $libs = opendir($folder);
    // loop inside to include each file, excluding windows default 'meta-link' . and ..
    while ($lib = readdir($libs)) {
        if ($lib != "." && $lib != "..")
            // require_once to be sure to require only one time
            require_once $folder . $lib;
}
    // close the dir for cleaning stuff
closedir($libs);
}

//Require all helpers
requireAll(DIR_HELPERS);

//Require all model classes
requireAll(DIR_MODEL);

//Require all mappers
requireAll(DIR_MAPPERS);

...


text:
Q: Google Drive service account for my android app I want to use google drive to upload and download file directly from my Andriod app without any user interaction.I have followed google quick start page of drive api and it works correctly but thing is i want app to authenticate it self directly without asking user to select account it there any way that. I can enter username and pass directly during code.
there are options like service account
when i google for this but no tutorial
there are other tutorials with php and ruby but they are on browser i want it to be integrated with my app. So as soon as i open my app it should fetch file from google drive without any user need
any help or link to tutorial for andriod app will be helpful

A: You can follow the service account sample in this repository.
Here's a snippet which shows how to build service account credential.
HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
...

GoogleCredential credential = GoogleCredential.fromStream(new FileInputStream("MyProject-1234.json"))
    .createScoped(Collections.singleton(PlusScopes.PLUS_ME));
// Set up global Plus instance.
plus = new Plus.Builder(httpTransport, jsonFactory, credential)
    .setApplicationName(APPLICATION_NAME).build();


text:
Q: There should always be a way to intervene and stop a bounty from being auto-awarded Auto-selecting answer for rewards is really annoying
This question had no good answers so I set a bounty on it. It received one new answer that was completely irrelevant, and that was auto-selected. I do understand the policy of losing the points regardless of if an answer is selected, in order to not motivate people to not accept an answer. But I don't see how the auto-selection feature contributes constructively to anything.
I figured this would have been discussed extensively elsewhere but I only found this from 2009.

A: According to the description in the help center. the bounty is only auto-awarded if there exists an answer that was created after the bounty started with a "minimum score of 2". Quote:

If you do not award your bounty within 7 days (plus the grace period), the highest voted answer created after the bounty started with a minimum score of 2 will be awarded half the bounty amount. [...] If there's no answer meeting those criteria, the bounty is not awarded to anyone.

This means that if the voting mechanism works the way it is supposed to, downright bad or irrelevant answers would not get a bounty, as they would not have a score of 2 or more.
However, I have noticed that bad answers (at least bad IMHO) sometimes receives a lot of upvotes, so the voting mechanism is far from perfect.
It is also a fact that people set bounties, receive a useful answer, and then don't bother (or forget) to accept the answer or award the bounty. I've experienced more than once that the person who set the bounty has thanked me for the answer in a comment, saying that is solved their problem, but never returned to SE in time to accept the answer or award the bounty. When I experience this, I am happy that the auto-award mechanism at least gives me half the points for my efforts.
So I think that auto-awarding should still be the default. Because of the "temptation" of the bounty, people tend to spend more effort to solve a problem with a bounty, and the present auto-award mechanism  solves the annoying problem of bounty-setters who don't care what happens after their problem has been solved.
Also, there should no way to get the bounty back, as such a mechanism is open to obvious abuse.
However, there should be a way for the bounty-setter to prevent the bounty from being awarded, even if the highest voted answer has a score of two or more.
Proposal: Add the criterion that if an answer has been downvoted by the bounty-setter, then it is not auto-awarded the bounty, no matter what its accumulated score is.
This gives the bounty-setter a way to prevent the bounty from being awarded a bad answer, while still allowing good answers to receive an auto-award if the bounty-setter is just negligent.


text:
Q: findByIdAndUpdate sometimes work and other times not I am trying to update two document in mongoose but I keep getting

UnhandledPromiseRejectionWarning: TypeError: Cannot read property '_id' of undefined"

But sometimes it works. What am I doing wrong?

const Installateurs = require("../../Models/Installateurs.js");
const Opdrachten = require("../../Models/Opdracht.js");

const verzendOpdrachtNaarInstallateur = (req, response) => {

  Opdrachten.findByIdAndUpdate(req.body._id, req.body).then((result) => {
    const id = result.installateurs[0]._id;

    Installateurs.findById(id).then((res) => {
      res.opdrachten.push(result._id);
      res.huidigeOpdracht.push(result._id);

      console.log(res);

      Installateurs.findByIdAndUpdate(id, res, { new: true })
        .then((updatedInstal) => {
          response.json(updatedInstal);
        })
        .catch((err) => console.log(err));
    });
  });
};

module.exports = verzendOpdrachtNaarInstallateur;

A: not sure but i think its because you have not handled error.
Try this
const Installateurs = require("../../Models/Installateurs.js");
const Opdrachten = require("../../Models/Opdracht.js");

const verzendOpdrachtNaarInstallateur = (req, response) => {

  Opdrachten.findByIdAndUpdate(req.body._id, req.body).then((result) => {
    const id = result.installateurs[0]._id;

    Installateurs.findById(id).then((res) => {
      res.opdrachten.push(result._id);
      res.huidigeOpdracht.push(result._id);

      console.log(res);

      Installateurs.findByIdAndUpdate(id, res, { new: true })
        .then((updatedInstal) => {
          response.json(updatedInstal);
        })
        .catch((err) => console.log(err));
    });
  }).catch((err) => console.log(err));
};

module.exports = verzendOpdrachtNaarInstallateur;

A: This is happening because "result" and "result.installateurs[0]" are undefined for certain "Opdrachten" ids. Would have been better if you could mention the line number for error as well.
The code snippet although shows some shortcomings that are causing the issue.

const Installateurs = require("../../Models/Installateurs.js");
const Opdrachten = require("../../Models/Opdracht.js");

const verzendOpdrachtNaarInstallateur = (req, response) => {
  // make sure here that the req.body is parsed and contains "_id"
  Opdrachten.findByIdAndUpdate(req.body._id, req.body).then((result) => {
    // handle result == null or other cases here
    if (result && result.installateurs && result.installateurs.length && result.installateurs[0]._id) {
      const id = result.installateurs[0]._id;

      Installateurs.findById(id).then((res) => {
        res.opdrachten.push(result._id);
        res.huidigeOpdracht.push(result._id);

        console.log(res);

        Installateurs.findByIdAndUpdate(id, res, {
            new: true
          })
          .then((updatedInstal) => {
            response.json(updatedInstal);
          })
          .catch((err) => console.log(err));
      });
    }

  }).catch((err) => console.log(err));
};

module.exports = verzendOpdrachtNaarInstallateur;

BONUS : try using async/await to avoid callback hell or promises.

A: From what I can tell from the code, Looks like:
Either Your
Opdrachten.findByIdAndUpdate is not returning result.installateurs  property
or
Your Installateurs.findById is returning undefined.
As much as I can tell from the context for the code.


text:
Q: What are convincing examples where pointer arithmetic is preferable to array subscripting? I'm preparing some slides for an introductory C class, and I'm trying to present good examples (and motivation) for using pointer arithmetic over array subscripting.
A lot of the examples I see in books are fairly equivalent. For example, many books show how to reverse the case of all values in a string, but with the exception of replacing an a[i]  with a *p the code is identical.
I am looking for a good (and short) example with single-dimensional arrays where pointer arithmetic can produce significantly more elegant code. Any ideas?

A: char *my_strcpy(const char *s, char *t) {
  char *u = t;
  while (*t++ = *s++);
  return u;
}

Why would you want to spoil such a beauty with an index? (See K&R, and how they build on up to this style.)There is a reason I used the above signature the way it is. Stop editing without asking for a clarification first. For those who think they know, look up the present signature -- you missed a few restrict qualifications.
Structure alignment testing and the offsetof macro implementation.

A: Pointer arithmetic may look fancy and "hackerish", but I have never encountered a case it was FASTER than the standard indexing. Just the opposite, I often encountered cases when it slowed the code down by a large factor.
For example, typical sequential looping through an array with a pointer may be less efficient than looping with a classic index on a modern processors, that support SSE extensions. Pointer arithmetic in a loop sufficiently blocks compilers from performing loop vectorization, which can yield typical 2x-4x performance boost. Additionally, using pointers instead of simple integer variables may result in needless memory store operations due to pointer aliasing.
So, generally pointer arithmetic instead of standard indexed access should NEVER be recommended.

A: Getting a pointer again instead of a value:
One usually uses pointer arithmetic when they want to get a pointer again.   To get a pointer while using an array index: you are 1) calculating the pointer offset, then 2) getting the value at that memory location, then 3) you have to use & to get the address again.  That's more typing and less clean syntax.
Example 1: Let's say you need a pointer to the 512th byte in a buffer
char buffer[1024]
char *p = buffer + 512;

Is cleaner than:
char buffer[1024];
char *p = &buffer[512];

Example 2: More efficient strcat
char buffer[1024];
strcpy(buffer, "hello ");
strcpy(buffer + 6, "world!");

This is cleaner than:
char buffer[1024];
strcpy(buffer, "hello ");
strcpy(&buffer[6], "world!");

Using pointer arithmetic ++ as an iterator:
Incrementing pointers with ++, and decrementing with -- is useful when iterating over each element in an array of elements.  It is cleaner than using a separate variable used to keep track of the offset.

Pointer subtraction:
You can use pointer subtraction with pointer arithmetic.  This can be useful in some cases to get the element before the one you are pointing to.  It can be done with array subscripts too, but it looks really bad and confusing.  Especially to a python programmer where a negative subscript is given to index something from the end of the list.

A: iterating through a 2-dimensional array where the position of a datum does not really matter
if you dont use pointers, you would have to keep track of two subscripts
with pointers, you could point to the top of your array, and with a single loop, zip through the whole thing

A: If you were using an old compiler, or some kind of specialist embedded systems compiler, there might be slight performance differences, but most modern compilers would probably optimize these (tiny) differences out.
The following article might be something you could draw on - depends on the level of your students:
http://geeks.netindonesia.net/blogs/risman/archive/2007/06/25/Pointer-Arithmetic-and-Array-Indexing.aspx

A: You're asking about C specifically, but C++ builds upon this as well:
Most pointer arithmetic naturally generalizes to the Forward Iterator concept.  Walking through memory with *p++ can be used for any sequenced container (linked list, skip list, vector, binary tree, B tree, etc), thanks to operator overloading.

A: Something fun I hope you never have to deal with: pointers can alias, whereas arrays cannot. Aliasing can cause all sorts of non-ideal code generation, the most common of which is using a pointer as an out parameter to another function. Basically, the compiler cannot assume that the pointer used by the function doesn't alias itself or anything else in that stack frame, so it has to reload the value from the pointer every time it's used. Or rather, to be safe it does.

A: Often the choice is just one of style - one looks or feels more natural than the other for a particular case.
There is also the argument that using indexes can cause the compiler to have to repeatedly recalculate offsets inside a loop - I'm not sure how often this is the case (other than in non-optimized builds), but I imagine it happens, but it's probably rarely a problem.
One area that I think is important in the long run (which might not apply to an introductory C class - but learn 'em early, I say) is that using pointer arithmetic applies to the idioms used in the C++ STL.  If you get them to understand pointer arithmetic and use it, then when they move on to the STL, they'll have a leg up on how to properly use iterators.

A: #include ctype.h
void skip_spaces( const char **ppsz )
{
  const char *psz = *ppsz;
  while( isspace(*psz) )
    psz++;
  *ppsz = psz;
}

void fn(void)
{
  char a[]="  Hello World!";
  const char *psz = a;
  skip_spaces( &psz );
  printf("\n%s", psz);
}


text:
Q: Oracle Apex - ORA-00917: missing comma Hello I'm trying to insert a new employee for my database here is my code:
INSERT INTO employees (employee_id, first_name, last_name, phone_number, job_id, salary, department_id)
VALUES (500, 'Alicia', 'Santos', 650.124.0000, 'MK_ASST', 10000, 20)

but oracle apex keeps shows this error
ORA-00917: missing comma
ORA-06512: at "SYS.WWV_DBMS_SQL_APEX_200200", line 670
ORA-06512: at "SYS.DBMS_SYS_SQL", line 1658
ORA-06512: at "SYS.WWV_DBMS_SQL_APEX_200200", line 656
ORA-06512: at "APEX_200200.WWV_FLOW_DYNAMIC_EXEC", line 1768

I dont know where is the missing comma is

A: Phone number can't be as you put it; enclose it into single quotes:
INSERT INTO employees (employee_id, first_name, last_name, phone_number, job_id, salary, department_id)
VALUES (500, 'Alicia', 'Santos', '650.124.0000', 'MK_ASST', 10000, 20)
                                 --------------


text:
Q: How can I manage multiple removable hard drives? I have a desktop PC which I use to play videos and movies on my TV, as well as play music. Storage is an issue so I have the following Icy Dock hard drive cage installed which allows me to swap in multiple drives.

Is there an easy way to keep track of what files are on all my removable hard drives with out actually swapping them in and out? Also is there anyway to ensure that each drive always has the same drive letter so that the paths to the files are always the same? I'm using Windows 7 Home Premium.

A: For cataloging your disks I recommend the free Gentibus CD.
It works very well and has a good and quick search function (that you can see in the image below):

For keeping drive letters I recommend the free USBDLM:

USBDLM is a Windows service that gives
  control over Window's drive letter
  assignment for USB drives. Running as
  service makes it independent of the
  logged on user's privileges, so there
  is no need to give the users the
  privilege to change drive letters.

Basically, one puts a small text file on the root directory of the disk, which dictates the drive-letter to use for this disk.

A: A simple way would be to do

dir [drive:] /b /s > [drive]-contents.txt

"/b" - bare format - no heading or summary
"/s" - recurses down all sub directories
This will produce a raw list of the contents of all folders you can then search that using Notepad (or other plain text editor). Store this file on your permanent hard drive and refer to it when you need to find something.
This does list folders as well so won't be very readable.


text:
Q: React - problems with filtering fetched data from global context I have a simple app showing items with prices on them. I created a global context as my global state. I'm trying to make a filter component where I can filter the items that I get from the context - filtering the items by prices (sort by highest or lowest).
Here's my filter component:
import * as React from "react";

const Filter = ({ updateFilter }) => {
  const [state, setState] = React.useState("");

  const handleChange = (prop, value) => {
    setState({
      [prop]: value,
    });
  };

  return (

        <form onChange={() => updateFilter(state)} noValidate>
          <select
            value={state.sortOrder}
            onChange={(event) =>
              handleChange("sortItems", event.target.value)
            }
          >
            <option value="">Choose...</option>
            <option value="highest">Highest</option>
            <option value="lowest">Lowest</option>
          </select>
        </form>

  );
};

export default Filter;

Here's the home component that is using the filter component above:
import React, { useContext, useState } from "react";
import Filter from "./shared/Filter";
import Card from "./Card";
import { GlobalContext } from "../context/GlobalState";

const defaultState = {
  sortItems: "",
};

const Home = () => {
  const { items } = useContext(GlobalContext);
  const [filter, setFilter] = useState(defaultState);

  const applyFilter = (items, filter) => {
    const { sortItems } = filter;
    let data = items;

    if (sortItems) {
      if (sortItems === "") {
        return data;
      }
      if (sortItems === "highest") {
        data = data.sort((a, b) => b.price - a.price);
      }
      if (sortItems === "lowest") {
        data = data.sort((a, b) => a.price - b.price);
      }
    }
    return data;
  };

  const updateFilter = (filter) => {
    setFilter(filter);
  };

  const filteredItems = applyFilter(items, filter);

  return (
    <React.Fragment>
      <Filter updateFilter={updateFilter} />

        {filteredItems.map((listing) => (
          <Link
            to={`items/${item.id}`}
          >
            <Card key={listing.id} listing={listing} />
          </Link>
        ))}

    </React.Fragment>
  );
};

export default Home;

For reference - items from my global context is returning an array of items like so:
[
  {
    "id": "1",
    "name": "Item A",
    "category": "A",
    "price": 10000
  },
  ...
  ..
  ..
]

The problem I'm having is now is that when I selected a filter for the first time, for example - Highest,  and I consoled log filteredItems, it was giving me the same unfiltered items from context. I then selected Lowest, when I consoled log my filteredItems, it gave what I selected previously which was Highest and my items are sorted from the highest price.
Why is there a lag in the filteredItems? What did I do wrong? Any help would be greatly appreciated!!

A: Here is a working example:
https://codesandbox.io/s/musing-wind-4gcbf?file=/src/GlobalContext.js
Some notes:

*

*Your applyFilter sets the data variable to reference items, and because sort mutates, you're mutating state through the reference. Instead, I conditionally sorted a copy of items in the return.

*While not directly using index as your iteration key, your item ids are linear and would impact react's tracking ability.


text:
Q: Как перевести экспоненциальною запись в обычную? Написал простенький скрипт который вычисляет долг моего друга .
Сумма выходит слишком огромной и записывается в экспоненциальную запись , а нужно в обычной что бы было по красоте.
Вопрос:
Как перевести экспоненциальную запись в обычную ?
let numbers = document.querySelector('h2')
let now = new Date()
let old = new Date('2021-06-1')
let days = Math.round((now.getTime() - old.getTime())/(1000*60*60*24))

function Debt(day){
    return 0.01*2**day
}

numbers.innerText=Debt(days) //1.5474250491067254e+24


text:
Q: PHP Regex to find if string is formatted with commas and semicolons I need to find if a string is formatted in the following way:
text1,x%;text2,y%

So, these strings must be valid:
example, 10%; test, 22%; another, 90%

another example, 11.5%; yet other example, 91%

another, 11%; other example, 11.2%

example2, 20%

And the following must be invalid:
example3; 10%, test3, 22%; another3, 90%

example4; 20%

example5, 11%; test 5, 123%

another fail example, 11,5%; yet other example, 91%

I know some regex but this validation I don't even know how to start.
EDIT: Added more examples.

A: You can use the following regex:
^[\w\s]+,\s*\d+(?:\.\d+)?%(?:;\s*[\p{L}\s]+,\s*\d+(?:\.\d+)?%)*$

See demo
Regex explanation:
Basically, it consists of 2 parts, the one before ; and the rest optional sequences.

*

*^ - Beginning of a string

*[\w\s]+ - 1 or more alphanumeric or whitespace characters followed by...

*, - a comma, then

*\s* - optional whitespace

*\d+(?:\.\d+)?% - a float or integer number (decimal part is optional due to ?) and a percentage sign

*(?:;\s*[\p{L}\s]+,\s*\d+(?:\.\d+)?%)* - the 2nd part that matches 0 or more sequences of...

*

*;\s* - a semi-colon followed by optional whitespace

*[\p{L}\s]+ - 1 or more letters (\p{L}) or whitespace

*,\s* - comma followed by optional whitespace

*\d+(?:\.\d+)?% - a float or integer number (decimal part is optional) and a percentage sign

*$ - End of string


text:
Q: getting SocketTimeoutException while using smack 4.1.2 in android to connect to my ejabberd server I am trying to connect to ejabberd server using smack API 4.1.2 (no asmack) on android device. while running smackClient program , I am getting below error
java.net.SocketTimeOutException:Failed to connect to abc.example.com/182.*.*.* (on port 5222) after 30000ms,'abc.example.com:5222' failed because java.net.ConnectionException: Failed to connect to abc.example.com/182.*.*.* (on port 5222) after 30000ms

Connection to same ejabberd server using same android device is working fine using xmpp clients like xabber. so Issue is surely with client code I have written. Below is the snippet of my code
XMPPTCPConnectionConfiguration config = XMPPTCPConnectionConfiguration.builder()
.setUsernameAndPassword(userName, password)
.setServiceName("abc.example.com")
.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled)
.setSendPresence(true)
.build();
connection = new XMPPTCPConnection(config);
connection.connect();
connection.login(userName, password);

I am missing something in my client code that xabber is having so xabber connection is working from same device using same credential.
Please help

A: Hard to tell without real IP and names in your example. However, my best guess would be about how the address to your IP server is resolved.
There seems to be discrepancy in your example with server (example.com) and service name in your code (abc.example.com).
My guess it that your client is attempting to connect to another machine that the one the XMPP server is running on.
So, here are the things to check when you have issues with a server not replying:

*

*Check how the address of the domain is resolved. You may need to specify another machine name that the domain. If this is a test domain, there is possibly not a DNS setup, so you may even need to specify server IP (while still configuring the client to use an XMPP domain, that's two different things).

*In client, log the IP you are trying to connect to, to make sure this is the one where the server is running.

*If server is not on the main domain server, you may even need to do DNS SRV record queries for XMPP C2S service.

A: For me , it took hours to find the solution.
I forget to turnoff the VPN application(Express VPN) .Network tunneling was the root cause .
And change the Network protocol version properties as below ,

Choose the 1st option (Obtain DNS server address automatically).

A: My experience: I used following code
DomainBareJid xmppServiceDomain = JidCreate.domainBareFrom("desktop-urvfr83");
            //DomainBareJid xmppServiceDomain = JidCreate.domainBareFrom("192.168.1.3");
            InetAddress addr = InetAddress.getByName("192.168.1.3");

            XMPPTCPConnectionConfiguration config = XMPPTCPConnectionConfiguration.builder()
                    .setUsernameAndPassword("alir", "111111")
                    .setHostAddress(addr)
                    .setResource("phonn")
                    .setXmppDomain(xmppServiceDomain)
                    .setSecurityMode(ConnectionConfiguration.SecurityMode.disabled)
                    .setPort(5222)
                    .build();

but it could not connect and produced timeout connection exception. When I disabled windows firewall it worked correctly and connected.


text:
Q: Converting Imperative Expressions to Functional style paradigm I have the following Scala snippet from my code. I am not able to convert it into functional style. I could do it at other places in my code but not able to change the below one to functional. Issue is once the code exhausts all pattern matching options, then only it should send back "NA". Following code is doing that, but it's not in functional style (for-yield)
var matches = new ListBuffer[List[String]]()
      for (line <- caselist){
        var count = 0
        for (pat <- pattern if (!pat.findAllIn(line).isEmpty)){
          count += 1
          matches += pat.findAllIn(line).toList
        }
        if (count == 0){
          matches += List("NA")
        }
       }
      return matches.toList
     }

A: Your question is not entirely complete, so I can't be sure, but I believe the following will do the job:
  for {
    line <- caselist
    matches = pattern.map(_.findAllIn(line).toList)
  } yield matches.flatten match {
    case Nil => List("NA")
    case ms => ms
  }

A: This should do the job. Using foreach and filter to generate the matches and checking to make sure there is a match for each line will work.
caseList.foreach{ line =>
  val results = pattern.foreach ( pat => pat.findAllIn(line).toList )
  val filteredResults = results.filter( ! _.isEmpty )
  if ( filteredResults.isEmpty ) List("NA")
  else filteredResults
}

Functional doesn't mean you can't have intermediate named values.


text:
Q: ColdFusion structkey starting with number Why does this fail:
<CFIF isdefined("URL.3dfile")>...</CFIF>

with following message:

Parameter 1 of function IsDefined, which is now URL.3dfile, must be a syntactically valid variable name.

and this won't:
<CFIF structkeyexists(URL,"3dfile")>...</CFIF>

Is the way it get's parsed not much the same? And .. are variables starting with numbers invalid or aren't they?

A: Seybsen - variables names should not begin with a number. This is likely a legacy of older non-java version of CF Where a variable was not part of an object.
However, in the java world everything IS an object. This leads to a syntactical nuance. If you are using variable names in dotted notation your var name will likely throw an error. But use it in other ways and it will succeed.
So this sort of syntax works
    url['33foo']
But setting a variable name directly - 33foo = true - will not work.
Here's a post with a full explanation.
http://www.coldfusionmuse.com/index.cfm/2005/9/8/isdefined%20vs%20structkeyexists