text:
Q: How do I do a SIP telephone call I want to constract a telephone-caller inside my java application. For this pupose I used a JAIN-SIP library. After the first INVITE the system needs Proxy-Authentication. The second invite is conscructed with the help of "AuthenticationHelperImpl.class":https://gitorious.org/0xdroid/external_nist-sip/source/1e0f37693341071f316852c8e05a08deef2b7fc4:java/gov/nist/javax/sip/clientauthutils/AuthenticationHelperImpl.java#L311, includes Proxy-Authentication header and lloks like:
INVITE sip:+11111111111@fpbx.de;maddr=fpbx.de SIP/2.0
Call-ID: 1c609509a43b721ab11c396c1e6ea9e7@192.168.17.107
CSeq: 2 INVITE
From: "77735hk6iu" <sip:77735hk6iu@fpbx.de>
To: "+111111111111111" <sip:+11111111111@fpbx.de>
Via: SIP/2.0/UDP 192.168.17.107:34567;rport;branch=z9hG4bK-383337-5bc4fd6b7a616843fce9eaa243bcb10e
Max-Forwards: 70
Contact: <sip:77735hk6iu@192.168.17.107:5060>
Content-Type: application/sdp
Proxy-Authorization: Digest       username="77735hk6iu",realm="fpbx.de",nonce="VLaIxVS2h5muPS30F2zLdXHjup6ELyen",uri="sip:+111111111111@fpbx.de:5060;maddr=fpbx.de",response="47ea578c6b01c99fd3ed2b41c60983df"
Content-Length: 61

v=0
o=- 130565705777141827 1 IN IP4 192.168.17.107
s=call

After that I receive at the beginning code 100 message ("your call is very important for us") followed with 408 code message ("Request Timeout").
What I did to imporve the situation:

*

*tried different phone number formats: 004930208488480,
04930208488480, 049, 0049, sdfhajfkhsk. For all these numbers I
become the same combination on messages.

*tried to use port in request uri

*tried to remove maddr from request uri.

*tried to fullfill the message body with codek settings.

*to set and remove rport from via header
If you now what I'm doing wrong, please, help me.
Thank you in advance.

