text:
Q: Can't access samba share over VPN Samba share is on Ubuntu 8.04
Samba config is below:

# Name mangling options
;   preserve case = yes
;   short preserve case = yes

# Most people will find that this option gives better performance.
# See smb.conf(5) and /usr/share/doc/samba-doc/htmldocs/speed.html
# for details
# You may want to add the following on a Linux system:
#         SO_RCVBUF=8192 SO_SNDBUF=8192
   socket options = TCP_NODELAY

#======================= Share Definitions =======================

[public]
        comment = Public Directory
        path = /home/public
        # inherit permissions = no
        # public = yes
        read only = no
        # writeable = yes
        # force create mode = 0775
        # force directory mode = 6775
        # force user = nobody
        # force group = users
        guest ok = yes
        guest only = yes

Out put from samba error log when I try to connect to the share over vpn:

[2011/04/07 15:01:23, 0] lib/access.c:check_access(327)
  Denied connection from  (10.0.1.2)
[2011/04/07 15:01:23, 1] smbd/process.c:process_smb(1062)
  Connection denied from 10.0.1.2
[2011/04/07 15:01:23, 0] lib/access.c:check_access(327)
  Denied connection from  (10.0.1.2)
[2011/04/07 15:01:23, 1] smbd/process.c:process_smb(1062)
  Connection denied from 10.0.1.2
[2011/04/07 15:01:31, 0] lib/access.c:check_access(327)
  Denied connection from  (10.0.1.2)
[2011/04/07 15:01:31, 1] smbd/process.c:process_smb(1062)
  Connection denied from 10.0.1.2

I'm trying to access this share on Windows 7.
If anyone request any other information I'll post here:
When connecting via VPN my ip will be 10.0.1.x
On site it would be 10.0.0.x
IPTABLES -L shows no rules set up

A: The error log is pretty clear :
Connection denied from 10.0.1.2
Denied connection from  (10.0.1.2)

I guess the VPN clients are not in the same subnet as the lan, and there is some kind of ACL on the samba server to deny request from clients that are not on your lan.
Edit:
looking at your other question regarding this issue, your lan appears to be in 10.0.0.0/24. The client is in 10.0.1.2(/24 ?). The network acl issue make sense.
Edit2:
This should be Samba access-lists, not iptables. If iptables were blocking, the packets would have been dropped and nothing appeared in the logs.
Edit3:
Try to add the following in your smb.conf :
hosts allow = 10.0.0.0/255.255.254.0

and reload samba. This should allow networks 10.0.0.0/24 and 10.0.1.0/24 to access the shares.


text:
Q: whoami returns user but usermod complains it doesn't exist I have a linux(ubuntu) user "myuser"
whoami is able to return the username
myuser@host:/home/myuser$ whoami
myuser

id returns info related to the user too
myuser@host:~$ id
uid=43350(myuser) gid=600(staff) groups=600(staff),27(sudo)

Now I am trying to run docker commands without sudo. So I tried adding the user to the group, but usermod says user does not exist
myuser@host:/home/myuser$ sudo usermod -aG docker $USER
usermod: user 'myuser' does not exist

How do I fix this?
Edit: This is on a VM provided by corporate IT in my organization

redpajama_set_name: RedPajamaStackExchange


text:
Q: BinaryFormatter Deserialize randomly hangs while deserializing a NetworkStream I've tried to omit as much code as possible without obscuring the real problem areas.  If anyone needs to see the full code, let me know.
So we have built a dead simple TCP application that mitigates database connections, and handles all inbound database requests from a single node.  This code handles about 200,000 connections (requests and responses) and then somewhere randomly will hang on the BinaryFormatter.Deserialize method when receiving the request.  Does anyone have any ideas as to why this is happening?
There is no exception generated, it just hangs indefinitely.
The server code:
public class TCPServer
{
    /// <summary>
    /// The listener which listens for inbou nd requests.
    /// </summary>
    private TcpListener _tcpListener;

    /// <summary>
    /// The thread the inbound listener operates on.
    /// </summary>
    private Thread _listenerThread;

    private static object       _lockObject = new object();

    public TCPServer()
    {
        _tcpListener = new TcpListener( IPAddress.Any, 19926 );
        _listenerThread = new Thread( new ThreadStart( ListenForClients ) );
        _listenerThread.Start();
        //Get the server's ip so that the server can connect to its own database.
        DAL.ServerIP = GetLocalIP();
    }

    /// <summary>
    /// Waits for new clients to communicate.  When a new client request is heard,
    /// the connection is given its own processing thread.
    /// </summary>
    private void ListenForClients()
    {
        _tcpListener.Start();

        while( true )
        {
            TcpClient client = _tcpListener.AcceptTcpClient();
            Thread clientThread = new Thread( delegate()
            {
                //Pass in the Current Thread Number so that it can be locked in
                HandleClientComm( client );
            } );
            clientThread.Start();
        }
    }

    /// <summary>
    /// Handles all of the connections for requests.  After a request is recieved, the
    /// TcpClient is passed to this method in its own thread for processing.  This is
    /// where all of the magic happens.  Here we deserialize the NetworkStream and
    /// use the resulting object to determine which request the client is making, and
    /// respond appropriately.
    /// </summary>
    /// <param name="client"></param>
    private void HandleClientComm( object client )
    {
        lock( _lockObject )
        {
            Response response = new Response();
            TcpClient tcpClient = (TcpClient) client;
            try
            {
                NetworkStream clientStream = tcpClient.GetStream();

                IFormatter formatter = new BinaryFormatter();
                object result = formatter.Deserialize( clientStream );

                //Determine which type of request this is
                Response response = new Response();

                //Code Omitted, Determine which type of request, and use that to formulate the response.

                RespondToClient( tcpClient, response );
            }
            catch( Exception e )
            {
                response = new Response();
                response.ErrorMessage = e.ToString();
                RespondToClient( tcpClient, response );
            }
        }
    }

    private void RespondToClient( TcpClient client, Response response )
    {
        try
        {
            IFormatter formatter = new BinaryFormatter();
            NetworkStream stream = client.GetStream();
            formatter.Serialize( stream, response );

            stream.Close();
            client.Close();
        }
        catch( Exception e )
        {
            throw e;
        }
    }
}

The Client Code:
public class TCPClient
{
    public static string ServerIP = "192.168.2.200";

    private static Response RequestTCP<T>(T request)
    {
        try
        {
            TcpClient client = new TcpClient();
            IPEndPoint serverEndPoint = new IPEndPoint( IPAddress.Parse( ServerIP ), 19926 );

            client.Connect( serverEndPoint );
            NetworkStream stream = client.GetStream();
            IFormatter formatter = new BinaryFormatter();

            formatter.Serialize( stream, request );
            Response response = ( Response ) formatter.Deserialize( stream );
            return response;
        }
        catch( Exception e )
        {
            return new Response( "Error with the Response: " + e.ToString() );
        }
    }
}


text:
Q: Changing Navbar Elements Depending On the Page Using an If Statement Is there a way to use an if statement to manipulate elements in a navbar based on what page you are on?
For example, what I'm trying to do is that I made my navbar on my homescreen transparent and the link texts are black. If I hover over a navbar link, the link text becomes white with a black background (this is what my class nav-font accomplishes). See below screenshot:

However, I want this color scheme to be inverted (or opposite) for all other pages that aren't the home page. Is this currently possible with Rails?
So I want to do the following in my layout file (application.html.erb) using the following pseudocode:
<% if we're on the homepage %>

<%= link_to "About", about_path %>

<%= link_to "Contact", new_contact_path %>

<% else %>

<%= link_to "About", about_path %>

<%= link_to "Contact", new_contact_path %>

<% end %>

What I want to know is:

*

*Is this possible? If so, how might I go about accomplishing this?

*If not, is there a simpler solution or alternative?

A: try
<% if controller_name == "your controller" && action_name = "your method" %>

<%= link_to "About", about_path %>

<%= link_to "Contact", new_contact_path %>

<% else %>

<%= link_to "About", about_path %>

<%= link_to "Contact", new_contact_path %>

<% end %>


text:
Q: Is there a hotkey to switch between tabs in Caja? I am using Ubuntu 16.04 MATE, and am wondering whether there is a hotkey to switch between tabs in Caja? In Nautilus, it is possible to switch tabs with STRG + Tab, but in Caja, this doesn't work. Is there another hotkey, or is it possible to define STRG + Tab as hotkey for this action?

A: Try ctrl + page_down / page_up.
Works for me in Caja 1.12.7, ubuntu mate 16.04.2


text:
Q: Few Query about wcf with SSL & Certificate here i am asking few basic question about wcf ssl & certificate
i am new in wcf and also to be very honest that i have basic problem to understand the SSL & certificate.
1) i like to know that when we enable SSL then every time we need to use certificate or the same way when we attach certificate with wcf then SSL will be used implicitly.
2) SSL & Certificate both are same or different in concept ?
3) when we self host wcf service then can we enable SSL or certificate...which one will be applicable ?
4) tcp binding for certificate is not related with http. so when we work with tcp binding then can we enable SSL for tcp binding.
5) what is difference between SSL & Certificate ?
6) when we use certificate at service end then client end which consume & call the service they always need to install certificate. if not then when client need to install certificate & when not required. one guy told me that client need to install certificate only when mutual authentication is required but i do not know about what mutual authentication ?
i know i asked very basic question. if possible please explain all my points in details to clear my doubts. thanks
UPDATE
1) i like to know that when we enable SSL then every time we need to use certificate or
the same way when we attach certificate with wcf then SSL will be used implicitly.
you said as follows :-
When enabling Transport security the endpoint address must include the HTTPS protocol,
otherwise an exception will be thrown when you go to start the service. For HTTPS to work on that endpoint,
then you need an X.509 Certificate bound to the specified port as well.
why you said this :- When enabling Transport security the endpoint address must include the HTTPS protocol
https come to play when we host our wcf service in IIS. suppose when we host wcf service in self host
and tcp used as binding then why we need to include https in endpoint because you said enabling Transport
security and endpoint address must include the HTTPS protocol....is it correct ? may be i could not understand
what you are trying to say. can you please explain in detail what you are trying to say for the point 1
6) when we use certificate at service end then client end which consume & call the service they always
need to install certificate. if not then when client need to install certificate & when not required.
one guy told me that client need to install certificate only when mutual authentication is required
but i do not know about what mutual authentication ?
here i just trying to know that when wcf service will hosted and attached with certificate then is it mandatory
that client who consume the service he/she need to use certificate at client end ?
i guess it is not mandatory. only two end use certificate when mutual authentication would be consider.
am i right ?
in case of mutual authentication server & client end need to install or use same certificate or client can use different certificate purchase from abc.com and server end purchase certificate from xyz.com.
please clearly discuss my above two points in details. thanks for your time & answer.

A: Okay here we go:

1) i like to know that when we enable SSL then every time we need to
  use certificate or the same way when we attach certificate with wcf
  then SSL will be used implicitly.

When enabling Transport security the endpoint address must include the HTTPS protocol, otherwise an exception will be thrown when you go to start the service. For HTTPS to work on that endpoint, then you need an X.509 Certificate bound to the specified port as well.

2) SSL & Certificate both are same or different in concept ?

SSL certificates are a type of X.509 Certificate*. In TLS (which SSL is a predecessor of), virtually all certificates are X.509 certificates.

