text:
Q: How to structure unitofwork / service layer / repository, so that they work with DI (Unity) and Moq for Unit Testing I have an MVC app (EF6, SQL Server CE 4), that I recently refactored to add a UnitOfWork class and a service layer (so that I could utilise a single DbContext per request, and conduct transactions successfully).
Previously, I was using Unity to inject the repositories into the controller. My unit tests (for the controllers) were simple to setup - I just mocked each repository, and passed those into the controller constructor.
After refactoring, I now use Unity to inject the Service Layer (to the controller) and UnitOfWork (into the Service Layer). The Service Layer now instantiates each repository, by passing the UnitOfWork.DbContext to the repository's constructor.
In my Unit Tests, I am attempting to mock the UnitOfWork, and the ServiceLayer (and pass the mocked UnitOfWork object into the ServiceLayer's constructor).  However, the tests fail, saying "TestFixtureSetup failed in ControllerTest".
I assume it's due to how I'm attempting to pass the UnitOfWork mock into the ServiceLayer mock, so would appreciate any guidance on how to do this correctly.
Relevant code snippets below.
UnitOfWork
public interface IUnitOfWork:IDisposable
{
    void Save();
    IDSMContext Context { get; }
}

public class UnitOfWork : IUnitOfWork, IDisposable
{
    private IDSMContext _context;

    public UnitOfWork()
    {
       _context = new IDSMContext();
    }

    public IDSMContext Context
    {
        get {return _context;}
    }

    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);
    }
}

Service Layer
public interface IService
{
    // Repositories
    IUserRepository Users { get; }
    IUserTeamRepository UserTeams { get; }
    IPlayerRepository Players { get; }
    IGameRepository Games { get; }
    IUserTeam_PlayerRepository UserTeamPlayers { get; }

    void Save();
}

public class Service: IService, IDisposable
{
    private IUnitOfWork _unitOfWork;
    private IUserRepository _userRepository;
    private IUserTeamRepository _userTeamRepository;
    private IPlayerRepository _playerRepository;
    private IGameRepository _gameRepository;
    private IUserTeam_PlayerRepository _userTeamPlayerRepository;

    public Service(IUnitOfWork unitOfWork)
    {
        _unitOfWork = unitOfWork;
        initialiseRepos();
    }

    private void initialiseRepos(){
        _userRepository = _userRepository ?? new UserRepository(_unitOfWork.Context);
        _userTeamRepository = _userTeamRepository ?? new UserTeamRepository(_unitOfWork.Context);
        _playerRepository = _playerRepository ?? new PlayerRepository(_unitOfWork.Context);
        _gameRepository = _gameRepository ?? new GameRepository(_unitOfWork.Context);
        _userTeamPlayerRepository = _userTeamPlayerRepository ?? new UserTeam_PlayerRepository(_unitOfWork.Context);
    }

    public IUserRepository Users { get { return _userRepository; } }
    public IUserTeamRepository UserTeams { get { return _userTeamRepository; } }
    public IPlayerRepository Players { get { return _playerRepository; } }
    public IGameRepository Games { get { return _gameRepository; } }
    public IUserTeam_PlayerRepository UserTeamPlayers { get { return _userTeamPlayerRepository; } }