A: I think, Maybe your Proxy-Authorization header is wrong. Maybe you is miscalculated. I wanted to share my resolve.
authUser is your phoneNumber. (for example: 77735hk6iu )
authPass is your user's password.
msg is your invite request.(Headers !)
AccountManagerImpl accountManagerImp = new AccountManagerImpl(authUser, AuthPass);
        AuthenticationHelperImpl authenticationHelperImpl = new AuthenticationHelperImpl(accountManagerImp);

        try {
           this.authentication = authenticationHelperImpl.handleChallenge(msg, (SIPClientTransaction)trans);

AuthenticationHelperImple.java Class :
   public AuthorizationHeader handleChallenge(Response challenge, ClientTransaction challengedTransaction) throws SipException {

  SIPRequest challengedRequest = ((SIPRequest) challengedTransaction.getRequest());

  ListIterator authHeaders = null;

  if (challenge.getStatusCode() == Response.UNAUTHORIZED) {
     authHeaders = challenge.getHeaders(WWWAuthenticateHeader.NAME);
  }
  else {
     if (challenge.getStatusCode() == Response.PROXY_AUTHENTICATION_REQUIRED) {
        authHeaders = challenge.getHeaders(ProxyAuthenticateHeader.NAME);
     }
     else {
        throw new IllegalArgumentException("Unexpected status code ");
     }
  }

  if (authHeaders == null) {
     throw new IllegalArgumentException("Could not find WWWAuthenticate or ProxyAuthenticate headers");
  }

  WWWAuthenticateHeader authHeader = null;
  while (authHeaders.hasNext()) {
     authHeader = (WWWAuthenticateHeader) authHeaders.next();
     String realm = authHeader.getRealm();

     this.uri = challengedRequest.getRequestURI();

     this.requestMethod = challengedRequest.getMethod();
     this.requestBody = (challengedRequest.getContent() == null) ? "" : new String(challengedRequest.getRawContent());

     if (this.accountManager instanceof SecureAccountManager) {
        UserCredentialHash credHash = ((SecureAccountManager) this.accountManager).getCredentialHash(challengedTransaction,
                                                                                realm);
        if (credHash == null) {
           logger.logDebug("Could not find creds");
           throw new SipException("Cannot find user creds for the given user name and realm");
        }

        this.authorizationHeader = this.getAuthorization(requestMethod, uri.toString(), requestBody, authHeader, credHash);
     }
     else {
        UserCredentials userCreds = ((AccountManager) this.accountManager).getCredentials(challengedTransaction, realm);
        if (userCreds == null) {
           throw new SipException("Cannot find user creds for the given user name and realm");
        }
        // sipDomain = userCreds.getSipDomain();
        // we haven't yet authenticated this realm since we were
        // started.

       this.authorizationHeader = this.getAuthorization(requestMethod, uri.toString(), requestBody, authHeader, userCreds);
     }
  }

  return this.authorizationHeader;

}
getAuthorization function :
 public AuthorizationHeader getAuthorization(String method,
                                           String uri,
                                           String requestBody,
                                           WWWAuthenticateHeader authHeader,
                                           UserCredentials userCredentials) throws SecurityException {
  String response = null;
  String qopList = authHeader.getQop();
  String qop = (qopList != null) ? "auth" : null;
  String nc_value = "00000001";
  String cnonce = "xyz";

  try {
     response = MessageDigestAlgorithm.calculateResponse(authHeader.getAlgorithm(),
                                                        userCredentials.getUserName(), authHeader.getRealm(),userCredentials.getPassword(), authHeader.getNonce(), nc_value, // JvB added
                                                 cnonce, // JvB added
                                                 method, uri, requestBody, qop,logger);
  }
  catch (NullPointerException exc) {
     throw new SecurityException("The received authenticate header was malformatted: " + exc.getMessage());
  }

  AuthorizationHeader authorization = null;
  try {
      if (authHeader instanceof ProxyAuthenticateHeader) {
         if (this.headerFactory != null) {
            authorization = headerFactory.createProxyAuthorizationHeader(authHeader.getScheme());
         }
         else {
            authorization = new ProxyAuthorization();
            authorization.setScheme(authHeader.getScheme());
         }
      }
      else {
         if (this.headerFactory != null) {
            authorization = headerFactory.createAuthorizationHeader(authHeader.getScheme());
         }
         else {
            authorization = new Authorization();
            authorization.setScheme(authHeader.getScheme());
         }
      }

      authorization.setUsername(userCredentials.getUserName());
      authorization.setRealm(authHeader.getRealm());
      authorization.setNonce(authHeader.getNonce());
      authorization.setParameter("uri", uri);
      authorization.setResponse(response);
      if (authHeader.getAlgorithm() != null) {
          authorization.setAlgorithm(authHeader.getAlgorithm());
      }

      if (authHeader.getOpaque() != null) {
          authorization.setOpaque(authHeader.getOpaque());
      }

      // jvb added
      if (qop != null) {
          authorization.setQop(qop);
          authorization.setCNonce(cnonce);
          authorization.setNonceCount(Integer.parseInt(nc_value));
      }

      authorization.setResponse(response);

  } catch (ParseException ex) {
      throw new RuntimeException("Failed to create an authorization header!");
  }

  return authorization;

}
Finally, your  this.authentication variable is ProxyAuthorizationHeader. You must put this.authentication in your INVITE message. And than you will sent SipMessage from transaction or dialog to JAIN-SIP stack.
Good Luck !

A: The problem was partly solved when a removed "maddr=fpbx.de" from request URI and from proxy-auth. uri
fpr this a used handleCahllenge method with boolean arguments:
inviteTid = authenticationHelper.handleChallenge(response, tid, sipProvider, 15, **true**);

But I still don't know how I can a acchieve sponaneous telephone number.

A: The 100 message is hop-by-hop, that is to say it just means the next hop got your request.  Other messages will typically be end-to-end (so, if you got a 180 Ringing, that typically means the endpoint being called sent the 180).  A 408 typically shows up when one of the hops sent the INVITE but never got a response (and your SIP stack might be generating that internally when it doesn't get a provisional response in a reasonable timeframe -- usually about 32 seconds with the default SIP timers).
I don't know your network setup, but there are several private IPs in that message (of the 192.168.x.x variety).  If I had to guess, your first hop is sending the 100 back to the IP/port it received it from, but the next response is following the Via headers (as it should), and the hop after you isn't respecting the rport parameter, so the response is getting lost.  Alternately, your NAT is poorly configured and is closing the hole it created for the INVITE too quickly.
If you have a proxy on the edge of your network that this message is going out, it is either putting bad Via headers on the message (possibly with the internal IP instead of the external IP) or it is sending the INVITE to the wrong place (causing it to never get a response), and the 408 is coming from it.


text:
Q: Limit the sending of messages at the same time I was wondering if there is a way to block the sending of multiple messages at the same time from different people in a channel discord. Whether his silk with discord.js or discord.py. In itself, I want the bot to take into account the first message sent and ignore others sent at the same time
cordially,
Quentin S.

A: One solution would be to track the timestamp of the last message listened to, and then ignore any messages sent before a set amount of time has elapsed. See this example...
let lastMessageTime;
const sec = 2; // Seconds to wait between messages.

client.on('message', message => {
  if (!message.guild || message.author.bot) return;

  if (lastMessageTime && message.createdTimestamp - (sec * 1000) < lastMessageTime) return;
  else lastMessageTime = message.createdTimestamp;

  // Continue with 'message' event.
});

redpajama_set_name: RedPajamaStackExchange


text:
Q: Validar el input solo si es int Tengo un programa que genera un numero al azar entre dos valores que ingresa el usuario, quien posteriormente debe adivinar en una determinada cantidad de intentos.
import random
print("introduce los valores entre los que quieres que este el numero:")

#eleccion de los valores entre los que estara el numero

while True:

  print("primer numero:")
  x = int(input())

  print("segundo numero:")
  y= int(input())

  if x>y:
    print("El primer numero debe ser menor al segundo")

  else:
    break

print(f"el numero estara entre {x} y {y} ")

numero_azar = random.randint(x,y)

intentos_realizados = 0

print("tienes 5 intentos")

while intentos_realizados <5:

  n = int(input())

  intentos_realizados = intentos_realizados + 1

  if n >numero_azar:
    print("el numero es mas bajo")

  elif n<numero_azar:
    print("el numero es mas alto")

  else:
    print("Correcto")
    break

if n == numero_azar:
 print(f"muy bien, adivinsate el numero en un total de {intentos_realizados} intentos")
else:
 print(f"el numero en el que estaba pensando era {numero_azar}")

Me gustaria saber como "forzar" a quien ejecute el programa a elegir dos numeros (int); para que no elija "str" lo que llevaria a un error. Esto en la primera parte del programa:
while True:

 print("primer numero:")
 x = int(input())

 print("segundo numero:")
 y= int(input())

 if x>y:
  print("El primer numero debe ser menor al segundo")

 else:
  break

Tambien si tienen alguna sugerencia sobre como optimizar el codigo o hacerlo mas "pythonic" seria genial.
Esto especialmente en esta primera parte, considero que siempre es mejor poder manejar cualquier error que el usuario pueda cometer (otro ejemplo seria que introduzca rangos de numeros no validos).

A: Para evitar usar try - excepts puedes usar isnumeric() que comprueba si una cadena está compuesta de números.
def input_int(msg):
    while True:
        var = input(msg)
        if var.isnumeric():
            break
        print("La entrada no es un numero, reintente")
    return int(var)

x = input_int("Primer numero: ")
y = input_int("Segundo numero: ")
# .
# .
# .
# resto del código

A: Puedes agregar las sentencias try ... except por si la conversión falla vuelva a iniciar.

    while True:
        print("primer numero:")

        try:
            x = int(input())
        except:
            continue

        print("segundo numero:")
        try:
            y = int(input())
        except:
            continue

        if x > y:
            print("El primer numero debe ser menor al segundo")
        else:
            break


text:
Q: Returning multiple elements in robot framework script I'm having an issue with Robot.
I run this method within a python script and everything is ok.
go_button = self.driver.find_elements_by_css_selector(".xxx")[0]

Basically I need to grab the first element that matches this selector and I can do this no problem via python directly.
However, I cannnot do the same via Robot. I have something like this:
Click Button    css=.xxx

I guess my question is, how can I index results if a locator returns more than 1 result

A: How about using XPATH locator as below to select the 1st element?
xpath=//*[@class='xxx'][1]


text:
Q: Plotly change color mapping interactively based on data frame values I have a data frame from which I want to create a scatter plot from, which I do via
import plotly.express as px
fig = px.scatter(df, x="X", y="Y", color="size")

I want interactively change the color mapping by a dropdown menu for all columns in the data frame (beside X, Y).
What I need is to probably set this one up correctly:
fig.update_layout(active=0,
        buttons=[              # my idea would be to use a list comprehension here
            dict(label = col,
                  method = 'restyle',
                  ...?)
               for col in filter( exclude_columns, df.columns)
                ])

I found this SO topic change-plotly-express-color-variable-with-button but there are some things not clear to me.
They create a px.scatter as well as multiple graph objects:
fig1 = px.scatter(df, "sepal_length", "sepal_width", color="species")
fig2 = px.scatter(df, "sepal_length", "sepal_width", color="petal_length")

fig = go.Figure()
fig.add_trace(go.Scatter(fig1.data[0], visible=True))
fig.add_trace(go.Scatter(fig1.data[1], visible=True))
fig.add_trace(go.Scatter(fig1.data[2], visible=True))

fig.add_trace(go.Scatter(fig2.data[0], visible=False))

fig.update_layout(
    updatemenus=[
        dict(
            buttons=list([
                dict(
                    args=["visible", [True,True,True,False]],
                    label="species",
                    method="restyle"
                ),
                dict(
                    args=["visible", [False,False,False,True]],
                    label="petal length",
                    method="restyle"
                ),
            ]),

Sidequestions?
I might have a misconception here but as I have a medium amount of columns, creating many px.scatter objects sounds inefficient, is that necessary? As just the color mapping needs to be changed?
Likewise I don't understand the visible parameter I've seen there and in other tutorials, why has it length 4, for every species?
Main question:
How can I build this dropdown menu to support an arbitrary range of columns?

A: I created a working example below to demonstrate how you can change the color of the trace based on some column value.You could use similar concept to change size as well.
I don't like to mix Plotly Express and Graph Objects traces as it can be quite confusing. I prefer to use Graph Objects library as it gives the programmer more control of layout and trace properties.
Please study the example below.
import plotly.express as px
import plotly.graph_objects as go
import pandas as pd
from numpy import identity

df = pd.read_csv("https://raw.githubusercontent.com/mwaskom/seaborn-data/master/iris.csv")

# filter columns for dropdown
exclude_cols = ['species']
labels = [col_name for col_name in df.columns if col_name not in exclude_cols]
# make default figure
data = [go.Scatter(x=df['sepal_length'], y=df['sepal_width'], visible=False, mode='markers', marker_color=df[c], marker_size=30) for c in labels]
# first trace is visible by default
data[0]['visible'] = True
# create figure
fig = go.Figure(
    data=data,
    layout=go.Layout(title="Iris plots"))

# update laytout with dropdown menu
visible = identity(len(labels), dtype=bool)
buttons= [dict(args=["visible", visible[i, :]], label=l, method="restyle")
            for (i, l) in enumerate(labels)]
fig.update_layout(
    updatemenus=[
        dict(
            buttons=buttons,
            showactive=True,
            x=0.05,
            xanchor="left",
            y=1.2,
            yanchor="top"
        ),
    ]
)

fig.update_layout(
    annotations=[
        dict(
            x=0.01,
            xref="paper",
            y=1.16,
            yref="paper",
            align="left",
            showarrow=False),
    ])
fig.update_layout(xaxis_title_text='sepal_length',
                  yaxis_title_text='sepal_width',)
fig.show()

As an aside, if you need to do more interactivity it's worth learning about Dash. I think it's much easier to do this in Dash than natively in Plotly with the use of callbacks. That is up to you entirely if you are willing and able to invest the time to learn it.


text:
Q: Django-PostgresPool max poolsize Here is my setting :
DATABASE_POOL_ARGS = {
    'max_overflow': 3,
    'pool_size': 3,
    'recycle': 300
}

I set pool_size =3
But I look up the result in postgres( SELECT sum(numbackends) FROM pg_stat_database;  )
The number still over 3 , How can I set the connection   ??
I want to set the max to 100,And let all requests share these 100  connections to communicate with postgresql

A: pool_size is the number of idle connections (ie at least these many will always be connected), and max_overflow is the maximum allowed on top of that.
So the total maximum is pool_size + max_overflow. You should set pool_size to the minimum number you think you will typically need, and max_overflow to 100 - pool_size.


text:
Q: Quartz.Net method DateBuilder.TodayAt() on the StartAt() JobScheduler What would happen if I used the DateBuilder.TodayAt to create a date to start my job, but that time had already passed, would the job start?
Example:
Let's say I have a job that I want Quartz to run it everyday at 5 am.
But I'm setting this at 9 am today, would this code work?
.StartAt(DateBuilder.TodayAt(5, 0, 0))
.WithSimpleSchedule(x => x
.WithIntervalInHours(24)
.RepeatForever())

So, since the datebuilder created a datetime for today at 5 am, this job would never start, right? So it can never repeat forever.
Or would Quartz.net understand that and fire it anyway tomorrow at 5 am and so on?
Would there be a better way to do this? Creating a job that runs everyday at 5 am?
Thank you.

A: I found a way to create this job by setting the time for the next day, so is certain that the specific time has not yet passed.
Like this:
.StartAt(DateBuilder.TomorrowAt(5, 0, 0))


text:
Q: Database security What aspects should be considered in order to have a secure database?
Along with avoiding sqlInjection, what else should be considered? What should not be done?

A: Shut it down and wipe the disks....several times.
Slightly less extreme is
Firstly secure the server, storage, network and OS level

*

*The database server should have minimal open ports (eg just SSH on port 22 and the listener on 1521). Also beware out outgoing connections. The db can make HTTP requests, send emails and all sorts of things....which you probably don't want in a secure environment.

*No-one should have access the the database server. Actually the most senior DBA probably needs access, and one deputy in case the Senior DBA is ill or otherwise unavailable. You may want to audit all access. You may want to force the DBAs to actually request access from a sysadmin before they can access the server. You probably want to lock down where they can access it from (ie specific work PC) and possibly times as well.

*Transparent Data Encryption should be used so that all data in the database is encrypted before it hits the files. So even if someone gets the disks or the backups they can't read them

*You might want to encrypt network traffic between the database and the application.

Next you want to lock down user database access

*

*Generally access by schema owners should only be required for installation/upgrades. Apart from that the schema should be locked.

*it is safer to separate out an application layer in the DB so that the application accounts can only execute pre-defined functions (ie can't delete every row in a table). A DB application layer is a very good defense against SQL injection because the connected user simply doesn't have select permissions on the tables.

*Store encrypted values in preference to clear-text, and hashed values in preference to encrypted values and store nothing that you don't need. Do you actually need people's names, addresses, phone numbers, credit cards, SSNs, passwords ?

*Depending on your architecture you may benefit from passwords that expire on a regular basis, or authentication though another mechanism.

Don't forget DR. While I was joking about wiping the disks, if your risk assessment is that someone would do very well putting you out of business for a few days (or permanently), burning down your data center is a security matter.

A: Here is a checklist for SQL Server security which seems focused on the configuration of the SQL server itself:
http://www.sqlsecurity.com/FAQs/SQLSecurityChecklist/tabid/57/Default.aspx
Additionally (if you are unable to rely on the windows only security model) you would also want to go through the required excercise of encrypting connection strings.

A: A pretty open question.
A good start is to read some of the basics, Wikipedia has a nice article on it. Then you have to look into the details of your specific system. Nearly all database engines provide a heap of information how to specifically secure their systems. And don't forget to look over the horizon: not only has the database be "secured", also the system it runs on.
SQL Injection is a common, but one of many security concerns to be taken into notice.

A: In Oracle, a frequent design choice I see being made is that the application always logs in as a single database user/schema - the owner of all the objects for that application.
A better design is to have one user/schema that owns the objects for the application, then REVOKE CREATE SESSION from that user. Then, create another user/schema which will own no objects (except perhaps for synonyms) that will be used by the application to log into the database. Then, issue the minimum necessary grants (SELECT, INSERT, UPDATE, DELETE, EXECUTE, etc) to the application user.
That way, you know that even if a bug in the application might allow a user to do something that they shouldn't (e.g. delete records from a table), your database privileges will ensure that it won't happen.
Otherwise, if the application logs in as the owner, it is not possible to REVOKE any privileges on any of the objects.


text:
Q: Windows Batch File - Need to remove line breaks from parameter I have a powershell script that will run a query and export the results to Excel.  I want to hook this into SQL Studio Management Studio (2008)'s external tools.  SSMS will not allow powershell scripts so I am using a batch file to get it started.
In the external tools section you can specify some predefined arguments.  The argument that I want is called "current text".  This argument passes whatever is highlighted to the tool (batch file).  My batch file then passes that argument on to a powershell script.
The problem is that if the user has a query that spans multiple lines highlighted then the powershell script fails because of the linebreaks.  It seems it would be relatively easy to strip them out, or better yet, replace them with a space?
Here is my batch file:
echo %~1
call powershell ^& 'c:\temp\ExportSQL.ps1' -query "%~1"

My question is how can I replace newlines and carriage returns from %1 with a space before passing it to the powershell script?  TIA.

A: First, I can't believe that you have really linefeeds in your parameter %1, as it is possible, but a bit complex to achieve this.
To control this you could use
echo on
rem # %1 #

To handle CR and linefeed characters you have to use the delayed expansion, as percent expansion of such a content is not possible.
With percent expansion CR's are always removed, linefeeds removes the rest of the line or in a block context they append a new command line.
So it's not possible to handle content with linefeeds in a parameter like %1 ..%9.
You need it stored in a variable.
Assuming you have content with newlines in a variable, you could replace it with spaces.
The empty lines in this example are important for the result.
@echo off
set text=This contains a ^

newline
setlocal EnableDelayedExpansion
set ^"result=!text:^

= !"
echo Content of text is   "!text!"
echo ----
echo Content of result is "!result!"

--- Output ---
Content of text is   "This contains a
newline"
----
Content of result is "This contains a  newline"


text:
Q: Round a number to the nearest 0.05 ending with either a 0.025 or 0.075 A = [0.123 0.234 0.562 0.665 ]
B = [0.125 0.225 0.575 0.675]
C = [-43.975 -43.925 -43.875 -43.825 -43.775 -43.725 -43.675]

I would like make array A look like array B. The satellite data I am working with has a 0.05 degree resolution so it's latitude and longitude values are numbered like in array C. So the numbers go up in increments of 0.05 but end in either 25 or 75 as in array C. I have numbers like in array A which I need to match with the grid of the satellite data. I need to round or transform my numbers as in array A to look like those in array B.
I've tried using round and using math.ceil but neither worked fully.

A: Here's a rounding algorithm to do that:

*

*Add 0.025

*Multiply by 20

*Round to the nearest integer

*Divide by 20

*Subtract 0.025

*Round to 3 decimal places (to handle floating point precision issues)

E.g. in python:
def x_round(x): return round((round((x+0.025)*20)/20)-0.025,3);

A = [0.123, 0.234, 0.562, 0.665]

for item in A:
    print(x_round(item))

Output:
0.125
0.225
0.575
0.675


A: Here's a version that looks for the closest neighbour that ends with 0.025 or 0.075. (Handling negative input is left to the reader.)
JavaScript code:

function f(n){
  n = n * 1000
  let m = n % 100
  if (m <= 50)
    return (n - m + 25) / 1000
  else
    return (n - m + 75) / 1000
}

var A = [0.123, 0.234, 0.562, 0.665]

console.log(JSON.stringify(A))
console.log(JSON.stringify(A.map(x => f(x))))


text:
Q: How to run node in webhosting? I'am creating 2d mmorpg game and I upload client and socket.io server on webhosting, but don't know how to start server.js, if i'am right then I have to run node with package.json but I don't know how to run it in webhosting...
My package.json:
{
  "name": "Example server",
  "version": "0.0.0",
  "main": "server.js",
  "author": "Aurelijus",
  "private": true,
  "license": "BSD",
  "dependencies": {
    "express": "4.13.4"
  },
  "scripts": {
    "start": "node server.js"
  }
}

server example:
var http = require("http").createServer(), io = require("socket.io").listen(http);

http.listen(8080);

//================================  Connection stuff ================================//
io.sockets.on("connection", function(socket)
{
    socket.on('player connected', function(data)
    {
    };
});
console.log('Server listening on port %s', http.address().port);

Thanks, I hope it's not out of topic :\

A: To start a node on a webserver it is the same as locally.
npm install
npm start


text:
Q: Counting incidences from one data frame, entering results into a different data frame I have two data frames:  households and individuals.
This is households:
structure(list(ID = 1:5), class = "data.frame", row.names = c(NA,
-5L))

This is individuals:
structure(list(ID = c(1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 3L,
3L, 4L, 4L, 4L, 4L, 5L, 5L), Yesno = c(1L, 0L, 1L, 0L, 0L, 0L,
1L, 1L, 1L, 0L, 0L, 1L, 1L, 0L, 0L, 1L, 0L)), class = "data.frame", row.names = c(NA,
-17L))

I'm trying to to add a new column to households that counts the number of times variable Yesno is equal to 1, grouping results by ID.
I have tried
households$Count <- as.numeric(ave(individuals$Yesno[individuals$Yesno == 1], households$ID, FUN = count))

households should look like this:
ID  Count
1   2
2   3
3   0
4   2
5   1

A: Option 1: In base R
Using merge and aggregate
aggregate(Yesno ~ ID, merge(households, individuals), FUN = sum)
#  ID Yesno
#1  1     2
#2  2     3
#3  3     0
#4  4     2
#5  5     1

Option 2: With dplyr
Using left_join and group_by+summarise
library(dplyr)
left_join(households, individuals) %>%
    group_by(ID) %>%
    summarise(Count = sum(Yesno))
#Joining, by = "ID"
## A tibble: 5 x 2
#     ID Count
#  <int> <int>
#1     1     2
#2     2     3
#3     3     0
#4     4     2
#5     5     1

Option 3: With data.table
library(data.table)
setDT(households)
setDT(individuals)
households[individuals, on = "ID"][, .(Count = sum(Yesno)), by = ID]
#   ID Count
#1:  1     2
#2:  2     3
#3:  3     0
#4:  4     2
#5:  5     1

Sample data
households <- structure(list(ID = 1:5), class = "data.frame", row.names = c(NA,
-5L))

individuals <- structure(list(ID = c(1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 3L,
3L, 4L, 4L, 4L, 4L, 5L, 5L), Yesno = c(1L, 0L, 1L, 0L, 0L, 0L,
1L, 1L, 1L, 0L, 0L, 1L, 1L, 0L, 0L, 1L, 0L)), class = "data.frame", row.names = c(NA,
-17L))

A: Another base R approach using sapply is to loop over each ID in households and subset that ID from  individuals and count how many of them have 1 in Yesno column.
households$Count <- sapply(households$ID, function(x)
                   sum(individuals$Yesno[individuals$ID == x] == 1))

households
#  ID Count
#1  1     2
#2  2     3
#3  3     0
#4  4     2
#5  5     1

The == 1 part in the function can be removed if the Yesno column has only 0's and 1's.


text:
Q: How to use svg-crowbar on specific svgelement All:
What I want to do is using JS to save specific svg to a file( it can be svg, or other formats).
Some posts suggest svg-crowbar, I tried the example on its page(http://nytimes.github.io/svg-crowbar/ ), it is amazing and work well, but I do not know how to control it to download specific SVG on my page with JS.
Could anyone give me an example of how to call svg-crowbar API to download specific SVG element on the page.
Thanks


text:
Q: Not getting lines - std::getline I posted this question a couple of days back and i just have another question, I have it outputting the first line of the data but it inst outputting the rest of the lines kinda stumped.
ifstream myReadFile;
    myReadFile.open("Data.txt");
    system("cls");
    std::cout << "Wip" << std::endl;

    ifstream myReadFile;
     myReadFile.open("Data.txt");
     std::string output;
     std::getline(myReadFile, output);
     std::cout << output << "\n";
     myReadFile.close();
system("pause");
return 0;

sample data
Name: jobes lobes
Age: 89
Address: 9 neuern_st mucgregor brosbane australia

A: You need to use a while loop so you can extract continuously. Extraction will finish when the stream fails to extract:
while (std::getline(myReadFile, output))
{
    std::cout << output << "\n";
}


text:
Q: Use datasource of admin grid in another grid In Magento 2.2.5, I am using datasource in the grid and it is working fine.
I want to use the same datasource in another grid with some filters. I am using vendorname_module_deal_listing_data_source again in the another grid. But it is keeps loading. I cannot find any errors in console and log anywhere.
Code of di.xml is:
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/ObjectManager/etc/config.xsd">
<type name="Magento\Framework\View\Element\UiComponent\DataProvider\CollectionFactory">
    <arguments>
        <argument name="collections" xsi:type="array">
            <item name="vendorname_module_deal_listing_data_source" xsi:type="string">Vendorname\Module\Model\ResourceModel\Deal\Collection</item>
        </argument>
    </arguments>
</type>
<virtualType name="Vendorname\Module\Model\ResourceModel\Deal\Collection" type="Magento\Framework\View\Element\UiComponent\DataProvider\SearchResult">
    <arguments>
        <argument name="mainTable" xsi:type="string">module_manage_deal</argument>
        <argument name="resourceModel" xsi:type="string">Vendorname\Module\Model\ResourceModel\Deal</argument>
    </arguments>
</virtualType>

Update:
admin layout Code: https://pastebin.com/ZRw0ug9D
Screenshot: https://prnt.sc/kzqzov
Working Grid's UI Component: https://pastebin.com/Lb7QZmUt
Copied Grid's UI Component: https://pastebin.com/i3DXVita

A: As per your original data source name:
In both file data source name should be  same like below:
                   <argument name="name" xsi:type="string">vendorname_module_deal_listing_data_source</argument>

but in copied code i am found diff datasource name:
        <argument name="name" xsi:type="string">vendorname_customergroup_deal_listing_data_source</argument>

Can you please check and make it same


text:
Q: Counting an aggregate result in SQL I am a novice SQL programmer, but have a question that I can't seem to find the answer to.
Suppose you have a table with two fields, like this:
ID         ReportText

100        aaaaaaaaa
100        bbbbbbbbb
101        ccccccccc
101        ddddddddd

I am trying to get a count of entries for each ID, that is:
ID         TotalCount

100        2
101        2

(Let's assume that all the entries are distinct.)
Any ideas on how to do this?
Thanks!

A: A simple count with the group by seems to be enough :
select [id]
     , count(*) as [TotalCount]
from [tbl]
group by [id]


text:
Q: Visual Studio 2013 changes Shortcuts Randomly I'm using Visual Studio 2013 Ultimate.
The "Default Collection of Settings" are set to "C#"
Until a few weeks ago everything worked fine.
Then, from one day to another, the Search-Shortcut changed from Ctrl+F to Alt+F3. I didn't knew why, and because I was at a relatively important project, I let everything as it was.
But now, this morning, it happened again.
I saved the Project, Checked in everything into the TFS 2012, Checked out for the latest version.
Then I opened a file and made some changes and then I wanted to save it.
But Ctrl+s didn't do anything.
Well, I looked under "File", and I saw, that the shortcut had changed:
It was no longer Ctrl+s but now it was Shift+F12.
So I went to "Tools -> Import and Export settings -> Reset" and I resetted all Settings.
I reopened the Visual Studio and voilà, everything as before: Search at Ctrl+F, Save at Ctrl+S, like nothing happened.
My Question is now: Why did something like this happen? I never made any changes to the shortcuts and I didn't change anything else willingly.
Has anyone faced this issue too? I found nothing like this at Google...
Thanks for your answers


text:
Q: passing variables Ok here is an example of what I'm dealing with at the moment:
@implementation ECHOAppDelegate
 ...
 @end

 @interface PtyView (PtyPrivate)
 -(void)startTask;
 -(void) didRead: (NSNotification *)fileNoty;
 @end

 @implementation PtyView
 ...
 -(void)startTask {
 //starts task
 }
 @end

Now, if I wanted to "trigger" startTask from the ECHOAppDelegate implementation, how would I do that? Now, it says that it wasn't declared.

A: First, make sure you import the PtyView header. In ECHOAppDelegate.m:
#import "PtyView.h"

Then, assuming you have an instance of PtyView:
[myPtyViewObj startTask];


text:
Q: Update the library to a specific version This is the version of golang.org/x/net library I am using
golang.org/x/net v0.0.0-20181005035420-146acd28ed58

v0.0.0 is a release(it means there is no release)
20181005 is the time for commit
146acd28ed58- short for commit id
what is 035420 in the middle of the version?
The issue I want to upgrade this library to
https://github.com/golang/net/commit/7e3656a0809f6f95abd88ac65313578f80b00df2

So I derived the following part:
   golang.org/x/net v0.0.0-20200506       -7e3656a0809f

I can't find what should be in the middle?

A: Go Wiki: Modules: How to Upgrade and Downgrade Dependencies:

To upgrade or downgrade to a more specific version, 'go get' allows version selection to be overridden by adding an @version suffix or "module query" to the package argument, such as go get foo@v1.6.2, go get foo@e3702bed2, or go get foo@'<v1.6.2'.

So in your case just run:
go get golang.org/x/net@7e3656a0809f6f95abd88ac65313578f80b00df2

See related: Go modules pulls old version of a package


text:
Q: How to Make An Excel Graph Without Hardcoding the Data Range I have a graph getting data from a simple 2-row date and production amt. associated with that specific date. However, we are constantly adding more and more rows to this and I would like the graph to be self-updating every time we add more rows instead of having to change the formula's data range every single time we update the sheet.
Right now the formula we're using for the graphs is:
=SERIES(,'PRODUCTION SITE A'!$A$4:$A$125,'PRODUCTION SITE A'!$B$4:$B$125,1). Here's an example spreadsheet on Google Sheets to make it more visible what exactly I'm doing.

A: You can graph and chart dynamic ranges by putting the data in a Formatted Table. Highlight everything from [Date - Amt Produced] down to the last row of data (not including Total), and click "Format As Table".
Now, when you add lines to the data, the Table will expand - as will the graph! If it does not automatically expand, you can manually expand the table (and thus the graph) by simply clicking inside the Table, then clicking "Resize Table" in the Table Tools>Design tab.
Notably, if there is a blank line directly below the Table, entering data there will cause the Table to automatically expand its size to include the new data. If you have a Total row directly below the Table, you may have to "Insert" a row above the Total row, then enter data. My suggestion would be to move the Total somewhere else (perhaps above the Table?), so that you can simply type in the next blank line below the Table and have the Table adjust its size for you without the Total getting in the way.


text:
Q: Cannot read data from DATA USAGE screen of device on button click I am opening DATA USAGE screen on button click from my application, using the following Intent:-
Intent intent = new Intent();
    intent.setComponent(new ComponentName("com.android.settings","com.android.settings.Settings$DataUsageSummaryActivity"));
    startActivity(intent);
Now I want to read the data usage of a particular application, say YouTube, and print the same on an EditText in my application. Can anybody suggest how to achieve this?


text:
Q: Rendering specific values on React.js Modal I am trying to render some array/object values in a Modal with React. The problem is when I trigger the modal, values from all modals are rendered.
I searched and learned that it's because I need to store the value ID in state and then tell react to trigger that specific ID not all. But I don't know how to apply it.
Here's a basic example:
const items = [{id: 1, name: 'John', friends: ['Michael', 'Tom']},{id: 2, name:
'Robert', friends: ['Jim', 'Max']}]

const [show, setShow] = useState(false);
<>
{items.map((i) => {

{i.name}

<button onClick={() => setShow(true)}>View Friends</button>

;
})}
{show ?
{items.map((i) => i.friends)}
 : null} **I know this is wrong**
</>

So I was wondering how can I store the ID to let React know that I want that specific item to render and not all.

A: Save id in state
const [show, setShow] = useState(null);
...
<button onClick={() => setShow(i.id)}>View Friends</button>
...
{show !== null &&
{ items.find(i => i.id === show).friends }
}

A: You have to save the selection id in the component state.
const items = [{id: 1, name: 'John', friends: ['Michael', 'Tom']},{id: 2, name:
'Robert', friends: ['Jim', 'Max']}]

const [show, setShow] = useState(false);
const [id, setId] = useState(null);
<>
{items.map((i) => {

{i.name}

// set the user's selection into another local state
<button onClick={() => { setShow(true); setId(i.id)}}>View Friends</button>

;
})}
// filter the current records for the selected id
{show &&
{items.filter(obj => obj.id === id)?[0].friends}
}
</>

A: First store the selected record in state like
const [selectedRecord,setSelectedRecord] = useState(null);

now when you click on button update selected record like this
<button onClick={() => { setShow(true); setSelectedRecord(i)}}>View Friends</button>

and use it to render inside modal like this
{show ?
name :{selectedRecord.name} Friends :{ selected.friends.join(',')}
 : null}

Finally your code should be like this
const items = [{id: 1, name: 'John', friends: ['Michael', 'Tom']},{id: 2, name:
'Robert', friends: ['Jim', 'Max']}]

 const [show, setShow] = useState(false);
 const [selectedRecord,setSelectedRecord] = useState(null);
 <>
  {
    items.map((i) => {

{i.name}

     // set the user's selection into another local state
    <button onClick={() => { setShow(true); setSelectedRecord(i)}}>View Friends</button>

;
 })}
   {show ?
name :{selectedRecord.name} Friends :{   selected.friends.join(',')}
 : null}
  </>


text:
Q: Session loss and regeneration on page redirect I am having this problem for two days now. I am using the database driver of laravel and session data is regenerated on every page load therefore losing old session and populating the session table. I am using laravel 4.2.6 on localhost and below is my app/config/session.php.
return array(
 'driver' => 'database',
 'lifetime' => 120,
 'expire_on_close' => true,
 'files' => storage_path().'/sessions',
 'connection' => 'mongodb',
 'table' => 'sessions',
 'lottery' => array(2, 100),
 'cookie' => 'laravel_session',
 'path' => '/',
 'domain' => null,
 'secure' => false,
);

Please help.


text:
Q: How to remove first two characters from a date string (MM/dd/yyyy) in array? I have an array that stores date input from users but I want to remove or trim the first two characters (basically, I want to remove the month) from every date inputted in the array:
class MainClass
{
    {
    //Main Program....
    }

public static int GetInput (string[] date)
{
    int loop;

    (for int i=0 ; i < loop ; i++)
    dArray[i] = Console.ReadLine();
}
}

class OtherClass
{
    //Required data properties, etc...

    public string TrimFirstTwoMonthChar(string dateInput)
    {
      char[] delimiter = {'/', '-', .... }

      string[] monthNumberRemoved = dateInput.Split(delimeter);

     // How would I code the rest of this function so that it removes the first 2 characters from "MM/dd/yyyy".
     //Keep in mind I have also allowed users to input the date in formats like
     //"M/dd/yyyy" (such as 3/07/2011 vs 03/07/2011)
     //so sometimes I would only need to remove ONE NOT TWO of the month character //
    }
}

A: Something like this?
public string TrimFirstTwoMonthChar(string dateInput)
{
  char[] delimiter = {'/', '-', .... }

  string[] monthNumberRemoved = dateInput.Split(delimeter);

  return monthNumberRemoved[1] + "/" + monthNumberRemoved[2];
}

A: With string, you can use a simple substring:
public static string TrimFirstTwoMonthChar(string dateInput)
{
    var indexOfFirstBar = dateInput.IndexOf('/');
    var start = indexOfFirstBar + 1;

    return dateInput.Substring(start, dateInput.Length - start);
}

But I suggest you to convert to DateTime and use the date format you want:
public static string TrimFirstTwoMonthChar(string dateInput)
{
    var date = Convert.ToDateTime(dateInput);
    return date.ToString("dd/yyyy"); // Use the format you want here
}

About Convert.ToDateTime and date formats.


text:
Q: How do you draw a GdkPixbuf in python? Ok, so I'm trying to overlay a picture of a printer on top of a image (blueprint of floorplan).  I originally was looking at pixmaps, but had trouble finding anything about them in GTK 3.0 (found how to use them in pygtk, but not the same thing).  Anyways, here's what I have right now (I'm leaving out what I think to be insignificant parts of my code.  Also, the program builds fine, but I don't see any image overlay):
import cairo
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, Gdk, GdkPixbuf

class ClientGUI:
    def build_interface(self):

        # Window
        self.window = Gtk.Window(Gtk.WindowType.TOPLEVEL, title="SG Print Assist")
        self.window.add(self.topbox)
        self.window.set_name('window')
        self.window.show()

        self.hbox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=6)
        # Department combobox; calls a function from another py file that retrieves the model to use.  In my program there are two other combo boxes that are dependent on this one.
        self.department_combo = Gtk.ComboBox.new_with_model_and_entry(self.logic.get_department_store())
        self.department_combo.connect("changed", self.on_department_combo_changed)
        self.department_combo.set_entry_text_column(0)
        self.hbox.pack_start(self.department_combo, False, False, 0)
        self.department_combo.show()
        self.hbox.show()

        # Image; will change to different images (floor plans) based on user input into combobox
        self.image = Gtk.Image()
        self.image.set_from_file("pics/City Logo.jpg")
        self.image.show()

        # XPM;  This isn't a printer, but for testing purposes it really doesn't matter.
        printer_xpm = [
            "48 48 64 1",
            "       c None",
            ".      c #DF7DCF3CC71B",
            "X      c #965875D669A6",
            "o      c #71C671C671C6",
            "O      c #A699A289A699",
            "+      c #965892489658",
            "@      c #8E38410330C2",
            "#      c #D75C7DF769A6",
            "$      c #F7DECF3CC71B",
            "%      c #96588A288E38",
            "&      c #A69992489E79",
            "*      c #8E3886178E38",
            "=      c #104008200820",
            "-      c #596510401040",
            ";      c #C71B30C230C2",
            ":      c #C71B9A699658",
            ">      c #618561856185",
            ",      c #20811C712081",
            "<      c #104000000000",
            "1      c #861720812081",
            "2      c #DF7D4D344103",
            "3      c #79E769A671C6",
            "4      c #861782078617",
            "5      c #41033CF34103",
            "6      c #000000000000",
            "7      c #49241C711040",
            "8      c #492445144924",
            "9      c #082008200820",
            "0      c #69A618611861",
            "q      c #B6DA71C65144",
            "w      c #410330C238E3",
            "e      c #CF3CBAEAB6DA",
            "r      c #71C6451430C2",
            "t      c #EFBEDB6CD75C",
            "y      c #28A208200820",
            "u      c #186110401040",
            "i      c #596528A21861",
            "p      c #71C661855965",
            "a      c #A69996589658",
            "s      c #30C228A230C2",
            "d      c #BEFBA289AEBA",
            "f      c #596545145144",
            "g      c #30C230C230C2",
            "h      c #8E3882078617",
            "j      c #208118612081",
            "k      c #38E30C300820",
            "l      c #30C2208128A2",
            "z      c #38E328A238E3",
            "x      c #514438E34924",
            "c      c #618555555965",
            "v      c #30C2208130C2",
            "b      c #38E328A230C2",
            "n      c #28A228A228A2",
            "m      c #41032CB228A2",
            "M      c #104010401040",
            "N      c #492438E34103",
            "B      c #28A2208128A2",
            "V      c #A699596538E3",
            "C      c #30C21C711040",
            "Z      c #30C218611040",
            "A      c #965865955965",
            "S      c #618534D32081",
            "D      c #38E31C711040",
            "F      c #082000000820",
            "                                                ",
            "          .XoO                                  ",
            "         +@#$%o&                                ",
            "         *=-;#::o+                              ",
            "           >,<12#:34                            ",
            "             45671#:X3                          ",
            "               +89<02qwo                        ",
            "e*                >,67;ro                       ",
            "ty>                 459@>+&&                    ",
            "$2u+                  ><ipas8*                  ",
            "%$;=*                *3:.Xa.dfg>                ",
            "Oh$;ya             *3d.a8j,Xe.d3g8+             ",
            " Oh$;ka          *3d$a8lz,,xxc:.e3g54           ",
            "  Oh$;kO       *pd$%svbzz,sxxxxfX..&wn>         ",
            "   Oh$@mO    *3dthwlsslszjzxxxxxxx3:td8M4       ",
            "    Oh$@g& *3d$XNlvvvlllm,mNwxxxxxxxfa.:,B*     ",
            "     Oh$@,Od.czlllllzlmmqV@V#V@fxxxxxxxf:%j5&   ",
            "      Oh$1hd5lllslllCCZrV#r#:#2AxxxxxxxxxcdwM*  ",
            "       OXq6c.%8vvvllZZiqqApA:mq:Xxcpcxxxxxfdc9* ",
            "        2r<6gde3bllZZrVi7S@SV77A::qApxxxxxxfdcM ",
            "        :,q-6MN.dfmZZrrSS:#riirDSAX@Af5xxxxxfevo",
            "         +A26jguXtAZZZC7iDiCCrVVii7Cmmmxxxxxx%3g",
            "          *#16jszN..3DZZZZrCVSA2rZrV7Dmmwxxxx&en",
            "           p2yFvzssXe:fCZZCiiD7iiZDiDSSZwwxx8e*>",
            "           OA1<jzxwwc:$d%NDZZZZCCCZCCZZCmxxfd.B ",
            "            3206Bwxxszx%et.eaAp77m77mmmf3&eeeg* ",
            "             @26MvzxNzvlbwfpdettttttttttt.c,n&  ",
            "             *;16=lsNwwNwgsvslbwwvccc3pcfu<o    ",
            "              p;<69BvwwsszslllbBlllllllu<5+     ",
            "              OS0y6FBlvvvzvzss,u=Blllj=54       ",
            "               c1-699Blvlllllu7k96MMMg4         ",
            "               *10y8n6FjvllllB<166668           ",
            "                S-kg+>666<M<996-y6n<8*          ",
            "                p71=4 m69996kD8Z-66698&&        ",
            "                &i0ycm6n4 ogk17,0<6666g         ",
            "                 N-k-<>     >=01-kuu666>        ",
            "                 ,6ky&      &46-10ul,66,        ",
            "                 Ou0<>       o66y<ulw<66&       ",
            "                  *kk5       >66By7=xu664       ",
            "                   <<M4      466lj<Mxu66o       ",
            "                   *>>       +66uv,zN666*       ",
            "                              566,xxj669        ",
            "                              4666FF666>        ",
            "                               >966666M         ",
            "                                oM6668+         ",
            "                                  *4            ",
            "                                                ",
            "                                                "
        ]

        # Pixbuf; the printer image I'm trying to overlay on the image.  Will probably create a class to represent the printer objects overlaying which contains position member variables.  Will then make a list of these to overlay all of them over the image at different positions.
        pixbuf = GdkPixbuf.Pixbuf.new_from_xpm_data(printer_xpm)
        w, h = pixbuf.get_width(), pixbuf.get_height()

        surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, w, h)
        context = cairo.Context(surface)

        Gdk.cairo_set_source_pixbuf(context, pixbuf, 100, 100)
        context.paint()

Any help would be greatly appreciated.  Thanks.


text:
Q: Transparent background for png image with CSS I wonder is it possible to make transparent background for only 1 color of a png image.
For exemple if my image contains 2 colors red and blue, I wanna make transparent (or change opacity) only the red color.

A: No, you will need to use a img editor like adobe illustrator.
CSS will not do it for you.


text:
Q: Split mysql data into 3 bootstrap md columns with php im trying to divide some info retrieved from a mysql db to 3 columns ("col-md-4") without repeating the info. I have been have trouble with mysqli_fecth_assoc() beacuse it replicates the info in all columns. Any idea? Thanks in advance

    <?php while($fila = mysqli_fetch_assoc($resultado)){ ?>

<?php echo $fila["Nombre"];?>

<?php echo $fila["Nombre"];?>

<?php echo $fila["Nombre"];?>

    <?php } ?>

the problem with thath code is that it repeats the same $fila["Nombre"] in all columns.

A: I think this code will help to get the expected result.
<?php
    $tempFila = array();

    while($fila = mysqli_fetch_assoc($resultado)){
        $tempFila[] = $fila["Nombre"];
    }

    $count = count($tempFila);
?>

        <?php for ($i = 0; $i < $count;) { ?>

<?php echo (!empty($tempFila[$i])) ? $tempFila[$i] : ''; $i++; ?>

<?php echo (!empty($tempFila[$i])) ? $tempFila[$i] : ''; $i++; ?>

<?php echo (!empty($tempFila[$i])) ? $tempFila[$i] : ''; $i++; ?>

        <?php } ?>


text:
Q: How access db postgres with other user I'm new to postgres.
I created a postgres docker container; when I access through the command "psql -U postgres" I access regularly and the prompt becomes like this: postgres=#.
(At the moment I have not created a database I have left the default one)
I created some superuser accounts, and in fact when I type \du, they appear in the table.
So far no problem.....
Now I would like to log in as one of these created users so I exit and go back to "root@@0c23b98444fc".
What's the problem?
When I try to access one of these users (with the psql -U kate command), I get the error:
" psql: error: connection to server on socket "/var/run/postgresql/.s.PGSQL.5432" failed: FATAL: database "kate" does not exist.
I don't understand why the users were created regularly and I don't understand why the postgres user lets me log in while the others don't.
I hope for some help

A: you need to create database for kate or log in to default database with kate user.
example:
psql -U kate postgres => to login to postgres database with kate user.
alternatively, create default database for kate:
psql -U postgres
CREATE DATABASE kate OWNER kate;
GRANT ALL PRIVILEGES on DATABASE kate to kate;

then next time you can login with psql -U kate


text:
Q: Applying setStyle to QLabel in PySide/PyQt In PySide, I am trying to change the overall style of a simple GUI window (a QLabel object), as outlined at the PySide documentation:
http://srinikom.github.io/pyside-docs/PySide/QtGui/QStyle.html#detailed-description
That is, as described at that link, I want to use setStyle to change the overall GUI format to one of the pre-defined GUI styles (e.g., from Windows to Cleanlooks). (As I note below, this goal is different from tweaking colors and such using setStyleSheet, which I already know how to do).
To get started, I first checked what style types I have available:
print QtGui.QStyleFactory.keys()

This revealed many available styles, including 'Cleanlooks'.
Second, based on documentation from three sources (PySide, ZetCode, and Nullege), I tried to change my QLabel style to 'Cleanlooks':
QtGui.QApplication.setStyle(QtGui.QStyleFactory.create('Cleanlooks'))

Unfortunately, this changed nothing. In fact, nothing I enter has changed a single pixel in my Hello World widget. Not sure if relevant, but when I print the output of the previous line of code, I always get None. Full example code is below the fold.
I am in Windows 7, Python 2.7 running within iPython. Based on replies, this seems to be an issue with PyQt4 in Windows 7 too, not just PySide.
Just to be extra clear, I am not asking about how to use setStyleSheets to tweak my widget. This has been addressed decently already:
Styling with classes in Pyside + Python

Example of code I tried (other permutations I tried are shown in comments):
# coding: utf-8

import sys
from PySide import QtGui

class HelloWorldApp(QtGui.QLabel):
    def __init__(self):
        QtGui.QLabel.__init__(self, "Hello, world!")
        self.initUI()

    def initUI(self):
        QtGui.QApplication.setStyle(QtGui.QStyleFactory.create('Cleanlooks'))
        self.show()

def main():
    #QtGui.QApplication.setStyle(QtGui.QStyleFactory.create('Cleanlooks'))  #crashes program
    qt_app=QtGui.QApplication(sys.argv)
    #QtGui.QApplication.setStyle(QtGui.QStyleFactory.create('Cleanlooks'))  #does nothing
    exHell=HelloWorldApp()
    sys.exit(qt_app.exec_())

if __name__=="__main__":
    main()

A: The most helpful resource I found, which answered my question, was this wonderful gallery of widgets:
Widget Gallery
It shows the look of pretty much every type of widget under the different styles.
It turns out my "problem" with QLabel was not a bug, but rather that a bare QLabel is so simple that changing its style rarely influences how it looks. That is, when it is the only thing you have in your display, at best it will not be obvious when you change the style (as in my Hello World example in my question).
As expected, when I replaced the simple QLabel in my example with a combobox or other more complex widget, the style differences showed very clearly, just as described in the Widget Gallery.
Note the above Widget Gallery was pointed out when I asked about this at Qt Centre


text:
Q: Get the Query parameter from the URL in to Component I am trying to understand how I can get the Query parameter from the URl in to my Component. Below is what I tried, I set the route in the app-routing.module.ts like
  {
      path: 'ProjectShipment/userId/231',
      component: ProjectShipmentComponent,
      data: { title: 'Project Shipment' },
  }

And with in the project-shipment.component.ts I tried like
import {Router, ActivatedRoute, Params} from '@angular/router';
export class ProjectShipmentComponent implements OnInit {

  constructor( private activatedRoute: ActivatedRoute) { }

  ngOnInit() {
    debugger;
    this.activatedRoute.queryParams.subscribe(params => {
      const userId = params['userId'];
      console.log(userId);
    });}}

When I debug it I get undefined in the logs

What am I missing here

A: You need to change your route to
{
      path: 'ProjectShipment/:userId',
      component: ProjectShipmentComponent,
      data: { title: 'Project Shipment' },
  }

Then when you call it like yourhost/projectshipment/231 in your component
 this.activatedRoute.params.subscribe(params => {
      const userId = params['userId'];
      console.log(userId);
    })

to get queryparams you code is right but your route should
{
      path: 'ProjectShipment',
      component: ProjectShipmentComponent,
      data: { title: 'Project Shipment' },
  }

and url should be yourhost/projectshipment?userid=231


text:
Q: Search and replace colon (:) between double quotes using regular expressions I am fairly new to regular expression therefore this may be the simplest question you've seen on StackOverflow :-)
I have a large JSON file with text like this:
{..., "text": "BLAH BLAH", ...}
The text may contain any of the special characters and also characters like \", which I understand can be seen as escape character in regular expression. I am trying to find and replace a single character colon : with tilde ~ within the portion followed by "text" preferably in Notepad++. Any help will be greatly appreciated.

A: This regex will find all the : in the value for fields named text and replace the character with a ~. Note there were issues using regular expressions with Notepad++ v5. My demo here was tested in Notepad++ v6.3.3
Regex: ("text":\s"[^"]*?):
Replace with: $1~
Input string: {"not text": "12:34", "text": "BLAH:BLAH", "Never get a": ":oskupee"}

A: Here is what I did (thanks for all the help @Mike, but I had to make many edits. That's why I am answering my own question so other users can get the complete answer)

*

*Search for \"text\": \".*? : .*?\", in Notepad++

*Find and replace with \1~\2 to replace all : with ~

*Manually correct the mistakes

A: You can do this:
find: ("(?:[^"]+|(?<=\\)")*")\s*:
replace: $1~

The idea is to capture the content inside double quotes, to put it in the replacement.
I use a lookbehind to allow escaped double quotes inside double quotes.


text:
Q: Advanced OOP in PHP5? I want to know more about OOP in PHP 5.2.
Can anybody help me with a link to advanced OOP tutorials in PHP?
I know about static, public and private class member attributes, but I need more info about basic and advanced OO techniques. I hope somebody can help. :)

A: In order to first understand OOP with PHP, you must understand the core concepts behind OOP. Tutorials won't help you correctly grasps things like abstraction, inheritance, encapsulation, and polymorphism.
Grab a book about Object Oriented Programming, that is the best way to learn. One of my favorites is:
Design Patterns: Elements of Reusable Object-Oriented Software

If you want something more PHP oriented, I heard nothing but good things about:
PHP 5 Objects, Patterns, and Practice
PHP 5 Objects, Patterns, and Practice http://ecx.images-amazon.com/images/I/51BF7MF03NL._BO2,204,203,200_PIsitb-sticker-arrow-click,TopRight,35,-76_AA240_SH20_OU01_.jpg
Both are available at Amazon.com
I don't understand why so many young/new programmers have a total aversion for books when they start learning.

A: Have you checked out the OOP WikiBook entry?

A: This is good: http://www.tuxradar.com/practicalphp/6/0/0


text:
Q: How can I make unlimited windows using Xcode when developing a Mac app? I am trying to develop an application for the mac however I am having issues trying to make multiple windows such as when you click cmd+N on safari.
I have tried looking for tutorials on how to do it however the closest I have got to be able to do this is just by creating a separate window by using this tutorial here: https://www.youtube.com/watch?v=Z1Erw7aP0EQ
If anyone knows how I can make unlimited windows using Xcode I will highly appreciate it!

A: Just write a NSDocument-based app, as described in Apple's docs. BTW, Apple's docs are always worth visiting together with the various tutorials you can dig up with Google.
That said, the document architecture works best if your window is going to contain something that can be viewed as a document. If the Open... (and maybe Save...) menu items make sense for your data, then you'll likely be fine with the document architecture, otherwise you should be prepared to jump through a few hoops to tweak the architecture to your needs.


text:
Q: Reading Stream after using enableReceiveTimeout I am currently working on a Java project, one of the aims of which is to display current position of the user on a map. After code completion, I realized that there is a possibility of the user unplugging the GPS device while the application is still running. On recreating the above scenario, I found that the application forever hangs at the code :
detectedGPSPortBufferReader.readLine();

So, I went to the good old Java Docs and found the method enableReceiveTimeout() and everything works perfect. (Value is 30000, 30 seconds)
Now, I have managed to think of another scenario, wherein the user may re-plug the device back on. In this scenario, my clientele would want the device to start reading again. But unfortunately that ain't happening.
I am working with my buddy "The Good Old Java Docs" and would love for any one of you geek gods to guide me on my journey.
My Code :
try {
    myGPSConnector.detectedGPSPort.enableReceiveTimeout(3000);

    if(myGPSConnector.detectedGPSPortBufferReader.readLine() != null)
    {
        myGPSConnector.nmeaResponse = myGPSConnector.detectedGPSPortBufferReader.readLine();
        System.out.println(myGPSConnector.nmeaResponse);
    }
}
catch (Exception e)
{
    locationString = "GPS Device not detected.";
}

@derrabink : It can be a different stream, cuz I tried to work with the following extension to my code :
try {
    myGPSConnector.detectedGPSPort.enableReceiveTimeout(3000);

    if(myGPSConnector.detectedGPSPortBufferReader.readLine() != null)
    {
        myGPSConnector.nmeaResponse = myGPSConnector.detectedGPSPortBufferReader.readLine();
        System.out.println(defaultGPSConnector.nmeaResponse);
    }
}
catch (Exception e)
{
    locationString = "GPS Device not detected.";

    try {
        defaultGPSConnector.detectedGPSPort.enableReceiveTimeout(30);
        }
        catch (UnsupportedCommOperationException e1)
        {
            System.out.println("UnsupportedCommOperationException");
                        }

    try {
            locationString = defaultGPSConnector.detectedGPSPortBufferReader.readLine();
        }
    catch (IOException e1)
        {
            System.out.println("IOException ");
        }

And It always prints IOException

A: I'd change your if for a while statement:
while ( myGPSConnector.detectedGPSPortBufferReader.readLine() == null ) {
    // don't do anything. Will stay here until the client decides to plug it again.
}

myGPSConnector.nmeaResponse = myGPSConnector.detectedGPSPortBufferReader.readLine();
System.out.println(myGPSConnector.nmeaResponse);

Edit.
for (long stop=System.nanoTime()+TimeUnit.SECONDS.toNanos(30); stop>System.nanoTime();)
{

    //this loop will execute for exactly 30 seconds
    if ( myGPSConnector.detectedGPSPortBufferReader.readLine() != null )
    {
        myGPSConnector.nmeaResponse = myGPSConnector.
        detectedGPSPortBufferReader.readLine();
        System.out.println(myGPSConnector.nmeaResponse);
    }
}

So, you have a loop for 30 seconds, if nothing if there's nothing to read during those, that means the guy has better things to do than playing with GPS.
This is my approach. Caution, may not work.


text:
Q: Akka stream: process CSV with header Reading a CSV files using Akka Streams
- based on this question.
I have CSV read using Akka Streams.
Now I need to perform process it line by line - but I also need to know what were the names of headers.
Any options?
UPD.
Clarifying a bit.
FileIO.fromPath(Paths.get("a.csv))
.via(Framing.delimiter(ByteString("\n"), 256, true).map(_.utf8String))
.runForeach(println /* header  + current line for each line*/)

A: You can use prefixAndTail to take the first element - in this case the headers - and then combine it lazily with subsequent elements (the rows).
Here's an example with the headers and columns combined to form a Map[String, String]:
val flow: Flow[Seq[String], Map[String, String], NotUsed] = Flow[Seq[String]]
  .prefixAndTail(1).flatMapConcat { case (headers, rows) =>
    rows.map (row => headers.head.zip(row).toMap)
  }

val test: Source[Seq[String], NotUsed] = Source(
  List(Seq("col1", "col2"), Seq("a", "b"), Seq("1", "2")))

Await.result(test.via(flow).runForeach(println), 20.seconds)
// Map(col1 -> a, col2 -> b)
// Map(col1 -> 1, col2 -> 2)

A: Alpakka, the collection of Akka Streams connectors, provides CSV support:
Source
  .single(ByteString("""header1,header2,header3
                       |1,2,3
                       |4,5,6""".stripMargin))
  .via(CsvParsing.lineScanner())
  .via(CsvToMap.toMap())
  .map(_.mapValues(_.utf8String))
  .runForeach(println)

// Map(header1 -> 1, header2 -> 2, header3 -> 3)
// Map(header1 -> 4, header2 -> 5, header3 -> 6)


text:
Q: How to convert columns into rows in MS Access Please help me to understand, how to convert columns to rows in MS Access. I have the below table, I would like to convert as the below result table.
NoOf_A NoOf_B NoOf_C NoOf_D
200    300    400    500

Result Table:
Type_OfCValue  Total
NoOf_A          200
NoOf_B          300
NoOf_C          400
NoOf_D          500

A: you don't really convert columns to rows in the tables as they represent different concepts (column=structure, row=data).
What you need is a crosstab query. Check the link from excellent Allen Browne's site:
Crosstab queries
You can use a SELECT query first. Use that as source to your Crosstab query.


text:
Q: Creating Wizard HTML/CSS Interface Using jQueryUI I'm trying to create a wizard-like interface where there are back/next and start-over buttons with the main content taking up the majority of the space. This is in HTML/CSS and using jQueryUI for an HTML Application (HTA) to only target IE8. Currently this is what I have:
HTML:

        <button class="bottombutton" id="backbutton">Back</button>
        <button class="bottombutton" id="startoverbutton">Start Over</button>
        <button class="bottombutton" id="nextbutton">Next</button>

CSS:
.bottombutton {
    position: absolute;
    margin-top: 20px;
    bottom: 10px;
}

.centeredbuttons {
    margin-left: auto;
    margin-right: auto;
}

#backbutton {
    left: 10px;
}

#nextbutton {
    right: 10px;
}

#startoverbutton {
    position: absolute;
    left: 100px;
}

#maincontent {
    position: fixed;
    height: 340px;
    width: 96.3%;
    top: 12px;
    left: 12px;
}

However, the result is extremely inconsistent when using jQueryUI's Accordion depending on the contents of the Accordion (the Accordion is always placed into #maincontent) and I would like it to FILL the parent div (#maincontent). The height can easily vary between pages despite the Accordion being set to heightStyle: "fill". (Content is loaded dynamically into #maincontent using load().)
This is how I would like it to look (and some pages do):

And how some pages look (some are much worse than this):

A: Eventually I discovered how to fix this. My issues were largely due to trying to load content into a div (#maincontent) that had my sizing parameters on it. What I needed to be doing is specifying my sizing parameters on the accordion div instead with only the height size specified on #maincontent. Here's what I changed to make it work :
#maincontent {
    height: 300px;
}

#modeaccordion {
    height: 300px;
    width: 96.3%;
    position: fixed;
    top: 12px;
    left: 12px;
    max-height: 300px;
}

Now when loading between pages you can't even tell that they're totally different html pages -- the size remains very steady.


text:
Q: How do I parallellise a for loop, and save the results of each repetition in a matrix? I'm running a simulation for several repetitions and I'm trying to see if it would be possible to parallellise these repetitions to improve computation time.
Currently I simply run the simulation several times in a for loop, but ideally these could all be run at the same time, and then the results from each repetition saved to an array for processing.
Currently my code is something like
public static void getAllTheData(){

   int nReps = 10;
   double[][] allResults = new double[nReps][]

   //this for loop is what I want to parallellise
   for(int r = 0; r < nReps; r++){

       //run the simulation to completion here
       simulation.doStuffToCompletion()

       allResults[r] = simulation.getValues()

   }
//average allResults here and do further analysis
}

My question is, how can I run all these repetitions at the same time in parallel, and save the results from each parallel run in an allResults type array?
Thanks very much.

A: You can try something like parallel streams to do parallelism like one of the below lines.
Stream.of(allResults).parallel().forEach(i -> processData(i));

Arrays.stream(allResults).parallel().forEach(i -> processData(i));

A: Java is a synchronous language by default and to do work in parallel you would need to look into threads. I suggest looking into asynchronous function calls and ways to do it in Java.
Here is a previous question asked on this matter: How to asynchronously call a method in Java
With an asynchronous call, you can run your simulation on however many threads you want and collect the data as your simulation runs finish.


text:
Q: How to remove escape character from solr indexed field? I am indexing Json data into solr field, for eg
{"employees":[
    {"firstName":"John", "lastName":"Doe"},
    {"firstName":"Anna", "lastName":"Smith"},
    {"firstName":"Peter", "lastName":"Jones"}
]}

But Json is getting indexed with escaped characters, so now I am getting the json as
  "{\"employees\":[\n    {\"firstName\":\"John\", \"lastName\":\"Doe\"},\n    {\"firstName\":\"Anna\", \"lastName\":\"Smith\"},\n    {\"firstName\":\"Peter\", \"lastName\":\"Jones\"}\n]}"

Is there any way to index without escaping the json or de escaping result while displaying from the solr end solely ?

A: This is perfectly fine storage of json data in a solr textfield.
If you see it through admin, you will see the json in escaped format in the UI, but if you were to query this and then decode the json, it will return correct object in the language you are using.
Python example.
my_json_field =  json_string // read from solr using api calls or module like pysolr
my_obj = json.loads(my_json_field)

A: Finally solution was very simple by using Transforming Result Documents
eg,
fl=my_field_with_escaped_json:[json]

Thanks everyone


text:
Q: Is there a name for mapping recursive data types based on terminals and their ancestries? Let's say I have a type that looks like this:
data Term a = Terminal a
| Application (Term a) (Term a)
| Abstraction String (Term a)

Now, I want to map Term a to Term b. Ideally, I would be able to do this using a function  (a -> b) and just implement fmap. However, that doesn't work for me. The map from Terminal a to Terminal b is dependent not just on the value of a, but also the values of the ancestors of Terminal a (e.g. the depth of Terminal a). So it's more like [Term a] -> b which is messy, so I'm trying to decompose this into something cleaner.
So really, what I need is something like 2 functions and an initial value: (c -> Term a -> c) can be called on each of the ancestors in order to accumulate whatever we want. (I guess it's equivalent to ([Term a] -> c) but I'm not sure whether that confuses the situation or helps.) (c -> a -> b) can map Terminal a to Terminal b. (We also need an initial value of type c)
So I'm definition a function with the following type signature:
notQuiteANatTrans :: (c -> Term a -> c) -> (c -> a -> b) -> c -> Term a -> Term b

This isn't a natural transformation. (I don't think) Or if it is, it's mapping something like [Term a] -> [Term b] where each of those is the path from the root of the tree to the Terminal. Is there a name for this? Is there maybe a different way to decompose my arrows in order to get something cleaner?

A: I'm not sure I entirely understand the problem, so apologies if the following goes off on an irrelevant tangent...

The map from Terminal a to Terminal b is dependent not just on the value of a, but also the values of the ancestors of Terminal a (e.g. the depth of Terminal a).

This sounds reminiscent of having to examine a tree to find, for example, its depth. For a tree, you can do this with its catamorphism - see e.g. the examples for foldTree.
In general, if you know the catamorphism for a datatype, you can derive most other (perhaps all?) useful functions from it. So what's the catamorphism for Term a?
F-Algebra
You can derive the catamorphism from F-Algebras. I'll follow the process I've used in my own article series on catamorphisms.
Define the underlying endofunctor like this:
data TermF a c =
    TerminalF a
  | ApplicationF c c
  | AbstractionF String c
  deriving (Eq, Show)

instance Functor (TermF a) where
  fmap _ (TerminalF a) = TerminalF a
  fmap f (ApplicationF x y) = ApplicationF (f x) (f y)
  fmap f (AbstractionF s x) = AbstractionF s (f x)

This enables you to figure out the catamorphism by using typed holes:
termF = cata alg
  where alg      (TerminalF x) = _
        alg (ApplicationF x y) = _
        alg (AbstractionF s c) = _

If you try to compile this sketch, the compiler will complain about the type holes and tell you what you need. I used this process to arrive at this function:
termF :: (a -> c) -> (c -> c -> c) -> (String -> c -> c) -> Fix (TermF a) -> c
termF t appl abst = cata alg
  where alg      (TerminalF x) = t x
        alg (ApplicationF x y) = appl x y
        alg (AbstractionF s x) = abst s x

The catamorphism requires a mapper of the underlying type a -> c, as well as 'accumulators' for each of the recursive nodes.
Isomorphism
Fix (TermF a) is isomorphic with Term a, as witnessed by these two conversion functions:
toTerm :: Fix (TermF a) -> Term a
toTerm = termF Terminal Application Abstraction

fromTerm :: Term a -> Fix (TermF a)
fromTerm = ana coalg
  where coalg      (Terminal x) = TerminalF x
        coalg (Application x y) = ApplicationF x y
        coalg (Abstraction s x) = AbstractionF s x

This means that you can easily define the catamorphism for Term a using the catamorphism for Fix (TermF a). Let's call it foldTerm, as that's probably a little more idiomatic:
foldTerm :: (a -> c) -> (c -> c -> c) -> (String -> c -> c) -> Term a -> c
foldTerm t appl abst = termF t appl abst . fromTerm

Now that you know the type of foldTerm, you can throw away all the TermF machinery and implement it directly.
Direct implementation
Again, you can use typed holes for a simpler, more direct implementation:
foldTerm :: (a -> c) -> (c -> c -> c) -> (String -> c -> c) -> Term a -> c
foldTerm t appl abst      (Terminal x) = _
foldTerm t appl abst (Application x y) = _
foldTerm t appl abst (Abstraction s x) = _

The compiler will tell you what you need, and it's fairly clear that the implementation must be something like this:
foldTerm :: (a -> c) -> (c -> c -> c) -> (String -> c -> c) -> Term a -> c
foldTerm t appl abst      (Terminal x) = t x
foldTerm t appl abst (Application x y) = appl (recurse x) (recurse y)
  where recurse = foldTerm t appl abst
foldTerm t appl abst (Abstraction s x) = abst s (foldTerm t appl abst x)

Keep in mind that the output of foldTerm can be any type c, including Term b: c ~ Term b. Does that enable you do do what you're asking about?


text:
Q: Core Data strategy using in memory cache, or no core data at all? I have a user interface where the user can check off a bunch of items from a tableview, almost like a todo list. The items are populated from a Core Data stack.
I need to be able to take all of the items they're clicking through and put them into a "temporary" shopping cart. Once they're in the shopping cart, users can go through the list and remove the items, or just submit them to a server. The thing is, the selected items are temporary just like an internet based shopping cart. It's nothing something that gets persisted once the application closes. Once the view is no longer in display, I can assume that the shopping cart is safe to discard.
What's the best way to approach this? Since the user is essentially clicking on instances that map back to a Core Data entity .. should I setup a different persistence store such as in memory and add that store to my managed object context?

A: You can make a NSMutableArray for the shopping cart, and just add and remove the Core Data objects to/from that array.


text:
Q: Status bar cover action bar in Android I want my status bar to be transparent and match action bar color. But for different activities I have diffenrent color for action bar so I can't use "colorPrimaryDark" for my status bar. How to achive this?
v21\styles.xml
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimaryDark">@android:color/transparent</item>
    <item name="android:statusBarColor">@android:color/transparent</item>
    <item name="android:windowTranslucentStatus">true</item>
</style>
<style name="AppTheme.NoActionBar">
    <item name="windowActionBar">false</item>
    <item name="windowNoTitle">true</item>
    <item name="android:windowDrawsSystemBarBackgrounds">true</item>
    <item name="android:statusBarColor">@android:color/transparent</item>
</style>

Activities has "android:fitsSystemWindows="false""
This is what I have

And this is what I want

Same for other colors in action bar.
Any help?

A: This is the normal behavior - this command is for use cases when you want a picture that can't be stretched out behind the status bar like here.
Solution-
1. In my opinion from the picture just change the status bar color:
<item name="android:statusBarColor">@android:color/Red</item>

2. Increase the height of your action bar by 25dp (status bar height).


text:
Q: VBA code to iterate through a dropdown list and then copy/paste a range for each iteration into a new tab I have a worksheet ("Analysis") with a dropdown validation list that has 5 options. The dropdown is in cell B6. I want to iterate through the 5 options in this dropdown, which produce different summary results contained in the range B10:N25, and then copy the values into a new worksheet ("Output"). I would like the summary results for each of these 5 iterations in the "Output" sheet, so need the code to update the destination cell in the Output sheet with each loop so it doesn't paste over the same area. Thank you!
I've tried a couple VBA options, but those were written for single lines of data or for creating new tabs for each iteration.
Sub Iteration_Loop()
'
' Iteration_Loop Macro
' Loops through alternatives
'

' create variables
    Dim input As Range
    Dim c As Range

    Set input = Evaluate(Sheets("Analysis").Range("B6").Validation.Formula1)
    For Each c In input
    Calculate
    Sheets("Analysis").Range("B10:N25").Copy
    Sheets("Output Sheet").Range("C5").PasteSpecial Paste:=xlPasteValuesAndNumberFormats
    'Selection.PasteSpecial Paste:=xlPasteValuesAndNumberFormats, Operation:=
    '    xlNone , SkipBlanks:=False, Transpose:=False

    Next c

End Sub

I think this does the iteration, but just copies over the same range in Output.

A: though could not understand question clearly, it is assumed that destination cells change with the iteration (otherwise it is bound to overlap previously pasted area). I used it to be copied one below other with 20 rows block as shown
.
Input is a keyword in VBA and could not be used as variable.
Sub Iteration_Loop()
Dim Rng As Range
Dim c As Range
Dim DestRow As Long

     'Set Rng to the list of values in the validation list
Set Rng = Sheets("Analysis").Range(Sheets("Analysis").Range("B6").Validation.Formula1)
DestRow = 0

     For Each c In Rng.Cells
     Sheets("Analysis").Range("B6").Value = c.Value
     Application.Calculate
     Sheets("Analysis").Range("B10:N25").Copy
     Sheets("Output Sheet").Range("C" & DestRow + 5).PasteSpecial Paste:=xlPasteValuesAndNumberFormats
     DestRow = DestRow + 20
     Next c

End Sub

A: Here is my solution including comments in the code:
Sub t()

    'Input will give you an error
    Set Input_Analysis = Evaluate(Sheets("Analysis").Range("B6").Validation.Formula1)
    For Each Value In Input_Analysis
        'Calculate -> you can use Application.Calculation = xlCalculationAutomatic, you should set it to xlManual first if you want to stop it, default - auto
        Application.Calculation = xlCalculationAutomatic
        '+ 2 since you want to paste it at least (1) row beneath the last one
        Last_Filled_Row = ThisWorkbook.Sheets("Output Sheet").Range("C104764").End(xlUp).Row + 2
        'assuming you at least want to start pasting as of row 15
        If Last_Filled_Row < 15 Then
            Last_Filled_Row = 15
        End If

        ThisWorkbook.Sheets("Analysis").Range("B10:N25").Copy
        'use the row as retrieved above
        ThisWorkbook.Sheets("Output Sheet").Range("C" & Last_Filled_Row).PasteSpecial Paste:=xlPasteValuesAndNumberFormats
    Next Value

End Sub


text:
Q: How to show multiline text in a table cell I want to show a paragraph from database into a table cell.
The result is a large 1 line, ignoring how its organised in database.
ignoring 'enters' for example (new lines)
I want to show it exactly according to how it's written in database.
For example if paragraph is saved like this:
hello ,
my name is x.

I want it to be showed exactly like that, instead of:
hello, myname is x.

A: On your server-side code, replace the new lines (\n) with
.
If you're using PHP, you can use nl2br()

A: style="white-space:pre-wrap; word-wrap:break-word"

This would solve the issue of new line.
pre tag would add additional CSS than required.

A: I use the html code tag  after each line (see below) and it works for me.
George Benson

123 Main Street

New York, Ny 12344

A: I added only
 inside the  and it works good, break the line!

A: Wrap the content in a
 (pre-formatted text) tag

hello ,
my name is x.

A: Two suggestions to solving this problem:
SOLUTION 1:
{database text}
 or
{database text}

This is good solution if your text has no html tags or css properties. Also allows to maintain tabs for example.
SOLUTION 2: Replace \n with

 or

This is a solution if you would just like to add break-lines, without losing other text properties or formatting.
An example in php would be $text = str_replace("\n","
",$database_text);
You can also use

 or

, but this requires a bit more text parsing.

A: You want to use the CSS white-space:pre applied to the appropriate . To do this to all table cells, for example:
td { white-space:pre }

Alternatively, if you can change your markup, you can use a
 tag around your content. By default web browsers use their user-agent stylesheet to apply the same white-space:pre rule to this element.

The PRE element tells visual user agents that the enclosed text is "preformatted". When handling preformatted text, visual user agents:

*

*May leave white space intact.

*May render text with a fixed-pitch font.

*May disable automatic word wrap.

*Must not disable bidirectional processing.

A: For my case, I can use like this.
td { white-space:pre-line , word-break: break-all}

A: Hi I needed to do the same thing! Don't ask why but I was generating a html using python and needed a way to loop through items in a list and have each item take on a row of its own WITHIN A SINGLE CELL of a table.
I found that the br tag worked well for me. For example:
<!DOCTYPE html>

        <TITLE></TITLE>

                    item 1

                    item 2

                    item 3

                    item 4

This will produce the output that I wanted.

A: the below code works like magic to me >>
td { white-space:pre-line }

A: If you have a string variable with \n in it, that you want to put inside td, you can try

    {value
        .split('\n')
        .map((s, index) => (
            <React.Fragment key={index}>
                {s}

            </React.Fragment>
        ))}

A: I found a lot but all of them dont work for me. If you retrieved a long text from your db and put it on the table but just wanna do the front-end styling to break the word to the new line.
For my case, white-space: break-spaces; work for me

A: if you are working in only HTML you can use \n or
 or
 any tag
but if you are doing CRUD operations
" In my case, I'm using Jquery for creating and updating an  'td.html()' and retrieve 'td.html(input)'. "

A: Add a new CSS rule for td called white-space:nowrap.
td { white-space:nowrap }


text:
Q: WPF compile started failing for Interactions and Interactivity Today I stopped being able to compile my WPF project. I started getting a host of errors such as "The attachable property 'Behaviors' was not found in type 'Interaction' in the (xxx xaml file)."
I haven't changed any references (I have both the "Microsoft.Expression.Interactions" and "System.Windows.Interactivity" dll's referenced still in my project).
UPDATED:
The errors I am getting are similar to this one:
"Error  15  The type 'i:EventTrigger' was not found. Verify that you are not missing an assembly reference and that all referenced assemblies have been built.  (Xaml Filename here)"
i: is defined as: "xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity""
When recompiling it is now getting these errors. As mentioned above I still have those same DLL references in the project. I don't know what could have changed.
Thanks.
MORE COMPLETE INFORMATION:
This code had been running fine for hundreds of ongoing compiles over a year and a half.

*

*The only real change recently that I can think of is that yesterday I did a complete uninstall of Visual Studio 2013 RC. I don't know how this could make a difference though, and the referenced Dll's still exist.

*The 2 namespace references involved are:
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"  xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions"

*All elements referencing both i: and ie: are now failing to compile with errors similar to below:

*"The type 'i:EventTrigger' was not found. Verify that you are not missing an assembly reference and that all referenced assemblies have been built."

*"The type 'ei:FluidMoveSetTagBehavior' was not found. Verify that you are not missing an assembly reference and that all referenced assemblies have been built."

*HOWEVER, I found that when I change the namespace for i: above to: "clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity", the errors for i: go away.

However I can't seem to figure out the correct syntax to change the ei="http://schemas.microsoft.com/expression/2010/interactions" reference to the Microsoft.Expression.Interactions Assembly. I don't know why it makes a difference and I may be going down the wrong path, but it's my next step. Any help on that one?

A: After more digging I discovered that the uninstall I mentioned for VS 2013 RC must have also uninstalled the Expression Blend SDK for .Net 4.
Oddly enough the Dll's that I had referenced were leftover from the 3.5 SDK but the namespace was for the .Net 4 SDK and had always been working. (Until that SDK was uninstalled). A clue for me was when I went to enter another namespace and the "//schemas.microsoft.com/expression/2010/interactivity" selection was no longer in the intellisense list.
I reinstalled the Blend SDK for .Net 4 and all is well again. Thanks for the attempts to help. A reminder to me to always focus on the question "what has changed" even though it may not be where you suspect...


text:
Q: Is it possible to properly solder SMA connectors to flexible coax (RG400)? It looks like only crimp connectors are widely available for flexible double-shielded coax cable like RG400.
There is also wide availability of solder connectors for semi-rigid cable like RG402 (but it's single-shielded).
I personally like soldered connections, but is it even possible to have soldered SMA properly working on flexible cable like RG400? It is clear that I cannot simply use RG402 connector with RG400 cable due to diameter mismatch.
Is there any double-shielded semi-rigid coax cables compatible with RG402 soldered connectors?

A: That depends on what you mean by "properly".
Good quality SMA connectors are generally 'solder - crimp', you can either solder or crimp the center pin but the shield is always crimped.
There's really no reason to want to solder the shield, it's a pain to do, and the heat of soldering is likely to melt the insulation. Also, soldering the fine braid makes it less flexible and prone to breaking where the soldered part meets the non-soldered part.
I've crimped a lot of connectors of various types. Done correctly with the appropriate crimp tool it works very well. About the only time I see failures is when someone does it wrong, or in a cable that gets flexed a lot, such as a jumper used on test equipment, and there a soldered one would fail just as fast if not faster than a crimped one.


text:
Q: Referencing jQuery ui is not working I have the following:
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css"/>
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>

I would like to replace it in my server, so that I don't have to be connected to the internet. How can I add the following to my website?
I tried the following:
<link rel="stylesheet" href="../jquery-ui.css"/>
<script src="jquery-ui.tabs.js"></script>

It' not working? I don't know what folders to download from jquery, I am using the ui tabs, so I placed the following folders in the embedded webserver:
jquery-ui.css
jquery.ui.tabs.js

Can someone help?

A: use the jQuery Download Builder to download the jQuery UI package you need:
http://jqueryui.com/download/
or to just download jQuery UI with UI tabs
http://jqueryui.com/download/#!version=1.10.3&components=1111111110010001111011111111111111


text:
Q: Typescript 4.1.5 spread operator issue I create my own interface
interface MyType {
    [key :string] :boolean
}

And I want to use spread operator to update elements of array with new A object. Let's say:
aList = new Array<MyType >({['something']:true,['something2']:true});

and I would like to update element in this array by using spread operator like:
const B : MyType = {['something']: false};
this.aList = {...aList, B};

But I'm still getting error's , or B is adding to a aList like a new element . What could be wrong ?

*

*I can't just filter through aList due to the fact that B is in my scenario a $event with any type

A: You aren't actually storing an array of MyType at the moment, instead you have initialized aList to an object which contains an array. Define it as shown below:
let aList: MyType[] = [{'bbb':true}, {'aaa':true}];

Now,
// find out the key that needs to be replaced
let keyToFind = '';
for (let obj in B) {
  keyToFind = obj;
}

// loop over aList to see if there is a match for `keyTofind`;
// if found then replace that index and break
aList.forEach((obj, index) => {
  for (let key in obj) {
    if (key === keyToFind) {
      aList[index] = B;
      break;
    }
  }
})

A: @Wiktor,
Good evening. Below is the code.
interface MyType {
    [key: string]: boolean
}

let aList = new Array<MyType>({ ['something']: true }, { ['something2']: true });
console.log(aList);

const B: MyType = { ['something']: false };

for (let index = 0; index < aList.length; index++) {
    console.log(`${JSON.stringify(aList[index])} === ${JSON.stringify(B)}`);

    for (let destinationProperty in aList[index]) {
        for (let sourceProperty in B) {
            if (destinationProperty === sourceProperty) {
                aList[index] = B;
            }
        }
    }
}
console.log(aList);


text:
Q: ASP .Net Update individual element on asp page on textchanged postback I have two gridviews in a webform visual studio project. The first is a fixed size grid which, using javascript, I have managed to set up to return a grid reference which is then output to two textboxes. These textboxes then update a second grid with records that relate to the number in the clicked cell of the first grid:

The first gridview is the colourful one, the second gridview is the dash separated text below it. In the example you can see the selected cell references are D and 3a and the second grid below is showing the 6 students' names the number in the cell D 3a is referring to. This works great. However, after I click on the grid more than once the layout gets messed up:

As you can see the rendered headers disappear and this then cause issues with the layout and subsequently the grid reference positioning.
In the databound event for the first gridview I have the following vbcode that generates the additional headers on the gridview which disappear:
    If gvProgressGrid IsNot Nothing Then
        Dim row As New GridViewRow(0, -1, DataControlRowType.Header, DataControlRowState.Normal)

        Dim left As TableCell = New TableHeaderCell()
        left.ColumnSpan = 2
        row.Cells.Add(left)
        left.BorderStyle = BorderStyle.None

        Dim grades As TableCell = New TableHeaderCell()
        grades.ColumnSpan = 10
        grades.Text = "Grades"
        row.Cells.Add(grades)

        Dim cohort As TableCell = New TableHeaderCell()
        cohort.ColumnSpan = 1
        cohort.Text = "Cohort"
        cohort.RowSpan = 2
        cohort.BackColor = Drawing.Color.FromArgb(242, 242, 242)
        row.Cells.Add(cohort)

        Dim expected As TableCell = New TableHeaderCell()
        expected.ColumnSpan = 2

        Select Case strYear
            Case "11"
                expected.Text = "Students achieving expected progress (3 or more levels)"
            Case "10"
                expected.Text = "Students achieving expected progress (2 or more levels)"
            Case "9"
                expected.Text = "Students achieving expected progress (1 or more levels)"
        End Select

        expected.BackColor = Drawing.Color.FromArgb(216, 216, 216)
        expected.Width = 250
        row.Cells.Add(expected)

        Dim above As TableCell = New TableHeaderCell()
        above.ColumnSpan = 2
        Select Case strYear
            Case "11"
                above.Text = "Students achieving above expected progress (4 or more levels)"
            Case "10"
                above.Text = "Students achieving above expected progress (3 or more levels)"
            Case "9"
                above.Text = "Students achieving above expected progress (2 or more levels)"
        End Select
        above.BackColor = Drawing.Color.FromArgb(242, 242, 242)
        above.Width = 250
        row.Cells.Add(above)

        Dim t As Table = TryCast(gvProgressGrid.Controls(0), Table)
        If t IsNot Nothing Then
            t.Rows.AddAt(0, row)
        End If
    End If

I automatically trigger a change of text/loss of focus on the second textbox using the following code in my javascript (the script that grabs the grid reference of the first gridview on click):
document.getElementById("<%=tbKS2.ClientID%>").value = strKS2;
__doPostBack(document.getElementById("<%=tbKS2.ClientID%>").name, '')

It's only the second gridview that needs to update when the first grid is clicked and it appears as though the whole page or at the very least the first gridview is updating too.
How can I get it so that once the above textbox postback is triggered only my second gridview is updated and the rest of the elements on the page stay rendered how they are?
Thanks.

A: You will need to insert the row during RowCreated event of the grid:
Private Sub gvProgressGrid_RowCreated(sender As Object, e As GridViewRowEventArgs) Handles gvProgressGrid.RowCreated
    If e.Row.RowType = DataControlRowType.Header Then

        ' the rest of your code
        ' ...
        ' ...

    End If

End Sub