3) when we self host wcf service then can we enable SSL or
  certificate...which one will be applicable ?

When using Transport level security, the Self-Hosted Service will make use of the X.509 certificate bound to the port of the endpoint that it is listening at. Setting the service certificate will have no impact in this case.

4) tcp binding for certificate is not related with http. so when we
  work with tcp binding then can we enable SSL for tcp binding.

Yes, Transport level security provided for TCP is Windows security by default which is SSL over TCP. When using SSL over TCP, you must explicitly specify the certificate by using the SetCertificate method on the Self-Hosted Service.

5) what is difference between SSL & Certificate ?

As stated above, essentially SSL is a subset of X.509 Certificates - technically speaking the relationship isn't as simple as that, but typically you use X.509 Certificates for SSL\TLS.

6) when we use certificate at service end then client end which
  consume & call the service they always need to install certificate. if
  not then when client need to install certificate & when not required.
  one guy told me that client need to install certificate only when
  mutual authentication is required but i do not know about what mutual
  authentication ?

Mutual SSL authentication is when the client and server each provide a digital certificate so each party can verify the identity of the other. Here's a great article on Mutual SSL Authentication if you're interested.
This isn't necessary though and only one of the many options you have when using Transport security - see more options here: HttpClientCredentialType.
You can also still do security at the Transport level while passing credentials at the Message level by using TransportWithMessageCredential - then you can use set Client Credentials to use a BasicHttpMessageCredentialType and use UserName instead.
*: Other types of certificates can be used for SSL\TLS such as OpenPGP - but it is far from common.


text:
Q: How use OOP in component state of Reactjs? I want store custom instance of class in component state, but i don't know how change data on correct way
Before change instance i make clone of object.
For example i have a custom object with some properties:
this.state={
 user: new User();
}

when need change data i make
const user = _.cloneDeep(this.state.user);
user.setSettings(/*some object of settings*/)
this.setState({user});

It's ok use cloneDeep every time? Maybe there's a better way change data and do not break react life cycles?

A: It's generally inappropriate to use cloneDeep on class instances since a class can have instantiation logic that breaks when an instance is cloned. It's preferable to create a new class instance with new, a class also should support cloning in order for new instance to be successfully hydrated from existing instance:
Foo.clone(fooInstance)

Where clone is something like:
class Foo {
  static clone(instance) {
    const barArg = instance.bar;
    const bazarg = instance.baz;
    return new Foo(barArg, bazArg);
  }
  ...
}

This puts additional constraints on class design.
Since immutable state is idiomatic to React, the use of class instances complicates state management because of these concerns. This is the reason why it's preferable to use plain objects for React state.


