text:
Q: WebAPI2 / Angular job Interview skill assessment [SHARE] - NULL values A few months back, there was a job position who required a pre interview task assessment. I'm actually new to .NET, so I passed and decided to apply to another job which didn't require .net as much. Long story short. Since then, the idea of solving this problem hunts me and  It bothers me that I was able to get really close to the solution and didn't actually finished it.
So, if anybody wants to practice their .net /webapi2/ angular skills here it is:
screenshot
I get a weird error (NULL values) when I'm almost finishing this task
My Homecontroller.cs
namespace KLab.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            ViewBag.Title = "Home Page";

            return View();
        }
        public JsonResult GetSections()
        {
            var db = new KLabDBEntities();
            var samples = db.Samples.Include("User").Include("Status").ToList();
            return Json(samples, JsonRequestBehavior.AllowGet);
        }
    }
}

Since this is WEb API I've changed the angular code to the following:
my App.js
var myApp = angular.module('myApp', []);
myApp.controller('maincontroller', function ($scope, SampleService) {

getSamples();

function getSamples() {
    SampleService.getSamples()
        .success(function (Samples) {
            $scope.Samples = Samples;
        });
}
});

my service.js
myApp.factory('SampleService', ['$http', function ($http) {

var urlBase = 'http://localhost:35656/api';
var SampleService = {};
SampleService.getSamples = function () {
    return $http.get(urlBase + '/Samples');
};

return SampleService;

}]);

My index.cshtml

Samples

    Samples Id
    Code Number
    Date
    User Id
    Status Id

    {{Sample.SampleId}}
    {{Sample.CodeNumber}}
    {{Sample.Date.replace('/Date(','').replace(')/','') | date:"MM/dd/yyyy"}}
    {{Sample.UserId}}
    {{Sample.StatusId}}

Everything else is default from the WeBAPI2 template from Visual Studio.
so my Models are generated by Entity Framework:
When I build i get:
Samples Id  CodeNumber  Date    UserId  StatusId

data           data     data      1         6

data           data     data      2         4