    public void Save()
    {
        _unitOfWork.Save();
    }

Unity Container Instance Setup
    Instance.RegisterType<IService, Service>(new PerThreadLifetimeManager())
            .RegisterType<IUnitOfWork, UnitOfWork>();

Controller Constructor
public GameController(IService service)
    {
        _service = service;
    }

Test Constructor
_mockUnitOfWork = new Mock<IUnitOfWork>();
_mockServiceLayer = new Mock<IService>(_mockUnitOfWork.Object); //this line fails

Test Controller Method
GameController Controller = new GameController(_mockServiceLayer.Object);

A: If you want to test methods of GameController you just need to mock/stub the dependencies of that class. Just do this:
_mockServiceLayer = new Mock<IService>();
_controller = new GameController(_mockServiceLayer.Object);

When you are testing the Controller, you shouldn't worry about the dependencies of the service. UnitOfWork is never exposed outside your service, so don't worry about it when testing the controller. On your tests you may now setup expectations of methods called on your service, like verifying that Save was called once (If you were testing the service, then you would worry about the IService.Save calling Save on a mock of the IUnitOfWork!):
_mockServiceLayer.Verify(s=> s.Save(), Times.Once());

The problem you will find is that your service class is not abstracting the controller from the repositories, as your controller will get the repositories via the properties in IService and query directly the repositories. So if you want to test your controller methods, you will still need to mock the repositories, doing something like:
//Initialization before each test:
_mockUserRepo = new Mock<IUserRepository>();
//...other repositories
_mockServiceLayer = new Mock<IService>();
_mockServiceLayer.Setup(s => s.Users).Returns(_mockUserRepo.Object);
//... setup properties in IService for other repositories
_controller = new GameController(_mockServiceLayer.Object);

//In some test:
var user = new User();
_mockUserRepo.Setup(s => s.Get(123)).Returns(user);

call some controller method and make sure returned model is "user"

This way you may find yourself configuring the expectations and data returned by a few repositories and the UnityOfWork, just for testing the methods in the Controller! Not to mention that your Controller class effectively depends on your repositories, not just on the service.
Another approach would be if your service class contains higher level methods like GetUser, CreateUser or AddUserToTeam (likely having multiple services with closely related methods). The service would then shield the controller from retrieving/sending data to the repositories and using the UnitOfWork.
That way in your tests you would only need to mock IService.
For example a test for a typical "GET" action may look like:
//Arrange
var user = new User();
_mockServiceLayer.Setup(s => s.GetUser(123)).Returns(user);

//Act
var viewResult = _controller.GetUser(123) as ViewResult;

//Assert
Assert.AreEqual(user, viewResult.Model);

Hopefully this will help clarifying things a bit!

A: In the line that fails you are mocking the IService which does not have a constructor, so passing it args will cause it to fail. Since you are only trying to unit test the controller, you should change the line to this:
_mockServiceLayer = new Mock<IService>();

and then specify the the behaviors you want using _mockServiceLayer.Setup(...). Remember your interface doesn't know anything about your unit of work so you do not need to mock the unit of work.
If you actually want to test the controller and service layer together then you would do something like this:
_mockUnitOfWork = new Mock<IUnitOfWork>();
var serviceLayer = new Service(_mockUnitOfWork.Object);
var controller = new GameController(serviceLayer);

You would probably be better off unit testing the controllers and the serviceLayer separately, each time mocking the layer below.


text:
Q: MSSQL Triggers for a column value changed in a record I am a newbie in the T-SQL Triggers domain and would like a hand on this matter.
Context:
I have 2 MSSQL tables, Tickets (TicketNumber as PrimaryKey,Status int, etc...) and Actions (Id as PrimaryKey, IdTicket as ForeignKey, Status int, etc...).
One ticket can have several Actions.

*

*When a user updates a solution's status to "close"(New.Status=0 <> Old.Status),

*The trigger must be fired and check the status of all the solutions with the same IdTicket.

*If all the Actions are closed,

*then the triggers closes the Ticket.

Do you have any idea how I should achieve that ?
I already began to write my trigger but am a bit blocked about how and when to say to the trigger to fire the UPDATE Tickets query.
USE [DataBaseName]
GO
CREATE TRIGGER [dbo].[TriggerClosureAction]
ON [dbo].[Actions]
AFTER UPDATE,DELETE
IF (UPDATE(Status))
  BEGIN
    IF (INSERTED.Status<>DELETED.Status AND INSERTED.Status=0) --Here do the If
    Exists(SELECT Status FROM [dbo].[Actions] WHERE IdTicket=IdTicket
  END;
END;

A: Here's how I would write this:
CREATE TRIGGER [dbo].[TriggerClosureAction]
ON [dbo].[Actions]
AFTER UPDATE,DELETE
AS

    UPDATE t
    SET [Status] = 0
    FROM dbo.Tickets As t
    -- update only records effected from the current operation
    INNER JOIN DELETED As d
        ON t.TicketNumber = d.IdTicket

    -- No records left for that ticket number with status 1 in the actions table
    WHERE NOT EXISTS
    (
        SELECT 1
        FROM Actions As A
        WHERE A.IdTicket = t.TicketNumber
        AND A.[Status] <> 0
    )

Updating the tickets table using a join to the deleted table to make sure only relevant records gets updated - since the deleted table contains all the records effected from the delete or update statement that fired the trigger, where there are no records left if the actions table where the status is not 0 - since this is an after trigger, the data in the actions table will already reflect the results of the statement that fired the trigger.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Jquery Toggle working in IE/Chrome, Undefined in FF I seem to be having the opposite problem as everyone else, my Javascript isn't working in Firefox. Firebug is telling me the id is undefined, but it isn't, unless FF doesn't recognize  tags as objects to be controlled by javascript like IE/Chrome?
PHP Looks like this:
echo 'Details';
echo '
';
echo '';
echo '
';
   Bunch of Content Here.
echo '
';
echo 	;
echo
;

Javascript is just
function toggle(id){
$(id).toggle();}

The Sections toggle correctly in Both IE and Chrome, but Firefox returns "details_0 is not defined" etc. for every single one.
Any Suggestions? It's actually crashing at the call, weird enough because I put an Alert in the first line of toggle and it never fires, so it's not even making it that far. What am I missing?
thanks!

A: Call it like this: toggle(\'text in here\').
And in the toggle function call it like this: $("#" + id).toggle();.

A: The reason it works at all is because some browser actually create window level variable details_something. So you are passing reference to your tr instead of string value its id.
Make sure value you pass to toggle() is enclosed in quotes. And make sure you prepend it with #


text:
Q: Erro ao debugar webservice (asmx) localmente no Visual Studio Estou tentando debugar localmente um webservice (asmx) a partir do Visual Studio.
Ao tentar criar a conexão com o banco de dados, ocorre a seguinte exceção:

Falha na solicitação da permissão de tipo
  'System.Security.Permissions.FileIOPermission, mscorlib,
  Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'.

Eu já alterei no cabeçalho da classe, incluindo a permissão:
[System.Security.Permissions.PermissionSet(System.Security.Permissions.SecurityAction.Assert, Unrestricted = true)]

E também adicionei no Web.config:
<securityPolicy>
<trustLevel name="Full" policyFile="internal"/>
</securityPolicy>

Mesmo assim, o erro permanece. O mesmo webservice está rodando sem problema na máquina de Produção.
Alguém sabe o que fazer para reverter essa situação na máquina local com o Visual Studio?

A: Apenas atualizando, encontrei o "problema". Eu abri o projeto remotamente (em rede). Depois que copiei o projeto para máquina local, consegui debugar sem problemas. Fica a dica.


text:
Q: C++ string comparison #include "stdafx.h"
#include "iostream"
#include "string"

using namespace std;

void main()
{
string a = "a";
string b(1, -70); /*constructor, create a string having 1 character that its value is equal to -70*/
cout<<((b>a)?b:a);
}

//output on screen: b was printed, not a (!)

Why b>a although the value of b is less than the value of a?
How can I rectify this situation?

A: On VS2010, I found that the char  was signed - hence not the desired explanation.
Stepping through the debugger on the comparison, I eventually hit the code:
template<> struct char_traits<char>
 { // properties of a string or stream char element
 typedef char _Elem;
 typedef _Elem char_type;
 typedef int int_type;
 typedef streampos pos_type;
 typedef streamoff off_type;
 typedef _Mbstatet state_type;

 static int __CLRCALL_OR_CDECL compare(const _Elem *_First1, const _Elem *_First2,
  size_t _Count)
  { // compare [_First1, _First1 + _Count) with [_First2, ...)
  return (_CSTD memcmp(_First1, _First2, _Count));
  }
// etc
};

So the real comparision boils down to a memcmp. Checking that out, we find "evaluated as unsigned char values", hence the problem.
Cf. Arytom's answer - Interesting, I did not know this. Looking it up:
The 1998 standard 21.1.3.1:6 on char_traits states 'lt' is defined identically to the built in operator <.
The N3126 draft, 21.2.3.1:5 states it should be as for unsigned char.

A: Strings are always compared as unsigned char regardless of the signess of actual character.
std::string took this behavior from C where strcmp uses characters in range 0-255 even if the char is in range -128 -- 127.
So basically -70 is 186 and 186 > 'a'
Edit: Reference to standard. I don't have C++98/2003 near me just C++0x, but:
"Working Draft, Standard for Programming Language C++", N2915, 21.2.3.1, remark 5 says:

The two-argument members eq and lt shall be defined identically to the built-in operators == and < for type unsigned char.

i.e. characters compared as unsigned char. (it references to character traits specialization for char)

A: See the binary equivalent value of -70 as a 1 character.


text:
Q: How to solve variable not initialize in flutter State? I am using floor to develop app with sqlite db.
But when I start to initialize the database object I got this error:
Variable database has not been initialized.

This is my code:

class _DoctorScreenPageState extends State<DoctorScreenPage> {
  late AppDatabase database;
  List<Doctor> doctors = [];
  late StreamSubscription subscription;

  @override
  void initState() {
    super.initState();
    $FloorAppDatabase
        .databaseBuilder('database.db')
        .build()
        .then((value) async {
      database = value;

    });

  }
}


text:
Q: Cheap switch 125V 5A fuse blew Cheap switch glass fuse blew, 125V 5A. Found a 125V 8A fuse in a string of Christmas lights. Can I use it to replace 125V 5A?

A: No. You can't. The rest of the system is expecting the fuse to blow at 5A. Your new fuse will blow at 8A, which means it will pass 6A through without any problem which could cause the downstream circuits to be destroyed or catch fire since they're not expecting that.


text: Q: How can i make all captions like this? I want all of my captions inside latex look like this. The font is default serif font. I am not using any special document class, nor do I want to. I am using "book" class. Please help.


text:
Q: Editing SAS config files to execute R (making SAS play well with others) There are many things that R just does better. Hence, I am trying to set my system up so I can execute R commands from within SAS using the [submit /R;] and [endsubmit;] commands. However I need some help getting my config files set up properly to do this.
First Steps (to allow SAS to read the R language):
I checked to see if my system was set up to read the R language (code below).
proc options option=rlang;
run;

I got the following in my log:
SAS (r) Proprietary Software Release 9.3  TS1M0

NORLANG           Do not support access to R language interfaces

This meant I needed to add the -RLANG option to the config file. I did that. Below is an example of my config file (C:\Program Files\SASHome\SASFoundation\9.3\sasv9.cfg):
-RLANG
-config "C:\Program Files\SASHome\SASFoundation\9.3\nls\en\sasv9.cfg"

(NOTE: the -RLANG had to be above the config reference for this to be recognized properly.)
And the resulting output in my log after re-opening enterprise guide and re-running the proc options code above:
SAS (r) Proprietary Software Release 9.3  TS1M0

RLANG             Support access to R language interfaces

Issue (specific to Enterprise Guide?):
I am using SAS 9.3 and R 2.15.2, so according to this (http://blogs.sas.com/content/iml/2013/09/16/what-versions-of-r-are-supported-by-sas/) these versions are compatible.
However, I execute SAS through Enterprise Guide 4.3 (I like organization better). It appears that Enterprise Guide may require some additional stuff in the config file to allow R to run and recognize where it is on my computer.
For example, I try running the following code:
Proc iml;
  submit /R;
        directory <- "C:\\Data\\Filepath"
        FILEpattern1 <- "Fall 12-13.xlsx"

        setwd(directory)
        filenames1 <- list.files(pattern=FILEpattern1)
  endsubmit;

And I get the following error:
15         Proc iml;
NOTE: IML Ready
16         submit /R;
17         directory <- "C:\\Data\\Filepath"
18         FILEpattern1 <- "Fall 12-13.xlsx"
19
20         setwd(directory)
21         filenames1 <- list.files(pattern=FILEpattern1)
22         endsubmit;
ERROR: SAS could not initialize the R language interface.

statement : SUBMIT at line 16 column 1

According to this thread (https://communities.sas.com/thread/34758), individuals using Enterprise Guide also need to define where R_Home is on their computer. The thread discusses changing something in sasenv_local but I need more specific directions.
Any suggestions or advice on how to get this working?

A: If the issue is solely defining R_HOME in the local environment variables, you have at least three options.  You can add this to your config file if you have access to that (the file referenced in -config in the OP):
-SET R_HOME "r_home location"

You could use options set to do the same thing (options set=R_HOME='r_home location';) if you don't have permission to modify your config file, as well.
You also should be able to modify the environment variable in Windows directly, by going to My Computer, right click-properties, Advanced, Environment Variables, and setting it there.  Again, this requires administrative rights.
See this paper for more information.
As noted by the OP. R_HOME needs to be set to the base directory for R (such as c:\program files\R), not to the \bin folder or any other particular location.


text:
Q: Issue with python 2 to python 3 TypeError: cannot use a string pattern on a bytes-like object I have the following code and would like to make it compatible with both python 2.7 and python 3.6
from re import sub, findall

return sub(r'  ', ' ', sub(r'(\s){2,}', ' ',sub(r'[^a-z|\s|,]|_|
(x)\1{1,}', '', x.lower())))

I received the following error:
TypeError: cannot use a string pattern on a bytes-like object
I understood that the python3 distinguishes byte and string(unicode),but not sure how to proceed.
Thanks.
tried the following and not working
return sub(rb'  ', b' ', sub(rb'(\s){2,}', b' ',sub(rb'[^a-z|\s|,]|_|(x)\1{1,}', b'', x.lower())))

A: Have you tried using re.findall? For instance:
import re

respdata =      # the data you are reading

content = re.findall(r'#findall from and too#', str(respdata))    # output in string
for contents in content:
    print(contents)    # print results

A: The "string" you have must be a series of bytes, which you can convert to a real string using x.decode('utf-8'). You can see the problem with a simple example:
>>> import re
>>> s = bytes('hello', 'utf-8')
>>> s
b'hello'
>>> re.search(r'[he]', s)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/Cellar/python/3.7.4/Frameworks/Python.framework/Versions/3.7/lib/python3.7/re.py", line 183, in search
    return _compile(pattern, flags).search(string)
TypeError: cannot use a string pattern on a bytes-like object
>>> s.decode('utf-8')
'hello'
>>> re.search(r'[he]', s.decode('utf-8'))
<re.Match object; span=(0, 1), match='h'>

I'm assuming your bytes represent UTF-8 data, but if you're working with a different encoding then just pass its name to decode() instead.


text:
Q: Nexmo API SMS delivery receipt I'm using laravel Notifications to send a text message to registered users of my application.
I was originally using the default Nexmo channel but have since created my own channel to rule out any issues.
I am storing each message in my database, with each message having a 'messages' array column which contains JSON response information for each physical message sent by Nexmo.
eg.
[{"to":"441122334455","message-id":"0B00000099A49D63","status":"0","remaining-balance":"7.00500000","message-price":"0.03330000","network":"23410"}]

My custom SMS channel is as follows
namespace App\Notifications\Channels;

use Illuminate\Notifications\Notification;
use Nexmo\Laravel\Facade\Nexmo;

class CustomSmsChannel
{
    /**
     * Send the given notification.
     *
     * @param  mixed  $notifiable
     * @param  \Illuminate\Notifications\Notification  $notification
     * @return void
     */
    public function send($notifiable, Notification $notification)
    {
        $message = $notification->toCustomSms($notifiable);

        return Nexmo::message()->send([
            'to' => $notifiable->phone_number,
            'from' => env('NEXMO_FROM'),
            'text' => $message->content,
            'status-report-req' => 1
        ]);

    }
}

This sends the message OK and I receive it fine, no issues there.
I've set the web hook on the Nexmo control panel for delivery receipts to the correct URL (I'm using http, does it need to be https?)
My routes file is as follows
Route::get('sms/delivery-status', 'SmsController@deliveryStatus');

With my SmsController method
/**
 * The webhook for Nexmo to receive delivery statuses.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return  \Illuminate\Http\Response
 */
public function deliveryStatus(Request $request)
{
    if (!isset($request->messageId) OR !isset($request->status)) {
        Log::error('Not a valid delivery receipt');
        return;
    }

    // Loop for all main SMS messages with the given phone number.
    $entries = SmsHistory::where('phone_number', $request->to)->get();

    // Loop through each of the SMS message to that number.
    foreach ($entries as $item) {
        // Loop through each of the rsent messages for the main message.
        foreach ($item->messages as $key => $message) {
            // Check whether the given messageID matches the one stored in the messages array field.
            if ($message['message-id'] == $request->messageId) {
                $messages = $item->messages;
                // Remove the current message
                array_pull($messages, $key);
                // Add the new message
                $messages = array_add($messages, $key, $request->input());
                $item->messages = $messages;
                $item->save();
            }
        }
    }

    return response('OK', 200);
}

Which in a nutshell, searches for all messages where the phone_number matches the 'to' value. Then for each message it loops through each of the message parts sent by Nexmo (stored in the JSON column) to match the messageId.
Once the messageId is found, it replaces the JSON with the JSON provided on the receipt eg.
[{"msisdn":"441122334455","to":"441122334455","network-code":"23410","messageId":"0B000000999B5FCB","price":"0.02000000","status":"delivered","scts":"1208121359","err-code":"0","message-timestamp":"\\2020-01-01\\ 12:00:00"}]

This is then used to confirm that the message has been delivered in my views (by making sure all parts are shown as delivered, etc)
If I perform the GET request manually and set the correct 'to' and 'messageId' variables in the request the database row is updated fine so that rules that out.
Sorry for the long post and it's probably not the most eloquent way of doing this but what am I missing?!

A: I found the issue.
Logging the request (why I didn't do this I don't know but thank you for suggesting it) I realised that I was searching for a matching phone_number for the wrong number.
Common sense stated that I used 'to' but I needed to use 'msisdn'?!
Anyway, changed this in the controller and it's not working fine! :)


text:
Q: How I can append a string to the tuples in a list? I'm creating an application that generates walking bass lines from specified chords. It always begins with the root (1st chord tone), then the permutations of the 1st, 3rd and 5th chord tones follow.
I'd like to append a string (the root) to the tuples (the permutations) in a list in Python, but my code doesn't work. Let me put my code:
# pip install pychord

from pychord import Chord
from itertools import permutations

def returnPermutations(arr, r):
    return list(permutations(arr, r))

c7 = Chord("C7")
print("c7.components()", c7.components())
print("Get the Triad: c7.components()[0:3]: ", c7.components()[0:3])

chordTonePermutations = returnPermutations(c7.components()[0:3], 3)
print("chordTonePermutations: ", chordTonePermutations)
print("chordTonePermutations[0]: ", chordTonePermutations[0])

# walkingBass = tuple((c7.components()[0],)) + chordTonePermutations[0]
walkingBass = list(tuple((c7.components()[0],)) + chordTonePermutations[0])

walkingBassList = []
# walkingBassList = list.append(walkingBass)

for chordTones in chordTonePermutations:
  print("chordTones", chordTones)
  walkingBass = tuple((c7.components()[0],)) + chordTones
  # walkingBass = list(tuple((c7.components()[0],)) + chordTones)
  walkingBassList = list.append(walkingBass)

print("walkingBass", walkingBass)

print("walkingBassList", walkingBassList)
# What I expect is a list of tuples which always begins with the root 'C',
# plus the permutations of the triad (the first 3 chord tones):
# walkingBassList [
# ('C', 'C', 'E', 'G'),
# ('C', 'C', 'G', 'E'),
# ('C', 'E', 'C', 'G'),
# ('C', 'E', 'G', 'C'),
# ('C', 'G', 'C', 'E'),
# ('C', 'G', 'E', 'C')]

... This code gives me the following output with an error:
c7.components() ['C', 'E', 'G', 'Bb']
Get the Triad: c7.components()[0:3]:  ['C', 'E', 'G']
chordTonePermutations:  [('C', 'E', 'G'), ('C', 'G', 'E'), ('E', 'C', 'G'), ('E', 'G', 'C'), ('G', 'C', 'E'), ('G', 'E', 'C')]
chordTonePermutations[0]:  ('C', 'E', 'G')
chordTones ('C', 'E', 'G')
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-84-3a01c9d6da74> in <module>()
     24   walkingBass = tuple((c7.components()[0],)) + chordTones
     25   # walkingBass = list(tuple((c7.components()[0],)) + chordTones)
---> 26   walkingBassList = list.append(walkingBass)
     27
     28 print("walkingBass", walkingBass)

TypeError: descriptor 'append' requires a 'list' object but received a 'tuple'

So, I surrounded the tuple with a list:
  # walkingBass = tuple((c7.components()[0],)) + chordTones
  walkingBass = list(tuple((c7.components()[0],)) + chordTones)

Now it gives me TypeError: append() takes exactly one argument (0 given):
TypeError                                 Traceback (most recent call last)
<ipython-input-86-e2ecc32a34c8> in <module>()
     24   # walkingBass = tuple((c7.components()[0],)) + chordTones
     25   walkingBass = list(tuple((c7.components()[0],)) + chordTones)
---> 26   walkingBassList = list.append(walkingBass)
     27
     28 print("walkingBass", walkingBass)

TypeError: append() takes exactly one argument (0 given)

... Wait. (0 given)? One argument walkingBass is already given, right? What's wrong with me?
The following question doesn't help me because the append really doesn't have any argument.
It keeps saying: TypeError: append() takes exactly one argument (0 given)
... I'm totally confused. Could anyone help me to fix this? Thank you in advance.

A: You're trying to invoke append as a function, but it's a method.  So instead of doing:
walkingBassList = list.append(walkingBass)

You need to do:
walkingBassList.append(walkingBass)

In the append method, self gets bound to walkingBassList so it knows what to append to.  Without that information, there isn't much it could do.

A: walkingBassList = list.append(walkingBass)

should be
walkingBassList.append(walkingBass)


text:
Q: Python Appending DataFrame, weird for loop error I'm working on some NFL statistics web scraping, honestly the activity doesn't matter much. I spent a ton of time debugging because I couldn't believe what it was doing, either I'm going crazy or there is some sort of bug in a package or python itself. Here's the code I'm working with:
import pandas as pd
from bs4 import BeautifulSoup as bs
import requests
import string
import numpy as np

#get player list
players = pd.DataFrame({"name":[],"url":[],"positions":[],"startYear":[],"endYear":[]})
letters = list(string.ascii_uppercase)
for letter in letters:
    print(letter)
    players_html = requests.get("https://www.pro-football-reference.com/players/"+letter+"/")
    soup = bs(players_html.content,"html.parser")
    for player in soup.find("div",{"id":"div_players"}).find_all("p"):
        temp_row = {}
        temp_row["url"] = "https://www.pro-football-reference.com"+player.find("a")["href"]
        temp_row["name"] = player.text.split("(")[0].strip()
        years = player.text.split(")")[1].strip()
        temp_row["startYear"] = int(years.split("-")[0])
        temp_row["endYear"] = int(years.split("-")[1])
        temp_row["positions"] = player.text.split("(")[1].split(")")[0]
        players = players.append(temp_row,ignore_index=True)
players = players[players.endYear > 2000]
players.reset_index(inplace=True,drop=True)

game_df = pd.DataFrame()
def apply_test(row):
    #print(row)
    url = row['url']
    #print(list(range(int(row['startYear']),int(row['endYear'])+1)))
    for yr in range(int(row['startYear']),int(row['endYear'])+1):
        print(yr)
        content = requests.get(url.split(".htm")[0]+"/gamelog/"+str(yr)).content
        soup = bs(content,'html.parser').find("div",{"id":"all_stats"})
        #overheader
        over_headers = []
        for over in soup.find("thead").find("tr").find_all("th"):
            if("colspan" in over.attrs.keys()):
                for i in range(0,int(over['colspan'])):
                    over_headers = over_headers + [over.text]
            else:
                over_headers = over_headers + [over.text]
        #headers
        headers = []
        for header in soup.find("thead").find_all("tr")[1].find_all("th"):
            headers = headers + [header.text]
        all_headers = [a+"___"+b for a,b in zip(over_headers,headers)]
        #remove first column, it's meaningless
        all_headers = all_headers[1:len(all_headers)]
        for row in soup.find("tbody").find_all("tr"):
            temp_row = {}
            for i,col in enumerate(row.find_all("td")):
                temp_row[all_headers[i]] = col.text
            game_df = game_df.append(temp_row,ignore_index=True)
players.apply(apply_test,axis=1)

Now again I could get into what I'm trying to do, but there seems to be a much higher-level issue here. startYear and endYear in the for loop are 2013 and 2014, so the loop should be setting the yr variable to 2013 then 2014. But when you look at what prints out due to the print(yr), you realize it's printing out 2013 twice. But if you simply comment out the game_df = game_df.append(temp_row,ignore_index=True) line, the printouts of yr are correct. There is an error shortly after the first two lines, but that is expected and one I am comfortable debugging. But the fact that appending to a global dataframe is causing a for loop to behave differently is blowing my mind right now. Can someone help with this?
Thanks.

A: I don't really follow what the overall aim is but I do note two things:

*

*You either need the local game_df to be declared as global game_df before  game_df = game_df.append(temp_row,ignore_index=True) or better still pass as an arg in the def signature though you would need to amend this: players.apply(apply_test,axis=1) accordingly.

*You need to handle the cases of find returning None e.g. with soup.find("thead").find_all("tr")[1].find_all("th") for page https://www.pro-football-reference.com/players/A/AaitIs00/gamelog/2014. Perhaps put in try except blocks with appropriate default values to be supplied.


text:
Q: Calculate the probability P(X $\ge$ Y) I've been given the following exercise:
Given the function $$
\rho(x,y) =
\left\{
\begin{array}
\\cxy &,\ x \ge 0,\ 1-x \ge y \ge 0 \\
0 &, \ elsewhere \\
\end{array}
\right.
$$
a) Find $c$ so that $\rho$ is a probability density function (calculated to be 24).
b) Calculate $P( X \le \frac{1}{2}, \ Y \le \frac{1}{4})$. I've solved this one too.
c) Calculate the probability $P(X\ge Y)$
It's the last question where I get stuck. I've tried to do this method but it requires the two random variables be independent functions.
I've tried integrating them to get the functions $(f_x(x) = \int\rho(x,y)\ dy)$ but applying what I get to the method above doesn't give me sensical results.
Any and all answers are appreciated, thank you.

A: The region of integration of $\rho$ is given by the red below.

Consider, in addition, the line $Y = X$. The region for which $Y \leq X$ is given by the green.

The intersection of the red and green regions will give you the appropriate region of integration to calculate $P(Y \leq X)$, given in blue:

My suggestion would be to partition this triangle into two regions $T_1$ and $T_2$:

The intersection of the two lines occurs when $X = 1 - X$, or $2X = 1$, or $X = 1/2$, where $Y = 1/2$ as well. I have also included other points worth noting.

The region $T_1$ is given by $X$-bounds of $0$ and $1/2$, and $Y$-bounds of $0$ and $X$.
The region $T_2$ is given by $X$-bounds of $1/2$ and $1$, and $Y$-bounds of $0$ and $1 - X$.
Therefore, the desired probability is given by
$$\int_{0}^{1/2}\int_{0}^{x}\rho(x, y)\text{ d}y\text{ d}x + \int_{1/2}^{1}\int_{0}^{1-x}\rho(x, y)\text{ d}y\text{ d}x = \dfrac{1}{2}\text{.}$$
I will leave the integration details to you.


text:
Q: Chromecast update meta data for stream without restarting stream I'm initially casting in iOS with this code:
metadata setString:lblSongInfo.text forKey:kGCKMetadataKeyTitle];
[metadata setString:currentStation.stationName
             forKey:kGCKMetadataKeySubtitle];

[metadata addImage:[[GCKImage alloc]
                    initWithURL:[[NSURL alloc] initWithString:urlString]
                    width:300
                    height:300]];

//define Media information
GCKMediaInformation *mediaInformation =
[[GCKMediaInformation alloc] initWithContentID:
 streamURL
                                    streamType:GCKMediaStreamTypeLive
                                   contentType:@"audio/mp3"
                                      metadata:metadata
                                streamDuration:0
                                    customData:nil];

//cast audio
[_mediaControlChannel loadMedia:mediaInformation autoplay:TRUE playPosition:0];

How can I update just the meta data for this media item (title, subtitle, and image) without reloading the audio stream again? I don't want an interruption in playback. Any help is appreciated.

A: You need to write your own custom receiver to be able to receive data out-of-band; if you stick with the Styled/Default receivers, those receivers will not be able to receive that type of messages. To send pure data to a receiver, you have two options:

*

*Use the customData field that is available in some media control commands, or

*Add a new namespace and use that to send data whenever you want.

The first option is limited to those scenarios where it is enough for you to send data when trying to send a media control command to the receiver.
In your case, the cleanest solution is to use the second option, but you can potentially use the first option and send a collection of metadata when you, say, load the media and then have a custom logic on the receiver to extract that collection and update the metadata following your own logic (e.g. periodically). If that satisfies your requirements, then you won't be needing a new namespace but that has its limitations and creating a namespace is truly trivial.


text:
Q: moving asp.net membership specific settings to a separate config file Is it possible to move the asp.net membership/role settings to a separate config file. This is helpful for custom membership providers.
<authentication  mode="Forms">
  <forms loginUrl="~/Login.aspx" timeout="144600" slidingExpiration="true">
</authentication>
<membership defaultProvider="TestMembership">
   <providers>
      <add name="TestMembership" type="Test.Membership.TestMembership">
   </providers>
</membership>
<roleManager enabled="true" defaultProvider="TestRole"
             cacheRolesInCookie="true" cookieName=".Test" cookieTimeout="1440"
             cookiePath="/">
   <providers>
      <add name="TestRole" type="Test.Membership.TestRole" />
   </providers>
</roleManager>

A: Any .NET configuration section can be externalized - try this:
<authentication configSource="auth.config" />
<membership configSource="members.config" />
<roleManager configSource="roles.config" />

or whatever names you want to use.
The individual files need to contain the whole section that you've externalized:
auth.config
<?xml version="1.0" encoding="utf-8"?>
<authentication  mode="Forms">
  <forms loginUrl="~/Login.aspx" timeout="144600" slidingExpiration="true">
</authentication>

members.config
<?xml version="1.0" encoding="utf-8"?>
<membership defaultProvider="TestMembership">
   <providers>
      <add name="TestMembership" type="Test.Membership.TestMembership">
   </providers>
</membership>

roles.config
<?xml version="1.0" encoding="utf-8"?>
<roleManager enabled="true" defaultProvider="TestRole"
             cacheRolesInCookie="true" cookieName=".Test" cookieTimeout="1440"
             cookiePath="/">
   <providers>
      <add name="TestRole" type="Test.Membership.TestRole" />
   </providers>
</roleManager>


text:
Q: Choose 13 cards from a standard deck of cards. How many 4-of-a-kinds are there? I believe the answer is 13 * $13\choose4$ * $48\choose9$.
There are $13\choose4$ to draw 4 of the same cards, and multiply by 13 for each possible rank (A, 2, 3, ..., K). Then there are $48\choose9$ to choose the remaining cards.
One thing I am not certain of, is whether this accounts for the possibility of having  two 4-of-a-kinds or three  4-of-a-kinds, but I believe it is, since having two and three means you have one.

A: There is only 1 way to get four of a kind
13 * $4\choose4$ * $48\choose9$

A: There are $13$ ways to choose the rank of a four of a kind, one way to select all the cards of that rank, and $\binom{52 - 4}{13 - 4} = \binom{48}{9}$ ways to select the other nine cards in the hand from the other $48$ cards in the deck.  Hence, there are
$$\binom{13}{1}\binom{48}{9}$$
$13$-card hands that contain a four of a kind.
However, we have counted hands with two four of a kinds twice, once for each way we could designate one of the ranks as the one from which the four of a kind was drawn.  We only want to count them once, so we must subtract them from the total.
There are $\binom{13}{2}$ ways to select two ranks from which four of a kinds are drawn, one way to draw all the cards of those ranks, and $\binom{52 - 2 \cdot 4}{13 - 2 \cdot 4} = \binom{44}{5}$ ways to choose the remaining five cards in the hand from the remaining $44$ cards in the deck.  Hence, there are
$$\binom{13}{2}\binom{44}{5}$$
$13$-card hands with two four of a kinds.
However, we have subtracted too much.  We counted hands with three four of a kinds three times when we counted hands that contain a four of a kind, once for each way we could designate one of the ranks as the rank from which a four of a kind is drawn.  We subtracted those hands three times when we counted hands that contain two four of a kinds, once for each $\binom{3}{2}$ ways we could designate two of those three ranks as the ranks from which two four of a kinds were drawn.  Hence, we have not counted hands with three four of a kinds at all.
There are $\binom{13}{3}$ ways to choose the ranks of the three four of a kinds, one way to choose all the cards of each of those ranks, and $\binom{52 - 3 \cdot 4}{13 - 3 \cdot 4} = \binom{40}{1}$ ways to choose the remaining card in the hand from the $40$ remaining cards in the deck.  Hence, there are
$$\binom{13}{3}\binom{40}{1}$$
hands with three four of a kinds.
By the Inclusion-Exclusion Principle, the number of $13$-card hands that contain a four of a kind is
$$\binom{13}{1}\binom{48}{9} - \binom{13}{2}\binom{44}{5} + \binom{13}{3}\binom{40}{1}$$


text:
Q: Authenticating with SharePoint 2013 from node.js I have a command-line script written in JavaScript which needs to connect to a REST Api on a remote SharePoint site, but I cannot figure out how to authenticate. I can log on in a browser using forms authentication, and by inspecting the request I should be able to reproduce it in node.js to get the appropriate auth cookie or token.  However, I actually get a 403 Forbidden.  I don't know if this is the best way of doing it, but I can't find very much info on it.  Here is my script:
var http = require('http');
var querystring = require('querystring');

var postData = querystring.stringify({
  'ctl00$PlaceHolderMain$signInControl$UserName': 'restapi',
  'ctl00$PlaceHolderMain$signInControl$password': 'my_password',
  'ctl00$PlaceHolderMain$signInControl$login': 'Sign In'
});

var options = {
  hostname: 'sharepoint.example.com',
  port: 80,

  path: '/_layouts/15/Authenticate.aspx?Source=%2F',
  method: 'POST',
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded',
    'Content-Length': postData.length
  }
};

var req = http.request(options, function(res) {
  console.log('STATUS: ' + res.statusCode);
  console.log('HEADERS: ', res.headers);
  res.setEncoding('utf8');
  res.on('data', function (chunk) {
    console.log('BODY: ' + chunk);
  });
});

req.on('error', function(e) {
  console.log('problem with request: ' + e.message);
});

// write data to request body
req.write(postData);
req.end();

And the response headers are:
{ 'cache-control': 'private',
  'content-type': 'text/plain; charset=utf-8',
  server: 'Microsoft-IIS/8.5',
  'x-sharepointhealthscore': '0',
  'x-aspnet-version': '4.0.30319',
  sprequestguid: '366d149d-79af-b07c-1764-dec7001b46a2',
  'request-id': '366d149d-79af-b07c-1764-dec7001b46a2',
  'x-frame-options': 'SAMEORIGIN',
  sprequestduration: '7',
  spiislatency: '0',
  'x-forms_based_auth_required': 'http://sharepoint.example.com/_login/default.aspx?ReturnUrl=/_layouts/15/error.aspx&Source=%2f_layouts%2f15%2fAuthenticate.aspx%3fSource%3d%252F',
  'x-forms_based_auth_return_url': 'http://sharepoint.example.com/_layouts/15/error.aspx',
  'x-msdavext_error': '917656; Access denied. Before opening files in this location, you must first browse to the web site and select the option to login automatically.',
  'x-powered-by': 'ASP.NET',
  microsoftsharepointteamservices: '15.0.0.4569',
  'x-content-type-options': 'nosniff',
  'x-ms-invokeapp': '1; RequireReadOnly',
  date: 'Sat, 27 Jun 2015 10:53:28 GMT',
  connection: 'close',
  'content-length': '13' }

Any suggestions?

A: Are you sure that REST API allows CORS? because a 403 Forbidden might mean that you are not allowed to contact that endpoint from outside.
Does that remote SharePoint app use AD for authentication?
if so you might need to check this package https://www.npmjs.com/package/activedirectory


text:
Q: How to write a proxy with C#? i have coding a web application which has multi user. they are select data or insert data every thing is that. But selecting some data need too many time such as using LINQ or mathematical calculation. i thing that:
my user1 :
select * from MyTable -----> save as caching via proxy server in machine

my user2 :
select * from MyTable2 -----> save as caching via proxy server in machine

my user3 :
insert into MyTable2 -----> Update caching(select * from MyTable2) via proxy server in machine

How to write a proxy server to select Faster and update select result if another user update table?

A: I guess I understand what you mean. If you want to achieve the result shown on your drawing, then one way would be to have server cache all the data which is requested by any machine. I think this is too much overhead in terms of the memory, but you can accomplish this in many ways. For example, create a proxy class which handles all database calls and then caches the results. Whenever next call is done, the handler class checks the proxy and returns if such exists; if not, then it makes a call and adds results to the cache.
BTW, I think this part is already taken into account by existing ORMs, no?

A: Why would you want a Proxy for that?
What you want to accomplish is one of the benefits of use ADO Entity Framework
You have tutorials everywhere in the web, but you can start with this one
ADO Entity Framework is smart enough to cache objects that are used many times and refresh them when they are not in sync, they also have a series of fantastic properties like late-binding and concurrency handling.


text:
Q: How can i rewrite this as so i want open this large file as rb with "file:" thing infront of it so i can use request.post to upload a video sooo  how can i rewrite this line
file = {'file': open(file_path, 'rb')}

as
with {'file': open("somefile.txt")} as f:

while keeping {'file': }
this is orgnial code
def read_in_chunks(file_object, chunk_size=100000000): #Change Chunk Size According To Your Internet Speed
    """Generator to read a file piece by piece.
    Default chunk size: 1k."""
    while True:
        data = file_object.read(chunk_size)
        if not data:
            break
        yield data

# Upload
def upload(login, key, file_path):
    sha256_hash = hashlib.sha256()
    with open(file_path, "rb") as f:
        for byte_block in iter(lambda: f.read(4096), b""):
            sha256_hash.update(byte_block)
        sha256 = sha256_hash.hexdigest()
    url = f'https://api.streamtape.com/file/ul?login={login}&key={key}&sha256={sha256}'
    data = requests.get(url).json()
    upload_url = data['result']['url']
    #file = {'file': open(file_path, 'rb')}
    with open(file_path, 'rb') as file_obj:
        for file_chunk in read_in_chunks(file_obj):
                print("uploading")
                upload_request = requests.post(upload_url, data=file_chunk)

    #upload_request = requests.post(upload_url, files=file)
    upload_response = upload_request.json()
    return upload_response

it's working but it's not uploading the file to api as it doesnot have th " { file: } "
here
with open(file_path, 'rb') as file_obj:
    for file_chunk in read_in_chunks(file_obj):
            print("uploading")
            upload_request = requests.post(upload_url, data=file_chunk)

A: It seems you wanted to give requests.post a dictionary with the key 'file' for its data argument. You can just do that like this:
upload_request = requests.post(upload_url, data={'file': file_chunk})


text:
Q: connecting to data base sends only one word iOS I want to send some string text data from my iphone to the server.
I am using a php file on my server. The php works fine if i use it on
the webpage but only sends one word if there are 2 words nothing will
be send like the connection does not exist.
PHP:

if (isset ($_GET["vic"]))
        $name = $_GET["vic"];
    else
        $name = "empty text";

$con = mysql_connect('sqlserver', 'username', 'pasword');
if (!$con) {
    die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_select_db(db_name);

$sql = "insert into Vici (VIC) values('$name');";
    $res = mysql_query($sql,$con) or die(mysql_error());

mysql_close($con);

?>

iOS:
- (IBAction)add
{

    NSString *vic = txtVic.text;

    NSString *strURL = [NSString stringWithFormat:@"%@%@",@"http://URL",vic];

    NSData *dataURL = [NSData dataWithContentsOfURL:[NSURL URLWithString:strURL]];

    NSString *strResult = [[NSString alloc] initWithData:dataURL encoding:NSUTF8StringEncoding];

    NSString *povezava = @"Connected successfully ";
    if([povezava isEqualToString:strResult])
        izpis.text = @"added";

}

I did not use any real info because its private. Than you.

A: You should replace
NSString *vic = txtVic.text;
with
NSString *vic = [txtVic.text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
as @DineshRaja commented.

A: NSString *strURL = [NSString stringWithFormat:@"%@%@",@"http://URL",vic];
This string will give You

http://URLvic

If I understand correctly Your link should looks like http://URL/?vic=%@

NSString *strURL = [NSString stringWithFormat:@"%@/?vic=%@",@"http://URL",vic];


text:
Q: SQL Return datas from the second table based on the data of the first table I have two SQL Server tables that are not linked together (No join) and I want to get the data from the second table based on the data of the first table. In the first table I have this:
Table 1
id  name
----------
4   BOX-A
8   PART-D

Table 2
id  name
------------
14  BOX-A1
25  BOX-A2
38  TOOL-A1
39  TOOL-A2
40  PART-D1
41  PART-D2

What I want to do is that for each name found in table 1, I want to return all the matches in the table 2, so at the end I will have something like this:
id  name
-----------
14  BOX-A1
25  BOX-A2
40  PART-D1
41  PART-D2

A: You can use join or exists:
select t2.*
from table2 t2
where exists (select 1 from table1 t1 where t2.name like concat(t1.name, '%'));


text:
Q: How to remove formatting data while extract text from .rtf file? We are facing a problem while extract text from .rtf file. We are using following code and it is also extract document formatting text like \nNormal;\nHeading;\nBody Text;\nList;\ncaption;\nIndex;\nPreformatted Text;\nStarWriter\n
And we are using following code to extract text from .rtf file:
<?php

// Function that checks whether the data are the on-screen text.
// It works in the following way:
// an array arrfailAt stores the control words for the current state of the stack, which show that
// input data are something else than plain text.
// For example, there may be a description of font or color palette etc.
function rtf_isPlainText($s) {
    $arrfailAt = array("*", "fonttbl", "colortbl", "datastore", "themedata");
    for ($i = 0; $i < count($arrfailAt); $i++)
        if (!empty($s[$arrfailAt[$i]])) return false;
    return true;
}

function rtf2text($filename) {
    // Read the data from the input file.
    $text = file_get_contents($filename);
    if (!strlen($text))
        return "";

    // Create empty stack array.
    $document = "";
    $stack = array();
    $j = -1;
    // Read the data character-by- character…
    for ($i = 0, $len = strlen($text); $i < $len; $i++) {
        $c = $text[$i];

        // Depending on current character select the further actions.
        switch ($c) {
            // the most important key word backslash
            case "\\":
                // read next character
                $nc = $text[$i + 1];

                // If it is another backslash or nonbreaking space or hyphen,
                // then the character is plain text and add it to the output stream.
                if ($nc == '\\' && rtf_isPlainText($stack[$j])) $document .= '\\';
                elseif ($nc == '~' && rtf_isPlainText($stack[$j])) $document .= ' ';
                elseif ($nc == '_' && rtf_isPlainText($stack[$j])) $document .= '-';
                // If it is an asterisk mark, add it to the stack.
                elseif ($nc == '*') $stack[$j]["*"] = true;
                // If it is a single quote, read next two characters that are the hexadecimal notation
                // of a character we should add to the output stream.
                elseif ($nc == "'") {
                    $hex = substr($text, $i + 2, 2);
                    if (rtf_isPlainText($stack[$j]))
                        $document .= html_entity_decode("&#".hexdec($hex).";");
                    //Shift the pointer.
                    $i += 2;
                // Since, we've found the alphabetic character, the next characters are control word
                // and, possibly, some digit parameter.
                } elseif ($nc >= 'a' && $nc <= 'z' || $nc >= 'A' && $nc <= 'Z') {
                    $word = "";
                    $param = null;

                    // Start reading characters after the backslash.
                    for ($k = $i + 1, $m = 0; $k < strlen($text); $k++, $m++) {
                        $nc = $text[$k];
                        // If the current character is a letter and there were no digits before it,
                        // then we're still reading the control word. If there were digits, we should stop
                        // since we reach the end of the control word.
                        if ($nc >= 'a' && $nc <= 'z' || $nc >= 'A' && $nc <= 'Z') {
                            if (empty($param))
                                $word .= $nc;
                            else
                                break;
                        // If it is a digit, store the parameter.
                        } elseif ($nc >= '0' && $nc <= '9')
                            $param .= $nc;
                        // Since minus sign may occur only before a digit parameter, check whether
                        // $param is empty. Otherwise, we reach the end of the control word.
                        elseif ($nc == '-') {
                            if (empty($param))
                                $param .= $nc;
                            else
                                break;
                        } else
                            break;
                    }
                    // Shift the pointer on the number of read characters.
                    $i += $m - 1;

                    // Start analyzing what we've read. We are interested mostly in control words.
                    $toText = "";
                    switch (strtolower($word)) {
                        // If the control word is "u", then its parameter is the decimal notation of the
                        // Unicode character that should be added to the output stream.
                        // We need to check whether the stack contains \ucN control word. If it does,
                        // we should remove the N characters from the output stream.
                        case "u":
                            $toText .= html_entity_decode("&#x".dechex($param).";");
                            $ucDelta = @$stack[$j]["uc"];
                            if ($ucDelta > 0)
                                $i += $ucDelta;
                        break;
                        // Select line feeds, spaces and tabs.
                        case "par": case "page": case "column": case "line": case "lbr":
                            $toText .= "\n";
                        break;
                        case "emspace": case "enspace": case "qmspace":
                            $toText .= " ";
                        break;
                        case "tab": $toText .= "\t"; break;
                        // Add current date and time instead of corresponding labels.
                        case "chdate": $toText .= date("m.d.Y"); break;
                        case "chdpl": $toText .= date("l, j F Y"); break;
                        case "chdpa": $toText .= date("D, j M Y"); break;
                        case "chtime": $toText .= date("H:i:s"); break;
                        // Replace some reserved characters to their html analogs.
                        case "emdash": $toText .= html_entity_decode("—"); break;
                        case "endash": $toText .= html_entity_decode("–"); break;
                        case "bullet": $toText .= html_entity_decode("•"); break;
                        case "lquote": $toText .= html_entity_decode("‘"); break;
                        case "rquote": $toText .= html_entity_decode("’"); break;
                        case "ldblquote": $toText .= html_entity_decode("«"); break;
                        case "rdblquote": $toText .= html_entity_decode("»"); break;
                        // Add all other to the control words stack. If a control word
                        // does not include parameters, set &param to true.
                        default:
                            $stack[$j][strtolower($word)] = empty($param) ? true : $param;
                        break;
                    }
                    // Add data to the output stream if required.
                    if (rtf_isPlainText($stack[$j]))
                        $document .= $toText;
                }

                $i++;
            break;
            // If we read the opening brace {, then new subgroup starts and we add
            // new array stack element and write the data from previous stack element to it.
            case "{":
                array_push($stack, $stack[$j++]);
            break;
            // If we read the closing brace }, then we reach the end of subgroup and should remove
            // the last stack element.
            case "}":
                array_pop($stack);
                $j--;
            break;
            // Skip "trash".
            case '\0': case '\r': case '\f': case '\n': break;
            // Add other data to the output stream if required.
            default:
                if (rtf_isPlainText($stack[$j]))
                    $document .= $c;
            break;
        }
    }
    // Return result.
    return $document;
}
?>

Looking forward to positive solution. Thanks


text:
Q: Ember.js not sending data to the template/view in a Rails app I am learning Ember.js as we speak and what I am trying to do is to integrate it into a Rails application (vanilla app, just for playing around), since most of the time I'm working with Rails. So far so good, I managed to install it (I am using ember-rails), but I encountered a small problem and it seems I cannot figure it out, even if I watched (I suppose) every tutorial about Ember and Rails out there.
So, the problem is that I cannot make the router pass any kind of data to the view/template. I even hardcoded there a JSON object (and not rely on the adapter) to see if this works, but with no success. So, my code looks like this:
Rails Gemfile Gemfile:

ruby "1.9.3"

gem 'rails', '3.2.16'
gem 'sqlite3'
gem 'jquery-rails'
gem 'ember-rails'
gem 'ember-source'
gem 'pg'

group :assets do
  gem 'sass-rails',   '~> 3.2.3'
  gem 'coffee-rails', '~> 3.2.1'

  # See https://github.com/sstephenson/execjs#readme for more supported runtimes
  gem 'therubyracer', :platforms => :ruby

  gem 'uglifier', '>= 1.0.3'
end

Rails controller app/controllers/users_controller.rb:

class UsersController < ApplicationController
  def index
    @a_users = User.all

    respond_to do |format|
      format.html
      format.json {render :json => @a_users}
    end
  end
end

Rails model app/models/users.rb:

class User < ActiveRecord::Base
  validates :first_name, :presence => true
  validates :last_name, :presence => true
end

Rails serializer app/serializers/user_serializer.rb:

class UserSerializer < ActiveModel::Serializer
  attributes :first_name, :last_name
end

Rails routes config/routes.rb

NewEmberOnRails::Application.routes.draw do
  root :to => 'home#index'
  resources :users
end

And this pretty much covers the Rails part. If I go and visit localhost:3000/users.json I get a nice formatted JSON object on this format (consider I have a John Doe user in the database):
{"users":[{"first_name":"John","last_name":"Doe"}]}
The Ember.js part, I have written as following:
Ember store app/assets/javascripts/store.js

NewEmberOnRails.Store = DS.Store.extend({
  // Override the default adapter with the `DS.ActiveModelAdapter` which
  // is built to work nicely with the ActiveModel::Serializers gem.
  adapter: DS.ActiveModelAdapter
  // revision: 11,
  // url: 'http://localhost:3000'
});

I even played around with revision and url but nothing.
Ember router app/assets/javascripts/router.js

NewEmberOnRails.Router.map(function() {
  return this.resource('users');
});

Ember route app/assets/javascripts/route.rb

NewEmberOnRails.UsersRoute = Ember.Route.extend({
  model: function() {
    // return this.get('store').find('user');
    return {users: [{
      first_name: "John",
      last_name: "Doe"
    }, {
      first_name: "Big",
      last_name: "Bang"
    }]};
  }
});

As you can see, I've commented the store here, and returned a hardcoded object here, but nothing.
Ember controller app/assets/javascripts/controller/users.js

NewEmberOnRails.usersController = Ember.Controller.extend({
  resourceType: NewEmberOnRails.User
});

Ember model app/assets/javascripts/model/user.js

var attr = DS.attr;

NewEmberOnRails.User = DS.Model.extend(
  first_name = attr(),
  last_name = attr()
);

And finally, the views, Rails and Ember together (I guess I'm doing something wrong here, but I cannot figure it out what):
Rails users view app/views/users/index.html.erb

Users

So, this is calling the Ember view, here (app/assets/javascripts/views/users/list.js):

NewEmberOnRails.ListUsersView = Ember.View.extend({
  templateName: 'users/users',
  usersBinding: 'NewEmberOnRails.usersController'
});

That is using the users template here (app/assets/javascripts/template/users/users.handlebars):

{{#each users}}
  {{view NewEmberOnRails.ShowUserView userBinding="this"}}
{{else}}
  No users!
{{/each}}

Now, in ShowUserView I have (app/assets/javascripts/views/users/show.js):

NewEmberOnRails.ShowUserView = Ember.View.extend({
  templateName: 'users/show'
});

And is rendering this template (app/assets/javascripts/templates/users/show.handlebars)

First Name: {{user.first_name}}

So, to wrap up everything... when I access localhost:3000/users I only get No users!, witch lead me to two possibilities:

*

*I do not have any users array at the time I'm iterating through it in app/assets/javascripts/template/users/users.handlebars

*I have it, but is empty, so there is a problem between the route and my views/templates.

Does anybody have any idea?

A: You can do it however you wish, of course, but if it were mine, I would have my route return an array and make my controller extend ArrayController.  Seems simpler and will match what you are really going to get from the store (collection of User).  Unless you really want to return a single object containing an array, this is counter to 'normal' Ember Data usage--
In the code in NewEmberOnRails.UsersRoute, you have commented out the store.find and replaced it with something that is not the same thing...  Try this:
NewEmberOnRails.UsersRoute = Ember.Route.extend({
  model: function() {
    // return this.get('store').find('user');
    return [{
      first_name: "John",
      last_name: "Doe"
    }, {
      first_name: "Big",
      last_name: "Bang"
    }];
  }
});

and:
NewEmberOnRails.usersController = Ember.ArrayController.extend({
    resourceType: NewEmberOnRails.User
});


text:
Q: highcharts image not resized after window resize Is there any way to resize highcharts rendered image after window resize?
I have set up a fiddle file here.
events: {

load: function() {
                    var img = this.renderer.image('http://www.highcharts.com/demo/gfx/skies.jpg', (200),30,200,300);
                    img.add();
                        }

        }

Click on the window restore down button, then you will see the image is not at the correct place. Can someone help me with this?

A: try using the redraw event to re-size the image
Fiddle Demo Here that should give you a start,
make sure you have a reference for the image var img; so you can remove it and added with the redraw event


text:
Q: bind message supplies 2 parameters, but prepared statement "" requires 1
*

*I am using pg-promise to execute the following query

Here is the raw query variable
const query = `SELECT * FROM feed_items WHERE feed_item_id=$1 AND '{$2}' <@ tags`

*

*tags is an array and I want to check if item is present in the array

*I keep getting this error bind message supplies 2 parameters, but prepared statement "" requires 1 despite supplying 2 values
Can someone please suggest where I am going wrong

A: Prepared Statements won't let you do it, because it is too limited. But pg-promise native formatting is quite flexible, and you can do it in several ways...

*

*Via ':value' filter, you can use either '{$2#}' or {$2:value}

*Via Custom Type Formatting, you can use $2 directly, while wrapping the value into the following:
const wrap = a => ({rawType: true, toPostgres: () => pgp.as.format('{$1#}', [a])});

or like this:
const wrap = a => ({rawType: true, toPostgres: () => pgp.as.format('{$1:value}', [a])});

or even like this:
const wrap = a => ({rawType: true, toPostgres: () => `'{${pgp.as.value(a)}}'`});

example:*
await db.any('SELECT ... $1 <@ tags', [wrap(123)]);
//=> SELECT ... '{123}' <@tags'


text:
Q: german umlaute are not displayed in terminal I have a file 'test.txt' with the following content: ä, ö, ü.
When I type
 cat test.txt
 �, �, �

What is wrong?
The system is running Ubuntu 18.04.3 LTS.
I checked locales installed german support, but I can't get it working properly.


text:
Q: Base class includes field but type not compatible with type of control
The base class includes the field 'lbl', but its type (web.App_Code.CustomLabelControl) is not compatible with the type of control (web.App_Code.CustomLabelControl).

I had done many custom controls before the same way but today I ran into this error.
I have a web application project with the below class in App_Code directory a tagprefix reference in web.config for the control in class.
What do I do now?
Web.Config
<system.web>
    <pages>
        <controls>
            <add namespace="web.App_Code" tagPrefix="CControls"/>...

Markup
<form id="form1" runat="server">
<div>
    <CControls:CustomLabelControl runat="server" OnClickText="Welcome" ID="lbl">
    </CControls:CustomLabelControl>
</div>
</form>

Class File
namespace web.App_Code
{
    public class CustomLabelControl : Control, IPostBackEventHandler, IPostBackDataHandler
    {
        private string _onClickText;

        public CustomLabelControl()
        {

        }

        public string OnClickText
        {
            get { return _onClickText; }
            set { _onClickText = value; }
        }

        public void RaisePostBackEvent(string eventArgument)
        {
            throw new System.NotImplementedException();
        }

        public bool LoadPostData(string postDataKey, NameValueCollection postCollection)
        {
            throw new System.NotImplementedException();
        }

        public void RaisePostDataChangedEvent()
        {
            throw new System.NotImplementedException();
        }
    }
}

I've checked these resources already:

*

*The base class includes the field 'btnLogin', but its type (FoodOrder.App_Code.LinkButtonDefault) is not compatible

*http://support.microsoft.com/kb/919284

*Base class includes the field 'X', but its type (System.Web.UI.ScriptManager) is not compatible with the type of control (System.Web.UI.ScriptManager)

A: Try specifying the assembly name too:
<add tagPrefix="CControls" namespace="web.App_Code" assembly="web.App_Code" />

I would consider creating a dedicated namespace for your custom controls, just for the sake of clarity. Maybe something like web.App_Code.CustomControls:
<add tagPrefix="CControls" namespace="web.App_Code.CustomControls" assembly="web.App_Code.CustomControls" />

A: Unckeck the build (and publish) option  "Allow this precompiled site to be updatable"
It might not be enought for the runtime, so check the option "use fixed naming and single page assemblies" and it solved my case :)
here is a useful link about this error: http://forums.asp.net/t/960707.aspx

A: Refer the ascx user control in the web.conf instead of the aspx page like this:
<add tagPrefix="proj1" src="~/userControls/Invoiceshow.ascx" tagName="proj1tagname">

That solved my issue.

A: I know this is old, but I had the same error trying to change a textbox to a label control.  I simply changed the ID of the control from "Insulin" to "Insulin2" which fixed the issue.  I'm not sure why it worked, but that may be a question for Microsoft.
After looking into this more, I noticed if I closed the tab of the page I was working on in Visual Studio and then reopened it, the error went away all together?  I hope this helps somebody.

A: Encountered this problem while converting a Web Forms website to MVC Web App, and changing target framework to 4.6.
The solution for me was to set the controlRenderingCompatibilityVersion attribute on the pages element in web.config:
<system.web>
   <pages validateRequest="true" controlRenderingCompatibilityVersion="4.6" clientIDMode="AutoID">
</system.web>


text:
Q: How encrypting website data works If i wanted to encrypt a password on my website before its sent to the server, would i have to encrypt the password in javascript on the frontend for it to be hidden over the interent or could it be encrypted in my flask backend code over the interent somehow. Im just a little confused on what code is actually sent to the user to run locally on their own machine. Anything to help me undertand would help a lot.

A: As user amon said in comments, HTTPS is the standard way to encrypt passwords (and everything else) in transit between the browser and the server. There's only very rarely a good reason to use anything else there.
But for passwords that's not quite enough. You should also be concerned about the security of password information stored at rest in your database.
For the standard case of a user passwords to allow logging in to a website you want hashing, not encryption. This is because there's normally no need for anyone to ever read the password out of the database - all you need to be able to do is check that the password someone types when they try to log in matches the password set for that account.
Choose a purpose made password hashing algorithm that has been widely studied and recommended by information security experts over the last few years. As of 2021, such algorithms include Argon2 and bcrypt, but not SHA or MD5. The use of password hashing algorithms should mean that even if an attacker manages to get hold of all the information your system has they shouldn't easily be able to crack many user's passwords.


text:
Q: Group by Email Address of Data table in C# using LINQ I am having 2 columns (Email-ID as first column has duplicate values) and more than 1 row in my Data-table. Now i need to group by the rows according to Email-ID and write the new result into another Data table.
Current result:
MailID Name
v@v.in Venil
v@v.in Neithal
a@a.in Iniyan
a@a.in Kavin
b@b.in Oviya
b@b.in Thamizh

Expected result:
MailID Name
v@v.in Venil, Neithal
a@a.in Iniyan, Kavin
b@b.in Oviya, Thamizh

Kindly provide me the linq code to achieve the above result.
Thanks in advance.

A: from email in emailTable
group email by email.id into grp
order by grp.Key
select new { Email = g.Key, Names = /*Your code here to get the names be in comma separated or however*/ }

A: Use group by:
from email in emailAddresses
group email by email.emailId

A: var results = collection.GroupBy(p => p.emailID).ToList();

That is what you need.


text:
Q: What's the reason this antlr grammar is not matching this input? I apologize in advance about asking a so similar question, but i'm rather frustrated, and i will probably be able to explain better on a new question.
I'm trying to rewrite parts of a structured file, and thought of using antlr.
These files are lines of {X} tokens.
There is a character i'm looking ahead for, so that i can rewrite parts of the file different if i find it.
But this character ( '#' ), can occur in many parts of the file. However, if it appears on 4th {#} it determines if i need to rewrite part of the next {X} in a way, or in another way, or not at all (if there is nothing there).
Typical input:

{ 1 }{ Where to? # }{ Where to? }{ # }{ }{ G.Cabbie_Line = 1 }{ }{ }{ }{ }{ }{ }{ }
{ 2 }{ Just drive. }{ Just drive. }{ 0 }{ }{ npc.WorldMap( G.WorldMap_State ) }{ }{ }{ }{ }{ }{ }{ Not here. }

(I added the first # so you see it can be there.)
My grammar, antlr 3.3 - it is warns "line 1:31 no viable alternative at input '{ # }'" and "line 2:35 no viable alternative at input '{ 0 }'"
grammar VampireDialog;

options
{
output=AST;
ASTLabelType=CommonTree;
language=Java;
}
tokens
{
REWRITE;
}

@parser::header {
import java.util.LinkedList;
import java.io.File;
}

@members {
//the lookahead type i'm using ( ()=> ) wraps everything after in a if, including the actions ( {} )
//that i need to use to prepare the arguments for the replace rules. Declare them global.
    String condition, command, wrappedCommand; boolean isEmpty, alreadyProcessed;

    public static void main(String[] args) throws Exception {
        File vampireDir = new File(System.getProperty("user.home"), "Desktop/Vampire the Masquerade - Bloodlines/Vampire the Masquerade - Bloodlines/Vampire/dlg/dummy");

        List<File> files = new LinkedList<File>();
        getFiles(256, new File[]{vampireDir}, files, new LinkedList<File>());
        for (File f : files) {
            if (f.getName().endsWith(".dlg")) {
                System.out.println(f.getName());
                VampireDialogLexer lex = new VampireDialogLexer(new ANTLRFileStream(f.getAbsolutePath(), "Windows-1252"));
                TokenRewriteStream tokens = new TokenRewriteStream(lex);
                VampireDialogParser parser = new VampireDialogParser(tokens);
                    Tree t = (Tree) parser.dialog().getTree();
                    System.out.println(t.toStringTree());
            }
        }
    }

    public static void getFiles(int levels, File[] search, List<File> files, List<File> directories) {
        for (File f : search) {
            if (!f.exists()) {
                throw new AssertionError("Search file array has non-existing files");
            }
        }
        getFilesAux(levels, search, files, directories);
    }

    private static void getFilesAux(int levels, File[] startFiles, List<File> files, List<File> directories) {
        List<File[]> subFilesList = new ArrayList<File[]>(50);
        for (File f : startFiles) {
            File[] subFiles = f.listFiles();
            if (subFiles == null) {
                files.add(f);
            } else {
                directories.add(f);
                subFilesList.add(subFiles);
            }
        }

        if (levels > 0) {
            for (File[] subFiles : subFilesList) {
                getFilesAux(levels - 1, subFiles, files, directories);
            }
        }
    }
}

/*------------------------------------------------------------------
 * PARSER RULES
 *------------------------------------------------------------------*/
dialog : (ANY ANY ANY npc_or_pc ANY* NL*)*;

npc_or_pc : (ANY ANY) =>
         pc_marker  pc_condition
|        npc_marker npc_condition;

pc_marker  :  t=ANY {!t.getText().trim().isEmpty() && !t.getText().contains("#")}?;
npc_marker :  t=ANY {!t.getText().trim().isEmpty() &&  t.getText().contains("#")}?;

pc_condition : '{' condition_text '}'
   {
     condition = $condition_text.tree.toStringTree();
     isEmpty = condition.trim().isEmpty();
     command = "npc.Count()";
     wrappedCommand  =  "("+condition+") and "+ command;
     alreadyProcessed = condition.endsWith(command);
   }
   -> {alreadyProcessed}?   '{' condition_text '}'
   -> {isEmpty}?            '{' REWRITE[command] '}'
   ->                       '{' REWRITE[wrappedCommand] '}';

npc_condition : '{' condition_text '}'
   {
     condition = $condition_text.tree.toStringTree();
     isEmpty = condition.trim().isEmpty();
     command = "npc.Reset()";
     wrappedCommand  =  "("+condition+") and "+ command;
     alreadyProcessed = condition.endsWith(command);
   }
   -> {alreadyProcessed}?   '{' condition_text '}'
   -> {isEmpty}?            '{' REWRITE[command] '}'
   ->                       '{' REWRITE[wrappedCommand] '}';

marker_text :    TEXT;
condition_text : TEXT;

/*------------------------------------------------------------------
 * LEXER RULES
 *------------------------------------------------------------------*/
//in the parser ~('#') means: "match any token except the token that matches '#'"
//and in lexer rules ~('#') means: "match any character except '#'"

TEXT : ~('{'|NL|'}')*;
ANY : '{' TEXT '}';
NL : ( '\r' | '\n'| '\u000C');

A: There are 3 things going wrong in your grammar:

Problems
#1
In your npc_or_pc rule:
npc_or_pc
  :  (ANY ANY)=> pc_marker  pc_condition
  |              npc_marker npc_condition
  ;

you shouldn't be looking ahead for ANY ANY, because that would satisfy both pc_marker and npc_marker. You should look ahead for pc_marker followed by ANY (or pc_condition).

#2
In both your pc_condition and npc_condition rules:
pc_condition
  :  '{' condition_text '}'
  ;

npc_condition
  :  '{' condition_text '}'
  ;

you're using the tokens { and } but the lexer will never create such tokens. As soon as the lexer sees a { it will always be followed by TEXT '}', so the only tokens that the lexer produces will be of type ANY and NL: those are the only tokens available for the parser, which brings us to problem 3:
3
In your rules marker_text and condition_text:
marker_text    : TEXT;
condition_text : TEXT;

you're using the token TEXT, which will never be a part of the token stream (see #2).

Solutions
#1
Change the look ahead to look for pc_marker instead:
npc_or_pc
  :  (pc_marker ... )=> pc_marker  ...
  |                     npc_marker ...
  ;

#2
Remove both the pc_condition and npc_condition rules and replace them by ANY tokens:
npc_or_pc
  :  (pc_marker ANY)=> pc_marker  ANY
  |                    npc_marker ANY
  ;

#3
Remove both the marker_text and condition_text rules, you don't need them anymore since you removed pc_condition and npc_condition already.

Demo
Here's your modified grammar:
grammar VampireDialog;

dialog
  :  (line {System.out.print($line.text);})* EOF
  ;

line
  :  ANY ANY ANY npc_or_pc ANY* NL+
  ;

npc_or_pc
  :  (pc_marker ANY)=> pc_marker  ANY {System.out.print("PC  :: ");}
  |                    npc_marker ANY {System.out.print("NPC :: ");}
  ;

pc_marker
  :  t=ANY {!t.getText().trim().isEmpty() && !t.getText().contains("#")}?
  ;

npc_marker
  :  t=ANY {!t.getText().trim().isEmpty() &&  t.getText().contains("#")}?
  ;

TEXT : ~('{'|NL|'}')*;
ANY  : '{' TEXT '}';
NL   : ( '\r' | '\n'| '\u000C');

or even the slightly shorter equivalent:
grammar VampireDialog;

dialog
  :  (line {System.out.print($line.text);})* EOF
  ;

line
  :  ANY ANY ANY npc_or_pc ANY+ NL+
  ;

npc_or_pc
  :  (pc_marker ANY)=> pc_marker {System.out.print("PC  :: ");}
  |                    ANY       {System.out.print("NPC :: ");}
  ;

pc_marker
  :  t=ANY {!t.getText().trim().isEmpty() && !t.getText().contains("#")}?
  ;

ANY  : '{' ~('{'|NL|'}')* '}';
NL   : ( '\r' | '\n'| '\u000C');

which can be tested with:
import org.antlr.runtime.*;

public class Main {
    public static void main(String[] args) throws Exception {
        String source =
                "{ 1 }{ Where to? }{ Where to? }{ # }{ }{ G.Cabbie_Line = 1 }{ }{ }{ }{ }{ }{ }{ }\n" +
                "{ 2 }{ Just drive. }{ Just drive. }{ 0 }{ }{ npc.WorldMap( G.WorldMap_State ) }{ }{ }{ }{ }{ }{ }{ Not here. }\n";
        ANTLRStringStream in = new ANTLRStringStream(source);
        VampireDialogLexer lexer = new VampireDialogLexer(in);
        CommonTokenStream tokens = new CommonTokenStream(lexer);
        VampireDialogParser parser = new VampireDialogParser(tokens);
        parser.dialog();
    }
}

which will print the following to the console:
NPC :: { 1 }{ Where to? }{ Where to? }{ # }{ }{ G.Cabbie_Line = 1 }{ }{ }{ }{ }{ }{ }{ }
PC  :: { 2 }{ Just drive. }{ Just drive. }{ 0 }{ }{ npc.WorldMap( G.WorldMap_State ) }{ }{ }{ }{ }{ }{ }{ Not here. }


text:
Q: How to display last part of string containing multiple dots inside ng repeat? Below are my list of items :
 $scope.items = [
            {id=1,name:'code.lmn.1234.Lodashjs'},
            {id=2,name:'xyz.Suv.Angularjs'},
            {id=3,name:'www.kius.reactjs'}
           ]

Now I want to display last part of name so expected output is like below :
Lodashjs
Angularjs
reactjs

I don't want to create filter for this as that will impact performance. So is there any way to do this without filter?

var app = angular.module("myApp", []);
        app.controller("myController", function ($scope) {
        $scope.items = [
            {id:1,name:'code.lmn.1234.Lodashjs'},
            {id:2,name:'xyz.Suv.Angularjs'},
            {id:3,name:'www.kius.react.js'}
           ]

});

   {{item.name}}

A: Try this:

   {{ item.name.split('.').reverse()[0] }}

A: Yes it's so simple.
Just copy paste the below code:

   {{(item.name).substr((item.name).lastIndexOf('.') + 1, (item.name).length)}}

A: You can also use directive that will manipulate the name and return string after last "." dot.

    app.directive("myDirective", function(){
      return {
       scope: {
         "myDirectiveFn": "="
       },

       link: function(scope){
         scope.myDirectiveFn.match(/([^.]+)$/);

       }
      }
    });


text:
Q: WebPack dependency cannot be resolved in generated js with __webpack_require__ syntax TL;DR

*

*I'm using ts-loader for compiling TypeScript => JavaScript

*I have a dependency const WebSocket = require('ws'); in my uncompiled typescript code

*It gets compiled into var WebSocket = __webpack_require__(333); in my js output file

*This causes errors!

*If I manually revert var WebSocket = __webpack_require__(333); => const WebSocket = require('ws'); in the generated js file, the error can be avoided.

Therefore, my question is:
=> Can I "force" webpack to compile the dependency const WebSocket = require('ws'); => const WebSocket = require('ws'); (no changes)?
If there is any other way to enforce this dependency in the generated file, I'm happy to hear other suggestions as well of course.
Long story & background info
I'm trying to setup an angular 6 universal ssr (server-side rendering) scenario with websockets. I use webpack to compile the nodejs webserver from typescript => javascript. I keep getting an error "ReferenceError: WebSocket is not defined". After 2 weeks of troubleshooting, I finally figured out, that nodejs doesn't have native websocket support (browser has). So after adding "ws": "^6.0.0" to my package.json and importing it  (const WebSocket = require('ws');) into my webpack-compiled js file, I finally got it to work! However, if I import it into the uncompiled ts file, it will be compiled into var WebSocket = __webpack_require__(333); which doesn't work.
Apologies & Disclaimer
I also opened issues in the respective repos (https://github.com/angular/universal/issues/1042 & https://github.com/ReactiveX/rxjs/issues/3942), but nobody was able to help me. My question might be misleading, due to my very limited understanding of how webpack works. If this should be the case, I'm deeply sorry.


text:
Q: How to create a constant flow I am trying to create a constant flow of sprites moving from right to left.
The objects moving will be cars and the player needs to move the turtle across the road. However, I need to constantly add more manually. Is there a way to automate cars moving across in a random formation in a loop?
I've included my code so far below.
from turtle import Turtle
import random

COLORS = ["red", "orange", "yellow", "green", "blue", "purple"]
STARTING_MOVE_DISTANCE = 5
MOVE_INCREMENT = 10

class CarManager:

    def __init__(self):
        self.all_car = []
        self.car_speed = STARTING_MOVE_DISTANCE

        for cars in range(0, 10):
            new_car = Turtle("square")
            new_car.shapesize(1, 2)
            new_car.color(random.choice(COLORS))
            new_car.penup()
            random_x = random.randrange(-300, 300)
            random_y = random.randrange(-230, 250, 20)
            new_car.goto(random_x, random_y)
            self.all_car.append(new_car)

    def move_cars(self):
        for car in self.all_car:
            car.backward(self.car_speed)

import time
import turtle
from turtle import Screen
from player import Player
from car_manager import CarManager
from scoreboard import Scoreboard

screen = Screen()
screen.setup(width=800, height=600)
screen.tracer(0)

player = Player()
car_manager = CarManager()

screen.listen()
screen.onkey(player.go_up, "Up")

game_is_on = True
while game_is_on:
    time.sleep(0.1)
    screen.update()

    car_manager.move_cars()

screen.exitonclick()


text:
Q: FetchError: request to https://rf-werf.rdvd.com:3000/v1/locales failed, reason: connect ECONNREFUSED fe80::9030:9b22:8639:bfb3:3000 I am working on one windows application where one layer is built on top of Node.js where we basically calling one language API to get the list of languages.
Earlier when we were using Node v16.14.2, node-fetch -: 3.2.9, OS -: Windows10. It was working fine. But recently I only upgraded node from v16.14.2 to v18.5.0.
Now I am calling language API to get list of languages and it's not working and getting below error
FetchError: request to https://rf-werf.rdvd.com:3000/v1/locales failed, reason: connect ECONNREFUSED fe80::9030:9b22:8639:bfb3:3000
    at ClientRequest.<anonymous> (file:///C:/ASHISH_BUTOLA/broker/node_modules/node-fetch/src/index.js:108:11)
    at ClientRequest.emit (node:events:537:28)
    at TLSSocket.socketErrorListener (node:_http_client:465:9)
    at TLSSocket.emit (node:events:537:28)
    at emitErrorNT (node:internal/streams/destroy:151:8)
    at emitErrorCloseNT (node:internal/streams/destroy:116:3)
    at process.processTicksAndRejections (node:internal/process/task_queues:82:21) {
  type: 'system',
  errno: 'ECONNREFUSED',
  code: 'ECONNREFUSED',
  erroredSysCall: 'connect'
}

Here is my code which I tried.
    import fetch from 'node-fetch';
    import { Agent } from 'https';
    import { certificates } from '@self-trend/v2-util'; // private npm to get certificates

    async function getSupportedLanguages (payload) {
        let options = {
            method: 'GET',
            headers: {
                "user-agent":"broker v4.7.1",
                "content-type":"application/json",
                }
        }
        const isSecure = true // isSecure = false in cloud mode
        if (isSecure) {
            options.agent = new Agent(await getAgentOptions());
        }
        // Language API to get list of languages.
        const url = 'https:///rf-werf.rdvd.com:3000/v1/locales'
        try {
            const response = await fetch(url, options)
            console.log(`Options is ****${JSON.stringify(response)}`)
        }
        catch (err) {
            console.log(err)
        }
    }

    async function getAgentOptions () {
        const certs = await certificates.list();
        const agentOptions = {
          ca: [certs.root],
          cert: [certs.client],
          key: [certs.clientKey]
        };

        return agentOptions;
    }

So We basically call getSupportedLanguages function then inside it calling languages API to get list of languages. Do I need to add some extra params to agentOptions to make it work with v18.5.0 or something else in above code. Because above API works fine with Node(v18.5.0) in cloud where we don't add agents or certificate with HTTPS request.
So I think might be something missing with agents. But not sure. I tried with different node-fetch version but still not working. I called a public API(https://api.publicapis.org/entries) just to test if other API's are invoked or not. So Public API is working fine with Node(v18.5.0). Not able to figure out why languages API(https:///rf-werf.rdvd.com:3000/v1/locales) is not working with Node(v18.5.0)


text:
Q: textbox Insert and remove function in vb.net or c# How to update the text from the TextBox control?
Consider a TextBox that already contains the string "Wel"
To insert text in the TextBox, I use:
   TextBox1.Text = TextBox1.Text.Insert(3, "come")

And to remove characters from the TextBox:
    TextBox1.Text = TextBox1.Text.Remove(3, 4)

But I need to be able to do this:
    TextBox1.Text.Insert(3, "come");
    TextBox1.Text.Remove(3, 4);

However, this code doesn't update the TextBox.
It this possible?
Can this be accomplished via the append method?

A: Text property of TextBox is of type string which is immutable it's not possible to change the existing string. Insert() or Remove() returns a new instance of string with the modification and you will have to assign this new instance back to TextBox's Text property.
There is TextBox.AppendText() that you might be interested in. It appends text to the end of the string but you cannot do anything like Insert() or Remove() with it though.
EDIT:
for your keypress, you could do something like this
        char charToReplace = (char) (e.KeyChar + 1);    // substitute replacement char
        textBox1.SelectedText = new string(charToReplace,1);
        e.Handled = true;

A: 'string' is a immutable type, so each time string value changes new memory is allocated. So if you want to insert or remove text from TextBox, you have to assign it back to TextBox.Text property. However, if you just want to append text to the TextBox.Text, you can do
textBox.AppendText("Hello");


text:
Q: Alternative to Html.ValidationMessage In a view in MVC 5 I could do something like this to render a textbox and validation for it:
@Html.TextBox("Comment")
@Html.ValidationMessage("Comment")

If I was binding to a property on the model in a MVC Core View I would do this:
<input asp-for="Comment"/>

But what is the MVC Core alternative to Html.ValidationMessage to render a validation span tied to an input that's not bound to the model?

A:

is tied only in your property

this validation is for the model you could also set asp-validation-summary="All"


text:
Q: How to define dynamic values as constant in laravel I have a following method where i am simply submit the form and works absolutely fine
but i need to defie the follwing path in constant
$pathToStoreFile = public_path() . '/cases/' . $caseNumber . '/filesBefore/' . $revisions;

How can i do that. if i define in config then how can i pass the dynamic values in config array.
or if do  define("pathToStoreFile", public_path() . '/cases/' . $caseNumber . '/filesBefore/' . $revisions); then is there any difference in
$pathToStoreFile = public_path() . '/cases/' . $caseNumber . '/filesBefore/' . $revisions; and  define("pathToStoreFile", public_path() . '/cases/' . $caseNumber . '/filesBefore/' . $revisions);
public function caseSubmit(CaseStoreRequest $request)
        {
            $validator = $request->validated();

            $allowedfileExtension = ['stl'];

            $portal = $request->input('portal');
            $case_number = $request->input('case_number');
            $file_before = $request->file_before;
            $file_after = $request->file_after;

            $user_id = Auth::id();

            $caseifExist = Cases::where('case_number', "$case_number")->first();

            if ($caseifExist != null) {
                $caseId = $caseifExist->id;
                $caseNumber = $caseifExist->case_number;

                $number_of_patients = Cases::find($caseId)->patients;
                $revisions = count($number_of_patients) + 1;

            } elseif ($caseifExist == null) {

                $revisions = 0;
                $caseInputData = ['patient_name' => $patient_name,
                    'doctor_name' => $doctor_name,
                    'case_number' => $case_number,
                    'created_at' => $date,
                    'user_id' => $user_id,
                    'portal_id' => $portal_id
                ];

                $case = new Cases();

                $case_data = $case->storePatientCase($caseInputData);
                $caseId = $case_data->id;
                $caseNumber = $case_data->case_number;
            }

                /** code for move files before **/
               $pathToStoreFile = public_path() . '/cases/' . $caseNumber . '/filesBefore/' . $revisions;
                $filesBefore = $this->multiplefileUpload(pathToStoreFile, $file_before, $allowedfileExtension);
                $pathToStoreFile = public_path() . '/cases/' . $caseNumber . '/filesAfter/' . $revisions;
                $filesAfter = $this->multiplefileUpload($pathToStoreFile, $file_after, $allowedfileExtension);

        }


text:
Q: How can I make the footerview always stay at the bottom in UITableViewController? I am using a UITableviewcontroller and I want the footer view to always stay at the bottom of the screen. However, the y position of the footer view is changing as per the height of the tableviewcell. How can I always make it stick to the bottom of the screen?

A: The tableview footer view would always stay at the bottom of the tableview and would always scroll with it. If you need to make the footer view fixed at the bottom then you can not use a TableViewController.You will have to use UIViewController , put your tableView as a subview. Put the footer also as another subview and its done.

A: A footer is always added to the bottom of the content size. So my approach is
Approach 1: (Available for Both Static and Dynamic TableView)
Add a ViewController in Storyboard and set your footer view(or button) at the bottom of the ViewController.
Add a ContainerView in the ViewController and set constraint
Add a UITableViewController and embedded the tableview in the container view
Approach 2: (Available for both Dynamic TableView)
Add a ViewController, set footer view in the bottom, add UITableView and set your auto layout.
You can't set static tableview in a UIViewController

A: If you want to keep footerview always at the bottom of the tableview without floating property like footer for section then can use
tableView.tableFooterView = customFooterView

A: Swift Code which make the footerView fill the rest space at the bottom,
then you can use autolayout to make you view at the bottom in the footerView:
override func viewDidLayoutSubviews()
{
    super.viewDidLayoutSubviews()

    guard let footerView = tableView.tableFooterView else
    {
        return
    }

    var cellsHeight:CGFloat = tableView.tableHeaderView?.frame.height ?? 0

    let sections = self.numberOfSections(in: tableView)
    for section in 0..<sections
    {

        let rows = self.tableView(tableView, numberOfRowsInSection: section)

        for row in 0..<rows
        {
            let indexPath = IndexPath(item: row, section: section)
            cellsHeight += self.tableView(tableView, heightForRowAt: indexPath)
        }
    }

    var frame = footerView.frame

    frame.size.height = tableView.contentSize.height - cellsHeight;
    frame.origin.y = cellsHeight

    footerView.frame = frame
}

A: You cannot use a UITableViewController, but it's not necessary anyway.  You can easily add a UITableView to a regular UIViewController, and just use auto layout to add a UIView below the UITableView.  Here's a simple example, adding a red UIView below the UITableView:
import UIKit

class MyFooterTableViewController: UIViewController {

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    var data = [ "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve"]

    override func viewDidLoad() {
        super.viewDidLoad()
        self.tableView.dataSource = self
    }

    @IBOutlet weak var tableView: UITableView!

}

extension MyFooterTableViewController: UITableViewDataSource {
    // MARK: - Table view data source

    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return data.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "TableCellTest", for: indexPath)

        cell.textLabel?.text = data[indexPath.row]
        cell.detailTextLabel?.text = "BANANA"
        return cell
    }
}

The constraints on the Storyboard look like this:

The end result is this:

Full project code is here:
https://www.dropbox.com/s/pyp42nzumquompp/TableViewFooter.zip?dl=0

A: Override existing method of UiTableView
func allowsFooterViewToFloat() -> Bool {
return true
}


text:
Q: How to update embedded arrays with Horizon? What is an example of implementing embedded arrays with Horizon? So if the model were something like this:
{
  "$hz_v$": 9 ,
  "id":  "u012345" ,
  "userName": "Productive Joe",
  "todos": [
     {
       "id": "t012345",
       "text" : "First TODO",
       "date": "Thu Mar 23 2017 23:30:40 GMT-0700 (PDT)"
     },
     {
       "id": "t012346",
       "text" : "Second TODO",
       "date": "Fri Mar 24 2017 13:46:40 GMT-0700 (PDT)"
     },

  ]
}

I am trying to figure out how to update elements to the "todos" array. Say (1) if I have matching todos id, I want to update the todo and if not (2) push the new todo to the "todos" array.
My first thought was to try find(id) and upsert(), but I can't figure out the correct implementation.

A: You can do array.push() and then use the lodash uniq to remove duplicate: https://lodash.com/docs/4.17.4#uniq