text:
Q: redirect my IE visitors to a different page I made a site which index.php is a short animated series of texts (not my idea, I advised against it, but I'm not the boss) but anyway, my problem with this animation is that it is not supported by IE and it's not responsive either, so it looks crappy in phones as well.
My question is, does anyone here ever heard of a script or jquery I can use that will sniff the browser (IE > 1, Android, IOs, etc) and redirect them to a home.php within the same site?
Perhaps a PHP script with a header: Location...I don't know, anything.
p.s. I've tried everything I've read in stack overflow and nothing works.
This is the closest I've gotten to any response but not quite what I'm looking for
<script type="text/javascript">

  var sBrowser, sUsrAg = navigator.userAgent;

  if(sUsrAg.indexOf("Chrome") > -1) {
    sBrowser = "Google Chrome";
  } else if (sUsrAg.indexOf("Safari") > -1) {
    sBrowser = "Apple Safari";
  } else if (sUsrAg.indexOf("Opera") > -1) {
    sBrowser = "Opera";
  } else if (sUsrAg.indexOf("Firefox") > -1) {
    sBrowser = "Mozilla Firefox";
  } else if (sUsrAg.indexOf("MSIE") > -1) {
    sBrowser = "Microsoft Internet Explorer";
  }

  alert("You are using: " + sBrowser);
</script>

Thanks in advance

A: You have the browser identification working well, just need to redirect using javascript.
So something along the lines of:

var sUsrAg = navigator.userAgent;

if(sUsrAg.indexOf("Mobile") > -1) {
    window.location = '/unsupportedpagemobile.html';
} else if (sUsrAg.indexOf("MSIE") > -1) {
    window.location = '/unsupportedpageie.html';
}

</script>

A: Most CSS animations are handled just fine in modern versions of Internet Explorer. In fact, Internet Explorer supported unprefixed properties before many of its competition. Your CSS animations may not be working in IE due to unbalanced use of vendor prefixes. Are you only targeting things like -webkit-transition and -moz-transition, forgetting to also include transition?
Your animation won't work in earlier versions of Internet Explorer though, unless you polyfill them with jQuery using $.fn.animate to achieve similar behavior. This may or may not be possible considering the type of animation you're doing - if it's just sliding text around, and fading it in/out, then you could most certainly achieve the same effect for older versions of IE.
Last option would be to create IE-specific conditional comments and place within them a script to relocate the user to an alternative experience. Do not engage in browser sniffing; you're going to send users of IE11 (which can handle your modern experience) away, which makes no sense. Instead, use the features provided by the browsers you wish to target; such as conditional comments.
<!--[if lte IE 9]>
  <script>
    /*
      In this space we can do one of two things:
        1) Redirect user to an alternative experience with window.location, or
        2) Provide animations via jQuery .animate method.
    */
  </script>
<![endif]-->


text:
Q: How do I read a .txt file from my One Drive Documents folder with Python? I have registered the app, added read-write permissions on it, gotten admin consent, and gotten the token. When I make a GET request I get an error.
This my Python code:
import requests, sys, os, json

# Get token
params = {
    'client_id': clientID,
    'scope': 'https://graph.microsoft.com/.default',
    'client_secret': clientSecret,
    'grant_type': 'client_credentials'
 }

response = requests.post('https://login.microsoftonline.com/{tenant}/oauth2/v2.0/token', data=params)
jresp = response.json()
access_token = jresp['access_token']

# Get item
header = {'Authorization': 'Bearer ' + access_token}
response = requests.get('https://graph.microsoft.com/v1.0/me/drive/root:/Documents/WildRydes.txt', headers = header)
print response
print response.text
print response.content
sys.exit()

This is what is returned:
<Response [500]>
{
  "error": {
    "code": "BadRequest",
    "message": "Unable to retrieve user's mysite URL.",
    "innerError": {
      "request-id": ,
      "date": "2020-04-29T12:42:06"
    }
  }
}

I have been following the Microsoft Graph API documentation for the past two days straight. They are very good at theory but rubbish at showing concrete examples. Or maybe they're good at hiding where those are.


text:
Q: Spring @ComponentScan doesn't work on @Repository I have a repository in different package than the configuration class , so I annotated it as the following with @Repostiory:
package test;

@Repository
public interface UserTest extends JpaRepository<User, Long> {
}

I have done the component scan on it and it didn't work :
package com.app;
@SpringBootApplication
@ComponentScan({"test","com.app"})
public class Application extends SpringBootServletInitializer {
}

Exception : No qualifying bean of type 'test.UserTest' available: expected at least 1 bean which qualifies as autowire candidate.
why doesn't the component scan work on repository unless I add enableJpaRepositories ? I thought componetScan is enough

Update:
as some of the answers provides solution , I'm asking about explanation not solution . The following will work without even doing component scan on "test" :
SpringBootApplication
@EnableJpaRepositories({"test","com.app"})
public class Application extends SpringBootServletInitializer{
}

Now the question why do I even need to use componentscan on @Repository when it doesn't work ? why in the documentation the @Repository is scanned by componentscan when it doesnt have effect and @EnableJpaRepostiories is enoguh?
from Spring documentation on component scan :
Indicates whether automatic detection of classes annotated with @Component @Repository, @Service, or @Controller should be enabled.
the @Repository in my case is not detected

A: In order to let spring knows what DataSource is related to what Repository you should define it at the @EnableJpaRepositories annotation.
Try enabling jpa repositories like below.
@SpringBootApplication
@ComponentScan({"test","com.app"})
@EnableJpaRepositories("test")
public class Application extends SpringBootServletInitializer {
}

UPDATE : Why @EnableJpaRepositories needed?
@SpringBootApplication automatically provides the features of the following annotations
@Configuration
@EnableAutoConfiguration
@ComponentScan
But if you try defining your own annotation then spring boot will not take care of internal auto configurations so this is the reason we have to enable repositories.
I have projects in which only @SpringBootApplication is enough if you are not writing your own things.
I hope you got the point.
Golden words :
If you want to get the maximum advantage of spring boot's auto configuration feature, it is expected to put all your class packages under spring boot main application package (directly in main package or indirectly as sub packages).

A: I found an explanation about what I was doing wrong. The @Repository annotation with componentscan will not cause spring to implement the spring jpa repository. for the interfaces that implement crud repository enablejparepository should be used.
Now the use of @Repository with componentscan is when you have a repository class and you have your own DAO not for spring curd repo otherwise the implementation won't be created :
@Repository
public class UserTest {

    public List<Object> findById(long l) {

             .......
    }
}

A: you should use your code like below as @ComponentScan always work with basepackages so your implementation should be like below.
 package com.app;
    @SpringBootApplication
    @ComponentScan(basePackages={"test","com.app"})
    @EnableJPARepositories
    public class Application extends SpringBootServletInitializer {
    }


text:
Q: Angular 10 fails to map object from request to interface correctly When getting an object wrapped in a Result class I made, the controller and browser dev tools show the response is correct, however when I console log it from the subscription one of the nested values is undefined while the rest of the object is in tact. I've checked the interface for differences, there are none. Been stuck on this for a bit any help is much appreciated.
From Console.log

From Controller

Result class

Method calling service

service


text:
Q: Is there a way to find given process is Idle? I am working in an java application where i want to make sure that a given process in the computer is idle
ex:- if we start a download process in our computer my application should be able to monitor it (process) and tell when it is over,

A: If you start the process from another process, you can detect when it finishes with Process.waitFor() You can even use its exit code.

A: Most operating systems provide user commands to monitor activity of a process, like CPU or I/O. Or, at a higher level, you can get the status (running or not) of a process by its process identifier. You could exec these tools from Java, but there's nothing in core Java to do this, nor am I aware of any libraries for this purpose.
However, if you are thinking about killing a process because it is "idle", that generally wouldn't be safe. You have to know enough about the process in question to be sure it's okay to kill it, and if you know that much about it, you'll probably find that there's a way to get it to shut itself down cleanly.


text:
Q: Oracle Format Models Million / Billion I am looking to take a number, and truncate / round it and display it with a notation indicator like this:
10000000 --> 10M
1000000045.76 --> 100B
If < 1 Million, just leave it as is.  If >= 1 Million, display the M / B / T notation.   Does Oracle have a format model for this?


text:
Q: concatenate and de-dupe multiple rows I have some incoming rows in the below format.
| Col1 | Col2 | Col3 |
| 1    | A    | 1    |
| 1    | A    | 1,2  |
| 1    | A    | 1,3  |
| 1    | A    | 2,4  |

Desired outputsql is
| Col1 | Col2 | Col3    |
| 1    | A    | 1,2,3,4 |

Basically, group all rows based on Col1 and Col2 and then concatenate and remove duplicates from Col3.
SELECT COL1, COL2, {?????}
FROM TABLEA
GROUP BY COL1, COL2;

I could not think much at this moment. Any pointers would be much appreciated. I am inclined to WX2 database, but any ANSI compliant snippet would be helpful.

A: For SQL Server: first concatenate all col3 values using STUFF method and INSERT INTO CTE table.Based on this CTE tables split all rows as individual into single column based on CTE table.Finally concate all DISTINCT strings with help of STUFF.
 CREATE TABLE #table ( Col1 INT ,   Col2 VARCHAR(10) , Col3 VARCHAR(10))
 INSERT INTO #table ( Col1  ,   Col2  , Col3 )
 SELECT  1   , 'A'   , '1'  UNION ALL
 SELECT  1   , 'A'   , '1,2' UNION ALL
 SELECT  1   , 'A'   , '1,3'  UNION ALL
 SELECT  1   , 'A'   , '2,4'

 ;WITH CTEValues ( Colval ) AS
 (
   SELECT STUFF ( ( SELECT ',' +  Col3 FROM #table T2 WHERE T2.Col2 =
                T1.col2 FOR XML PATH('') ),1,1,'')
   FROM #table T1
   GROUP BY Col2
 )

 SELECT * INTO #CTEValues
 FROM CTEValues

 ;WITH CTEDistinct ( SplitValues , SplitRemain ) AS
 (
  SELECT SUBSTRING(Colval,0,CHARINDEX(',',Colval)),
         SUBSTRING(Colval,CHARINDEX(',',Colval)+1,LEN(Colval))
  FROM #CTEValues
  UNION ALL
  SELECT CASE WHEN CHARINDEX(',',SplitRemain) = 0 THEN SplitRemain ELSE
                   SUBSTRING(SplitRemain,0,CHARINDEX(',',SplitRemain)) END,
         CASE WHEN CHARINDEX(',',SplitRemain) = 0 THEN '' ELSE
        SUBSTRING(SplitRemain,CHARINDEX(',',SplitRemain)+1,LEN(SplitRemain))
        END
  FROM CTEDistinct
  WHERE SplitRemain <> ''
 )

  SELECT STUFF ( ( SELECT DISTINCT ',' +  SplitValues FROM CTEDistinct T2
  FOR XML PATH('') ),1,1,'')

A: You could try with transpose or concatenation functions. The difficulty comes from the fact that col3 is varchar and a conversion is needed to get the distinct values.
With MySQL :
SELECT col1, col2, GROUP_CONCAT(DISTINCT col3) AS col3 FROM
(SELECT col1, col2, CONVERT(SUBSTR(col3, 1), UNSIGNED INTEGER) AS col3 FROM (
SELECT 1 AS col1, 'A' AS col2, '1' AS col3 UNION ALL
SELECT 1 AS col1, 'A' AS col2, '1,2' AS col3 UNION ALL
SELECT 1 AS col1, 'A' AS col2, '1,3' AS col3 UNION ALL
SELECT 1 AS col1, 'A' AS col2, '2,4' AS col3
) AS t
UNION ALL
SELECT col1, col2, CONVERT(SUBSTR(col3, 3), UNSIGNED INTEGER) AS col3 FROM (
SELECT 1 AS col1, 'A' AS col2, '1' AS col3 UNION ALL
SELECT 1 AS col1, 'A' AS col2, '1,2' AS col3 UNION ALL
SELECT 1 AS col1, 'A' AS col2, '1,3' AS col3 UNION ALL
SELECT 1 AS col1, 'A' AS col2, '2,4' AS col3
) AS t1
) AS t2
WHERE col3 <> 0

Result :
col1 | col2 | col3
1    |   A  | 1,2,3,4

A: For Postgres use this:
select col1, col2, string_agg(distinct col3, ',') as col3
from (
   select col1, col2, x.col3
   from tablea, unnest(string_to_array(col3, ',')) as x(col3)
) t
group by col1, col2;

This is largely ANSI compliant except for the string_to_array() and string_agg() function.


text:
Q: Graph Theorem Question - Trees Let $G=(V,E)$ be an undirected tree.
Let $d$ be the maximum degree of a vertex in the tree.
Prove that $G$ has at least $d$ leaves.

I need some help proving this, should I consider a run of BFS on that vertex?
Is that the correct direction?
Thanks!

A: When you cut the tree at the given vertex of maximal degree $d$, you get $d$ separate trees. Show that each such tree has at least two leaves. One of them can possibly be the vertex at which you cut the original tree, but even if you take that into account, you still get $d$ leaves. Show that these leaves are also leaves in the uncut graph.
I leave the details for you to figure out.


text:
Q: Imports other than angular2 deps breaks webapp compilation In my angular 2 application I have issues with importing dependencies other than angular or my application components. (e.g. angular2-moment)
I have <base href="/">
Application runs via main (compilation.js contains all app modules):
<script src="/app/compilation.js"></script>
    <script>
        System.config({
            packages: {
                app: {
                    format: 'register',
                    defaultExtension: 'js'
                }
            }
        });
        System.import('main')
                .then(null, console.error.bind(console));
</script>

As soon as I inject anything from node_modules other than angular it makes the compilation fail. and I get a 404 from main.
import {Component} from "angular2/core";
import {ROUTER_PROVIDERS} from 'angular2/router';
import {HTTP_PROVIDERS} from "angular2/http";
import "rxjs/Rx";
import {HeaderComponent} from "./header/header.component";
import {HomeComponent} from "./home/home.component";
import {SidebarComponent} from "./side-bar/sidebar.component";
import {RouteConfig, ROUTER_DIRECTIVES} from "angular2/router";
import {enableProdMode} from "angular2/core";
//import {TimeAgoPipe} from 'angular2-moment'; <-- this breaks main (404)

The console error:
GET http://localhost:3001/main 404 (Not Found)
scheduleTask    @   angular2-polyfills.js:126

tsconfig is:
{
  "compilerOptions": {
    "target": "es5",
    "module": "system",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "removeComments": false,
    "noImplicitAny": false,
    "outDir": "app/",
    "outFile": "app/compilation.js",
    "declaration": true
  },
  "exclude": [
    "node_modules",
    "typings/main",
    "typings/main.d.ts"
  ]
}

Any help to save more hair on my head would be highly appreciated.

A: OK. Here is the answer but still not sure why things have to be so hard?
Solution only applies to bootstrap and angular moment and don't think all components will be the same.

*

*Define a path for each dependency in System.config

*Define moment to be loaded as a global

Within index.html
System.config({
    packageConfigPaths: ['node_modules/*/package.json'],
    paths: {
        'moment': '/node_modules/moment',
        'angular2-moment/*': '/node_modules/angular2-moment/*',
        "ng2-bootstrap/ng2-bootstrap": "node_modules/ng2-bootstrap/ng2-bootstrap"
    },
    packages: {
        app: {
            format: 'register',
            defaultExtension: 'js'
        }
    },
    meta: {
        moment: {
            format: 'global',
            globals: {
                moment: 'moment'
            }
        }
    }
});

Within ng2:
// you can use ng2-bootstrap file just fine
import {PAGINATION_DIRECTIVES} from 'ng2-bootstrap/ng2-bootstrap';
// but for angular moment also mention extension.
import {DurationPipe} from 'angular2-moment/DurationPipe.js';

Now with all this:
@Component({
    "selector": "my-component",
    directives: [PAGINATION_DIRECTIVES],
    pipes: [DurationPipe],
    "templateUrl": "app/templates/my-template.html",
})

I think I am pulling my hair out more now than when I asked the question.
Someone please clarify some of this for me.


text:
Q: Android Local VPN - filter URLs I'm trying to implement a local VPN service in my app to register the entrance to the address: example.com
Something like firewall app for Android.
As an example I used: https://github.com/hexene/LocalVPN
Regarding this example I'm able to set breakpoint in the process loop and debug packages.
But only what I get is: source/destination IP, HOST, protocol and other:
W/VPNRunnable: IP4Header{version=4, IHL=5, typeOfService=0, totalLength=40, identificationAndFlagsAndFragmentOffset=884883456, TTL=64, protocol=6:TCP, headerChecksum=14993, sourceAddress=10.0.0.2, destinationAddress=172.217.20.166, hostNameDesc=waw02s07-in-f166.1e100.net, hostNameSour=waw02s07-in-f166.1e100.net}

My question: It is possible to determine what is the full URL of the request?
URL like: http://example.com/test/page?a=111&b=222


text:
Q: How can I do an if statement inside the jQuery? I'm using the jQuery datimepicker (https://xdsoft.net/jqplugins/datetimepicker/)
And I would like to make an if statement in my date picker like this:
var a = 2;
$("#datetimeTo").datetimepicker({
        minDate:reservationDate,
        maxDate: '+1970/02/01',
        if(a == 2){
            minTime:'20:00',
        } else {
            minTime:'06:00'
        },
        format:'d/m/Y H:i',
        maxTime:'23:00'
  });

But it doesn't work...

A: You don't have to use if-else there. A ternary operator will work there.
    var a = 2;
    $("#datetimeTo").datetimepicker({
        minDate:reservationDate,
        maxDate: '+1970/02/01',
        minTime: a == 2?'20:00':'06:00',
        format:'d/m/Y H:i',
        maxTime:'23:00'
    });


text:
Q: Error after compiling "Thread 1: signal SIGABRT I am getting this error after compile my app the app is just frozen it worked before, but now it freezing and not loading. Code where it shows this error:
#import <UIKit/UIKit.h>

int main(int argc, char *argv[]) {

NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

int retVal = UIApplicationMain(argc, argv, nil, @"AppController");//(error is on this line)

[pool release];

return retVal;

}


text:
Q: Interactive pre-generated views I'm using a WPF application that reads data by a WCF application hosted in IIS.
To get data from the database I use Entity Framework 6.
My application is initial very slow therefore I wanted to use Interactive views. When I start my application the initial call is made and the views are created (a XML file). When I reset my application pool my program doesn't use the generated views in the XML but it creates again the XML file.
With this code the XML is created:
using (var ctx = new DataReportingContext(request.ConnectInfo))
{
    InteractiveViews
        .SetViewCacheFactory(
            ctx,
            new FileViewCacheFactory(@"d:\log\MyViews.xml"));
}

How can I re-use the views so I don't get the initial create of the views?


text:
Q: What am I doing wrong with 2's complement? Trying to understand why ~8 is -9.
My incorrect math is as follows:
1.) 8 in binary is 1000.
2.) Invert all bits: 0111.
3.) Add 1: 1000.
....and now I've got the same thing I started with. What am I doing wrong here?

A: Four bits can only represent -8 .. 7 in two's complement. To do your math on 8 you'll need at least five bits.
What you've done here is basically an overflow, as your 8 value is originally encoded as -9 anyway.
Here's a reworked version:
 8 = 01000
~8 = 10111
+1 = 11000

The secondary component of that is 1000, which when inverted is 0111, which is 7, and 7+1, accounting for the offset, puts you back at 8.

A: Let's work in 8 bits.
8 = 00001000
9 = 00001001

~8 = 11110111 Inverse of 8

Now let's do the 2's complement of 9 to get -9
00001001 9
11110110 Inverse
11110111 Add 1
-9 = 11110111

Note that ~8 = -9


text:
Q: React-Bootstrap / Panel / Font Awesome - How do I have a font awesome icon in the header of a panel For a panel, I wanted to have a font awesome icon in the header with some title. How do I do that?
Want to use:
<Panel header = "Panel Title" bsStyle="primary">
</Panel>