My goal is to change those id numbers to the actual data of the tables , they are foreign key values
I get no values in that column and when I call the JSON I get:
[{"SampleId":1,"CodeNumber":129076,"Date":"2015-01-02T00:00:00","UserId":6,"StatusId":3,"Status":null,"User":null},
{"SampleId":2,"CodeNumber":850314,"Date":"2015-06-15T00:00:00","UserId":7,"StatusId":3,"Status":null,"User":null},
{"SampleId":3,"CodeNumber":176033,"Date":"2015-07-31T00:00:00","UserId":7,"StatusId":0,"Status":null,"User":null},
{"SampleId":4,"CodeNumber":129629,"Date":"2015-01-21T00:00:00","UserId":3,"StatusId":0,"Status":null,"User":null},"

which is odd since , Status and user are null
Somebody has suggested that this "joins" must be done within a view on the Database itself and then should be called with angular. like a SQL view or using LINQ. Unfortunately, I do not know LINQ but I do know SQL I guess I can create a view with all the tables. Therefore the question is. How can i replace those ID values to the actual data that are related to those foreign keys (userid, statusid) ?
Here's the bulk data's screenshot:
bulk data


text:
Q: how to change the language / cultureinfo? How do I switch which resource file gets utilized based on current language?
I've got english and a czech resource/resx files:

I can get values out of this file by doing:
Dim mySetting = My.Resources.GlobalStrings.ResourceManager.GetString(value)

When I do this, it automatically uses GlobalStrings.resx.
How do I switch the language and force it to grab settings from GlobalStrings.cs-CZ.resx?
Please note that this is a WinForms application.

redpajama_set_name: RedPajamaStackExchange


text:
Q: NavigationStack Searchable .focused I need to configure when the user clicks in the Search box to fulfill the condition (display another View). Once he clicks Cancel to display the original view (which can already be tested via .onChange(of: searchText) { value in if (!value.isEmpty) {...)
NavigationStack {
            ...
if showView == true {}
            ...

        }

        .searchable(text: $searchText, placement: .navigationBarDrawer(displayMode: .always), prompt: LocalizedStringKey("Look for something"))
        .focused($focusState)
        .onChange(of: focusState, perform: {
        showView = true
            })

When the user starts searching, I need to show a different View and hide the original one because I have search settings on the new one. As soon as he clicks on the Search button, the search starts.

A: @FocusState isn't the way to handle this, as the search bar does update or respond to changes in this state.
What you need to use is the isSearching Environment variable in the view on which the .searchable modifier is applied, for example:
struct ContentView: View {

    @State private var searchText = ""

    var body: some View {
        NavigationView {
            SearchingView(searchText: $searchText)
                .searchable(text: $searchText, placement: .navigationBarDrawer(displayMode: .always), prompt: LocalizedStringKey("Look for something"))
        }
    }
}

struct SearchingView: View {
    @Environment(\.isSearching) private var isSearching
    @Binding var searchText: String

    var body: some View {
        if isSearching {
            // Show your filtered data view
        } else {
            // Show non-searching view
        }
    }
}


text:
Q: Rack: launching the proc from a standalone file I'd like to launch a simple proc from a standalone file:
# config.ru
require 'rack'
require File.expand_path '../app.rb', __FILE__
run @app

# app.rb
@app = Proc.new do |env|
  [
    200,
    {'Content-Type'=> 'text/html'},
    ["<title>My app</title>Hello world"]
  ]
end

But this causes the scope issue - the @app var, seems, is not visible inside the config.ru. Therefore the following is appeared inside the error log Message from application: missing run or map statement (RuntimeError) How do I handle this?

A: The workaround is using the method, provided by the module, rather than the instantce var:
#!/usr/bin/ruby
# app.rb
module AppModule
  def self.start_app
    Proc.new do |env|
      [
        200,
        {'Content-Type'=> 'text/html'},
        ["<title>ENV VARS</title>#{ENV.sort.each {|k,v| puts "#{k}=#{v}"}}"]
      ]
    end
  end
end

# config.ru
require 'rack'
require File.expand_path '../app.rb', __FILE__
run AppModule.start_app


text:
Q: What are the model configuration parameters in tensorflow object detection API? In the Config file  there are some parameters which I don't understand properly . I will mention them here.
first_stage_features_stride - Is this the ration of input/output ?
height_stride (In the first_stage_anchor_generator) - What is this ?

A: First stage feature stride is describing what is the output stride .
So you have to understand what is the difference between input and output strides . Please go with this answer .
Then height stride is the same , Which describe how an anchor should behave in the real image w.r.t the final feature-map .


text:
Q: Given $n$ integers $a_1$ to $a_n$ and an integer $K$, does there exist a solution which satisfies the following equation? Given $n$ integers $a_1$ to $a_n$ and an integer $K$, does there exist a solution which satisfies the following equation?
$$\sum_{i=1}^n a_i\cdot x_i = K $$
Note that all $x_i$ must need to be NON-NEGATIVE integers.
My Attempt:
This seems to be a NP-hard problem, special kind of Knapsack problem with exact value to match.
I don't have much idea apart from brute force on entire range like a knapsack problem.
Someone told me it can be solved efficiently by graph theory .

A: The coin problem, also called Frobenius problem, is probably what you are looking for:
https://en.wikipedia.org/wiki/Coin_problem
It is the problem of finding the largest $K$ that is not reachable, given the $a_i$.
For the problem to have a solution, the $a_i$ must have no common divisor greater than 1.
As for finding a solution with a computer:

*

*As we know that for 2 $a_i$ $x$ and $y$ (EDIT: which are coprime), the largest non-reachable number is $xy - x - y$, if $K$ is greater than this (for the two smallest coprime $a_i$) then the problem is solved positively.

*If not, then a brute force approach may not be too much costly, because the $a_i$ will be roughly greater than $\sqrt K$.


text:
Q: MVC Interface and Repository Difference I notice code where people create both 1) Interface and 2) Repository. Interface lists all data Crud operations, and Repository actually defines data Crud operations. Why not just combine them into one class? I heard it is something with level of abstraction? Why are they in two separates places? I am beginner so trying to learn the separation. Thanks,
Resources: Implementing Repository, Implement Repository Pattern
namespace ContosoUniversity.DAL
{
    public interface IStudentRepository : IDisposable
    {
        IEnumerable<Student> GetStudents();
        Student GetStudentByID(int studentId);
        void InsertStudent(Student student);
        void DeleteStudent(int studentID);
        void UpdateStudent(Student student);
        void Save();
    }
}

namespace ContosoUniversity.DAL
{
    public class StudentRepository : IStudentRepository, IDisposable
    {
        private SchoolContext context;

        public StudentRepository(SchoolContext context)
        {
            this.context = context;
        }

        public IEnumerable<Student> GetStudents()
        {
            return context.Students.ToList();
        }

        public Student GetStudentByID(int id)
        {
            return context.Students.Find(id);
        }

        public void InsertStudent(Student student)
        {
            context.Students.Add(student);
        }

        public void DeleteStudent(int studentID)
        {
            Student student = context.Students.Find(studentID);
            context.Students.Remove(student);
        }

        public void UpdateStudent(Student student)
        {
            context.Entry(student).State = EntityState.Modified;
        }

        public void Save()
        {
            context.SaveChanges();
        }

        private bool disposed = false;

        protected virtual void Dispose(bool disposing)
        {
            if (!this.disposed)
            {
                if (disposing)
                {
                    context.Dispose();
                }
            }
            this.disposed = true;
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
    }
}

A: By defining an interface, the consumer of your repository, which may be a Controller class, only needs to depend on your interface IStudentRepository and be loosely coupled. This follows the Dependency Inversion Principle. You can read more about these concepts from the topic of Dependency Injection.
A specific use case for it is that if one day you decide to change the implementation details of the CRUD operations in your repository, you can register this new service and do not require any changes on the consumer side of your repository (assuming you are making use of a dependency injection service).


text:
Q: XAMARIN open specific Browser I am currently working on a XAMARIN app that should open a web page in a specific browser.
The goal is not to open the default browser and also not in the app. Clicking a button should open for example the DuckDuckGo browser or Chrome, even if it is not the default.
The documentation only show how to open a browser, but I want to open a specific browser if it is installed.
Example:
    public async void OpenSpecificBrowser(string url)
    {
        //I don't wont default or in-app
        //Open link in firefox even if not default
        await Browser.OpenAsync(@"firefox://https://i.ytimg.com/vi/qF8f_0DYwog/maxresdefault.jpg");
    }

Is there a way to implement this?


text:
Q: WorldWind insert a clickable link in GeographicText Text renders on globe just fine, but I want to make it a clickable link. If I try to put HTML into the name component it just displays the HTML instead of rendering it and making it a clickable link.
How do I make the Geographic Text become a clickable link?
var temps = [

            {
                'name': 'Tokyo JP',
                'elevation': 10000,
                'latitude': 35.685,
                'longitude': 139.751389
            }
    ];

    var text,
        textAttributes = new WorldWind.TextAttributes(null),
        textLayer = new WorldWind.RenderableLayer("World Temperatures");

    // Set up the common text attributes.
    textAttributes.color = WorldWind.Color.CYAN;

    // Set the depth test property such that the terrain does not obscure the text.
    textAttributes.depthTest = false;

    // For each peak, create a text shape.
    for (var i = 0, len = temps.length; i < len; i++) {
        var temp = temps[i],
            tempPosition = new WorldWind.Position(temp.latitude, temp.longitude, temp.elevation);

        text = new WorldWind.GeographicText(tempPosition, temp.name);

        // Set the text attributes for this shape.
        text.attributes = textAttributes;

        // Add the text to the layer.
        textLayer.addRenderable(text);
    }

    // Add the text layer to the WorldWindow's layer list.
    wwd.addLayer(textLayer);

EDIT: I added the piece of code where the data is inserted into the object. I didn't add the code earlier because anyone with WorldWind experience should know exactly what I was talking about and maybe have greater insight into my specific issue. Though js is not my strongest language, maybe someone would be so kind as to point out the obvious to me, if it is truly an easy fix ;)
Basically this:
'name': 'Tokyo JP',

is the HTML I want rendered.


text:
Q: flutter Listview inside positioned container is not scrolling I have a positioned widget and it has a container as a child. The container has a Listview.seperated as a child but the listview is not scrolling. I tried to change the value of the bottom property but in a range of values , the listview has a small scrolling space at the top but other places wont effect the scrolling.
body: Stack(
    overflow: Overflow.visible,
    children: <Widget>[
      Container(
        height: screenSize.height * 0.2 + 150,
        width: screenSize.width,
        color: Color.fromRGBO(43, 49, 109, 1.0),
      ),
      Positioned(
          left: 20,
          top: -25,
          child: Lottie.asset('assets/gerdali.json',
            height: 400,
            width: 400,
            repeat: false
          )),
      Positioned(
        top: screenSize.height * 0.2 + 20 ,
        bottom: -screenSize.height,
        right:0.0 ,
        left: 0.0,
        child: Container(
          height: screenSize.height,
          width: screenSize.width,
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.only(
              topLeft: Radius.circular(80.0),
              topRight: Radius.circular(80.0)
            )
          ),
          child: ListView.separated(
            padding: EdgeInsets.only(left: 20.0,right: 20.0,top:80.0),
              itemBuilder:(context,index){
                return TextField(
                  decoration: InputDecoration(
                    filled: true,
                    fillColor: Colors.white,
                    hintText: "",
                    border: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(40.0)
                    )
                  ),
                );
              },
              separatorBuilder: (BuildContext,int index){
                return SizedBox(
                  height: 10.0,
                );
              },
              itemCount: 8),
        ),
      ),
      Positioned(
        top: screenSize.height * 0.2 - 60 ,
        left: screenSize.width / 2 - 75,
        child: RawMaterialButton(
          padding: EdgeInsets.all(40.0),
          fillColor: Colors.white,
          shape: CircleBorder(
            side: BorderSide(
              color: Colors.black,
              width: 1.0
            )
          ),
          elevation: 0.0,
          child: Icon(
            Icons.camera_alt,
            color: Colors.grey,
            size: 70.0,
          ),
          onPressed: (){},
        ),)
    ],

A: You can check this code, I just set a scroll view separately to adjust it manually.
Widget build(BuildContext context) {
    final screenSize = MediaQuery.of(context).size;
    return Scaffold(
      body: Stack(
        overflow: Overflow.visible,
        children: <Widget>[
          Positioned(
            top: 0,
            child: Container(
              height: screenSize.height * 0.2 + 150,
              width: screenSize.width,
              color: Color.fromRGBO(43, 49, 109, 1.0),
            ),
          ),
          Positioned(
              left: 20,
              top: -25,
              child: Image.asset('assets/gerdali.json',
                  height: 400, width: 400, repeat: false)),
          Positioned(
            top: screenSize.height * 0.2 + 20,
            bottom: -screenSize.height,
            right: 0.0,
            left: 0.0,
            child: Container(
              height: screenSize.height - (screenSize.height * 0.2 + 20),
              width: screenSize.width,
              decoration: BoxDecoration(
                  color: Colors.red,
                  borderRadius: BorderRadius.only(
                      topLeft: Radius.circular(80.0),
                      topRight: Radius.circular(80.0))),
              child: Column(
                children: [
                  SizedBox(
                    height: 50,
                  ),
                  Container(
                    height: screenSize.height - (screenSize.height * 0.2 + 70),
                    width: screenSize.width,
                    child: ListView.separated(
                        padding:
                            EdgeInsets.only(left: 20.0, right: 20.0, top: 30.0),
                        itemBuilder: (context, index) {
                          return TextField(
                            decoration: InputDecoration(
                                filled: true,
                                fillColor: Colors.white,
                                hintText: "",
                                border: OutlineInputBorder(
                                    borderRadius: BorderRadius.circular(40.0))),
                          );
                        },
                        separatorBuilder: (BuildContext, int index) {
                          return SizedBox(
                            height: 10.0,
                          );
                        },
                        itemCount: 10),
                  ),
                ],
              ),
            ),
          ),
          Positioned(
            top: screenSize.height * 0.2 - 60,
            left: screenSize.width / 2 - 75,
            child: RawMaterialButton(
              padding: EdgeInsets.all(40.0),
              fillColor: Colors.white,
              shape: CircleBorder(
                  side: BorderSide(color: Colors.black, width: 1.0)),
              elevation: 0.0,
              child: Icon(
                Icons.camera_alt,
                color: Colors.grey,
                size: 70.0,
              ),
              onPressed: () {},
            ),
          ),
        ],
      ),
    );
  }


text:
Q: Creating Test Class Quickly using Spring Tool Suite 4 as IntelliJ I was viewing a tutorial about Testing, The exhibitor in the video shows how to create a Test on IntelliJ using Alt + Enter over the name Class. Immediately appears a secondary menu with the option Create Test.

The good thing about this is that it creates the test class respecting the hierarchy of the package where the original class is located.
As is shown in the next image. Even creates a method name as the original Class. Example: public Examen findExamenPorNombre(String nombre) and the test class creates a method with void findExamenPorNombre(String nombre).

The Question is:
Is there something similar to this feature in Spring Tool Suite 4?
Without need to create manually a package hierarchy as the original class.

A: Yes, there is a quick-fix to create a new JUnit Test class from an existing class. Go to the class name, press Ctrl-1 (or Cmd-1, depending on your system), and select the "Create new JUnit test case" quick fix. It will open and pre-populate the wizard to create a new JUnit test.


text:
Q: Почему итератор python выводит только первое ключ-значение словаря? Есть код итерации словаря, при выполнении которого итератор проходит только по первым ключ-значениям, хотя в словаре их больше. Почему так и как это исправить?
Код
address_book_file = open("address_book_file", "rb")  # Открытие файла с словарем
dict_contact = pickle.load(address_book_file)  #Загрузка файла
for name, address in dict_contact.items():  # Итерация словаря
    print(dict_contact)   # Весь словарь
    print(name, address)  # Вывод итерации

Вывод
{'Mom': 'Mom1@rop.org', 'Dad': 'Daddy@rop.org', 'Sam': 'Sam@drop.box', 'kek': 'kekov@kek.org'}
Mom Mom1@rop.org

p.s
Пробовал играться с keys() и values(), но всё тщетно
upd
Больше кода
def search_contact():
    address_book_file = open("address_book_file", "rb")
    file_empty = os.path.getsize("address_book_file") == 0
    if not file_empty:
        search_name = input("Введите имя для поиска: ")
        dict_contact = pickle.load(address_book_file)
        for name, address in dict_contact.items():
            print(dict_contact)
            print(name, address)
            if search_name == name:
                print('\nКонтакт: {0}, с адресом {1}'.format(search_name, dict_contact[name]))
            else:
                print('Этого здесь нет')
                return
    else:
        print('Нет контактов')
    address_book_file.close()

A: Итерация у вас завершается досрочно из-за return в блоке else:
else:
    print('Этого здесь нет')
    return # после этого итерация прекращается

Лучше не перебирать все ключи словаря для поиска нужного ключа, а сразу моментально проверить наличие ключа в словаре (для чего словари собственно и предназначены):
if search_name in dict_contact:
    print('\nКонтакт: {0}, с адресом {1}'.format(search_name, dict_contact[search_name]))
else:
    print('Этого здесь нет')

И файл лучше открывать с помощью менеджера контекста, тогда он потом закроется автоматически по завершении блока кода:
with open("address_book_file", "rb") as address_book_file:
    # остальной код


text:
Q: different result of discrete fourier transform I know that the way we calculate discrete fourier transform($x$ is the given data set):\begin{aligned}X_{k}&=\sum _{n=0}^{N-1}x_{n}\cdot e^{-i2\pi kn/N}\end{aligned}and there is no problem with this definition.
I tried this on a simple data set:\begin{aligned}x=\begin{bmatrix}1\\0\\0\\1\end{bmatrix}\end{aligned} and i get:
\begin{aligned}X=\begin{bmatrix}2\\1+i\\0\\1-i\end{bmatrix}\end{aligned}
but when i try this in here i get $X/4$ instead of $X$.
i know that when i use the inverse i divide by the number of elements, but in that site they divided when they use DFT.
my question is: when do i divide by $N$? at DFT or at the inverse?

A: It is purely a matter of convention. Have a look at this question and its answers over at DSP.SE. You can also use the scaling constant $1/\sqrt{N}$ for both the transform and the inverse transform. In that case the DFT becomes a unitary transform.


text:
Q: Understanding querySelector & querySelectorAll's console output Who/what decides how to write the contents of an object to the console?
Sometimes you'll get a collapsable representation of the object literal while other times it simply prints the DOM structure.
Given this HTML:
<div class="container">
  <video src="low.mp4"></video>
  <video src="high.mp4"></video>
  <video src="mega.mp4"></video>
</div>

If we hit the console (WebKit/Firebug) with:
> var firstVideo = document.querySelector('video')

And then:
> firstVideo

It returns:
<video src="low.mp4"></video>

While, say we've got another object like:
var guitar = { name:'Stratocaster', strings:6 }

Asking the console for:
> guitar

Gives us:

I've run into the behavior a number of times but typically side-stepped my curiosity by some other means. Now it's sort of a pain so I'm looking into it some more. Is it simply because the object in question is a DOM element and the inspector is just helping us out?
(I realize my example is a little odd (comparing a DOM object and a literal), but it's the simplest/quickest way to illustrate the issue.)
Using some info from a previous question I could get a little more info about each object in question:
video.constructor returns:
HTMLVideoElementConstructor

While: guitar.constructor returns:
function Object() {
  [native code]
}

Why does it matter?
Situations like:
> firstVideo.parentElement

I can't look at this element and inspect its properties as simply when I have to go after each one individually (i.e., firstVideo.parentElement.offsetHeight), which is a total bummer.
So, where's the gap in my understanding--what's actually going on?

A: The consoles log differently if the result is an DOM element. They output the source HTML (or XML) of the element instead of listing its properties.
 - querySelector returns a DOM element, so the console shows the source of the element.
 - querySelectorAll returns an array of DOM elements, which should show an array as normal.
You can always force the output list the properties of an object by using dir(object).
You can check out the Firebug Command Line API.

A: When you log a dom node (that is your situation because querySelector returns an element) into the console you get its string representation because it's more clear and it makes you access some standard functionality like highlight the node if you hover the log message or get its location into the document if you click it. If you want to log a dom node like every other object to inspect its properties you can use console.dir(node).
In the other case when you log the constructor of a simple object and the constructor of a dom node the result is the same (in Firebug at least) because you are logging a function and the console prints its name, that is HTMLVideoElementConstructor for video elements and Object for simple objects.


text:
Q: Pass the stdout of `git diff --name-only` to an executable file as parameters of the file So, there's this executable file called pint (it's part of the Laravel 9 framework). It formats PHP files according to a configurable standard like PSR12.
Anyway, you can pass a list of the files you want to format as the parameters of pint like this:
pint file1 file2 file3 file4 ...
If you pass no argument, pint formats all files of the project.
So, what I'm trying to do is that I want pint to format only the files that have changed since the last commit. In other words, I want the output of git diff --name-only HEAD^ HEAD to be passed as parameters of pint in bash shell.
So, this is what I could come up with, but sadly it doesn't work:
git diff --name-only HEAD^ HEAD -o /dev/stdout | ./vendor/bin/pint
Which says: fatal: /dev/stdout: '/dev/stdout' is outside repository at '/home/user/directory' and then it proceeds to execute ./vendor/bin/pint normally as if no argument had been passed.
I suppose I should somehow convert new line to space before passing it to pint but I'm not sure.

A: | is for piping to standard input, but pint expects the filenames to be command-line arguments, not stdin.
Use $(...) to substitute the output of a command into the command line.
./vendor/bin/pint $(git diff --name-only HEAD^ HEAD)

Note that this won't work if any of the filenames contain whitespace, since the spaces will be treated as filename delimiters.


text:
Q: Invalid convertedStatus When i am converting lead via apex, i get an error Invalid ConvertedStatus.

*

*I have made sure that the Lead Status has correct converted status.

*Also the status is Active

*We have recordtypes set on Lead. Also made
sure that the lead status    values are accessible for the
processes.

The regular lead convert from UI works, somehow its the code which fails
The code is part of managed package, which works on a few orgs, but is failing on one org.
Is there any other setting that i might be missing out which could be causing the error.
          lc.setLeadId(leads.Id);
          lc.setAccountId(opps[0].accountId);
          lc.setConvertedStatus(CStatus); // CStatus has the correct status
          lc.setDoNotCreateOpportunity(donotCreateOpp);
                    if(!donotCreateOpp)
                    {
                        if(leads.Company == null)
                            lc.setOpportunityName(leads.lastname);
                        else
                            lc.setOpportunityName(leads.company);
                    }
          lcs.add(lc);
          lcrs = Database.convertLead(lcs, false);

for(Database.LeadConvertResult lcr : lcrs) {
                System.debug( 'processing a lead convert result');
                if(!lcr.isSuccess()) {
                    System.debug(System.LoggingLevel.ERROR, 'lead conversion failed for lead with id: ' + lcr.getLeadId());
                    //Lead l = newLeads.get(lcr.getLeadId());
                    error = true;

                    for(Database.Error dbe : lcr.getErrors()) {
                        System.debug(System.LoggingLevel.ERROR, dbe.getMessage());
                        //HandleException.LogException(dbe,lcr.getLeadId());
                        Apexpages.addMessage( new ApexPages.Message (ApexPages.Severity.ERROR, 'There was an error converting this Lead. ' + dbe.getmessage()));
                        return null;
                    }
                }
            }

UPDATE :
Looking at documentation here https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/langCon_apex_dml_examples_convertlead.htm
Can some help me understand what this means. It refers to lead source on the lead record or on opp?

Record types: If the organization uses record types, the default
  record type of the new owner is assigned to records created during
  lead conversion. The default record type of the user converting the
  lead determines the lead source values available during conversion. If
  the desired lead source values are not available, add the values to
  the default record type of the user converting the lead.

A: The issue turned out to be that the API name of converted Status  was different to MasterLabel. And i was passing the masterlabel on the code which was causing the issue .
Now i changed the api name to be same as the master label and code works fine.
Is it better to pass the API name of lead status OR use the Master Label? My gut feeling is to use the API name.

A: According to your updated question, during conversion system will look for Lead Source of the Lead object.
The user who is converting the Lead must have valid recordtype assginment and the Lead Source should be assigned to the user's profile who is converting the Lead.

The default record type of the user converting the lead determines the lead source values available during conversion. If the desired lead source values are not available, add the values to the default record type of the user converting the lead.

For example, Lead's recordtype is Marketing Lead and Lead source is Campaign. Now the user who is converting the lead has separate recordype assigned to his profile where Campaign lead source doesn't exist then, system will throw that error.

A: This error is due to either:

*

*Not having an active Lead Process defined in Salesforce associated with your Lead record types

*Having a Lead Process defined but not having the specific Lead Status noted in the logfile associated with that Lead Process

*Not associating the Lead Process that includes the noted status (Like examples  "Contacted" or "Qualified" with the record type of the Leads that are selected for conversion
The Lead Process is needed to define valid picklist values for Lead Statuses that can be used with specific Lead record types.

A: You can set the users record type by:
Setup | Manage users | Profiles | Select a profile | Object Settings | Leads (or whichever object) | Edit| Select from the list of record types- default is the column on the Right.


text:
Q: What is `#pragma pack` for in network programming?  #pragma pack(push)
 #pragma pack(1)

I downloaded a tutorial and it has these lines in the header file.
I will appreciate if you guys can provide me any tutorials or references related to this.

A: Microsoft's explanation:
http://msdn.microsoft.com/en-us/library/aa273913(v=vs.60).aspx
IBM's AIX xlC explanation:
http://publib.boulder.ibm.com/infocenter/comphelp/v8v101/index.jsp?topic=%2Fcom.ibm.xlcpp8a.doc%2Fcompiler%2Fref%2Frnpgpack.htm
Basically, it determines the byte boundaries that will be used when storing a structure or union.  The push/pop acts as a way to store and retrieve these settings on a stack.
For future reference, you might save yourself some time by searching for the keywords you're asking as about on the web.  All I did to find this information was search for "pragma pack" at http://www.google.com

A: All #pragma statements are vendor specific.
This one is Microsoft specific, and describes how much "packing" (in bytes) the compiler can add to structs for better alignment.
The #pragma pack(push) simply saves and previous setting in a stack. You can then change the packing conditions for a certain block of code, and later on #pragma pack(pop) to restore the previous settings.

A: It's the MSVC++ specific packing specifier. You can find out exactly what it does from the documentation.
The packing changes how much padding the compiler is allowed to insert between data members of a given struct (or class) to maintain alignment. In the case of networking code, the #pragma pack specifier is probably being used so that a structure can be cast to a char* or void* to be passed to some network API, to send the entire struct over the network at once.
(Note this is unsafe as different machines have different rules for alignment and byte order; this will only work if both machines on each end of the wire use the same hardware type)


text:
Q: Get 403 while opening wss with node js to WhatsApp I try to write an WhatsApp node, and want to open an wss connection, but always get an 403. Maybe someone see my error:
import WebSocket from 'ws';

const ws = new WebSocket('wss://w8.web.whatsapp.com/ws', '["admin", "init", [0, 2, 7314], ["Mac OS 10.13.2", "Chrome"], true]');

ws.on('open', function open() {
  ws.send('["admin", "init", [0, 2, 7314], ["Mac OS 10.13.2", "Chrome"], true]');
});

ws.on('message', function incoming(data) {
  console.log(data);
});

this is only an test, and I hardcoded the values.
But the server always response an 403

A: you have to put a header

var WebSocketClient = require('websocket').client;

var client = new WebSocketClient();

client.on('connectFailed', function(error) {
    console.log('Connect Error: ' + error.toString());
});
 client.onmessage = function(e) {
        console.log(e)
        }
client.on('connect', function(connection) {
    console.log('WebSocket Client Connected');

    connection.on('error', function(error) {
        console.log("Connection Error: " + error.toString());
    });

});

client.connect('wss://w6.web.whatsapp.com/ws', null, null, {
"Accept-Encoding": "gzip, deflate, br",
"Accept-Language": "ar,en-US;q=0.9,en;q=0.8",
"Cache-Control": "no-cache",
"Connection": "Upgrade",
"Host": "w6.web.whatsapp.com",
"Origin": "https://web.whatsapp.com" ,
"Pragma": "no-cache",
"Sec-WebSocket-Extensions": "permessage-deflate; client_max_window_bits",
'Sec-WebSocket-Key' : 'her ur key from header in url',
'Sec-WebSocket-Version':"13",
"Upgrade": "websocket",
"User-Agent": "here your agent"
}, null);


text:
Q: How to fix CJK punctuation at the beginning of line in iText7/iText7.pdfhtml I have encountered this problem when using iText7/iText7.pdfhtml to convert HTML string into PDF file. I had found some similar questions like:

*

*How to fix orphaned punctuation in iText

*iText Chinese punctuation at the beginning of line
But these questions' solution is for iText5, I have tried these solutions at my application but failed at last. My code goes like this:
IList<IElement> elements = HtmlConverter.ConvertToElements(pdfHtmlString, properties);
Document document = new Document(pdfDoc);
CJKSplitCharacters splitCharacters = new CJKSplitCharacters();
document.SetFontProvider(fp);
document.SetSplitCharacters(splitCharacters);
document.SetProperty(Property.SPLIT_CHARACTERS, splitCharacters);
foreach (IElement e in elements)
{
     try
     {
          document.Add((AreaBreak)e);
     }
     catch
     {
          document.Add((IBlockElement)e);
     }
}

Code for CJKSplitCharacters:
public class CJKSplitCharacters : ISplitCharacters
{
    // line of text cannot start or end with this character
    static char u2060 = '\u2060';   //       - ZERO WIDTH NO BREAK SPACE

    // a line of text cannot start with any following characters in NOT_BEGIN_CHARACTERS[]
    static char[] NOT_BEGIN_CHARACTERS = new char[]{u30fb, u2022, uff65, u300d, uff09, u0021, u0025, u0029, u002c,
      u002e, u003f, u005d, u007d, uff61, uff63, uff64, uff67, uff68, uff69, uff6a, uff6b, uff6c, uff6d, uff6e,
      uff6f, uff70, uff9e, uff9f, u3001, u3002, uff0c, uff0e, uff1a, uff1b, uff1f, uff01, u309b, u309c, u30fd,
      u30fe, u309d, u309e, u3005, u30fc, u2019, u201d, u3015, uff3d, uff5d, u3009, u300b, u300f, u3011, u00b0,
      u2032, u2033, u2103, u00a2, uff05, u2030, u3041, u3043, u3045, u3047, u3049, u3063, u3083, u3085, u3087,
      u308e, u30a1, u30a3, u30a5, u30a7, u30a9, u30c3, u30e3, u30e5, u30e7, u30ee, u30f5, u30f6, u2060};

    // a line of text cannot end with any following characters in NOT_ENDING_CHARACTERS[]
    static char[] NOT_ENDING_CHARACTERS = new char[]{u0024, u0028, u005b, u007b, u00a3, u00a5, u201c, u2018, u3008,
      u300a, u300c, u300e, u3010, u3014, uff62, uff08, uff3b, uff5b, uffe5, uff04, u2060};

    /// <summary>
    ///
    /// </summary>
    /// <param name="text"></param>
    /// <param name="glyphPos"></param>
    /// <returns></returns>
    public bool IsSplitCharacter(GlyphLine text, int glyphPos)
    {
        if (!text.Get(glyphPos).HasValidUnicode())
        {
            return false;
        }
        int charCode = text.Get(glyphPos).GetUnicode();

        if (NOT_BEGIN_CHARACTERS.Contains((char)charCode))
        {
            return false;
        }
        return new DefaultSplitCharacters().IsSplitCharacter(text, glyphPos);
    }

My source code is here: Source Code
My problem as follows:

Thank you very much for your help in advance!

A: I guess the problem is in IsSplitCharacter method implementation. You are not using NOT_ENDING_CHARACTERS and are only using NOT_BEGIN_CHARACTERS.
Although I cannot reproduce your sample due to lack of source string data (which means I haven't tested my approach), I think the way you should implement the method in question is the following:
public bool IsSplitCharacter(GlyphLine text, int glyphPos)
{
    if (!text.Get(glyphPos).HasValidUnicode())
    {
        return false;
    }
    int charCode = text.Get(glyphPos).GetUnicode();

    if (NOT_ENDING_CHARACTERS.Contains((char)charCode))
    {
        return false;
    }

    // Look ahead for the next non-whitespace character and check it not to be in NOT_BEGIN_CHARACTERS list
    for (int i = 1; glyphPos + i < text.end; i++)
    {
        if (!text.Get(glyphPos + i).HasValidUnicode())
        {
            break;
        }
        if (!TextUtil.isSpaceOrWhitespace(text.Get(glyphPos + i)))
        {
            if (NOT_BEGIN_CHARACTERS.Contains(text.Get(glyphPos + i).GetUnicode()))
            {
                return false;
            }
            break;
        }
    }

    return new DefaultSplitCharacters().IsSplitCharacter(text, glyphPos);
}

Please also note that your implementation is not very efficient and you should replace char arrays with HashSets to speed up the Contains lookup which is now linear with respect to sizes of your arrays. Also instead of creating DefaultSplitCharacters instance each time in IsSplitCharacter, you should create it once as a field in your CJKSplitCharacters class and reuse it.


text:
Q: PowerQuery - Master & Sub Rows - Reference Values of Another Row Based on Formula or Logic PowerQuery - Master & Sub Rows - Reference Values of Another Row Based on Formula or Logic
I am analyzing vulnerability scanner export data in Excel and developing ticketing from it using some power queries. I've gotten the data into a format that allows me to analyze and determine which have tickets already and which do not. For those that do not, they may already have a master ticket created, but some may not. During my analysis, I will determine if a ticket needs to be created or not, and the output from that should include the master ticket number (if one already created) to link it to, or if no master ticket has already been created, then use the index number of the master ticket that will also be created.
Some example data of what I'm starting out with is:

CVE
Description
Team
Locations
Master
Matching Ticket
Create Ticket

CVE-2021-12345
Vuln Description 1

True
Tic-1234
No

CVE-2021-12345
Vuln Description 1
Ops
1, 2, 3

Yes

CVE-2021-12345
Vuln Description 1
Dev
4, 5, 6

Yes

CVE-2021-12345
Vuln Description 1
InfoSec
7, 8, 9

Yes

CVE-2021-67891
Vuln Description 2

True

Yes

CVE-2021-67891
Vuln Description 2
Dev
4, 5, 6

Yes

CVE-2021-23456
Vuln Description 3

True
Tic-4567
No

CVE-2021-23456
Vuln Description 3
InfoSec
7, 8, 9

Yes

CVE-2021-23456
Vuln Description 3
Ops
1, 2, 3

Yes

CVE-2021-78912
Vuln Description 4

True

Yes

CVE-2021-78912
Vuln Description 4
Dev
4, 5, 6

Yes

CVE-2021-78912
Vuln Description 4
Ops
4, 5, 6

Yes

CVE-2021-78912
Vuln Description 4
InfoSec
4, 5, 6

Yes

I can understand the logic of getting the matching this as I want it with an excel formula as something like: If create ticket equals yes, then (if master does not equal true, then (if the lookup for the matching CVE that has master equals true and has a value in matching ticket, then return the value in matching ticket column, else (if master does not equal true, then (if the lookup for the matching CVE that has master equals true, and does not have a value in matching ticket, then result the value of an index number, else leave blank), else leave blank), else leave blank), else leave blank).
However, I'm trying to make this more repeatable with a power query and I'm having trouble finding the right functions. From this existing dataset, I would use Power Query to create a new query/table and filter all of the rows that do not have yes in the create ticket column, and add an index row. From there I'd like to add a new column specifically for this linking logic, and I can't seem to get the logic right. I know that I can use if then logic in those columns, but getting the data from another row based on matching values is what I am having trouble with.
The output I'm essentially looking for is:

CVE
Description
Team
Locations
Master
Create Ticket
Index
Linked Ticket

CVE-2021-12345
Vuln Description 1
Ops
1, 2, 3

Yes
1
Tic-1234

CVE-2021-12345
Vuln Description 1
Dev
4, 5, 6

Yes
2
Tic-1234

CVE-2021-12345
Vuln Description 1
InfoSec
7, 8, 9

Yes
3
Tic-1234

CVE-2021-67891
Vuln Description 2

True
Yes
4

CVE-2021-67891
Vuln Description 2
Dev
4, 5, 6

Yes
5
4

CVE-2021-23456
Vuln Description 3
InfoSec
7, 8, 9

Yes
6
Tic-4567

CVE-2021-23456
Vuln Description 3
Ops
1, 2, 3

Yes
7
Tic-4567

CVE-2021-78912
Vuln Description 4

True
Yes
8

CVE-2021-78912
Vuln Description 4
Dev
4, 5, 6

Yes
9
8

CVE-2021-78912
Vuln Description 4
Ops
4, 5, 6

Yes
10
8

CVE-2021-78912
Vuln Description 4
InfoSec
4, 5, 6

Yes
11
8

Any assistance is appreciated.

A: It is basically just filtering and merging
Filter Master = True, merge that against the original table and expand matching ticket
Filter for create ticket = yes
Add index
Filter Master = True, merge that against the data before this step and expand index
do an if/then statement to determine null, ticket or index
let Source = Excel.CurrentWorkbook(){[Name="Table2"]}[Content],
#"Merged Queries" = Table.NestedJoin(Source,{"CVE"},Table.SelectRows(Source, each ([Master] = true)),{"CVE"},"Table2",JoinKind.LeftOuter),
#"Expanded Table2" = Table.ExpandTableColumn(#"Merged Queries", "Table2", {"Matching Ticket"}, {"zLinked Ticket"}),
#"Filtered Rows" = Table.SelectRows(#"Expanded Table2", each ([Create Ticket] = "Yes")),
#"Added Index" = Table.AddIndexColumn(#"Filtered Rows", "Index", 1, 1),
#"Merged Queries1" = Table.NestedJoin(#"Added Index",{"CVE"},Table.SelectRows(#"Added Index", each ([Master] = true)),{"CVE"},"Table2",JoinKind.LeftOuter),
#"Expanded Table1" = Table.ExpandTableColumn(#"Merged Queries1", "Table2", {"Index"}, {"Index.1"}),
#"Added Custom" = Table.AddColumn(#"Expanded Table1", "Custom", each if [Master]=null and [zLinked Ticket]=null then [Index.1] else if [Master]=null then [zLinked Ticket] else null),
#"Removed Columns" = Table.RemoveColumns(#"Added Custom",{"zLinked Ticket", "Index.1"})
in #"Removed Columns"


text:
Q: Bad Character code (256)/ \select@language{greek} I was trying to install minted package in TeXLive. I installed it and then run sudo tlmgr update --all. It was running slow so I stopped it using Ctrl+Z in an ubuntu terminal and then I run sudo tlmgr update --list. After that I installed texlive-latex-extra and python-pygments. Later on I run sudo tlmgr update --all again and let it finish.
After that I am trying to run a simple code using listings and greek but I get an error

Bad Character code (256)

A MWE that illustrated the problem is the following
\documentclass{book}

\usepackage[english,greek]{babel}
\usepackage[iso-8859-7]{inputenc}
% %\usepackage[utf8]{inputenc}
\usepackage{kerkis}
\usepackage{pifont}
% %
\newcommand{\sw}{\selectlanguage{english}}
\newcommand{\sq}{\selectlanguage{greek}}
\newcommand{\eng}[1]{\latintext#1\greektext}
\newcommand{\gre}[1]{\greektext#1\latintext}

\usepackage{xcolor}
\usepackage{listings}
\usepackage{textcomp}

\definecolor{listinggray}{gray}{0.9}
\definecolor{lbcolor}{rgb}{0.9,0.9,0.9}

\lstdefinestyle{JavaStyle}{
        backgroundcolor=\color{lbcolor},
    tabsize=4,
%   rulecolor=,
    language=Java,      % choose the language of the code
        basicstyle=\scriptsize,     % the size of the fonts that are used for the code
        upquote=true,
        aboveskip={1.5\baselineskip},
        columns=fixed,
        showstringspaces=false,
        extendedchars=false,
        breaklines=true,
        prebreak = \raisebox{0ex}[0ex][0ex]{\ensuremath{\hookleftarrow}},
        frame=single,
        numbers=left,
        showtabs=false,
        showspaces=false,
        showstringspaces=false,
        identifierstyle=\ttfamily,
        keywordstyle=\color[rgb]{0,0,1},
        %commentstyle=\color[rgb]{0.026,0.112,0.095},
        commentstyle=\itshape\color{green!40!black},
        stringstyle=\itshape\color{red!90!black},
        numberstyle=\itshape\color{yellow!50!black}
}

\lstdefinestyle{CppStyle}{
        backgroundcolor=\color{lbcolor},
    tabsize=4,
%   rulecolor=,
    language=C++,       % choose the language of the code
        basicstyle=\scriptsize,     % the size of the fonts that are used for the code
        upquote=true,
        aboveskip={1.5\baselineskip},
        columns=fixed,
        showstringspaces=false,
        extendedchars=false,
        breaklines=true,
        prebreak = \raisebox{0ex}[0ex][0ex]{\ensuremath{\hookleftarrow}},
        frame=single,
        numbers=left,
        showtabs=false,
        showspaces=false,
        showstringspaces=false,
        identifierstyle=\ttfamily,
        keywordstyle=\color[rgb]{0,0,1},
        %commentstyle=\color[rgb]{0.026,0.112,0.095},
        commentstyle=\itshape\color{green!40!black},
        stringstyle=\itshape\color{red!90!black},
        numberstyle=\itshape\color{yellow!50!black}
}
\begin{document}
 This is a dummy text. kjhbki
\end{document}

The .aux file says
\relax
\select@language{greek}
\@writefile{toc}{\select@language{greek}}
\@writefile{lof}{\select@language{greek}}
\@writefile{lot}{\select@language{greek}}

while the .log file can be found here
Any idea why is this happening and how to fix this? Note that if I remove the listings preamble, delete all produced files and build the document, everything works fine.

A: (Too long for a comment). It is a babel bug. It relies on a temporary counter and fails when listings sets it to 256:
\documentclass{book}

\usepackage[english,greek]{babel}

\begin{document}
\makeatletter
\@tempcnta=256
\selectlanguage{greek}

\end{document}

Sent a bug report to the babel maintainer or the babel-greek maintainer.

A:
UPDATE
The problem has been fixed with babel-greek version 1.9e, released on 2015/11/27

Original answer
Here's a temporary fix, that should work if Greek is the last language loaded; it just restores the value of \@tempcnta to what it would be if listings is not loaded. However, this is a bug in babel-greek: no package should rely on any particular value of \@tempcnta; my impression is that some code has been added that is useless.
\documentclass{article}
\usepackage[greek]{babel}
\usepackage{listings}

\makeatletter
\AtBeginDocument{%
  \expandafter\def\expandafter\originalTeX\expandafter{%
    \expandafter\@tempcnta\number253\expandafter\relax\originalTeX}%
}
\makeatother

\begin{document}
a
\end{document}

The bad code is in line 376 of greek.ldf that says
376       \babel@savevariable{\lccode\@tempcnta}\lccode\@tempcnta=\@tempcnta

while it should be
376       \expandafter\babel@savevariable\expandafter{\expandafter\lccode\the\@tempcnta}\lccode\@tempcnta=\@tempcnta

so the correct instructions
\babel@savevariable{\lccode128}
\babel@savevariable{\lccode129}
...
\babel@savevariable{\lccode252}

are executed instead of doing several times the useless (and wrong)
\babel@savevariable{\lccode\@tempcnta}

Thus a better temporary fix would be
\documentclass{article}
\usepackage[greek]{babel}
\usepackage{listings}

\makeatletter
% Avoid the spurious error
\AtBeginDocument{%
  \expandafter\def\expandafter\originalTeX\expandafter{%
    \expandafter\@tempcnta\number253\expandafter\relax\originalTeX}%
}
% apply the fix
\addto\extrasgreek{%
  \@tempcnta=128
  \@whilenum\@tempcnta<253\do{%
    \expandafter\babel@savevariable\expandafter{\expandafter\lccode\the\@tempcnta}%
    \lccode\@tempcnta=\@tempcnta
    \advance\@tempcnta\@ne
  }%
}
\makeatother
\begin{document}
a
b
\end{document}


text:
Q: Find the ratio of the lengths of the bisectors of internal angles of $B$ and $C$ The ratios of the lengths of the sides $BC$ and $AC$ of a triangle $ABC$ to the radius of the circumscribed circle are equal to $2$ and $\frac{3}{2}$ respectively.Find the ratio of the lengths of the bisectors of internal angles of $B$ and $C$.

We are given $\frac{BC}{R}=\frac{a}{R}=2$ and $\frac{AC}{R}=\frac{b}{R}=\frac{3}{2}$,where $R$ is the circumradius of the triangle $ABC$.
$a=2R,b=\frac{3}{2}R$
I know that $m_b$=length of angle bisector of angle $B=\frac{2\sqrt{acs(s-b)}}{a+c}$ and  $m_c$=length of angle bisector of angle $C=\frac{2\sqrt{abs(s-c)}}{a+b}$ but i need the third side in order to use these formulae,which i do not know.What should i do?

A: 1) prove that $A = \frac{\pi}{2}$:
Using consequence of $\sin$-theorem :
$$b = 2R\sin{A}$$
Now you could finish by yourself.

A: Use known formula of the bisector length
$$ m_c= \frac{2 a b \cos (A/2)}{a+b}  $$
and triangle half angle  identity
$$ \cos (C/2) =\sqrt{ \frac{s(s-c)}{ab} } $$
to get bisector length in your formula. You can use the Sine Rule and cycle the sides with symmetry.


text:
Q: Mongoose: Sorting what's the best way to sort the following documents in a collection:
{"topic":"11.Topic","text":"a.Text"}
{"topic":"2.Topic","text":"a.Text"}
{"topic":"1.Topic","text":"a.Text"}

I am using the following
find.(topic:req.body.topic).(sort({topic:1}))

but is not working (because the fields are strings and not numbers so I get):
{"topic":"1.Topic","text":"a.Text"},
{"topic":"11.Topic","text":"a.Text"},
{"topic":"2.Topic","text":"a.Text"}

but i'd like to get:
{"topic":"1.Topic","text":"a.Text"},
{"topic":"2.Topic","text":"a.Text"},
{"topic":"11.Topic","text":"a.Text"}

I read another post here that this will require complex sorting which mongoose doesn't have. So perhaps there is no real solution with this architecture?
Your help is greatly appreciated

A: i will suggest you make your topic filed as type : Number, and create another field topic_text.
Your Schema would look like:
var documentSchema = new mongoose.Schema({

    topic : Number,
    topic_text : String,
    text : String

});

Normal document would look something like this:
{document1:[{"topic":11,"topic_text" : "Topic" ,"text":"a.Text"},
        {"topic":2,"topic_text" : "Topic","text":"a.Text"},
        {"topic":1,"topic_text" : "Topic","text":"a.Text"}]}

Thus, you will be able to use .sort({topic : 1}) ,and get the result you want.
while using topic value, append topic_text to it.
find(topic:req.body.topic).sort({topic:1}).exec(function(err,result)
{
    var topic = result[0].topic + result[0].topic_text;//use index i to extract the value from result array.
})

A: If you do not want (or maybe do not even can) change the shape of your documents to include a numeric field for the topic number then you can achieve your desired sorting with the aggregation framework.
The following pipeline essentially splits the topic strings like '11.Topic' by the dot '.' and then prefixes the first part of the resulting array with a fixed number of leading zeros so that sorting by those strings will result in 'emulated' numeric sorting.
Note however that this pipeline uses $split and $strLenBytes operators which are pretty new so you may have to update your mongoDB instance - I used version 3.3.10.
db.getCollection('yourCollection').aggregate([
    {
        $project: {
            topic: 1,
            text: 1,
            tmp: {
                $let: {
                    vars: {
                        numStr: { $arrayElemAt: [{ $split: ["$topic", "."] }, 0] }
                    },
                    in: {
                        topicNumStr: "$$numStr",
                        topicNumStrLen:  { $strLenBytes: "$$numStr" }
                    }
                }
            }
        }
    },
    {
        $project: {
            topic: 1,
            text: 1,
            topicNumber: { $substr: [{ $concat: ["_0000", "$tmp.topicNumStr"] }, "$tmp.topicNumStrLen", 5] },
        }
    },
    {
        $sort: { topicNumber: 1 }
    },
    {
        $project: {
            topic: 1,
            text: 1
        }
    }
 ])


text:
Q: iPhone Core Data - Import additional content I'm in the position of looking at over the air distribution of additional content for our Core Data centric app. We need to find a good way to encapsulate new additional content bundles for import into the app.
I'm considering the following:
Option 1> Creating .sql files with insert statements to update the underlying SQLite layer directly (we get these as a by product of creating our content anyway).
Option 2> Distribution the new content in full .sqlite files, with which to create temporary managed object contexts and copy the data into the main context via the core layer. On the outset this seems like an expensive option compared the "as lean as it can be" option 1.
Can anyone suggest any other options or recommend the best approach from experience with this?

A: You could ship the modules as pre-processed SQLite persistent stores. These modules could then be attached to your app's store coordinator at startup. Kind of like loading plugins.
If the content really must live in the main store, you could import the content from one store to the other in the background, or something.
Maybe that's what you're suggesting by your option #2...
Another valid approach is to define a more generic external data format, eg something in JSON, XML, CSV, even vanilla SQLite, ship your data modules in the format, and import from there into your app's persistent store.
Your option #1 is risky, as it depends knowing the internal schema of the CD SQLite store, which Apple reserves the right to change at their discretion without telling you. I wouldn't ship on this option.
I'd go with either importing JSON or shipping pre-baked SQLite persistent stores.

A: Option1 is very dangerous because the Core Data SQLite schema is undocumented and subject to change without warning (assuming you can accurately reverse engineer it in the first place.)
Option 2 is your best option. It might seem expensive but remember that Core Data is first and foremost an object graph management API and only secondly a persistence API. Object graphs have not only data but also relationships and behaviors. The only reliable way to add objects to an object graph is to do so while the graph is "alive" i.e. by instantiating live objects and inserting them into the live (active) graph.
Writer/programmer Marcus Zarra has written about this issue several times and explains how to use configurations and even "plugin" data models and stores to import and export graphs from Core Data.


text:
Q: Remove Ip From Ip and domain restriction through powershell on iis How to remove ip and domain restrictions with powershell? I tried many references solution but i still cannot solve its. please help me,
References 1
Remove Ip From Ip and domain restriction through powershell
references 2
https://www.titanwolf.org/Network/q/e32d7a33-0bf8-44c4-a162-dda21736d9d2/y

A: I think you may need to check the existing webconfig file to confirm the result of the modification.
File name: ApplicationHost.config
Location (IIS7 or higher version): %WinDir%\System32\Inetsrv\Config
For the command below, I changed the location from your original which will not make any difference.
Set-WebConfigurationProperty /system.webserver/security/ipsecurity -Name allowUnlisted -Value "true" -Location "IIS:\Sites\default web site"

According to the given image, you set the value to "true" for the property name "allowUnlisted" in the location "system.webserver/security/ipsecurity", which could be found there. The section would be
<system.webserver>
 <security>
  <ipSecurity allowUnlisted="true">
  </ipSecurity>
 </security>
</system.webserver>

Then, if you want to change the last setting, you just need to modify the value to "false".
Command:
Set-WebConfigurationProperty /system.webserver/security/ipsecurity -Name allowUnlisted -Value "false" -Location "IIS:\Sites\default web site"

The result would be:
<system.webserver>
     <security>
      <ipSecurity allowUnlisted="false">
      </ipSecurity>
     </security>
    </system.webserver>

For further usage of the command, you could read below example.
Command: Add allowed ip
add-WebConfiguration /system.webserver/security/ipsecurity -Location "iis:\default web site" -Value @{ipaddress="192.168.1.1";allowed="true"} -PSPath IIS:\

Result:
   <system.webserver>
     <security>
      <ipSecurity allowUnlisted="false">
        <add ipAddress="192.168.1.1" allowed="true" />
      </ipSecurity>
     </security>
    </system.webserver>

Command: Remove the allowed ip
Remove-WebConfigurationProperty /system.webServer/security/ipSecurity -location "iis:\default web site" -Name "." -AtElement @{ipAddress="192.168.1.1";allowed="true"}  -PSPath IIS:\

Result:
   <system.webserver>
     <security>
      <ipSecurity allowUnlisted="false">
      </ipSecurity>
     </security>
    </system.webserver>

Another way to remove it: Set allow from "true" to "false"
Command:
Set-WebConfigurationProperty /system.webserver/security/ipsecurity -Name "." -AtElement @{ipAddress="192.168.1.1";allowed="true"} -Value @{ipAddress="192.168.1.1";allowed="false"} -Location "IIS:\Sites\default web site"

Result:
<system.webserver>
 <security>
  <ipSecurity allowUnlisted="false">
    <add ipAddress="192.168.1.1" allowed="false" />
  </ipSecurity>
 </security>
</system.webserver>

Hope helps.


text:
Q: Gnash installation flash player Gnash is a nice flash player which is outdated and unsupported this year, the package and dependencies still can be downloaded from https://packages.ubuntu.com/bionic/gnash, can I install them to Focal Fossa, like Amule, can it?

A: You try to manually install them, but there are no guarantees they'll still work, and if you get dependency errors (because they require library versions that no longer exist) that's the end of it.
If you can get your hands on the source packages and know a few things about compiling you might get a little longer life out of it, but there's almost certainly a reason it's no longer supported.


text:
Q: How should I go about creating a profile page or information text field on a rails app? I had just recently completed a mockup version of Twitter and would like to implement a profile section where each user can describe themselves in text.  This section should appear on their profile page and the user index page as well so that a user searching or browsing user accounts would be able to narrow down their search through reading this profile page, thus allowing one to know who to follow based on interested.
How can I have rails save and store this information?
Here I have an example of a text box and how it would look if it were in place.  It doesn't necessarily need to follow this exact format, anything will do really.

Above is the users index page where I would like the information to be display on the right hand side of each user.  It would be nice if this information type up would be searchable so that a user would know who to follow. Thanks in advance!

A: I think it really depends on how you want to handle the "profile information" that you want to add.  Like the guy above me, those tutorials are important and very helpful.
You can create a separate "info" model that contains a single string and belongs to a single user, and implement info like that... or you could simply add a string attribute to your User model, and have them update that attribute whenever the profile info gets changed.
Are you looking for an idea on "how" to do it, or actual code


text:
Q: How to approach preprocessing large number features for machine learning? I used to apply supervised machine learning for maximum few dozen "normal", natural features like human interpretable ones in Boston House Prices table. I usually try to understand each of them, think about how to preprocess them by sometimes binning continuous ones, re-categorizing and encoding categorical ones etc.
Now, however, I confront with very numerous (several hundred) features where this intimate one by one overview is clearly impossible. The easiest solution would be to accept the features as they are and handle them blindly en masse but in this way some evident optimization methods or even more importantly, some decisive corrections cannot be pointed out. For instance, R and/or Python Pandas are sometimes incorrectly identify numerical/categorical columns which is quite misleading if not spotted (missing data imputation must be applied very differently, and standardization is senseless in case of categorical ones, just mentioning two problems).
So my question is what is an appropriate way to handle and clear/correct these numerous features when one by one examination is out of question? Am I limited to use tree-based model types which are insensitive to NAs and scaling so no need for preprocessing?
(Just for being clear: this question is not about reducing the dimensionality.)

A: I would argue that you most certainly are not limited to just tree-based models.
You could always try and drop samples with missing feature values, although of course this could lead to too many samples being lost.
You already mention imputation and correctly assess that different data-types would need different strategies. You could write a pre-processing script that for each feature checks the data type and then applies your chosen strategy. This would be pretty similar to your one-by-one analysis conceptually, but if your script is written correctly you can analyze a dataset of a few thousand features in size with ease.
Hope this helps!


text:
Q: City center or city's center?
I own an apartment just outside the city center/city's center.

Can I say both? Which one would native speakers usually go with?

A: city center is more idiomatic, though the other option isn't wrong (at least not from a grammar perspective). One way to see this is through the Google Ngram Viewer, which shows city center is used about 10 times as often as city's center:

A: Like most people, I would nearly always say "city centre" (and similarly "town centre").
If someone said "city's centre", I would interpret that slightly differently.  I might regard that as a reference to the geographical centre of the city, whereas the area generally known as the "city centre" might not be precisely in the middle.
If you drill down to the specific uses of "city's centre" in Google NGrams, there are various shades of meaning being conveyed that are often a bit different from what we normally mean when we say "city centre":

The city takes up nearly 3,500 square miles of land, with 200 of these being occupied by the Wellspring, the deep, effervescent lake in the city's center.

The term "city centre" suggests a busy urban area.  It might sound odd to refer to a "lake in the city centre".

In light of these spatial changes, the traditional geographical concept of a city's center and periphery is now of only limited use

You could probably also say "a city centre and a city periphery", but "city's centre and periphery" works better.

At the city's center next to State House and the American Embassy is the Cotton Tree

The term "centre" is being used to refer to a specific point rather than a general area.
There are some sentences where "city centre" and "city's centre" work equally well, but others where they don't.


text:
Q: Swift slider with items I am trying to create list with items (similar to slider) that I can swipe left / right. I want to do it in swift.
It should look similar to this:

Can someone advice how should I start or is there some component that allows this?

A: Please take a look at UICollectionView, you should be able to configure the scroll mode to 'horizontal' and adjust the cell size to what you have pictured (height should equal your screen height, and width be slightly smaller than the screen width).
You will need to implement the UICollectionViewDataSource on your view controller to provide the content, and the UICollectionViewDelegate to respond to the user scrolling to a new item, so you can animate or adjust the size of the image.


text:
Q: Git avoid pushing new branches to remote through local config I am familiar with .git/config file in the repository (basic understanding) and I would like with some changes in this configuration file to avoid that a new branch in the remote is created. Is this possible?
I have seen a few nice approaches from the server side, but since we are using Bitbucket I believe it's not possible to add a bash hook to the repository, which would easily solve the problem. I have also seen some of the plugins and none seem to do it (or could not find it).
I've Spent some time reading and "trying" to understand better the config file format which has many options, hoping that one option will allow me to do this, but no success so far.
Bottom line:

*

*Most important is that no new branch except the existing ones are created in the remote

*If this parameter also avoids the creation of a new branch locally even better.

*I have no problem with local permissions. I understand that a user can edit the config file himself and just create the remote brannch, but this is not a security issue, it´s just a workflow improvement for our release process.

Any suggestion is highly appreciated.


text:
Q: Drilling Down the Data ColdFusion I am having trouble with drilling down some data, this is the table structure
Products Table
uid_product (unique id)
txt_prod_name (product name)
Table Name: tbl_products
Product Features
uid_feature(unique id)
txt_feature_name(feature name)Table Name: tbl_features
Assigned Product Features
uid_prodf (unique id)
uid_prodf_prodid (foreign key to uid_product)
uid_prodf_featid(foreign key to the uid_features)
Table Name: tbl_prod_features
One product can have many features hence the use of the tbl_prod_features table.
I have created the following query, to obtain the results;
<cfquery name="getFeatureProducts" datasource="#application.dsn#">
SELECT uid_product, txt_prod_name
FROM dbo.tbl_products
WHERE uid_product IN (SELECT (dbo.tbl_product_features.uid_prodf_prodid)
FROM dbo.tbl_product_features
WHERE  uid_prodf_featid IN (<cfqueryparam cfsqltype="CF_SQL_INTEGER" value="#arguments.uid_features#" list="yes">))
ORDER BY dbo.tbl_products.txt_prod_name
</cfquery>

This works great for getting all products associated to the features selected by the end user. However what I need to achieve is the following,
If a user selects;
Feature A = 5 products displayed (3 out of 5 of these products contains Feature B)
If the user then selects;
Feature B = 3 Products
Currently with the query using the in operator it will still retrieve 5 products.
My first thoughts was to create a dynamic where statement adding the AND operator, however uid_prodf_featid = 5 AND uid_prodf_featid = 6 will always produce 0 results.
My second idea was to build an array of product id's from the first drill down i.e. get the id's of the first 5 products, and pass them in to the query and then drill down the features, this works and the correct results are obtained.
However the user has the ability to remove features (and in any order), so I would somehow need to keep track of the products id's as and when they were added and removed.
I am sure I am overcomplicating this, but any help would be appreciated.

A: Use a HAVING clause to count the number of matching features and return only products that have all of the requested features.
For example, if arguments.uid_features always contains unique feature id's, you could do something like this:
SELECT p.uid_product, p.txt_prod_name
FROM   tbl_products p  INNER JOIN tbl_product_features f
           ON p.uid_product = f.uid_prodf_prodid
WHERE  f.uid_prodf_featid IN ( <cfqueryparam cfsqltype="CF_SQL_INTEGER" value="#arguments.uid_features#" list="true"> )
GROUP BY p.uid_product, p.txt_prod_name
HAVING COUNT(f.uid_prodf_featid) = <cfqueryparam cfsqltype="CF_SQL_INTEGER" value="#ListLen(arguments.uid_features)#">
ORDER BY p.txt_prod_name

A: I think this might work better. First, it gets rid of the sub-selects. Second, it filters on the selected feature IDs and then groups the resulting Products by related Feature.
SELECT
    a.uid_feature,
    a.txt_feature_name,
    c.uid_product,
    c.txt_prod_name
FROM
    tbl_features a
INNER JOIN
    tbl_prod_features b
    ON
        b.uid_prodf_featid = a.uid_feature
        <cfif listLen( arguments.uid_features ) NEQ 0>
            AND
            a.uid_feature IN (<cfqueryparam cfsqltype="CF_SQL_INTEGER" value="#arguments.uid_features#" list="yes">)
        </cfif>
INNER JOIN
    tbl_products c ON c.uid_product = b.uid_prodf_prodid
GROUP BY
    a.uid_feature
ORDER BY
    c.txt_prod_name


text:
Q: Fourier complex exponential series expansion I have a piecewise function that I need to calculate the complex Fourier series for.
It is for the function $f(x)$ that is 1 on $[-\pi/2,\pi/2]$ and zero elsewhere on $[-\pi,\pi]$
I calculated $c_0$ to be 0 and $c_n=\frac{-1}{2\pi in} *e^{inx}\bigg\rvert_{-\pi/2}^{\pi/2}$
I'm not sure where to go from here, the question also requires me to define the series as g(x) and evaluate $g(3\pi/2)$


text:
Q: C# syntax issue - trying to add value to data row I am trying to code a sort routine against a dynamicaly populated gridview names Users. I have a syntax error in the C# code where I am trying to populate a column in a row of a the datatable.
    for (int j = 0; j <= Users.Rows.Count - 1; j++)
    {
        DataRow dr = default(DataRow);
        GridViewRow row = Users.Rows[j];
        dr = dt.NewRow();
        DataView dvUsers = new DataView(dt);

        for (int i = 0; i <= row.Cells.Count - 1; i++)
        {
            dr.Item(i) = row.Cells[i].Text;
        }

        dt.Rows.Add(dr);
    }

Error message:

System.Data.DataRow does not contain a definition for "Item"

Can someone help with the correct syntax to assign this value to the datarow?
I am new to C#
thank you,

A: You just need to change the line
dr.Item(i) = row.Cells[i].Text;

to
dr[i] = row.Cells[i].Text;

Assuming the columns in the data table match the ordering of the cells in the table.
() are used to call methods, while [] indicates an indexer.  This is the reason for the compile error.  There isn't a method Item on DataRow, it is an indexer.
EDIT
Changed dr.Item[i] to dr[i].  As explained in the comments, Item is the default indexer, so you don't specify the property, the index provided to the object itself will be applied to the Item indexer.

A: Try this:
dr[i] = row.Cells[i].Text;


text:
Q: HBase load balancing by splitting regions I am having an HBase cluster of 5-nodes and mostly having input request of fetching sequential data.
For optimizing the storage, I ran manual region-splitting on highly loaded regions but it doesn't optimise much as it splits the region but mostly on same region-server.
How can I control region-splitting in this way
r-1(k1 to k2) on server s1,
r-2(k2 to k3) on server s2,
r-3(k3 to k4) on server s3,
r-4(k4 to k5) on server s4,
r-5(k5 to k6) on server s5,
r-6(k6 to k7) on server s1,

I.e, after splitting, no consecutive regions goes to same server to control the load on same server.

A: I am assuming by server you mean RegionServer. The regions are allotted regionservers randomly, so if your cluster is big enough, this situation should not occur (or should occur rarely). The idea is that you shouldn't need to bother about this. Also, understand that the regionserver is only a gateway for the data. It relies on HDFS to fetch the actual data, and where the data is coming from, is decided by HDFS.
Besides, even if consecutive regions end up being served by the same RS, you should be able to use multithreading to get the data faster. HBase already internally runs a separate thread for each region AFAIK. Usually, it doesn't lead to too much load. Did you see that there is actually excessive load due to this? Did you do any profiling to see what is causing the load?
So, there should really be no need to do this, but in special cases, you can use the HBaseAdmin.move method to achieve this. You can possibly write some code to go through all the regions of a table using HTable.getRegionLocations(), sort the regions as per the start keys and manually (using HBaseAdmin.move()) ensure that all consecutive regions are on separate regionservers. But I strongly doubt that this is actually a problem, and I would advise you to confirm this before going for this approach.


text:
Q: Couchapp with partial reader access It would be very elegant to run a full couchapp on Cloudant, but is seems there is no way of creating a public login page while the rest of the database requires authentication.
Can I serve public pages without opening the entire database?
Thanks,
Mikkel

A: The solution for CouchDB (see question How does a user login to a couchapp that has a reader role defined?) should also work in Cloudant.


text:
Q: jQuery PHP: Check if username already exist I'm trying to check the existence of an username already registered on my application using jQuery+Ajax+POST.
HTML

    Username

        <input type="text" id="username" class="form-control" name="username" placeholder="Username">

jQuery
$('#username').focusout(function() {
    var username = $('#username').val();
    checkUserExist(username);
})
function checkUserExist($uname) {
    $.post( "../core/lib/checkUserExist.php", function( data ) {
    if(data.html == 'true') {
       $('#userCheck').slideDown("slow");
       $('#userCheckLabel').text("This user already exist!")
    }
});

PHP
<?php
require_once('../../core/class.user.php');
$user = new USER();
$uname = $_POST['username'];

$stmt = $user->runQuery("SELECT user_nameFROM users WHERE user_name=:uname ");
$stmt->execute(array(':uname'=>$uname));
$row=$stmt->fetch(PDO::FETCH_ASSOC);

if($row['user_name']==$uname) {
    print 'true';
} else {
    print 'false';
}
?>

I Don't include class.user.php cause It's only handling the PDO Connection, If I remove the if(data.html == 'true') the connection work as expected and the message come out.
Behavior
The code work if I remove the if(data.html == 'true'). but with this it doesn't do anything, no errors in console. So I think the error is in the way I handle the PHP part.
Any suggestion?

A: Since you are returning string not HTML, so you have to do like below:-
$.post( "../core/lib/checkUserExist.php",{username: uname }, function( data ) {
     console.log(data);// check this and let me know the output
     if(data == 'true') {  // or try if(data)
       $('#userCheck').slideDown("slow");
       $('#userCheckLabel').text("This user already exist!")
    }
});


text:
Q: URL redirect from event handlers in React v4 I am new to React, and I am having an issue redirecting to a new page using JavaScript event handlers. I don't know what I am not getting right.
App.js
import React, { Component } from 'react';
import {Switch, Route} from 'react-router-dom';

import Nav, {Jumbotron} from '../partials/headobjs';
import Footer from '../partials/footer';
import Users from '../components/user';
import UserObj from '../components/userobj';
import Err404 from '../components/err404';

//import css files..
import '../css/styles.css';

class App extends Component {
  render() {
    return (

          <Jumbotron/>

          <Switch>
            <Route exact path='/' component={Users}/>
            <Route path='/user' component={UserObj}/>
            <Route component={Err404} />
          </Switch>

    );
  }
}

export default App;

Users.js
import React, { Component } from 'react';
import {Redirect} from 'react-router-dom';

class Users extends Component {

  constructor(){
    super();
    this.state = {
      name:aminu
    };
  }

  gotoURL(usr){
    let url = `/user/${usr}`;
    //console.log(url);
    return <Redirect to={url}/>
  }

  render() {
     return (

             <button onClick={this.gotoURL.bind(this, this.state.name)}>
               Go to {this.state.name} page
            </button>

    );
  }
}

export default Users;

I want the function gotoURL to redirect to a new route, but I'm not sure what I am doing wrong, I have tried using the browserHistory, and now I'm trying out the <Redirect/> class but yet to no avail.

A: Redirect component needs to be rendered and not returned to the onClick handler which is why it is not working. You can make use of history.push instead
gotoURL(usr){
    let url = `/user/${usr}`;
    //console.log(url);
    this.props.history.push(url);
  }

A: Instead of redirect from function, use render method and state to workout with redirect problem
class Users extends Component {

    constructor(){
        super();
        this.state = {
            name:'aminu',
            toUser: false
        };
    }

    gotoURL(usr){
        let url = `/user/${usr}`;
        //console.log(url);
        this.setState({toUser:true, goto: url})
    }

    render() {

        if (this.state.toUser === true) {
            return <Redirect to={this.state.goto}/>
        }

        return (

                <button onClick={this.gotoURL.bind(this, this.state.name)}>
                    Go to {this.state.name} page
                </button>

        );
    }
}

A: You can use Link component from react-v4 to change your route.
import { Link } from 'react-router-dom';

    <Link to={`/user/${usr}`}
        <button>
          Go to {this.state.name} page
        </button>
    </Link>


text:
Q: How to access multiple dictionaries values of the same keys from a list? I have this list:
f = ['a','b','c',['me','you','him/her'],
     {'apples':430,'peaches':239,'bananas':839},
     {'apples':123,'peaches':345,'bananas':536}]

I know i can access each item in this list if i use slices. For example to access the first dictionary i would do a
print(f[4]) #---> {'apples': 430, 'peaches': 239, 'bananas': 839}

To access a value of a key in the dictionary i do it like this:
print(f[4]['apples']) #---> 430

My question is how can i access the values of both apples keys (430,123) in those 2 separate dictionaries, to be displayed one after another automatically?
Can someone please advise, on how to fix this?
Thanks.

A: If I understand correctly, you want to retrieve the values of multiple dictionaries in the list. This can be done by using a list comprehension to iterate through the list and retrieve the values specified by the key, given that the list element is a dictionary.
Below is a lambda function that works on your list and returns the values stored at 'apples' as a list.
finder = lambda l, string: [x[string] for x in l if type(x) == dict]

print(finder(f, 'apples')) # [430, 123]
print(finder(f, 'peaches')) # [239, 345]

A: You can use a list comprehension to do this.
Note that without the if statement, you will get a KeyError if the dict doesn't have the "apples" key and TypeError if the item in the  list is not a dict
>>> f = ['a','b','c',['me','you','him/her'],
...      {'apples':430,'peaches':239,'bananas':839},
...      {'apples':123,'peaches':345,'bananas':536}]
>>> [item['apples'] for item in f if isinstance(item, dict) and 'apples' in item]
[430, 123]


text:
Q: Remove item animation from Recycler View with scroll I have some problem with animation on RecyclerView
I have chat list with lot of messages. Each message is removing with delay (20s) and animation fadeout(0.3s). All work fine but it look strange sometime. Because if message is removing then all item below going up during first item is removing (fadeout). It looks like cumulative views on first position.
I am thinking about start animation before remove item. But it is not good idea. Also I thought about combining removing animation with scrolling the removing view.

A: One thing you can do is animate/collapse the height of the item view from its full height to 0, then remove the item from the adapter and refresh after that animation is complete.


text:
Q: DateTime.toString not accounting for PM correctly from "dd/MM/yyyy h:mm:ss tt" to "yyyy-MM-ddTHH:mm:ss.fffZ" I am hitting a bit of a wall with this one.
I am currently trying to capture a DateTime in the format of yyyy-MM-ddTHH:mm:ss.fffZ as a string for an API call. However my original timestamp is currently formatted as a string like dd/MM/yyyy h:mm:ss tt.
My code is as follows:
string startingTimestamp = "04/28/2020 11:25:43 PM"

DateTime dt = DateTime.ParseExact(startingTimestamp, "MM/dd/yyyy hh:mm:ss tt", CultureInfo.InvariantCulture);
string finalTimestamp = dt.ToString("yyyy-MM-ddThh:mm:ss.fffZ");

What I would have expected to come out would be: 2020-04-28T23:25:43.511Z
But instead, I get: 2020-04-28T11:25:43.000Z.
In my debugging, I can see that the DateTime accounts for the PM, but it still outputs as 11:25 and not 23:25.
Am I missing some extra step to hard convert the DateTime to be 24H instead of 12H or is the toString method not the appropriate choice?

A: Try HH for 24 hour. Use hh for 12 hour.


text:
Q: Finding the dimension of set of Complex numbers over the set of Real numbers I am new to this area. I have idea about complex and real numbers. Any help would be appreciated to find the dimension.

A: Firstly, you should specify what is your definition of dimension of sets.
Naturally, dimension stands for dimension of vector spaces i.e. the cardinality of a basis. One thing that is relevant to your question is that if you consider set of real numbers and set of complex numbers  as vector spaces (with some operations, not merely sets!) then it can be proven easily that the vector space of complex numbers has dimension 2 over the vector space of real numbers. [Hint : Consider the polynomial $x^2 + 1 = 0 $  over the set of real numbers and then look at its roots. ]


text:
Q: Maven Tests not Running in sequential Order I'm using a TestNG framework for my automation project.
While running from command line i'm giving the following command.
mvn clean test -Dtest=Login,OpenImage,Logout
By running the above command it the order of execution was Login->Logout->OpenImage (may be in alphabetical order).
Can anyone help me how to run tests in the given order.
Note: As per my requirement I need to run my tests in the above way it self.
If it was through testNG.xml file then i guess preserve-order will work.
can anyone help me on this.....!!!!!
Thank you in advance..

A: First why do you need to run tests in a particula order because units should never rely on a particular order. But your question looks like more an integration tests.
If you need to run in order defined dependencies between the tests
@Test
public void serverStartedOk() {}

@Test(dependsOnMethods = { "serverStartedOk" })
public void method1() {}

The above defines the order that serverStartedOk will run before method1..based on the dependsOnMethods...


text:
Q: Getting Messege Twice Using IMvxMessenger I am working on Xamrin Android Application and I am using MvvmCross.In my application I have used IMvxMessenger.But I am getting messsge twice when I change the view and comeback to same view.And then It is Crashed.
What is the solution ?
Here is my code :
In ViewModel I have this code :
var messanger = Mvx.Resolve<IMvxMessenger>();
var message = new MyMessage(this,"Product has been added",cartListCount);
messanger.Publish(message);

And On View I have this code:
 private MvxSubscriptionToken _token;

 public override View OnCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
         {
        var view = base.OnCreateView(inflater, container, savedInstanceState);

         messenger = Mvx.Resolve<IMvxMessenger>();
        _token = messenger.SubscribeOnMainThread<MyMessage>(OnInputIsNeeded,MvxReference.Strong);

         return view;
         }

    private void OnInputIsNeeded(MyMessage _Message)
    {
        Toast.MakeText (this.Activity,_Message.Message, ToastLength.Short).Show();
        messenger.Unsubscribe<MyMessage> (_token);
    }

A: Views (whether Activities or Fragments) are created and destroyed all the time. Since you are subscribing in OnCreateView(), you should unsubscribe in OnDestroyView().
What's likely happening is that OnCreateView() is being called multiple times and causing multiple subscriptions to be added. MvxMessenger is broadcasting the message to all subscribers. If a View is destroyed, but hasn't unsubscribed, it's likely to crash since the callback no longer exists.


text:
Q: Check which tag is most relevant with title There are two dbs:
+-----+----------------+
| id  |     tag        |
+----------------------+
|  1  |      Audi      |
|  2  |      BMW       |
|  3  |  Volkswagen    |
|  4  |  Mercedes Benz |
+----------------------+

and
+-----+-------------------------------+------+
| id  |           title               |  tag |
+-------------------------------------+ -----+
|  1  |      Audi is a great car      | NULL |
+-------------------------------------+------+

What I need to do:
1.Check which tag is most relevant with title.
2.Extract most relevant tag and insert into database near title.
What I did so far:
function compareStrings($s1, $s2) {
    //one is empty, so no result
    if (strlen($s1)==0 || strlen($s2)==0) {
        return 0;
    }

    //replace none alphanumeric charactors
    //i left - in case its used to combine words
    $s1clean = preg_replace("/[^A-Za-z0-9-]/", ' ', $s1);
    $s2clean = preg_replace("/[^A-Za-z0-9-]/", ' ', $s2);

    //remove double spaces
    while (strpos($s1clean, "  ")!==false) {
        $s1clean = str_replace("  ", " ", $s1clean);
    }
    while (strpos($s2clean, "  ")!==false) {
        $s2clean = str_replace("  ", " ", $s2clean);
    }

    //create arrays
    $ar1 = explode(" ",$s1clean);
    $ar2 = explode(" ",$s2clean);
    $l1 = count($ar1);
    $l2 = count($ar2);

    //flip the arrays if needed so ar1 is always largest.
    if ($l2>$l1) {
        $t = $ar2;
        $ar2 = $ar1;
        $ar1 = $t;
    }

    //flip array 2, to make the words the keys
    $ar2 = array_flip($ar2);

    $maxwords = max($l1, $l2);
    $matches = 0;

    //find matching words
    foreach($ar1 as $word) {
        if (array_key_exists($word, $ar2))
            $matches++;
    }

    return ($matches / $maxwords) * 100;
}

$all_values = '';

$sql_object = "SELECT * FROM tag";
$result_object = mysql_query($sql_object);
while($row_object = mysql_fetch_array($result_object))
{
    $tag = $row_object['tag'];

    $sql_subject = "SELECT * FROM title ORDER BY added";
    $result_subject = mysql_query($sql_subject);
    while($row_subject = mysql_fetch_array($result_subject))
    {
        $title = $row_subject['title'];

        $all_values .= "Title($title) and Tag($tag) relevancy:". compareStrings($tag, $title) . "%"."<br/>";
    }
}
echo $all_values;

Output:
Title(Audi is a great car) and Tag(Audi) relevancy:20%
Title(Audi is a great car) and Tag(BMW) relevancy:0%
Title(Audi is a great car) and Tag(Volkswagen) relevancy:0%
Title(Audi is a great car) and Tag(Mercedes Benz) relevancy:0%

The question is: how to extract most relevant tag from $all_values and insert into database, because here I am stuck. Or maybe there is a better solution. I would appreciate any help.


text: Q: Some voice memos not playing on phone or itunes I have a bunch of voice memos, all under ten minutes long.  I frequently have trouble syncing them to iTunes--at the moment one in particular won't play on my phone (although it's listed with the correct title and duration) and it's not syncing to the correct playlist.  It appears in iTunes under my phone, but won't play.  Generally, I change all the Voice Memos to the type "Music" and add an artist.  Yesterday it played fine, both on iTunes and on my phone.  I haven't made any changes since then so I have no idea what's different. Using an iPhone 6 and iTunes 12.6


text:
Q: Attach sources not working in ScalaIDE I have the following imports in a Play! controller:
import reactivemongo.play.json.collection.JSONCollection
import reactivemongo.play.json.commands.JSONAggregationFramework.{Match,       Unwind, Project, AggregationResult}

The first import(JSONCollection case class) is in the ........ivy2\cache\org.reactivemongo\reactivemongo-play-json_2.11\jars\reactivemongo-play-json_2.11-0.11.14.jar
The second one (object JSONAggregationFramework) is in the same library but extends AggregationFramework which is in the:
.........ivy2\cache\org.reactivemongo\reactivemongo_2.11\jars\reactivemongo_2.11-0.11.14.jar
Both libraries have the sources and JavaDocs attached.
But, when I CTRL-Click in Eclipse(Scala IDE) on their name I get a fastidious
**Source Not Found
The source attachment does not contain the source for the...
You can change the source attachment by clicking ...**

error.
I checked and the source JARS contain the aforementioned classes.
Is this a bug, or am I doing something wrong?
P.S.
I can just go in the left pane and click to open any class in the reactivemongo_2.11-0.11.14.jar library and I'll arrive to the same issue!
This does not happen for the classes in:
.......ivy2\cache\org.reactivemongo\play2-reactivemongo_2.11\jars\play2-reactivemongo_2.11-0.11.14.jar though,
where I am able to see the sources.
Many thanks in advance!

A: Please verify have you done like this or not. click on jar file and --> go to Source attachments--> click on Edit button and select the source path of the jar file.


text:
Q: Install Delphi XE5 Android emulator not recognized I'm new to Delphi XE 5 and currently building my first multi platform firemonkey application. I would like to run my program on a mobile device, for testing first I need the emulator.  I installed the emulator from the Embarcadero app wave store, build id = 5554
In my Delphi program manger window I see this emulator <5554>  is available as a target (ZIEl) but I can not activate this target. Furthermore I can not use this device during program development as a testing device.
How to get this emulator running for my program ?

As shown in the tutorial video I also did find the USB debugging option on the emulator

A: Please Check this link:
Creating an Android Emulator:
http://docwiki.embarcadero.com/RADStudio/XE5/en/Creating_an_Android_Emulator
Before you create an Android emulator, you need to install an Android system image that your emulators can use.


text:
Q: Django. Revert previous page I have an image_delete django-controller. I use it on several pages. I need that after deleting the image, the controller returns me to the previous page. but I get an error. what is the problem? How to fix it?
views.py
class ImageDelete(DeleteView):
    model = Picture
    template_name = 'adminapp/pet/pet_image_delete.html'
    @method_decorator(user_passes_test(lambda x: x.is_superuser))
    def dispatch(self, *args, **kwargs):
        return super().dispatch(*args, **kwargs)

    def get_success_url(self):
        return HttpResponseRedirect(request.META.get('HTTP_REFERER'))

urls.py
path('delete/image/<int:pk>/', adminapp.ImageDelete.as_view(model=Picture), name='image_delete')

Error

A: You'll want self.request:
def get_success_url(self):
    return HttpResponseRedirect(self.request.META.get('HTTP_REFERER'))


text:
Q: Making long data wide and collapsing rows I'm trying to turn a dataframe from long to wide format. Currently the df is set up like so:
dput(head(df,10))
structure(list(TECH_ID = c("14050154", "14050154", "13835650",
"13835650", "13469601", "13469601", "13782883", "13782883", "12342837",
"12342837"), MNSCU_QUES = c("What language did you learn to speak first?",
"Which language do you speak most often at home?", "What language did you learn to speak first?",
"Which language do you speak most often at home?", "What language did you learn to speak first?",
"Which language do you speak most often at home?", "What language did you learn to speak first?",
"Which language do you speak most often at home?", "What language did you learn to speak first?",
"Which language do you speak most often at home?"), MNSCU_RESP = c("English and another language",
"Another", "English only", "English", "English only", "English",
"English and another language", "English", "English only", "English"
)), row.names = c(NA, 10L), class = "data.frame")

I am trying to set up the dataframe so it reads like this:

I've been trying to use this code here:
df_wide <- dcast(df, TECH_ID+MNSCU_RESP~MNSCU_QUES)
But the resulting dataframe looks like this:
Code:
dput(head(df_wide,10))
structure(list(TECH_ID = c("00007179", "00007179", "00008201",
"00008201", "00020900", "00020900", "00021757", "00021757", "00031227",
"00031227"), MNSCU_RESP = c("English", "English only", "English",
"English only", "English", "English only", "English", "English only",
"English", "English only"), `What language did you learn to speak first?` = c(0L,
1L, 0L, 1L, 0L, 1L, 0L, 1L, 0L, 1L), `Which language do you speak most often at home?` = c(1L,
0L, 1L, 0L, 1L, 0L, 1L, 0L, 1L, 0L)), row.names = c(NA, 10L), class = "data.frame")

Visual:

A: library(reshape2)

df <- structure(list(TECH_ID = c("14050154", "14050154", "13835650",
                           "13835650", "13469601", "13469601", "13782883", "13782883", "12342837",
                           "12342837"), MNSCU_QUES = c("What language did you learn to speak first?",
                                                       "Which language do you speak most often at home?", "What language did you learn to speak first?",
                                                       "Which language do you speak most often at home?", "What language did you learn to speak first?",
                                                       "Which language do you speak most often at home?", "What language did you learn to speak first?",
                                                       "Which language do you speak most often at home?", "What language did you learn to speak first?",
                                                       "Which language do you speak most often at home?"), MNSCU_RESP = c("English and another language",
                                                                                "Another", "English only", "English", "English only", "English",
                                                                                "English and another language", "English", "English only", "English"
                                                       )), row.names = c(NA, 10L), class = "data.frame")

df_wide <- reshape2::dcast(df, TECH_ID~MNSCU_QUES, value.var = "MNSCU_RESP")

> df_wide
   TECH_ID What language did you learn to speak first? Which language do you speak most often at home?
1 12342837                                English only                                         English
2 13469601                                English only                                         English
3 13782883                English and another language                                         English
4 13835650                                English only                                         English
5 14050154                English and another language                                         Another