But I need something like this:

      Panel Title

A: As i recall you can add an Element in the header attribute
<Panel header={
 Header
}>Content</Panel>

or
const title = (

     Header

);

<Panel header={title}>Content</Panel>

hope this helps.


text:
Q: Built-in Ethernet not working I am using a 13" MacBook Pro (mid 2012) and I have upgraded to OS X 10.11 El Capitan a while ago. Last night before going to bed I switched off the computer. Since this working the built-in Ethernet that was working fine does not seem to work anymore. I have deleted the network interfaces and rebooted the system, but still it does not show up in the network preferences. Is there a fix? What should I do?

A: For a very short window (a few hours) - Apple pushed an update that disabled the ethernet driver for some of the Macs.
If you can connect to WiFi and run this command:
sudo softwareupdate --background

That would fix the issue if yours failed to operate due to this bug. The details are covered at

*

*https://support.apple.com/HT205956
Also some more details are on this post:

*

*Ethernet not working on MacBook pro retina 13


text:
Q: How do I interpret these crash reports from iOS Hi I have had an iOS app in review, but it just got rejected... I have been trying to stimulate my ipad with iOS 6.1.3 to make it crash as described by apple:
Your app crashed when we tapped the action or option buttons.
But im failing, can the exact procedure of the crash be read from the report below?
Im suspecting they are doing something really crazy, can you tell me if the crash is network related? or if they have been pushing a certain button? I myself cant find enough information:
Symbolicated:
Exception Type:  EXC_CRASH (SIGABRT)
Exception Codes: 0x0000000000000000, 0x0000000000000000
Crashed Thread:  0

Last Exception Backtrace:
0   CoreFoundation                  0x32b0629e __exceptionPreprocess + 158
1   libobjc.A.dylib                 0x3a9aa97a objc_exception_throw + 26
2   CoreFoundation                  0x32b061c0 +[NSException raise:format:] + 100
3   UIKit                           0x34aab56c -[UINib instantiateWithOwner:options:] + 1632
4   UIKit                           0x34aaab96 -[UIViewController _loadViewFromNibNamed:bundle:] + 230
5   UIKit                           0x349a3038 -[UIViewController loadView] + 88
6   UIKit                           0x3492d468 -[UIViewController loadViewIfRequired] + 64
7   CodeFriend                      0x0000fb14 -[ThemesPopOverViewController initWithNibName:bundle:] (ThemesPopOverViewController.m:24)
8   CodeFriend                      0x0000e21a -[AppDelegate settingAct:] (AppDelegate.m:127)
9   UIKit                           0x349f90c0 -[UIApplication sendAction:to:from:forEvent:] + 68
10  UIKit                           0x349f9072 -[UIApplication sendAction:toTarget:fromSender:forEvent:] + 26
11  UIKit                           0x349f9050 -[UIControl sendAction:to:forEvent:] + 40
12  UIKit                           0x349f8906 -[UIControl(Internal) _sendActionsForEvents:withEvent:] + 498
13  UIKit                           0x349f8dfc -[UIControl touchesEnded:withEvent:] + 484
14  UIKit                           0x349215ec -[UIWindow _sendTouchesForEvent:] + 520
15  UIKit                           0x3490e7fc -[UIApplication sendEvent:] + 376
16  UIKit                           0x3490e116 _UIApplicationHandleEvent + 6150
17  GraphicsServices                0x3660259e _PurpleEventCallback + 586
18  GraphicsServices                0x366021ce PurpleEventCallback + 30
19  CoreFoundation                  0x32adb16e __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__ + 30
20  CoreFoundation                  0x32adb112 __CFRunLoopDoSource1 + 134
21  CoreFoundation                  0x32ad9f94 __CFRunLoopRun + 1380
22  CoreFoundation                  0x32a4ceb8 CFRunLoopRunSpecific + 352
23  CoreFoundation                  0x32a4cd44 0x32a44000 + 36164
24  GraphicsServices                0x366012e6 GSEventRunModal + 70
25  UIKit                           0x349622fc UIApplicationMain + 1116
26  CodeFriend                      0x0000d3b6 main (main.m:16)
27  libdyld.dylib                   0x3ade1b1c start + 0

Thread 0 name:  Dispatch queue: com.apple.main-thread
Thread 0 Crashed:
0   libsystem_kernel.dylib          0x3aea8350 __pthread_kill + 8
1   libsystem_c.dylib               0x3ae1f11e pthread_kill + 54
2   libsystem_c.dylib               0x3ae5b96e abort + 90
3   libc++abi.dylib                 0x3a3f9d4a abort_message + 70
4   libc++abi.dylib                 0x3a3f6ff4 default_terminate() + 20
5   libobjc.A.dylib                 0x3a9aaa74 _objc_terminate() + 144
6   libc++abi.dylib                 0x3a3f7078 safe_handler_caller(void (*)()) + 76
7   libc++abi.dylib                 0x3a3f7110 std::terminate() + 16
8   libc++abi.dylib                 0x3a3f8594 __cxa_rethrow + 84
9   libobjc.A.dylib                 0x3a9aa9cc objc_exception_rethrow + 8
10  CoreFoundation                  0x32a4cf1c CFRunLoopRunSpecific + 452
11  CoreFoundation                  0x32a4cd44 CFRunLoopRunInMode + 100
12  GraphicsServices                0x366012e6 GSEventRunModal + 70
13  UIKit                           0x349622fc UIApplicationMain + 1116
14  CodeFriend                      0x0000d3b6 main (main.m:16)
15  libdyld.dylib                   0x3ade1b1c start + 0

Thread 1:
0   libsystem_kernel.dylib          0x3aea8d98 __workq_kernreturn + 8
1   libsystem_c.dylib               0x3adf6cf6 _pthread_workq_return + 14
2   libsystem_c.dylib               0x3adf6a12 _pthread_wqthread + 362
3   libsystem_c.dylib               0x3adf68a0 start_wqthread + 4

Thread 2 name:  Dispatch queue: com.apple.libdispatch-manager
Thread 2:
0   libsystem_kernel.dylib          0x3ae98648 kevent64 + 24
1   libdispatch.dylib               0x3adc8974 _dispatch_mgr_invoke + 792
2   libdispatch.dylib               0x3adc8654 _dispatch_mgr_thread$VARIANT$mp + 32

Thread 3:
0   libsystem_kernel.dylib          0x3aea8d98 __workq_kernreturn + 8
1   libsystem_c.dylib               0x3adf6cf6 _pthread_workq_return + 14
2   libsystem_c.dylib               0x3adf6a12 _pthread_wqthread + 362
3   libsystem_c.dylib               0x3adf68a0 start_wqthread + 4

Thread 4 name:  WebThread
Thread 4:
0   libsystem_kernel.dylib          0x3ae97eb4 mach_msg_trap + 20
1   libsystem_kernel.dylib          0x3ae98048 mach_msg + 36
2   CoreFoundation                  0x32adb040 __CFRunLoopServiceMachPort + 124
3   CoreFoundation                  0x32ad9d9e __CFRunLoopRun + 878
4   CoreFoundation                  0x32a4ceb8 CFRunLoopRunSpecific + 352
5   CoreFoundation                  0x32a4cd44 CFRunLoopRunInMode + 100
6   WebCore                         0x38a3c500 RunWebThread(void*) + 440
7   libsystem_c.dylib               0x3ae0130e _pthread_start + 306
8   libsystem_c.dylib               0x3ae011d4 thread_start + 4

Thread 0 crashed with ARM Thread State (32-bit):
    r0: 0x00000000    r1: 0x00000000      r2: 0x00000000      r3: 0x3c99e534
    r4: 0x00000006    r5: 0x3c99eb88      r6: 0x1dda5554      r7: 0x2fdf7a14
    r8: 0x1dda5530    r9: 0x00000300     r10: 0x00000000     r11: 0x00000000
    ip: 0x00000148    sp: 0x2fdf7a08      lr: 0x3ae1f123      pc: 0x3aea8350
  cpsr: 0x00000010

So moving on: The code used to initialize the ThemesPopOverViewController is:
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil

    {
        self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
        if (self) {

            self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(20, 0, self.view.frame.size.width - 40, 350)];
            [self.tableView setBackgroundColor:[UIColor clearColor]];
            [self.tableView setDelegate:self];
            [self.tableView setDataSource:self];
            themes = [[NSArray alloc] initWithObjects:kRegexHighlightViewThemeArray];
            [self.view addSubview:self.tableView];
            int item = [themes indexOfObject:theDelegate.codeView.currentTheme];
            NSIndexPath *indexPath = [NSIndexPath indexPathForItem:item inSection:0];
            [self.tableView selectRowAtIndexPath:indexPath animated:YES scrollPosition:UITableViewScrollPositionNone];

        }

        return self;
    }

    - (void)viewDidLoad
    {
        [super viewDidLoad];

        // Do any additional setup after loading the view from its nib.
    }

I actually seems that even after the popover is removed from the view hierarchy the allocation done by the init method above occupies memory, it is ARC, do i need to set it to nil somewhere above removing the popover? So everytime the popover is pressed the memory allocations increase...

A: The most relevant information is:
7   CodeFriend   0x0000fb14 -[ThemesPopOverViewController initWithNibName:bundle:] (ThemesPopOverViewController.m:24)

ThemesPopOverViewController is being loaded from a nib file (xib). That means you have created a ThemesPopOverViewController instance and you are accessing its view for the first time (for example, by displaying it).
6   UIKit        0x3492d468 -[UIViewController loadViewIfRequired] + 64
5   UIKit        0x349a3038 -[UIViewController loadView] + 88
4   UIKit        0x34aaab96 -[UIViewController _loadViewFromNibNamed:bundle:] + 230

Methods called by UIKit to load the view
3   UIKit        0x34aab56c -[UINib instantiateWithOwner:options:] + 1632

Here is the view actually loaded and the IBOutlets in the owner are connected.
You can't learn more from the stack trace. I am pretty sure it's not a memory error, there should even be a descriptive error message because of the following line
2   CoreFoundation    0x32b061c0 +[NSException raise:format:] + 100

It's definitely not connection related. Probably it's an invalid nib (xib) file or invalid IBOutlets. Are you sure all the IBOutlet are properly synthesized?
I will also describe shortly what are the previous steps on the stack:
16  UIKit       0x3490e116 _UIApplicationHandleEvent + 6150
15  UIKit       0x3490e7fc -[UIApplication sendEvent:] + 376
14  UIKit       0x349215ec -[UIWindow _sendTouchesForEvent:] + 520

The application is processing a tap (touch event). The event is sent to a window (UIWindow).
13  UIKit       0x349f8dfc -[UIControl touchesEnded:withEvent:] + 484
12  UIKit       0x349f8906 -[UIControl(Internal) _sendActionsForEvents:withEvent:] + 498
11  UIKit       0x349f9050 -[UIControl sendAction:to:forEvent:] + 40

The event is a "touch up" event (touchesEnded is called) and the receiver is a button (UIButton inherits from UIControl). The button then generates an action, probably UIControlTouchUpInside and sends it.
10  UIKit       0x349f9072 -[UIApplication sendAction:toTarget:fromSender:forEvent:] + 26
9   UIKit       0x349f90c0 -[UIApplication sendAction:to:from:forEvent:] + 68

The application sends the action to the listeners.
8   CodeFriend  0x0000e21a -[AppDelegate settingAct:] (AppDelegate.m:127)

Method called -(void)settingAct in your AppDelegate is called in response to the action. From the name I can deduce that "Settings" button was touched. The method than tries to create a controller (popover?) and the crash happens.

A: You'll need to symbolicate the crash report by dragging it into the Xcode organizer window. If you have the symbols file for the build you sent (it should be there in the organizer with your app archives), Xcode will show you more information about what each thread was doing when the app crashed.


text:
Q: ansible playbook run with play tag gathers facts even that gathering facts set to 'no' Below ansible-playbook is run using ansible-playbook playbook.yml --tags=rancher
- name: instal docker
  hosts: rancher-server
  become: yes
  gather_facts: yes

  roles:
    - role: some_galaxy_role

- name: install rancher
  hosts: rancher-server
  become: yes
  gather_facts: no
  tasks:
    - name: install rancher
      debug:
  tags:
    - rancher

Only install rancher play is selected by rancher tag and runs as expected. However fact gathering of the first play install docker still runs and takes time. Why and is there a way to avoid it?
Below is the output of the playbook run:
PLAY [install docker] *********************************************************************************************************************************************************

TASK [Gathering Facts] *******************************************************************************************************************************************************
ok: [rancher-server1]
ok: [rancher-server2]

PLAY [install rancher]

A: You can put a tag on the play level so the whole Instal Docker play is skipped.
Given:
- name: Install Docker
  hosts: localhost
  gather_facts: yes
  tags:
    - docker

  tasks:
    - debug:

- name: Install rancher
  hosts: localhost
  gather_facts: yes
  tags:
    - rancher

  tasks:
    - debug:

When run with --tags rancher, this yields:
PLAY [Install Docker] *********************************************************************************************

PLAY [Install rancher] ********************************************************************************************

TASK [Gathering Facts] ********************************************************************************************
ok: [localhost]

TASK [debug] ******************************************************************************************************
ok: [localhost] =>
  msg: Hello world!

PLAY RECAP ********************************************************************************************************
localhost                  : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

On the other hand, please mind that you are not forced to gather all the facts, you can also gather subsets, to speed up plays.
For example, you can use a minimal subset of the facts only:
- name: Install Docker
  hosts: localhost
  gather_subset:
    - min

  tasks:
    - debug:

Of course, it all just depends what is needed in the some_galaxy_role that requires you to gather facts.


text:
Q: Exception: System.UnauthorizedAccessException, Message: Access to the path "" is denied I have following function which does text logging but I keep getting below error then and there. Its not coming every time but only sometime and that too at IIS level. IIS Apppool is stopped after this error.
An unhandled exception occurred and the process was terminated.

Application ID: /LM/W3SVC/2/ROOT/OrderHelpDesk
Process ID: 81044
Exception: System.UnauthorizedAccessException
Message: Access to the path '\Ser-file\ErrorLog\2018-09\09_27_2018.txt' is denied.
StackTrace:    at OrderHelpDesk.DAL.LogMessage(String Message)
     at OrderHelpDesk.ViewPendingOrderDetails.AutoGenMailToCSRProcessed(Entity objEntity)
     at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
     at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
     at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
     at System.Threading.ThreadHelper.ThreadStart()

public void LogMessage(string Message)
{
     Entity objEntity = new Entity();
     StreamWriter sw = null;

     try
     {
         objEntity.LogMessage = string.Format("\r\n{0:MM/dd/yyyy hh:mm:ss tt} : {1}", DateTime.Now, Message);
         objEntity.LogFilePath = ConfigurationManager.AppSettings.Get("ErrorLogPath");
         objEntity.LogFolderName = string.Format("{0:yyyy-MM}", DateTime.Now);
         objEntity.LogFilePath = objEntity.LogFilePath + objEntity.LogFolderName;

         if (!Directory.Exists(objEntity.LogFilePath))
         {
             Directory.CreateDirectory(objEntity.LogFilePath);
         }

         sw = File.AppendText(objEntity.LogFilePath + "\\" + string.Format("{0:MM_dd_yyyy}", DateTime.Now) + ".txt");
         sw.WriteLine(objEntity.LogMessage);
     }
     catch (Exception Ex)
     {
         throw Ex;
     }
     finally
     {
         sw.Close();
     }
}

A: Use already implemented logging libraries like NLog.
if you can't
This happens because LogMessage can be called simultaneously by several threads. In this case one thread will get log file, while the other will get AccessDenied and your pool will crash because sw is null, but you call sw.Close().
Use synchronization primitives and using construction (or check sw for null sw?.Close()):
static object locker = new object();
public void LogMessage(string Message)
{
   lock (locker)
   {
         Entity objEntity = new Entity();
         objEntity.LogMessage = string.Format("\r\n{0:MM/dd/yyyy hh:mm:ss tt} : {1}", DateTime.Now, Message);
         objEntity.LogFilePath = ConfigurationManager.AppSettings.Get("ErrorLogPath");
         objEntity.LogFolderName = string.Format("{0:yyyy-MM}", DateTime.Now);
         objEntity.LogFilePath = objEntity.LogFilePath + objEntity.LogFolderName;

         if (!Directory.Exists(objEntity.LogFilePath))
         {
             Directory.CreateDirectory(objEntity.LogFilePath);
         }

         using (StreamWriter sw = File.AppendText(objEntity.LogFilePath + "\\" + string.Format("{0:MM_dd_yyyy}", DateTime.Now) + ".txt"))
         {
             sw.WriteLine(objEntity.LogMessage);
         }
   }
}

A: It might be the issue of file/Folder Permission.


text:
Q: Update local state from redux state?store.subscribe is not getting called to update step in stepzilla I have to use redux state to maintain state of steps in stepzilla.
class MainWizard extends React.Component {
 constructor(props) {
    super(props);

    this.state = {
      CurrentWizardStep : 0,
    };

    store.subscribe(() => {
        console.log('Inside subscribe')
        this.setState({
            CurrentWizardStep : store.getState().selectedWizradStep
        });
      });
    }
render() {
    const steps =
        [
            { name: 'step1', component: <step1/> },
            { name: 'step2', component: <step2 /> },
            { name: 'step3', component: <step3 /> },
        ];
    return (
        <article className='step-progress'>
            <StepZilla
                steps={steps}
                preventEnterSubmission={true}
                nextTextOnFinalActinonStep={'Save'}
                hocValidationAppliedTo={[3]}
                //startAtStep={window.sessionStorage.getItem('step') ? parseFloat(window.sessionStorage.getItem('step')) : 0}
                startAtStep = {this.state.CurrentWizardStep}
                //onStepChange={(step) => window.sessionStorage.setItem('step', step)}
                showNavigation={false}
            />
        </article>
    );
}

}
redux state is getting update but after dispatch store.subscribe is not getting called?
Thanks in advance.
Shraddha


text:
Q: What is a typical method to scale out a software load balancer? I often see web app architectures with a SLB / reverse-proxy in front of a bunch of app servers.
What happens when the number of connections to the SLB requires too many resources for a single SLB to handle effectively?  For a concrete yet over-the-top example, consider 2 million persistent HTTP connections.  Clearly a single SLB cannot handle this.
What is the recommended configuration for scaling out a SLB?
Is it typical to create a group/cluster of LBs? If so, how is client load spread out between the group of LBs?

A: The key to scale an HTTP load balancing layer is to add another layer of lower-level (IP or TCP) load balancing first.  This layer can be built entirely with open-source software, although you'll get better results if you have modern routers.
The flows (TCP sessions) should be hashed using headers such as source/destination IP and TCP ports, to decide which frontend they go to.  You also need a mechanism to make sure that when a frontend dies, it stops getting used.
There are various strategies, I'm going to outline a couple that I've used in production on sites serving millions of users, so you can get the idea.  It would be too long to explain everything in details but I hope this answer will give you enough information/pointers to get started.  In order to implement these solutions you're going to need someone who is really knowledgeable about networking.
Admittedly what I'm describing here is much harder to implement than what is described in other answers, but this is really the state-of-the-art if you have a high-trafficked website with big scalability issues and availability requirements over 99.9%.  Provided you already have a network engineer kinda guy onboard, it costs less to setup and run (both in capex and opex) than load balancer appliances, and it can be scaled further at almost no additional cost (vs. buying a new, even more expensive appliance when you outgrow your current model).
First strategy: with a firewall
Presumably you have a couple routers on which your ISP uplinks are connected.  Your ISP provides 2 links (active/passive, using VRRP).  On your routers, you also use VRRP, and you route the traffic going to your public network to a firewall.  The firewalls (FW 1 and FW 2 below) also are also active/passive and will filter the traffic and send each flow to a healthy frontend server (your HTTP load balancers, FE 1 and FE 2 below).

      +--------------+       +--------------+
      | ISP router A |       | ISP router B |
      +--------------+       +--------------+
             |                      |
           ==#======================#==   (public network)
             |                      |
      +---------------+     +---------------+
      | Your router A |     | Your router B |
      +---------------+     +---------------+
             |                      |
           ==#=====#==========#=====#==   (RFC 1918 private network)
             |     |          |     |
       +------+ +------+  +------+ +------+
       | FW 1 | | FE 1 |  | FE 2 | | FW 2 |
       +------+ +------+  +------+ +------+

The goal is to have a flow look like this:

*

*ISP routes traffic going to your IPs to your active router.

*Your routers route the traffic to a VIP that uses an RFC 1918 address.  This VIP is owned by the active firewall, much like VRRP.  If you use OpenBSD for your firewall needs, then you can use CARP, a patent-free alternative to VRRP/HSRP.

*Your firewall applies the filter (e.g. "only allow 80/tcp and 443/tcp going to this particular IP address").

*Your firewall also acts as a router and forwards the packets to a healthy frontend.

*Your frontend terminates the TCP connection.

Now the magic happens in steps 4 and 5, so let's see in more details what they do.
Your firewall knows the list of frontends (FE 1 and FE 2), and it will pick one of them based on a particular aspect of the flow (e.g. by hashing the source IP and port, among other headers).  But it also needs to make sure that it's forwarding traffic to a healthy frontend, otherwise you will blackhole traffic.  If you use OpenBSD, for instance, you can use relayd.  What relayd does is simple: it health-checks all your frontends (e.g. by sending them a probe HTTP request), and whenever a frontend is healthy it adds it to a table that the firewall uses to select the next hop of the packets of a given flow.  If a frontend fails health checks, it is removed from the table and no packets are sent to it anymore.  When forwarding a packet to a frontend, all the firewall does is swapping the destination MAC address of the packet to be that of the frontend chosen.
In step 5, the packets from the user are received by your load balancer (be it Varnish, nginx, or whatever).  At this point, the packet is still destined to your public IP address so you need to alias your VIP(s) on the loopback interface.  This is called DSR (Direct Server Return), because your frontends terminate the TCP connection and the firewall in between only sees simplex traffic (only incoming packets).  Your router will route outgoing packets directly back to the ISP's routers.  This is especially good for HTTP traffic because requests tend to be smaller than responses, sometimes significantly so.  Just to be clear: this isn't an OpenBSD specific thing and is widely used in high-trafficked websites.
Gotchas:

*

*End users will directly connect to your frontend servers because you use DSR.  Maybe it was already the case, but if it was not, you need to make sure they're adequately secured.

*If you use OpenBSD, beware that the kernel is single threaded so the performance of a single CPU core will limit the throughput of a firewall.  It might be a problem depending on your type of NIC and the packet rate you're seeing.  There are ways to solve this problem (more on this below).

Second strategy: without a firewall
This strategy is more efficient but harder to setup because it depends more on the specifics of the routers you have.  The idea is to bypass the firewall above and have the routers do all the work the firewalls were doing.
You'll need routers that support per-port L3/L4 ACLs, BGP and ECMP, and Policy Based Routing (PBR).  Only high-end routers support these features, and they often have extra licensing fees to use BGP.  This is typically still cheaper than hardware load balancers, and is also far easier to scale.  The good thing about these high-end routers is that they tend to be line-rate (e.g. they can always max out the link, even on 10GbE interfaces, because all the decisions they make are done in hardware by ASICs).
On the ports on which you have your ISP uplinks, apply the ACL that used to be on the firewall (e.g. "only allow 80/tcp and 443/tcp going to this particular IP address").  Then have each one of your frontends maintain a BGP session with your router.  You can use the excellent OpenBGPD (if your frontends are on OpenBSD) or Quagga.  Your router will ECMP the traffic to the frontends that are healthy (because they're maintaining their BGP sessions).  The router will also route the traffic out appropriately using PBR.
Refinements

*

*With the firewall pair solution, it's nice if you can synchronize the TCP states across the firewalls, so that when one firewall fails, everything fails over smoothly to the other one. You can achieve this with pfsync.

*

*Bear in mind that pfsync will typically double the packet rate on your firewalls.

*HTTP is a stateless protocol, so it's not the end of the world if you reset all the connections during a firewall failover because you don't use pfsync.

*If you outgrow a single firewall, you can use ECMP on your router to route your traffic to more than one pair of firewall.

*If you use more than one pair of firewall, you might as well make them all active/active.  You can achieve this by having the firewalls maintain a BGP session with the routers, much like the frontends need to maintain one in the 2nd design without firewalls.

Sample relayd config
See also HOWTO at https://calomel.org/relayd.html

vip="1.2.3.4"  # Your public IP address
               # (you can have more than one, but don't need to)
fe1="10.1.2.101"
fe2="10.1.2.102"
fe3="10.1.2.103"
fe4="10.1.2.104"  # You can have any number of frontends.
int_if="em0"
table <fe> { $fe1 retry 2, $fe2 retry 2, $fe3 retry 2, $fe4 retry 2 }
table <fallback> { 127.0.0.1 }

redirect webtraffic {
        listen on $vip port 80
        session timeout 60
        route to <fe> check http "/healthcheck.html" digest "(the sha1sum of healthcheck.html)" interface $int_if
}

A: OK, there is already an accepted answer, but there is something to add..  The most common 'classical' ways of scaling the load balancer tier are (in no particular order):

*

*DNS Round Robin to publicize multiple IP addresses for the domain. For each IP address, implement a highly available server pair (2 servers cooperating on keeping one IP address working at all times.) Each IP corresponds to one load balancer cluster, either using appliances or servers with load balancing software. Scale horizontally by adding more load balancer pairs as needed.

*Routing or firewall tweaks to spread load to multiple load balancers. Have the front router or front firewall spread the incoming connections to several IP addresses (each representing one load balancer pair) by hashing the source IP address, having multiple equal-cost routes to the load balancers, or similar.

*A layer of IP level load balancers in front of a layer of HTTP level load balancers. IP-layer load balancing can be implemented in ASICs / silicon, and can be wicked fast for some things. Thus a single IP load balancer pair can often 'keep up' with a several HTTP/HTTPS level load balancers, and provide multi-gigabit performance levels while keeping the architecture nice and simple.
Going completely in-depth on the different ways doing the above would require a very long answer. But in general, it is not that hard to scale the load balancer tier, it is far harder to scale the application server tier and especially the database tier.
Whether you choose an appliance form factor (F5, Cisco, A10) or a generic server (Windows / Linux + software) matters less. The major considerations when scaling out the load balancer layer are:

*

*State-full versus stateless. Do you absolutely need sticky sessions, or can you live without? Not keeping state makes everything simpler.

*'Hardware' (ASICs) versus 'software' (general purpose servers) for load balancing. Each has its pros and cons, see the HAProxy overview documentation linked above.

*L3/4 (IP / TCP/IP) load balancing versus L7 (HTTP) load balancing. Again, pros and cons, the  HAProxy doc provides a good overview.

*SSL termination, where, on the webnodes or on the load balancer.

Generally, you don't need to worry about this before your website gets very large -- a single modern server with fx nginx will handle tens of thousands of plain HTTP requests per second. So don't do premature optimization, don't deal with this before you have to.

A: Personally I go to simpler, less configurable hardware load balancers at that point - things like Cisco's ACE/ASAs, Foundry ServerIrons, maybe even Zeus ZXTMs (a SW LB that's designed fro very heavy loads).

A: Load balancers can't easily be scaled by other load balancers since there will inherently be a single load balancer on the chain somewhere maintaining the connections. That said, balancers such as LVS or HAProxy have absurd capacity in the Gbps range. Once you get beyond the capabilities of a single load balancer (software, hardware, whatever), then you'll need to move into other techniques such as round robin DNS.

A: Perhaps instead of constantly keeping so many open connections to send replies, code your application in such a way so that clients will periodically poll your servers as often as necessary?
Is whatever you are doing actually requires a response this very millisecond or can a client wait 15/20 seconds until the next polling period?

A: A typical approach would be to create a cluster large enough to handle the required load
and to use a SLB which can do deterministic load-balancing (for the case of persistent connections).
Something like CARP uses a hash of the requesting IP to determine which backend web server would handle the request, this should be deterministic but not very useful if there is a firewall or NAT in front of your load balancer.
You may also find something like IPVS useful if you are running on Linux.


text:
Q: How to use pandas melt to convert multiple columns to rows I  have a data set as below in excel
   A              B       C           D         E           F        G
1                SKU                 Units                Sales
2               11/5/18  12/5/18    11/5/18   12/5/18    11/5/18   12/5/18
3 Description                       total=5   total=9    total=33  total =60
4 Nail Varnish   2345     2345          2       4          $15      $30
5 Eyeliner       2346     2345          3       5          $18      $30

I am using pandas to convert it to another excel with below structure
    Description     date          sku           Units          Sales
0   Nail Varnish    11/5/18       2345            2            $15
1    Eye liner      11/5/18       2346            3            $18
2   Nail Varnish    12/5/18       2345            4            $30
3    Eye liner      12/5/18       2346            5            $30

I have used melt function in pandas earlier to convert one column to row (for example either sales or Units) and i dont know if it works for three multi index columns.
df = pd.read_excel(filepath_name,index_col=False,usecols="A:G")
df2=pd.melt(df,id_vars=["SKU ","Units","Sales"], var_name ="Date", value_name='?)

But how can i convert my all there id vars(SKU, Units and Sales ) at one go.

A: Idea is created index with first column and MultiIndex by first 2 rows, so possible use DataFrame.stack:
df = pd.read_excel(filepath_name,index_col=[0],usecols="A:G", header=[0,1])

print (df.columns)
MultiIndex(levels=[['SKU', 'Sales', 'Units'], ['11/5/18', '12/5/18']],
           codes=[[0, 0, 2, 2, 1, 1], [0, 1, 0, 1, 0, 1]])

df = df.stack().rename_axis(('Description','date')).reset_index()
print (df)
    Description     date   SKU Sales  Units
0  Nail Varnish  11/5/18  2345   $15      2
1  Nail Varnish  12/5/18  2345   $30      4
2      Eyeliner  11/5/18  2346   $18      3
3      Eyeliner  12/5/18  2345   $30      5

If second values are missing in excel file need preprocessing:
print (df)
                 SKU Unnamed: 1_level_0   Units Unnamed: 3_level_0   Sales  \
             11/5/18            12/5/18 11/5/18            12/5/18 11/5/18
Nail Varnish    2345               2345       2                  4     $15
Eyeliner        2346               2345       3                  5     $18

             Unnamed: 5_level_0
                        12/5/18
Nail Varnish                $30
Eyeliner                    $30

a = df.columns.get_level_values(0)
b = df.columns.get_level_values(1)
a = a.where(~a.str.startswith('Unnamed')).to_series().ffill()
df.columns = [a, b]

print (df)
                 SKU           Units           Sales
             11/5/18 12/5/18 11/5/18 12/5/18 11/5/18 12/5/18
Nail Varnish    2345    2345       2       4     $15     $30
Eyeliner        2346    2345       3       5     $18     $30

EDIT1:
If need filter only some columns for reshape:
cols = ['SKU','Units','Sales']
df = df[cols].stack().rename_axis(('Description','date')).reset_index()
print (df)
    Description     date   SKU Sales  Units
0  Nail Varnish  11/5/18  2345   $15      2
1  Nail Varnish  12/5/18  2345   $30      4
2      Eyeliner  11/5/18  2346   $18      3
3      Eyeliner  12/5/18  2345   $30      5

EDIT1:
mux = pd.MultiIndex(levels=[['SKU ', 'Units', 'Unnamed: 0_level_0', 'Sales'],
                            ['11/5/18', '12/5/18', 'Unnamed: 0_level_1'],
                            ['total=5', 'total=9', 'total=33', 'total=60', 'Description', 'Unnamed: 1_level_2', 'Unnamed: 2_level_2']], codes=[[2, 0, 0, 1, 1, 3, 3], [2, 0, 1, 0, 1, 0, 1], [4, 5, 6, 1, 0, 2, 3]])

df = pd.DataFrame([range(7),range(7)], columns=mux)
print (df)
  Unnamed: 0_level_0               SKU                       Units          \
  Unnamed: 0_level_1            11/5/18            12/5/18 11/5/18 12/5/18
         Description Unnamed: 1_level_2 Unnamed: 2_level_2 total=9 total=5
0                  0                  1                  2       3       4
1                  0                  1                  2       3       4

     Sales
   11/5/18  12/5/18
  total=33 total=60
0        5        6
1        5        6

a = df.columns.get_level_values(0)
b = df.columns.get_level_values(1)
c = df.columns.get_level_values(2)
#forward fliing missing values
a = a.where(~a.str.startswith('Unnamed')).to_series().ffill()
b = b.where(~b.str.startswith('Unnamed')).to_series().ffill()
#repalce missing values by empty string
c = c.where(~c.str.startswith('Unnamed'), '')

df.columns = [a, b, c]

#convert first column to index
df = df.set_index(df.columns[0])
df.index.name='Desc'
print (df)
        SKU            Units            Sales
     11/5/18 12/5/18 11/5/18 12/5/18  11/5/18  12/5/18
                     total=9 total=5 total=33 total=60
Desc
0          1       2       3       4        5        6
0          1       2       3       4        5        6

#reshape and rename columns names
d = {'level_0':'a','level_1':'dates','level_2':'b'}
df = df.unstack().reset_index(name='vals').rename(columns=d)
print (df)
        a    dates         b  Desc  vals
0    SKU   11/5/18               0     1
1    SKU   11/5/18               0     1
2    SKU   12/5/18               0     2
3    SKU   12/5/18               0     2
4   Units  11/5/18   total=9     0     3
5   Units  11/5/18   total=9     0     3
6   Units  12/5/18   total=5     0     4
7   Units  12/5/18   total=5     0     4
8   Sales  11/5/18  total=33     0     5
9   Sales  11/5/18  total=33     0     5
10  Sales  12/5/18  total=60     0     6
11  Sales  12/5/18  total=60     0     6

A: melt is opposite to pivot.

and i dont know if it works for three or multi index columns.

Yes, it works for multi index columns. If columns are a MultiIndex then use col_level parameter to melt.
The examples are provided in the first link.


text:
Q: SwiftUI ForEach with .indices() does not update after onDelete my problem is: I have simple array with some Items. I want to display a List with these items using a ForEach with .indices().
(This is because my actual problem handles with Toggle in a List and for the isOn binding I need the index to address a model that is bound to an EnvironmentObject). So the solution to loop over the array items is no possible solution for my problem.
The simplified starting point looks like this:
struct ContentView: View {
    @State var items = ["Item1", "Item2", "Item3"]

    var body: some View {
        List {
            ForEach(items.indices) {index in
                Text(self.items[index])
            }.onDelete(perform: deleteItem)
        }
    }

    func deleteItem(indexSet: IndexSet) {
        self.items.remove(atOffsets: indexSet)
    }
}

If I now try to swipe-delete a row, I get this error message:
Thread 1: Fatal error: Index out of range

Debugging the index value inside the closure, I can see, that the indices of the items-array does not update. For example: If I delete the first row with "Item 1" and inspect the value of index after deleting the row it returns 2 instead of 0 (which is the expected first index of the array). Why is this and how can I fix this problem?
Thanks for your help!

A: Just use dynamic content ForEach constructor (_ data: .., id: ...)
ForEach(items.indices, id: \.self) {index in   // << here !!
    Text(self.items[index])
}.onDelete(perform: deleteItem)


text:
Q: why I can't download csv filetype,but PDF filetype success,is it the downloaded CSV file has been intercepted? As the title says,After I login by selenium,I try use mouse to click download botton,when I choose CSV filetype,I didn't see it at download path,but when I choose PDF filetype,I can see it.It should have nothing to do with my code, because I only use selenium to simulate logging in, and everything after logging in is done manually.is it the downloaded CSV file has been intercepted? what can I do about it?
Help me,please!


text:
Q: Colocando um vídeo dinâmico do YouTube em um  (asp.net) Boa noite! Estou tentando colocar um vídeo do youtube baseando-se em uma url guardada em um banco de dados sql, o problema é que a forma que eu achei de colocar, funciona apenas com alguma url estática, no seguinte modo:

Estou tentando colocar um valor variavel para src, pensei em uma label e depois atribuir no .Text, mas não funciona pois o Iframe para quando insiro a label no meio dele ... alguém tem ideia do que eu posso fazer?
Obrigado :D

A: Essa variável é server-side ou client-side? Nestes casos você tem duas soluções:
Exemplo 1: utilizar o atributo src do iframe.

// Captura elementos iframe, pode utilizar o método getElementById
var iframe = document.getElementsByTagName("iframe");
iframe[0].src = "https://www.youtube.com/embed/o_l4Ab5FRwM";

Exemplo 2 :Construir o iframe dinamicamente via javascript.

var iframe2 = document.createElement("iframe");
iframe2.src = "https://www.youtube.com/embed/o_l4Ab5FRwM";
iframe2.width = 560;
iframe2.height = 315;
iframe2.frameborder = 0;
iframe2.allowfullscreen = true;
document.body.appendChild(iframe2);


text:
Q: Bloc Stream Subscription Not listening to changes [Bloc to Bloc communication] Here is what I'm trying to do

*

*create two blocks login bloc and authentication bloc .

*From authentication bloc , the login bloc has been listened and event has been added.

*I have tried using stream subscription and bloc listener , both failed to listen to changes from login bloc.

*If anymore information needed , please reply to this question .

*The bloc code has been added , review the code and provide suggestion on the code
Login States
part of 'login_bloc.dart';
class LoginState extends Equatable {
const LoginState({
this.status = FormzStatus.pure,
this.username = const Username.pure(),
this.password = const Password.pure(),
this.userId = '',
this.authenticationStatus = AuthenticationStatus.unknown,
});
final FormzStatus status;
final Username username;
final Password password;
final String userId;
final AuthenticationStatus authenticationStatus;
LoginState copyWith(
    {FormzStatus? status,
    Username? username,
    Password? password,
    String? userId,
    AuthenticationStatus? authenticationStatus}) {
  return LoginState(
    status: status ?? this.status,
    username: username ?? this.username,
    password: password ?? this.password,
    userId: userId ?? this.userId,
    authenticationStatus: authenticationStatus ?? this.authenticationStatus,
  );
}

@override
List<Object> get props =>
    [status, username, password, userId, authenticationStatus];

}
class LoginInitialized extends LoginState {}
Login Bloc
import 'package:equatable/equatable.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

import 'package:formz/formz.dart';

import '../../Repositories/authentication_repository.dart';
import '../../models/password.dart';
import '../../models/username.dart';

part 'login_event.dart';
part 'login_state.dart';

class LoginBloc extends Bloc<LoginEvent, LoginState> {
  LoginBloc({
    required AuthenticationRepository authenticationRepository,
  })  : _authenticationRepository = authenticationRepository,
        super(const LoginState()) {
    on<LoginUsernameChanged>(_onUsernameChanged);
    on<LoginPasswordChanged>(_onPasswordChanged);
    on<LoginSubmitted>(_onSubmitted);
  }

  final AuthenticationRepository _authenticationRepository;

  void _onUsernameChanged(
    LoginUsernameChanged event,
    Emitter<LoginState> emit,
  ) {
    final username = Username.dirty(event.username);
    emit(state.copyWith(
      username: username,
      status: Formz.validate([state.password, username]),
    ));
  }

  void _onPasswordChanged(
    LoginPasswordChanged event,
    Emitter<LoginState> emit,
  ) {
    final password = Password.dirty(event.password);
    emit(state.copyWith(
      password: password,
      status: Formz.validate([password, state.username]),
    ));
  }

  void _onSubmitted(
    LoginSubmitted event,
    Emitter<LoginState> emit,
  ) async {
    // emit(LoginInitialized());
    if (state.status.isValidated) {
      emit(state.copyWith(status: FormzStatus.submissionInProgress));
      try {
        var loginresult = await _authenticationRepository.LoginUser(
          state.username.value,
          state.password.value,
        );

        emit(state.copyWith(
          authenticationStatus: Au,
            status: FormzStatus.submissionSuccess,
            userId: loginresult!.data?.id.toString()));
      } catch (_) {
        emit(state.copyWith(status: FormzStatus.submissionFailure));
      }
    }
  }

  @override
  void onTransition(Transition<LoginEvent, LoginState> transition) {
    super.onTransition(transition);
    print(transition);
  }
}

I want to listen the above bloc .
Authentication Bloc
import 'dart:async';
import 'package:equatable/equatable.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

import '../../Repositories/authentication_repository.dart';
import '../../Repositories/user_repository.dart';
import '../login_bloc/login_bloc.dart';

part 'authentication_event.dart';
part 'authentication_state.dart';

class AuthenticationBloc
    extends Bloc<AuthenticationEvent, AuthenticationState> {
  AuthenticationBloc(
    this._authenticationRepository,
    this._userRepository,
    this._loginBloc,
  ) : super(const UnknownAuthenticationState(AuthenticationStatus.unknown, 0)) {
    on<AuthenticationStatusChanged>(_onAuthenticationStatusChanged);
    on<AuthenticationLogoutRequested>(_onAuthenticationLogoutRequested);

    String? userId;

    _authenticationStatusSubscription =
        _authenticationRepository.status.listen((status) {
      add(AuthenticationStatusChanged(status, userId));
    });

    loginStreamSubscription = _loginBloc.stream.listen((loginState) {
      String userId = loginState.userId;
      add(AuthenticationStatusChanged(loginState.authenticationStatus, userId));
    });
  }

  final AuthenticationRepository _authenticationRepository;
  final UserRepository _userRepository;

  late StreamSubscription<AuthenticationStatus>
      _authenticationStatusSubscription;

  final LoginBloc _loginBloc;
  late StreamSubscription<LoginState> loginStreamSubscription;

  @override
  Future<void> close() {
    _authenticationStatusSubscription.cancel();
    loginStreamSubscription.cancel();
    _authenticationRepository.dispose();
    return super.close();
  }

  void _onAuthenticationStatusChanged(
    AuthenticationStatusChanged event,
    Emitter<AuthenticationState> emit,
  ) async {
    switch (event.status) {
      case AuthenticationStatus.unauthenticated:
        return emit(const NotAuthenticatedState(
            AuthenticationStatus.unauthenticated, 0));
      case AuthenticationStatus.authenticated:
        final user = await _userRepository.tryGetUser('3');
        return emit(user != ""
            ? Authenticated(
                AuthenticationStatus.authenticated, state.userId, user)
            : const NotAuthenticatedState(
                AuthenticationStatus.unauthenticated, 0));
      default:
        return emit(
            const UnknownAuthenticationState(AuthenticationStatus.unknown, 0));
    }
  }

  void _onAuthenticationLogoutRequested(
    AuthenticationLogoutRequested event,
    Emitter<AuthenticationState> emit,
  ) {
    _authenticationRepository.logOut();
  }
}


text:
Q: How to Send a Json file in Patch request Need to send a Bulk Patch request to add team members. Using CSV, I will able  do it one at a time, so converted into JSON file and using "FileToString" method to read the same like this
"members": [${__FileToString(${_eval(${convertcsv_Patch})}.txt,,)}]

but getting below error -
{"error":{"code":422,"message":"message.UNPROCESSABLE_ENTITY","errors":[{"scope":"error.scope","reason":"error.reason","message":"unknown token *\nNear:   \"members\": \r\n  [ *"}]}}

A: Description of HTTP Status 422 is

The HyperText Transfer Protocol (HTTP) 422 Unprocessable Entity response status code indicates that the server understands the content type of the request entity, and the syntax of the request entity is correct, but it was unable to process the contained instructions.
Important: The client should not repeat this request without
  modification.

That means the file is syntactically correct JSON file, but not what server is expecting.
What you should try:-

*

*Add View Result Tree

*Check request formed after reading the file and make appropriate changes to payload

A: It is impossible to say what's wrong without seeing:

*

*Your ${convertcsv_Patch})}.txt file

*The value of the ${convertcsv_Patch} variable in the Debug Sampler

*"Body data" tab of the HTTP Request sampler

*Request payload (Request -> Request Body view of the View Results Tree listener)

*Contents of jmeter.log file
Most probably your request is malformed, it should look like at least:
{"members":[${__FileToString(${_eval(${convertcsv_Patch})}.txt,,)}]}


text:
Q: Grafana/Loki: Log lines get highlighted with the search i used in the log panel in grafana from the use of my log select The lines are getting hightlighted with the search I used and doesn't seem to be a way to disable it. For example.
I used the following query and got
{host="server-01",job="systemd-journal",systemd_unit="appmx.service"} |~ `INFO:DB:flushed`

Notice how that part is highlighted in orange, i wasn't able to remove it.
I did a workaround but not sure its good for performance, i added the following to the end of the query
 | regexp `(?P<message>.*)` | line_format "{{.message}}"

This does fix it but seems I might be doing it wrong.
Anyone have any idea ?
Thanks in advance.


text:
Q: CI/CD pipelines with Docker Swarm We have a pretty simple Single Host Docker Swarm set up

*

*A docker compose file to manage all of our services. The latest services are tagged as latest. We don't use versioning yet because our dev process is quite rapid.

*A single host where we have the docker compose file.

*On pushes to main branch we run a bitbucket pipeline to ssh into our server vm and run docker stack deploy for our compose files with registry auth.
When we perform a lot of merges simultaneously,  we run into the following issue:
Error response from daemon: rpc error: code = Unknown desc = update out of sequence

What should we do to avoid this?


text:
Q: Can i hide a data field in a error log of a view? I've inherited a proyect and updated it from laravel 5.6 to laravel 8.
After the update, the daily error logs got way larger than before. Turns out, there is a model, general settings ('gs'), which gets inyected in all the views since some genius decided to place some html views inside it.
Taking out this general settings model is on my priorities, but it is literally in half the views and is a mayor refactor to remove it.
Right now i need to hide this model from the error log because i need to fix other stuff first, and it's really annoying to diagnose the server's error log.
Log after applying a bit of format to improve legibility for the example:
[2021-04-26 12:33:42] local.ERROR: Trying to get property 'name' of non-object
(View: /home/vagrant/code/proyect/resources/views/vendor/shop_page.blade.php)
{
 "view": {"view":"/home/vagrant/code/proyect/resources/views/vendor/shop_page.blade.php",
 "data": {"gs": "

    App\\GeneralSetting {#960<samp data-depth=1 class=sf-dump-expanded>
    #guarded: []
    +timestamps: false
    #connection: \"mysql\"
    #table: \"general_settings\"

....

"}},
"exception":"[object] (Facade\\Ignition\\Exceptions\\ViewException(code: 0): Trying to get property 'name' of non-object (View: /home/vagrant/code/prendasya/resources/views/vendor/shop_page.blade.php) at /home/vagrant/code/prendasya/resources/views/vendor/shop_page.blade.php:256)
[stacktrace]

Note: Each entry is aprox 8300 lines long
Is there some way to hide 'gs' inside 'data' ?
Thanks!


text:
Q: C# ASP.NET AJAX - random number changes, but only want it to change when "new question" button clicked I didn't want to over-complicate the question, but here goes...
I have a file of questions and answers. I want to use C# ASP.NET Core MVC to get question from file, format as JSON, return question value to webpage using AJAX. The question is displayed by clicking a button which runs the C# method by connecting to it with a Route[] statement. Then, also in AJAX on the same webpage, the user can submit their answer. If they are correct, it will tell them. This works if no RANDOM number is involved. The random number simply selects the line of the text-file containing the questions - that's all it does! However, the catch-22 is that when the user clicks on the "ANSWER" button to submit their answer, it re-runs the C# method, which generates a new random number, so has a good chance of selecting a different line from the file, hence containing a different answer and then it tells the user they got it wrong, even though they were correct...
The code on the webpage:
<!DOCTYPE html>

    <meta name="viewport" content="width=device-width" />
    <title>Index</title>

    <fieldset>
        <legend>Question...</legend>

        <input type="button" value="Click for question" id="showQ" />

        Answer: <input type="text" id="answer" />

        <input type="button" value="Click to submit answer" id="answerQ" />

    </fieldset>

The C# methods that pick up the values from AJAX...
[Route("answerQuestion")]
        [Route("answerQuestion/{answer}")]
        public IActionResult AnswerQuestion(string answer)
        {
            //Need to think of a way to get this to only run when "Next question" button is clicked and not when answer provided!
            //Problem is, if I make it so it only runs if "answer" is not set, then it complains that variable is undefined!
            //It's a bit of a catch-22!!!
            Random rnd = new Random();
            int randomNumber = rnd.Next(0, 10);

            string path = @"C:\Users\aposi\Desktop\csharpweb\HOWMVCWORKS\quizquestions.txt";
            if (System.IO.File.Exists(path))
            {
                string[] allLines = System.IO.File.ReadAllLines(path);
                string randomLine = allLines[randomNumber];
                string removedSlashN = randomLine.Replace("\n", "");
                string removedWhitespace = removedSlashN.Replace(" ", "");
                string[] separatedout = removedWhitespace.Split("|"); //Has to be string array data-type to work with Split() function
                string songname = separatedout[0];
                char songletter = songname[0];
                string artist = separatedout[1];

                if (string.IsNullOrEmpty(answer))
                {
                    return new JsonResult("Artist: " + artist + "First letter of songname: " + songletter);
                }
                else if (answer == songname)
                {
                        return new JsonResult("Well done! You guessed correctly that the song name is: " + songname);
                }
                else if (answer != songname)
                {
                        return new JsonResult("Sorry! You got it wrong! The song name was... " + songname);
                }
                else
                {
                    return new JsonResult("Something went wrong!!!");
                }
            }
            else
            {
                return new JsonResult("No question file found!");
            }
        }
    }
}

A: There are a couple ways you can go about it.

*

*Split this into two calls:

*

*GetQuestion, which returns the line number of the question with the question and

*AnswerQuestion, which accepts the line number, and that's the line where you look for the answer.

*Keep it with one call where you return the line number of the question with the question. Then you pass the line number back with the answer, and pull the answer from that line number and compare with their answer. Then you create a random number to find a new question.

*Keep it with one call, but return the answer with the question. You just keep that in your JavaScript until the user answers. Then you don't even need to make a new AJAX request to know if they were right.

I would keep it in one call only because using two would require, well, two requests, and loading the file twice.
But to keep it as one call, you would need to create a class and return that instead of just a string that gets displayed.
public class Question {
    public string Question { get; set; }

    // if you want to send the answer
    public string Answer { get; set; }

    // if you don't want to send the answer
    public int LineNumber { get; set; }

    // text you show in response to their answer. e.g. "Well done! ..."
    public string ResponseText { get; set; }
}

Then you return that class, with the properties set however you need depending on what happened. For example, if they answered correctly, it would look something like:
return new JsonResult(new Question {
    Question = $"Artist: {artist} First letter of song name: {songletter}",
    Answer = answer, //if you want
    LineNumber = randomNumber,
    ResponseText = $"Well done! You guessed correctly that the song name is: {songname}"
});


text:
Q: Has anyone used Smart Image Resizer on subdomain sites? I'm using Smart Image Resizer for dispalying images. This works fine on single site WP. But it does not work for WPMU.
Has anyone used Smart Image Resizer in WPMU using subdomains?

A: Ok, so I have kind of fixed it by hacking image.php file.
The problem was that Smart Image Resizer uses DOCUMENT_ROOT to define base upload folder. It does not include wordpress upload folders (for both WP and WPMU). So I added / changed some code in image.php file to fix this.
// Let's include Wordpress libraries
// We assume this file WILL be located in root folder
require_once($_SERVER['DOCUMENT_ROOT'].'/wp-blog-header.php');

// This must be included just after the above include. Otherwise we can get a 404 Not Found error in WPMU
header('HTTP/1.1 200 OK');    // ****** Wordpress hack ********

//Define upload dir for Wordpress
$upload_dir = wp_upload_dir();
define('WP_IMAGE_UPLOAD_DIR', str_replace("\\","/",$upload_dir['basedir']));
define('WP_IMAGE_UPLOAD_URL', str_replace("\\","/",$upload_dir['baseurl']));

// Replace the original code to remove base URL (and upload path)
$image = str_replace(WP_IMAGE_UPLOAD_URL,'',$_GET['image']);

// Then I replace the old docRoot with the new upload path,
// and kept the stripping of possible trailing slash off the document root
$docRoot    = preg_replace('/\/$/', '', WP_IMAGE_UPLOAD_DIR);

// Then I change the code so it uses correct upload path.
if (!file_exists(WP_IMAGE_UPLOAD_DIR . $image))
{
    header('HTTP/1.1 404 Not Found');
    echo 'Error: image does not exist: ' . WP_IMAGE_UPLOAD_DIR . $image;
    exit();
}

Now it works for both WP and WPMU.


text:
Q: Creating a toy 3D Array contains hourly frequency, temperature and lat,lon coordinates I want to create a 3-dimensional dataarray that stores temperature datas with corresponding latitude and longtitude and time with the hourly frequency. So I did the coding as follows;
np.random.seed(123)

temperature_3d = 15 + 10 * np.random.randn(24,4,4)    # 3-dimensional
lat = np.random.uniform(low=-90, high=90, size=(1,4))
lon = np.random.uniform(low=-180, high=180, size=(1,4))

# round to two digits after decimal point
temperature_3d = np.around(temperature_3d, decimals=2)
lat , lon = np.around([lat, lon], decimals=2)
date_rng = pd.date_range(start='1/1/2018T01:00', end='1/2/2018', freq='H')

da = xr.DataArray(data=temperature_3d,
                  coords={"lat": (["x","y"], lat),
                          "lon": (["x","y"], lon),
                          "day": date_rng},
                  dims=["x","y","day"])

da

And I get this error,
ValueError: conflicting sizes for dimension 'x': length 24 on the data but length 1 on coordinate 'lat'

Dimensionally it's wrong and I can fix it while not including time yet, My goal is to create a dataarray with the 720x40x40 dimensions (timexlat,lonxtime).
I'm also new in this kind of libraries. So I would be appreciated with the suggestions.

A: It looks like the shapes need to be matched correctly.
Firstly as your temperature data is of the shape (24,4,4),
temperature_3d = 15 + 10 * np.random.randn(24,4,4)    # 3-dimensional

you will need to put the date first in your dims:
da = xr.DataArray(data=temperature_3d,
              coords={"lat": (["x","y"], lat),
                      "lon": (["x","y"], lon),
                      "day": date_rng},
              dims=["day","x","y"])

Secondly, your lat and lon coords have a shape according to ["x","y"], so in the example you need a 4x4 grid for what the lat is at each point, and another 4x4 grid for the lon at each point. For this we can use np.meshgrid:
latgrid, longrid = np.meshgrid(lat,lon)

So, in full:
import numpy as np
import xarray as xa

np.random.seed(123)

temperature_3d = 15 + 10 * np.random.randn(24,4,4)    # 3-dimensional
lat = np.random.uniform(low=-90, high=90, size=(4))
lon = np.random.uniform(low=-180, high=180, size=(4))

# round to two digits after decimal point
temperature_3d = np.around(temperature_3d, decimals=2)
lat , lon = np.around([lat, lon], decimals=2)
latgrid, longrid = np.meshgrid(lat,lon)
date_rng = pd.date_range(start='1/1/2018T01:00', end='1/2/2018', freq='H')

da = xa.DataArray(data=temperature_3d,
              coords={"lat": (["x","y"], latgrid),
                      "lon": (["x","y"], longrid),
                      "day": date_rng},
              dims=["day","x","y"])
da


text:
Q: Why can't my SYSTEM Command Prompt access these files owned by SYSTEM and how do I fix it? I launched a Command Prompt under SYSTEM with PsExec to move a file owned by SYSTEM without changing the file and folder's permissions, but I'm still being denied access. What's going on here?

A: It's very likely that you need to run as trusted installer.  Some programs, like GWX do this.
Look for a proggie called runasti.exe on the internet, and it should do the magic,