text:
Q: Playing Multiple Videos when a user scrolls I am using the following script to play a video when it scrolls into the viewport, and when the user scrolls off the video it stops. The problem is it will only play one video, if i add the same html for a different source video, a blank screen appears. Any help will be appreciated. Here is the code i have;
    <script type='text/javascript' src="http://prinzhorn.github.io/skrollr/dist/skrollr.min.js"></script>
    <style type='text/css'></style>
    <script type='text/javascript'>//<![CDATA[
    $(window).load(function(){
    var s = skrollr.init({
        render: function(data) {
            var $seventh = $("#seventh");

            var $video = $("#video");
            var videoElem = $video[0];

            var videoTop = $video.offset().top;
            var videoBottom = videoTop + $video.height();

            var viewTop = $(window).scrollTop();
            var viewBottom = viewTop + $(window).height();

            //play video when opacity is at least 50% and at least some of the video player is show
            var isViewable = $seventh.css("opacity") > 0.5 && (videoTop < viewBottom && videoBottom > viewTop);
            if(isViewable) {
                if(videoElem.paused) {
                    videoElem.play();
                    console.log("play");
                }
            }
            else {
                if(!videoElem.paused) {
                    videoElem.pause();
                    console.log("pause");
                }
            }
        }
    });
    s.setScrollTop(500);
});//]]>

Thanks!


text:
Q: Changing "on-hold" reason in reopen review task While reviewing "on hold" questions for re-opening, I encountered several times the case where a question was put on hold for "Off topic - question does not demonstrate minimal understanding...". As a result the OP edited the question and practically dumped his entire  code there.
Now there is a minimal understanding of the subject but it's no no longer SSCCE.
Is it possible to have an option in "leave closed" but with a changed reason?

redpajama_set_name: RedPajamaStackExchange


text:
Q: OpenDj as backend and accessing through REST API doubts I'm doing a project using Open Am and OpenDJ as backend, I'm directly calling OpenDJ REST API for profile adding and Editing, I have the following doubts.
Is it possible to store JSON in to the OpenDj  field?
Any size limitation to fields in OpenDj  ?
Any change tracking option in OpenDj/Open AM ?
can Ido an Upsert (update if existing or Insert if it is new) through REST API?
can I add around 500 fields to a single profile? Any limitation?

A:
Is it possible to store JSON in to the OpenDj field?

You can store JSON in an attribute, however you should be aware about the format... (non ASCII values must be Base64 encoded before being stored).

Any size limitation to fields in OpenDj ?

Depending on the "syntax" (type) defined for a given attribute, there could be a limitation.

Any change tracking option in OpenDj/Open AM ?

OpenDJ audit log can be enabled to show change in LDIF format; see OpenDJ docs. OpenAM only consumes identity information from configured data stores.

can Ido an Upsert (update if existing or Insert if it is new) through REST API?

Yes, see https://backstage.forgerock.com/#!/docs/opendj/2.6.0/admin-guide/chap-rest-operations#update-rest

can I add around 500 fields to a single profile?

Yes, 'field' is called an attribute in LDAP world.

Any limitation?

apart from disk space and memory, not really


text:
Q: pyOpenSSL: wrong protocol version for the connection Environment:
Python 3.7 (Anaconda 5.3.1 on Windows)
pyOpenSSL 18.0
SSL.SSLEAY_VERSION: OpenSSL 1.0.2p  14 Aug 2018
I have a socket, which is used for some unencrypted communication and then is wrapped by pyOpenSSL:
sock = socket.socket()
sock.connect((address, port))
sock.send(msg)

context = SSL.Context(SSL.TLSv1_2_METHOD)
conn = SSL.Connection(context, sock)
conn.set_connect_state()
conn.do_handshake()

I expect the protocol to be TLS 1.2, which is specified for the context object, but Wireshark shows the following:
Secure Sockets Layer
    TLSv1 Record Layer: Handshake Protocol: Client Hello
        Content Type: Handshake (22)
        Version: TLS 1.0 (0x0301)
        Length: 302
        Handshake Protocol: Client Hello
            Handshake Type: Client Hello (1)
            Length: 298
            Version: TLS 1.2 (0x0303)

And I get:
Error: [('SSL routines', 'SSL3_GET_RECORD', 'wrong version number')]

I suppose the error has something to do with the fact that TLS 1.0 is used, but I don't understand where does it come from? If I check conn.get_protocol_version_name(), it shows TLSv1.2
Any ideas?

A: After further investigation I am going to answer the question myself. TLS 1.0 (0x0301) in the record layer of a ClientHello message is expected in OpenSSL.
I got wrong version number because the request was not routed correctly on the server side, so the response was not a valid ServerHello message.


text:
Q: Android studio 2.2 preview 5 design editor/preview seem to be broken? After updating from Android studio 2.2 preview 4 to 5, Design and Preview tabs stopped to show previews.
They don't show anything, only the error (described below) and a tip "Try to refresh the layout".
Refreshing and choosing different options in a top bar (API, device orientation) doesn't help.
Was trying File -> Invalidate Caches/Restart. Doesn't help either.
Any suggestions?
java.nio.file.InvalidPathException: Illegal char <:> at index 8: @android:drawable/ic_menu_send
at sun.nio.fs.WindowsPathParser.normalize(WindowsPathParser.java:182)
at sun.nio.fs.WindowsPathParser.parse(WindowsPathParser.java:153)
at sun.nio.fs.WindowsPathParser.parse(WindowsPathParser.java:77)
at sun.nio.fs.WindowsPath.parse(WindowsPath.java:94)
at sun.nio.fs.WindowsFileSystem.getPath(WindowsFileSystem.java:255)
at java.nio.file.Paths.get(Paths.java:84)
at com.android.ide.common.res2.ResourceItem.parseFileName(ResourceItem.java:585)
at com.android.ide.common.res2.ResourceItem.parseXmlToResourceValue(ResourceItem.java:405)
at com.android.ide.common.res2.ResourceItem.getResourceValue(ResourceItem.java:240)
at com.android.ide.common.res2.AbstractResourceRepository.getConfiguredResources(AbstractResourceRepository.java:393)
at com.android.ide.common.res2.AbstractResourceRepository.getConfiguredResources(AbstractResourceRepository.java:349)
at com.android.tools.idea.configurations.ResourceResolverCache$1.compute(ResourceResolverCache.java:166)
at com.android.tools.idea.configurations.ResourceResolverCache$1.compute(ResourceResolverCache.java:163)
at com.intellij.openapi.application.impl.ApplicationImpl.runReadAction(ApplicationImpl.java:966)
at com.android.tools.idea.configurations.ResourceResolverCache.getResourceResolver(ResourceResolverCache.java:163)
at com.android.tools.idea.configurations.Configuration.getResourceResolver(Configuration.java:1212)
at com.android.tools.idea.rendering.RenderTask.getResourceResolver(RenderTask.java:198)
at com.android.tools.idea.rendering.RenderTask.createRenderSession(RenderTask.java:425)
at com.android.tools.idea.rendering.RenderTask.lambda$inflate$52(RenderTask.java:659)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)

UPD1: Seem to be an issue.

A: In your activity.xml file there must be a line as xmlns:app="". Delete it.

A: There is an error in xml file check that no
android:  or  xmlns:app=""

A: Fixed in Android studio 2.2 (Canary) Preview 6 (also see issue).


text:
Q: I am unable to display icon on Phonegap application for iPhone I am having problems diplaying icon on iphone. On Android it is displayed properly. I used Phonegap Build to compile the app. This is the code I used in the config.xml file
<icon src="images/icon.png"  gap:platform="ios" width="57" height="57" />

A: Do you have defined the default icon?
<icon src="icon.png" /><!-- default; don't change location! -->

Here is the section for iOS, how I use it in my PhoneGap Build projects.
<icon src="icon.png" /><!-- default; don't change location! -->
<icon src="icons/ios/classic.png" gap:platform="ios" width="57" height="57" />
<icon src="icons/ios/ipad.png" gap:platform="ios" width="72" height="72" />
<icon src="icons/ios/retina.png" gap:platform="ios" width="114" height="114" />
<icon src="icons/ios/retina_ipad.png" gap:platform="ios" width="144" height="144" />

And don't change the location of the default icon, like mentioned in the sample (as comment).


text:
Q: Trying to join table on the row with a max value I feel like I need to use a sub-query but I'm having trouble getting the query to work right
As a scenario, I have an auction_item that has bids on it, there are three bids.
I want to get just the user information for the highest bid on that item.
The info I have is the item_id, so I need to look up bids on that item id, and join the user table on the user_id of the bid row with the highest bid for that item.
SELECT user.* FROM text2bid_users AS user
INNER JOIN (SELECT user_id,MAX(bid_amt) FROM text2bid_bids
WHERE item_id = 11479) AS bid
ON user.user_id = bid.user_id

Problem is it's returning the first row from bids instead of the one with the max bid_amt
Hoping someone can point me in the right direction here

A: Try the following Query:
select user.* from text2bid_users as user
where user.user_id =(select user_id from text2bid_bids
                        where item_id = 11479
                        order by bid_amt desc limit 1);


text:
Q: Como añadir imagen a correo enviado desde python Estoy intentando añadir una imagen al final de un correo enviado desde python pero me esta dando error. Hasta el mensaje lo enviaba usando html e incluso podia añadir links sin ningun problema.
message = "
Hola %s,

 Se ha detectado una alerta de seguridad

 Si este cambio ha sido voluntario, por favor, ignore este mensaje. De lo contrario por favor hago acceda al siguiente link para localizar su SIM y desactivarla:

  Localizar y desactivar SIM

    Muchas gracias,

    Equipo de Soporte ponteaprueba
 " % (customer, iccid)
mime_message = MIMEText(message, "html", _charset = "uft-8")
mime_message["From"] = "ponteaprueba@gmail.com"
mime_message["To"] = recipient
mime_message["Subject"] = "Alert"
#We try to make the conection with the SMTP server
smtp = SMTP('smtp.gmail.com', 587)
smtp.ehlo()
smtp.starttls()
smtp.ehlo()
print "Conexion exitosa con Gmail"
print "Concectado a Gmail"
#We introduce the credentials of the sender in the SMTP server and send the email.
smtp.login(username, pass)
smtp.sendmail(username,recipient,mime_message.as_string())
smtp.quit()
return "Mensaje enviado"

¿Puede ser porque es una imagen de internet? ¿Existe alguna forma de coger una imagen igual que haces con un link?
Gracias

A: # Importamos librerías
import smtplib
import mimetypes

# Importamos los módulos necesarios
from email.MIMEMultipart import MIMEMultipart
from email.MIMEImage import MIMEImage
from email.mime.text import MIMEText

# Creamos objeto Multipart, quien será el recipiente que enviaremos
msg = MIMEMultipart()
msg['From']="Remitente@gmail.com"
msg['To']="Destinatario@gmail.com"
msg['Subject']="Alarma Activada"
msg.attach(MIMEText("La alarma de movimiento ha sido activada, verifique la integridad de su vivienda."))

# Adjuntamos Imagen
file = open("Imagen.jpg", "rb")
attach_image = MIMEImage(file.read())
attach_image.add_header('Content-Disposition', 'attachment; filename = "Alarma"')
msg.attach(attach_image)

# Autenticamos
mailServer = smtplib.SMTP('smtp.gmail.com',587)
mailServer.ehlo()
mailServer.starttls()
mailServer.ehlo()
mailServer.login("Destinario@gmail.com","Password")

# Enviamos
mailServer.sendmail("Destinatario@gmail.com", "Remitente@gmail.com", msg.as_string())

# Cerramos conexión
mailServer.close()

Este código funciona para enviar una imagen adjunta, espero sea de utilidad

A: El problema está en que la cadena mensaje está mal construida. Usas el mismo tipo de comillas que usas para delimitar la cadena, como caractéres dentro de ella, sin escapar estos caractéres adecuadamente. Esto rompe tu cadena. Por ejemplo:
>>> cadena = "Dime "hola""

Dará un error de sintaxis:

SyntaxError: invalid syntax

En Python puedes crear una cadena usando comillas simples ('cadena'), dobles ("cadena") o triples ('''cadena'''). Si necesitas usar las comillas como un carácter cualquiera dentro de tu cadena, tienes dos opciones:

*

*Usar una secuecia de escape:
cadena = "Dime \"hola\""

*Usar un tipo de comillas como delimitador y otro como carácter interno:
cadena = 'Dime "hola"'
cadena = '''Dime "hola"'''
cadena = "Dime 'hola'"

En tu caso lo más simple (menos cambios requiere) es usar comillas simples para delimitar la cadena y dobles dentro de ella.
Por otro lado usas dos parámetros para formatear la cadena customery iccid pero solo usas uno en la cadena, esto dará también error:

TypeError: not all arguments converted during string formatting

Si uno no hace falta, quítalo. Si hacen falta los dos, añade el %s correspondiente en el lugar que toque.
Para terminar, el uso de % para formatear cadenas es válido pero considera algo "anticuado" en favor del método str.format o incluso de los literales de cadena formateados (Python 3.6) que son más trasparentes y más flexibles (permitiendo por ejemplo tabular datos fácilmente):
nombre = 'Juan'
edad = 24

# Usando % como en c

cad1 = 'Hola me llamo %s y tengo %i años.' % (nombre, edad))

# Usando el método str.format
cad2 = 'Hola me llamo {} y tengo {} años.'.format(nombre, edad))

# Usando literales de cadena formateados (Python >= 3.6):
cad3 = f'Hola me llamo {nombre} y tengo {edad} años.'

print(cad1, cad2, cad3, sep='\n')

Salida:

Hola me llamo Juan y tengo 24 años.
  Hola me llamo Juan y tengo 24 años.
  Hola me llamo Juan y tengo 24 años.


text:
Q: how to set next token to its corresponding jtextfeild I am reading a CSV file token by token so that each  token belong to a jtextfeild how to do because it shows last token in jtextfeild
while(st.hasMoreTokens()){
//display csv values
 String setText= st.nextToken();// here what should I do that each JTextFeild get next token;
 ModTxt.setText();
 MinSpeedTxt.setText();
 MaxSpeedTxt.setText();

A: You need to call nextToken() to get the next field in your CSV string and set it in your textfield.
 ModTxt.setText(st.nextToken());
 MinSpeedTxt.setText(st.nextToken());
 MaxSpeedTxt.setText(st.nextToken());


text:
Q: Move all numbers in a string to the end I need help figuring out how to move numbers to the end of a string.
For example, 'y0b3' should become 'yb03'.

A: Since you tagged generator... you could write the following generator for this task:
def digits_last(string):
    hold = []
    for c in string:
        if c.isdigit():
            hold.append(c)
        else:
            yield c
    yield from hold

Demo:
>>> ''.join(digits_last('y0b3y0b3u0b2'))
>>> 'ybybub030302'

A: You could do something like this:
def group(string):

    digits = []
    non_digits = []
    for c in string:
        if c.isdigit():
            digits.append(c)
        else:
            non_digits.append(c)

    return ''.join(non_digits) + ''.join(digits)

result = group('y0b3')

print(result)

Output
yb03

The idea is to group each character into digit and non_digits then put the non digits first and the digits last. For joining both digits and non_digits use join.


text:
Q: Electron project cannot import package that uses fs In our project we have nested packages, one of which uses fs to read files from the machine (B):
import fs from "fs";

Then we have another package (A), that imports this package (B). The application is being run on electron, and it uses React (we don't have any webpack configs). Although the electron works fine, it throws the following error when it's trying to call a method from the package B that uses fs.
TypeError: fs_1.default.existsSync is not a function

We have also tried to include the fs package with const fs = require("fs") and const fs = window.require("fs") in B with no success. I guess the main point would be to allow other packages (B-C-D-...) work normally even if the package A (that imports them) would be using electron.
Everything electron related that is imported to the package A is done using the following method:
const { ipcRenderer } = window.require('electron');
This does not work on the other packages with fs. If the B package is tested without electron, it works correctly, so the issue arises somehow from the usage of Electron.
tsconfig.json moduleResolution is set to "node", and Electron window has the following settings:
const win = new BrowserWindow({
  width: 800,
  height: 600,
  webPreferences: {
    nodeIntegration: true,
    contextIsolation: false,
  },
});

How should the application be able to use the fs package, even if it is imported by package built on Electron?


text:
Q: How do I translate the QGraphicView to the position where I doulbleclicked? I'm trying to translate the position of the QGraphicView to the position where I doubleclicked on. I tried the function translate and centerOn but none of them work. So I'm gessing I'm doing something wrong.
For a simple example, if I use this code:
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
import sys

class SurfViewer(QMainWindow):
    def __init__(self, parent=None):
        super(SurfViewer, self).__init__()
        self.parent = parent
        self.setFixedWidth(600)
        self.setFixedHeight(600)
        photo = PhotoViewer()
        self.setCentralWidget(photo)

class PhotoViewer(QGraphicsView):
    def __init__(self, parent=None):
        super(PhotoViewer, self).__init__(parent)
        self.parent=parent
        self.scene = QGraphicsScene(self)
        self.setScene(self.scene)
        self.setTransformationAnchor(QGraphicsView.AnchorUnderMouse)
        self.setResizeAnchor(QGraphicsView.AnchorUnderMouse)
        self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
        self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
        self.setFrameShape(QFrame.NoFrame)
        self.UpdateScene()
        self.scene.update()

    def mouseDoubleClickEvent(self, event):
        position = QPointF(event.pos())
        position = self.mapToScene(position.x(),position.y())
        print(position)
        print(position.isNull())
        if not position.isNull():
            #self.centerOn(position)
            print(position.x(),position.y())
            self.centerOn(position.x(),position.y())
            self.scene.update()
            self.update()

    def UpdateScene(self,):
        xsize=100
        ysize=100
        newitem = QGraphicsEllipseItem(0-xsize/2., 0-ysize/2., xsize, ysize)
        newitem.setBrush(QBrush(Qt.black, style = Qt.SolidPattern))
        self.scene.addItem(newitem)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = SurfViewer(app)
    ex.setWindowTitle('window')
    ex.show()
    sys.exit(app.exec_( ))

I plot a circle in the middle of the view. when I double click on the view, I enter to the mouseDoubleClickEvent fonction and I get the coordinate of the mouse during the click with QPointF(event.pos()). Hopefully, this is working.
Now I would like the position I got be the center of the view. So I tried to translate the view with both translate or centerOn but nothing happend. I also try to map the corrdinate to the scene but that didn't help neither.

A: centerOn() only makes the position visible, if it is already visible it will not make any change. The solution is to move the sceneRect centering it on the point that is pressed:
def mouseDoubleClickEvent(self, event):
    p = self.mapToScene(event.pos())
    r = self.sceneRect()
    r.moveCenter(p)
    self.setSceneRect(r)


text:
Q: Filtering out RSS items with Magpie that contain a specific image Working with Wordpress on this. I'm using Magpie to grab an RSS feed, but I only want it to display items that include a specific image. Here is the particular tag that I want to search for:
<media:thumbnail url="http://media.publicbroadcasting.net/wfpl/events/images/ourPick5.gif"/>

And here's the specific code I'm using in this application. It's basic, and I'm not incredibly adept at Magpie or PHP (I'm assuming there are more elegant ways of doing this for someone with a more robust knowledge of PHP):
<?php include_once(ABSPATH.WPINC.'/rss.php'); $feed = fetch_rss('http://www.publicbroadcasting.net/wfpl/.eventsfeed'); $items = array_slice($feed->items, 0, 4);?>

<?php if (!empty($items)) : ?>
<?php foreach ($items as $item) : ?>

<?php if (!preg_match('/<media:thumbnail\surl\="http:\/\/media.publicbroadcasting.net\/wfpl\/events\/images\/ourPick5.gif".+?>/i', $item['description']))
continue; ?>

<a href="<?php echo $item['link']; ?>">
<?php echo $item['title']; ?>

<?php echo $item['description']; ?>

<?php endforeach; ?>
<?php endif; ?>

Again, I only want to display the items with that specific image url in the "media:thumbnail" tag and discard all other items.

A: Add this part,
<?php if (!preg_match('/<media:thumbnail\surl\="http:\/\/media.publicbroadcasting.net\/wfpl\/events\/images\/ourPick5.gif".+?>/i', $item['description']))
    continue; ?>

before

<a href="<?php echo $item['link']; ?>">
<?php echo $item['title']; ?>

<?php echo $item['description']; ?>


text:
Q: How do you handle TDD in the continuous integration? Imagine you are implementing the user story containing various new features and adding complexity to the code base. The existing code is quite well covered and you have just decided upon interfaces. You are starting to implement the functionality starting with tests.
Now you have fairly complex test cases based on the requirements but the implementation is nowhere near the point when you are able to commit to the SCM fully working code and many test are failing (as they should).
There is an assumption that in continuous integration all builds should be green if possible and thus you shouldn't commit as you would break the build. But you also shouldn't "Go dark" and keep such amount of code for yourself...
What is the suggested procedure in such situation?

A: Do not decide on all interfaces beforehand. Develop incrementally in a typical TDD rhythm: write a test; make the test pass; refactor. That should keep everything in good shape, the bar will always be green and you can check code in without worrying that you will break the build.
It requires a different style of writing code, but you will get used to the rhythm eventually.

A: What about skipping those tests that you know won't pass because the functionality is currently missing?
Make it obvious that you are skipping the tests too! Really make it scream "like a stuck pig", as they say in Oz! (-:
As you add functionality, enable the associated tests and keep "your bar green!"
Here's another great article over at The Pragmatic Programmers that covers making broken windows obvious to others.
HTH
cheers,
Rob


text:
Q: Need help to change this c# code to Vb public void ChangeList(IEnumerable<LineInfo> newLineList)
{
    if (InvokeRequired)
    {
        BeginInvoke((Action<MainForm, IEnumerable<LineInfo>>)((t, e1) => t.ChangeList(e1)), this, newLineList);
        return;
    }
}

A: Public Sub ChangeList(ByVal newLineList As IEnumerable(Of LineInfo))
    If InvokeRequired Then
        BeginInvoke( DirectCast( (Sub(t, e1) t.ChangeList(e1)), (Action(Of MainForm, IEnumerable(Of LineInfo)) ) ), Me, newLineList)
        Exit Sub
    End If
End Sub

I did this without a compiler handy, so there may be a miss-placed parentheses in that BeginInvoke call somewhere, but otherwise it should be right.
The Telerik converter that others are using is missing the generic type on the newLineList argument and tries to use a Function lambda (which expects a return value) rather than a Sub lambda (which does not need a return value).

A: according to the Telerik code converter it is:
Public Sub ChangeList(newLineList As IEnumerable(Of LineInfo))
    If InvokeRequired Then
        BeginInvoke(DirectCast(Function(t, e1) t.ChangeList(e1), Action(Of MainForm, IEnumerable(Of LineInfo))), Me, newLineList)
        Return
    End If
End Sub

That is not the only converter available, there is another one here
EDIT
you can get around the compiler warning like by changing it to a function:
Public Function ChangeList(newLineList As IEnumerable(Of LineInfo))
    If InvokeRequired Then
        BeginInvoke(DirectCast(Function(t, e1) t.ChangeList(e1), Action(Of MainForm, IEnumerable(Of LineInfo))), Me, newLineList)
    End If
End Function

I now get a warning that it doesn't return a value on all paths and that you might get a null reference exception if you try and use the result.  As long as you don't you should be ok.
you can remove the warning by explicitly returning nothing:
Public Function ChangeList(newLineList As IEnumerable(Of LineInfo))
    If InvokeRequired Then
        BeginInvoke(DirectCast(Function(t, e1) t.ChangeList(e1), Action(Of MainForm, IEnumerable(Of LineInfo))), Me, newLineList)
    End If
    Return Nothing
End Function

This is untested though, but may help you

A: Have you tried the c# to vb converters online? c# to VB converter
Public Sub ChangeList(newLineList As IEnumerable)
If InvokeRequired Then

    BeginInvoke(DirectCast(Function(t, e1) t.ChangeList(e1), Action(Of MainForm, IEnumerable(Of LineInfo))), Me, newLineList)
    Return
End If

End Sub

A: Public Sub ChangeList(newLineList As IEnumerable)
    If InvokeRequired Then

        BeginInvoke(DirectCast(Function(t, e1) t.ChangeList(e1), Action(Of MainForm, IEnumerable(Of LineInfo))), Me, newLineList)
        Return
    End If

End Sub

you might want to edit your question and also use this
http://www.developerfusion.com/tools/convert/csharp-to-vb/


text:
Q: Low bandwidth tools Does anyone know a good mechanism for measuring or reporting on page sizes?
I have a low bandwidth (humanitarian client) use case and trying to evaluate my pages, hi-res imagery or other page size issues, across the org. As an example, even a standard Lightning page view seems to be coming in at around 700kb, which seems high.
If there's something on the AppEchange that would be great, but otherwise any direction in reporting, API tools or creating this through other mechanisms would be really helpful.
I have searched the Salesforce AppExchange, and available metadata/other API and so far haven't found anything. Event Monitoring has logs that help general page load performance and I found an article around improving performance, but haven't found ways to identify SIZE as would be needed for low bandwidth scenarios.
Don't know where to start yet, unfortunately. This could be a programmatic solution, in which case I'd love some direction, but it could also be tools available elsewhere I'm not aware of.


text:
Q: How to set a time length of ssh and redirect the error message I have a hostlist and there are several hosts. I want to use ssh to connect to them. I want to see whether the host is available or not by the time length of ssh takes. If it take long than 5s (which means it is not available). Then stop it, and ssh to next host. Once a host is available, then output the name of host. I previously use nmap, but the IT security told it is not allowed to install it on the desktop on campus.
HOSTS=`cat $host_list`
for line in $HOSTS
do
ssh -o ConnectTimeout=5s $line true >> /dev/null
RESULT=$?
if [ $RESULT -eq 0 ]
then
echo $line > succeed.txt
else
echo $line > fail.txt
fi
done

The above script is all I can do.
The problem is when it is failed, I want to redirect the error message
ssh: connect to host c28-0112-05.ad.mtu.edu port 22: No route to host. But I still get the error message.

A: Close enough:
timeout -5s "ssh $line true"

That is:

*

*Use correct quotes. timeout `ssh …` cannot possibly work here, because it means "run 'ssh', capture its output, then give the output to 'timeout'."

*Run ssh in "batch" mode, that is, give it a command to run. Without it, ssh will run in interactive mode, and will hang forever even on successful connections.
You could also try:
ssh -o ConnectTimeout=5s $line true

A: ssh has the -o switch, which allows you to provide additional options. Of particular use here is the ConnectTimeout option, which takes an arguement specified in seconds:
ssh -o ConnectTimeout=5 123.123.123.123
In addition, ConnectionAttempts might also be useful to you.


text:
Q: How do I resample two dataframes to achieve a specific correlation? I have a dataset of (people and their wealth) and (restaurants and their price). I want to resample this data (with replacement) such that there is a specific correlation between wealth and price. How would I go about doing that? Code below for clarity
library(tidyverse)
set.seed(1)

n_people <- 100
n_resteraunts <- 100
desired_cor <- 0.5

# Generate people and wealth
people <- tibble(
  names = letters[1:n_people],
  wealth = rnorm(n=n_people)
)

# Generate resteraunts and price
resteraunts <- tibble(
  resteraunt = LETTERS[1:n_resteraunts],
  price = rnorm(n=n_resteraunts)
)

# Now I want to create a new dataframe that mixes people and resteraunts to achieve
# a correlation of  `desired_cor` between `price` and `wealth`


text:
Q: Wrapping a visual studio database unit test in a transaction to eliminate database changes persisting I'm using VS 2015 Unit Tests for a SQL Server 2012 database.  I would like to be able to use the pre-test to insert the test data and wrap the whole unit test in a transaction which can be rolled back at the end of the test.  I've tried wrapping the entire test code in a TransactionScope (below) but it does not rollback the inserts.
            using (TransactionScope scope = new TransactionScope())
        {
            SqlDatabaseTestActions testActions = this.dbo_Proc1TestData;
            // Execute the pre-test script
            //
            System.Diagnostics.Trace.WriteLineIf((testActions.PretestAction != null), "Executing pre-test script...");
            SqlExecutionResult[] pretestResults = TestService.Execute(this.PrivilegedContext, this.PrivilegedContext, testActions.PretestAction);
            try
            {
                // Execute the test script
                //
                System.Diagnostics.Trace.WriteLineIf((testActions.TestAction != null), "Executing test script...");
                SqlExecutionResult[] testResults = TestService.Execute(this.ExecutionContext, this.PrivilegedContext, testActions.TestAction);
            }
            finally
            {
                // Execute the post-test script
                //
                System.Diagnostics.Trace.WriteLineIf((testActions.PosttestAction != null), "Executing post-test script...");
                SqlExecutionResult[] posttestResults = TestService.Execute(this.PrivilegedContext, this.PrivilegedContext, testActions.PosttestAction);
            }
        }

Are there any other ways to accomplish this without resorting to deleting the data in the post-test?

A: It turns out that the ExecutionContext and PrivilegedContext have already been created and therefore do not enlist in the transaction created by TransactionScope. The fix is to add calls to EnlistTransaction for each context inside the using statement:
        using (TransactionScope scope = new TransactionScope(TransactionScopeOption.RequiresNew))
        {
            this.ExecutionContext.Connection.EnlistTransaction(Transaction.Current);
            this.PrivilegedContext.Connection.EnlistTransaction(Transaction.Current);


text:
Q: Gradle dependencies - range matching I am trying to add the following dependency to my Gradle build file:
compile 'org.eclipse.scout.sdk.deps:org.eclipse.core.resources:3.10.+'

This package depends on a lot of other packages, that are located in the same repository. The problem is that for some reason, Gradle deems them unworthy. Here's an example of the errors I've been getting:

Could not find any version that matches org.eclipse.scout.sdk.deps:org.eclipse.equinox.common:[3.7.0,3.7.1).
Versions that do not match:
3.7.0.v20150402-1709

Note that 3.7.0.v20150402-1709 does match [3.7.0,3.7.1)
Some additional technical details:

*

*I'm working on Gradle v. 2.11.

*This dependency, as well as its' dependencies, are located in the following repository:
https://repo1.maven.org/maven2/
Edit 1:
Yes, I could just exclude the transitive dependencies and add them with the correct version numbers, but it's such a horrible solution I can't bring myself to write it down. Hoping someone out there has an elegant solution.


text:
Q: ajax to return error status code I am working on a small site where I am doing an ajax call to delete a row from a table. What I'd like to do is to have the php return a status code to trigger the .success or .fail function in my ajax request.
Looking to different questions I came up with this solution but it is not working:
AJAX call:
  function delete_mov(id){
    $.ajax("delete_mov.php?id="+id
    )
    .success(function(){
      bootbox.alert("Movimento "+id+" correttamente cancellato");
    })
    .fail(function(){
      bootbox.alert("Problemi a cancellare il movimento "+id);
    });
  }

and php:
try{
    $s = $dbh -> prepare("DELETE FROM movimenti_banca WHERE di=$id");
    $s -> execute();
}
catch (PDOException $e){
    http_response_code(500);
    exit;
    //$message = $error_message.' '.$e->getMessage();
}
http_response_code(200);

What I cannot get is to trigger the .fail when the query is not executed or returns errors. I am sure this query fails because I put an error inside (di instead of id) to be sure of this.
The .fail is triggered if I remove the php file to be called.
EDIT: modified my code to test it with http_response_code but still not triggering the 500 status when the query fails.
EDIT2: debugging I realized that even if the query has an error (di=$id should be id=$id) the catch part is not entered and so the status 500 is never set

A: In your PHP code, use http_response_code function to set HTTP status code to whatever you dream of.

A: jQuery has no idea what your PHP script is supposed to be doing, so it's not looking for a "status" variable in your returned result. All jQuery knows is whether the actual HTTP request "worked". If it gets back a 200 result, that's success no matter what's in the result.
You either need to have your success handler look for cases where the HTTP request succeeded but the data says "error", or (better) have the PHP script use http_response_code() to change the HTTP status from 200 to something like 400 or 500 that will indicate an error.


text:
Q: How to resolve Information - Not a valid month error? When running a PowerCenter session that uses an Oracle database view as a source the session fails with one of the following errors:
ORA-01843: Not a valid month.
In SqL developer it runs without any issues
Column : Report_date : Data Type : date.
In mapping parameter variable defined as String
Passing report date dynamically using  param file &Control table
Select * from ABC
Where report_date=to_char(31-MAR-21,'DD-MON-RR')
--Error: not valid month
Could you please advise on it

A: You need to put single quotes around infa mapping parameter. Like this -
First calculate Report_Date and put the value in infa param file in correct format. You can use control table too. But you need to create a param file from that.
param file should look like
[folder.workflow.session]
$$Report_Date='21-Oct-2021'

Then in mapping you can call it in source qualifier as -
Select * from ABC Where report_date=to_char('$$Report_Date','DD-MON-RR')

single quote will ensure your data is passed as string.
Now, if youdont want to use param file, you can use control file as a new source and join with the SQL above to get desired result. But first approach is faster.


text:
Q: voice output smartphones(JS) So,I have already a code for voice output :

<script type="text/javascript">
var msg = new SpeechSynthesisUtterance('Hello World');
window.speechSynthesis.speak(msg);

</script>

But on my smartphone that dont work!(I already tryed with a webside link and as HTML data on phone.)
Thx for every answer!

A: As you can see here SpeechSynthesisUtterance isn't supported everywhere and you are apparently using a browser on your phone that doesn't support it.


text:
Q: Common Lisp Keyboard Interrupt Is there a cross-implementation (at minimum SBCL, CCL, Lispworks and CLISP), cross-platform (Linux/Windows/OS X) way of capturing keyboard interrupts in Common Lisp? Or more specifically, to let a keyboard interrupt through?
I've got this code snippet in a file
...
(handler-case
    ...
  ((not simple-error) () (error! +400+ ready)))
...

whose purpose is to handle errors, but let the user interrupt the program with a keyboard interrupt (which in SBCL on Linux manifests as a simple-error). However, this doesn't seem to work in CCL (where that error clause seems to trigger even when the main code doesn't throw an error).
What's the right approach in this situation?


text:
Q: Gouping SQL Query result I have this SQL query
SELECT id, meta_key, meta_value,
FROM  wp_posts post
INNER JOIN wp_postmeta meta
ON post.ID = meta.POST_ID
WHERE post.post_status = 'publish'
AND ( meta.meta_key = 'brand' OR meta.meta_key = 'price' )

which has a result like this
id --|-- meta_key --|--  meta_value
-----------------------------------
42 --|-- brand    --|--  mercedes
44 --|-- brand    --|--  honda
46 --|-- brand    --|--  honda
42 --|-- price    --|--  20
44 --|-- price    --|--  20
46 --|-- price    --|--  50

How can I achieve a result like this?
brand --|-- UNIQUE ID COUNT  --|-- Total price sum of IDs relating to brand
----------------------------------------------
honda --|-------  2  ----------|-- 70
mercedes|-------  1  ----------|-- 20

I did try to set another result column for brand and price, but still not quite sure how to group the result
SELECT id, meta_key, meta_value,
(CASE WHEN meta_key = 'brand' THEN meta_value END) as brand,
(CASE WHEN meta_key = 'price' THEN meta_value END) as price
FROM  wp_posts post
INNER JOIN wp_postmeta meta
ON post.ID = meta.POST_ID
WHERE post.post_status = 'publish'
AND ( meta.meta_key = 'brand' OR meta.meta_key = 'price' )

resulting to this
id --|-- meta_key --|--  meta_value  --|-- brand  --|--  Price
--------------------------------------------------------------
42 --|-- brand    --|--  mercedes    --|-- mercedes |--  NULL
44 --|-- brand    --|--  honda       --|-- honda  --|--  NULL
46 --|-- brand    --|--  honda       --|-- honda  --|--  NULL
42 --|-- price    --|--  20          --|-- NULL   --|--  20
44 --|-- price    --|--  20          --|-- NULL   --|--  20
46 --|-- price    --|--  50          --|-- NULL   --|--  50

Appreciate any help

A: Change your single join of wp_postmeta into two separate joins, one for brands and one for prices:
select brands.meta_value brand
    , count(distinct posts.id) unique_id_count
    , sum(price.meta_value) price
from wp_posts posts
inner join wp_postmeta brands
    on posts.id = brands.post_id
    and brands.meta_key = 'brand'
inner join wp_postmeta price
    on posts.id = price.post_id
    and price.meta_key = 'price'
WHERE posts.post_status = 'publish'
group by brands.meta_value


text:
Q: Can I add an ActiveX control to a Comctlib.Toolbar (mscomctl) control? $Hello_all,
I'm adding functionality to a VB6 application (yes, I know, an amazing task :P) and I need to drop an ActiveX control (it looks like a button but does more things) into a comctlib (Microsoft Common Controls) Toolbar.
Is this possible at all? I don't mind using the Winapi, interop or whatever is needed as I really need this feature. If this is not possible with the Comctlib control is there another toolbar control for VB6 where I can drop other ActiveX controls?
Thanks in advance for helping me with this outdated technology.

A: In addition to its intrinsic Buttons collection, the toolbar acts as a general container. So, to position any (non-lightweight*) control/s you want between existing buttons, insert a new button and set its Style property to PlaceHolder – that creates a blank area in the desired position – and place your control/s there.
Of course you will have to manually reposition any such control/s if you dynamically show/hide/add/remove buttons at runtime.
* To display lightweight controls, you could place them inside any other container control – e.g. a borderless PictureBox – first.


text:
Q: Does Apple or/and Google store allow Web View App (including Login and Payment Gateway) with Push-Notification feature? I want to publish an app which contains a WebView (with Login, Payment Gateway) and push-Notification. The web is online programme for Smoke Quitting. We need to address both B2B and B2C segments, therefore we need integrate payment gateway due to different pricing. Does Apple / Google allow it?

A: @Daniel, This question has a very broad scope and pointers to be explained because Google Play Store and Apple App Store has different app review guidelines. In short we can conclude it very briefly as follows:

Google Play Store( Android OS):
Google Play Store is not tough with the app publishing guidelines/ minimal app functionality. You can have the Android app with mentioned functionalities.
Even your app will be available in 5-6 hours after you will publish your app.

Apple App Store( iOS):
Apple Review Guideline - 4.2 | app minimal functionality
Apple Review Guidelines
Apple is very concerned about app's significance on app store like it should not copy of other app and it should have some minimum functionality( excluding push notification, location feature etc.).
So you should go with the more functionalities or you should go for iOS native functionality rather than just web view. App review takes approximately 1-5 days to get approved/rejected.

According to Apple:
If your app is not particularly useful, unique, or "app-like," it doesn't belong on the App Store. If your App doesn't provide some sort of lasting entertainment value, or is just plain creepy, it may not be accepted.


text:
Q: Nuxt throws 'The "path" argument must be of type string' or console spam What I'm doing & what's wrong
I'm working on a new project (GitHub repo) and when I'm trying to run a local dev server I'm getting this error:
> jakub-suchenek@1.1.0 dev
> nuxt

   ╭───────────────────────────────────────╮
   │                                       │
   │   Nuxt @ v2.15.7                      │
   │                                       │
   │   ▸ Environment: development          │
   │   ▸ Rendering:   server-side          │
   │   ▸ Target:      server               │
   │                                       │
   │   Listening: http://localhost:3000/   │
   │                                       │
   ╰───────────────────────────────────────╯

i Preparing project for development                                                                           19:29:23
i Initial build may take a while                                                                              19:29:23
i Discovered Components: .nuxt/components/readme.md                                                           19:29:23
√ Builder initialized                                                                                19:29:23

 ERROR  The "path" argument must be of type string. Received undefined                                        19:29:23

  at new NodeError (node:internal/errors:371:5)
  at validateString (node:internal/validators:119:11)
  at Object.extname (node:path:837:5)
  at node_modules\@nuxt\builder\dist\builder.js:413:98
  at Array.map (<anonymous>)
  at Builder.normalizePlugins (node_modules\@nuxt\builder\dist\builder.js:409:28)
  at async Builder.generateRoutesAndFiles (node_modules\@nuxt\builder\dist\builder.js:371:31)
  at async Builder.build (node_modules\@nuxt\builder\dist\builder.js:319:5)
  at async Object._buildDev (node_modules\@nuxt\cli\dist\cli-dev.js:107:5)
  at async Object.startDev (node_modules\@nuxt\cli\dist\cli-dev.js:65:7)
  at async Object.run (node_modules\@nuxt\cli\dist\cli-dev.js:52:5)
  at async NuxtCommand.run (node_modules\@nuxt\cli\dist\cli-index.js:413:7)

But this occurs only when I have this in my nuxt.config.js file:
plugins: [ "@babel/plugin-proposal-private-property-in-object", { "loose": true }],

Without this plugin config, I have A LOT of spam in the console.
plugins: [],

A few hundred times:
 WARN  Though the "loose" option was set to "false" in your @babel/preset-env config, it will not be used for @babel/plugin-proposal-private-property-in-object since the "loose" mode option was set to "true" for @babel/plugin-proposal-private-methods.
The "loose" option must be the same for @babel/plugin-proposal-class-properties, @babel/plugin-proposal-private-methods and @babel/plugin-proposal-private-property-in-object (when they are enabled): you can silence this warning by explicitly adding
        ["@babel/plugin-proposal-private-property-in-object", { "loose": true }]
to the "plugins" section of your Babel config.

What I've tried

*

*Changing Nuxt.js version (2.15, 2.14, 2.13).

*Reinstalling node packages.

My question
What is the best solution for this? To do not have console spam with "WARN" and have a working app.
Or is there no solution? According to this post, for now there's no way to do not have these awful WARN errors in the console.

My code:
(open-sourced on GitHub)

*

*nuxt.config.js

*package.json

A: This is a new bug that is already fixed and pending to be released.
More info can be found here: Latest Nuxt v2.15.7 install with babel "loose" option warnings


text:
Q: ¿¡No se puede insertar código (cualquier lenguaje) como si fuera un data en una tabla mysql? Tengo un formulario que envia los datos a una página y esta los introduce a una tabla php dentro de una fila con tipo de dato, varchar(500). Funciona de maravilla, lo que introduzco en el formulario se introduce en la tabla.
Pero el problema está en que un día se me ocurrió introducir en este input un código simple de lenguaje php para almacenarlo en mysql. El código era este: echo 'Hola'; . Pero en vez de almacenarlo de dice que ha habido un error y que no existe mysqli_query($conn, $query);, lo que debeía existir si funcionara bien. Es muy extraño, por que si meto una frase normal si que la almacena. ¿Acaso mysql no permite almacenar código? ¿Hay alguna forma de hacerlo? Muchas gracias de antelación. PD: me gustaría almacenarlo como texto, no como código ejecutable.
Este es el formulario:
<form action="publicar.php" method="POST">
 <input type="text" id ="input" required placeholder="¡Crappea la estupidez del día!"
 name="publicacion">
 <input type="text" id ="input2" value = "<?= $grupo2; ?>" name="grupo">

  <button type="submit" name="publicar">

   </button>

</form>

Y este es el código de publicar.php que almacena los datos:
<?php
session_start();
require 'database.php';
if(isset($_SESSION['user_id'])){
    $records = $conn->prepare('SELECT id, email, password, nombre FROM usuarios WHERE id=:id');
    $records->bindParam(':id', $_SESSION['user_id']);
    $records->execute();
    $results = $records->fetch(PDO::FETCH_ASSOC);
    $user=null;
    if(count($results)>0){
        $user=$results;
    }
}
$conn = mysqli_connect(
    'localhost',
    'root',
    '',
    'crapping',
);

if (isset($_POST['publicar'])){
    $publicacion = $_POST['publicacion'];
    $nombre= $user['nombre'];
    $grupo = $_POST['grupo'];
    $query = "INSERT INTO publicaciones(nombre, publicacion, grupo) VALUES ('$nombre',
    '$publicacion', '$grupo')";
    $resultado = mysqli_query($conn, $query);
    if (!$resultado){
    die("Ha habido un error.");
    }
    $_SESSION['message'] = 'Task Saved';
    $_SESSION['message_type'] = 'success';
    header("location: Pagina.php?grupo2=".$grupo);
}
?>


text:
Q: How to correct angular acceleration using forces in Unity I'm developing a space game that need to have some real physics, like orbits and conservation of mommentum in space, the problem is, I can't develope a code that identify the angular acceleration of a body in space and correct it using mommentum forces.
Here is the function that I wrote to try to stabilize the rotation:
    void RCS_Stabilize()
    {
        Vector3 localangularvelocity = transform.InverseTransformDirection(rigidBody.angularVelocity);
        Debug.Log(localangularvelocity);

        if (!isRCSinUse)
        {
            if (localangularvelocity.x < RCSthreshole)
            {
                RCS_Pitch(1);
            }
            else if (localangularvelocity.x > -RCSthreshole)
            {
                RCS_Pitch(-1);
        }
              // after that i do the same for y and z

And this is the RCS_Pitch function:
    void RCS_Pitch(int direction)
    {
        rigidBody.AddRelativeTorque(new Vector3(direction * RCSPower, 0, 0));

        if (direction == 1) // Just show the smoke effect
        {
            RCSeffect[0].startSpeed = 1f;
            RCSeffect[3].startSpeed = 1f;
        }
        else
        {
            RCSeffect[1].startSpeed = 1f;
            RCSeffect[2].startSpeed = 1f;
        }
    }

These functions kinda work, but they're called basically every frame, causing the smoke effect to be turned on every frame and flickering sometimes.

A: The problem seems to be in that you don't reset the startSpeed of your ParticleSystems when they are not in use.
Try adding the following code at the beginning of the RCS_Stabilize function:
foreach (var rcsEffect in RCSEffect) {
  rcsEffect.startSpeed = 0f;
}

or better yet, to make it a bit more natural-looking, try adding a decay there. Using an RCS thruster would maximize the particle velocity and it quickly decays when thrusters are not in use:
foreach (var rcsEffect in RCSEffect) {
  // adjust the 0.3f lerp factor yourself
  rcsEffect.startSpeed = Mathf.Lerp(rcsEffect.startSpeed, 0f, 0.3f);
}


text:
Q: Django password reset function view Using class based views kind of hide all the complexity in the django code so I prefer using the function based view then afterwards move to class based views.
Is there by any chance you can write a custom password reset view to change user's password either than using django's class based views? I am able to do it with class based views but understanding it, is a problem since all the complexity is hidden. If anyone has a link to an article explaining that in detail I would be glad since google is giving me nothing.

A: Why do you need a separate function to change the user's password when you can use the Django built-in User model.
from django.contrib.auth.models import User
user = User.objects.get(username='your_user_name')
user.set_password('your_password')
user.save()

Practice DRY (Don't repeat yourself). If it is available built-in and is feasible you should go with it rather than reinventing it.
Cheers,
Ref: Django auth system


text:
Q: How to draw an image on another image? I have a UWP SoftwareBitmap to which I would like to add padding on two sides (as if it's shown in Fit mode) and get the result as a SoftwareBitmap. I assume I need to copy it onto a new empty SoftwareBitmap, but I can't find any way to do that.

A:
How to draw an image on another image?

You could use Win2D library to draw an image with padding. If you used SoftwareBitmap as the source, please try to convert it to file at first and you could refer to this document.
We need to make Win2D CanvasRenderTarget and set it's width as image width + 2 * padding width. Then use CanvasRenderTarget to create DrawingSession and draw your image. For more please refer to the following code.
// file parameter is the image file
using (var stream = await file.OpenAsync(FileAccessMode.Read))
{   //padding width
    float padding = 30;
    var device = new CanvasDevice();
    var bitmap = await CanvasBitmap.LoadAsync(device, stream);
    var renderer = new CanvasRenderTarget(device,
                                          bitmap.SizeInPixels.Width+ 2*padding,
                                          bitmap.SizeInPixels.Height, bitmap.Dpi);
    using (var ds = renderer.CreateDrawingSession())
    {   // draw image from point xy = point(padding,0)
        ds.DrawImage(bitmap,padding,0);
    }
    stream.Seek(0);
    InMemoryRandomAccessStream randomAccessStream = new InMemoryRandomAccessStream();
    await renderer.SaveAsync(randomAccessStream, CanvasBitmapFileFormat.Png);
    BitmapDecoder decoder = await BitmapDecoder.CreateAsync(randomAccessStream);
    var softwareBitmap = await decoder.GetSoftwareBitmapAsync();

}

I need to copy it onto a new empty SoftwareBitmap, but I can't find any way to do that.

You could use CopyTo method to copy the current SoftwareBitmap into the provided SoftwareBitmap object.


text:
Q: Extract parameterised type from self in scala I have class with parameterised type
abstract class Worker[T] {
  def conf1: ...
  def conf2: ...
  def doWork ...
}

abstract class SpecializedWorker[T: TypeTag] extends Worker[T] {
  //some behavior overriden (used fields from Trait that i want create)
}

I want to create trait that can be mixed to Worker.
trait Extension {
  self: Worker[_] =>

  def someParameter: ... // only several workers can have that. thats why i need trait
  def produceSpecializedWorker = new SpecializedWorker[???]() {}
}

How to extract type information from self to replace ???

A: Here is a way to extract a type parameter:
trait Extension {
  self: Worker[_] =>
  def mkSpWorker[T](implicit ev: this.type <:< Worker[T]) = new SpecializedWorker[T]() {}
}

But I wouldn't recommend that :) You could define a type member in Worker that can be used in Extension.
abstract class Worker[T] {
  type TT = T
}

trait Extension {
  self: Worker[_] =>
  def mkSpWorker = new SpecializedWorker[TT]() {}
}

Or you could just consider giving Extension a type parameter. It's not such a big deal, I think.


text:
Q: scipy cannot import integrate.solve_bvp I have just installed scipy and  tried few example codes. My scipy version is 0.17.0. But I can't figure out what's wrong going with scipy.integrate.solve_bvp. I am trying to run the following code from this link,
# In the second example we solve a simple Sturm-Liouville problem::

# y'' + k**2 * y = 0
# y(0) = y(1) = 0

# It is known that a non-trivial solution y = A * sin(k * x) is possible for
# k = pi * n, where n is an integer. To establish the normalization constant
# A = 1 we add a boundary condition::

# y'(0) = k

# Again we rewrite our equation as a first order system and implement its
# right-hand side evaluation::

# y1' = y2
# y2' = -k**2 * y1

import numpy as np
from scipy.integrate import solve_bvp

def fun(x, y, p):
    k = p[0]
    return np.vstack((y[1], -k**2 * y[0]))

# Note that parameters p are passed as a vector (with one element in our
# case).

# Implement the boundary conditions:

def bc(ya, yb, p):
    k = p[0]
    return np.array([ya[0], yb[0], ya[1] - k])

# Setup the initial mesh and guess for y. We aim to find the solution for
# k = 2 * pi, to achieve that we set values of y to approximately follow
# sin(2 * pi * x):

x = np.linspace(0, 1, 5)
y = np.zeros((2, x.size))
y[0, 1] = 1
y[0, 3] = -1

# Run the solver with 6 as an initial guess for k.

sol = solve_bvp(fun, bc, x, y, p=[6])

# We see that the found k is approximately correct:

sol.p[0]
# 6.28329460046

# And finally plot the solution to see the anticipated sinusoid:

x_plot = np.linspace(0, 1, 100)
y_plot = sol.sol(x_plot)[0]
plt.plot(x_plot, y_plot)
plt.xlabel("x")
plt.ylabel("y")
plt.show()

I am getting this error,
Traceback (most recent call last):
  File "my.py", line 19, in <module>
    from scipy.integrate import solve_bvp
ImportError: cannot import name solve_bvp

Why I am getting this error? Other scipy integrators like scipy.integrate.odeint, scipy.integrate.ode are working fine.

A: If you go to the documentation for the function, under the heading "Notes" you will see that the function is new as of version 0.18.0


text:
Q: Вращение круга коряво отображается Если навести на круг курсор и сделать в браузере масштаб 80%, то круг при вращении не ровный.

span{
  display: inline-block;
  width: 100px;
  height: 100px;
  border: 2px dotted red;
  border-radius: 50%;
}
span:hover{
  animation: spin 1s infinite linear;
}
@keyframes spin {
 100% {
  transform: rotate(360deg);
 }
}

https://jsfiddle.net/xcpLemot/
как это можно исправить? т.е. чтобы при вращении круг был ровный
В хроме масштаб выбирается кликнув в верхнем правом углу на точки.

A: Как вариант, можно сделать так:

div{
  padding: 2px;
  display: inline-flex;
}
span{
  display: inline-block;
  width: 100px;
  height: 100px;
  border: 2px dotted red;
  border-radius: 50%;
}
div:hover{
  animation: spin 1s infinite linear;
}
@keyframes spin {
 100% {
  transform: rotate(360deg);
 }
}


text:
Q: How to execute last line of CMD execution regardless of how second to last returned I've got a simple batch file that executes a script and never runs the final line.  That is, in the example below, I'm executing the "dir" command and after that returning to the directory I started in.
When I replace the "dir" command with my own program, the last line does not get executed. I assume there must be a return code or something else causing that.
My question is how can I always get the last line to execute (the cd current) regardless of what happened on the line before that.
set current="%cd%"
cd %1
dir
cd "%current%"


text:
Q: WCF Data Service: Bad Request - Error in query syntax I have WCF Data Service application. The back-end database is Ingress and it uses nHibernate.
I am trying to fetch and update records from one of the tables. Its structure is given here under:

First three highlighted columns make primary key.
In my client application I am querying the data like below:
private void LoadItemDetails(string itemCode, int commentDate)
{
    using(var dc = new MyDataContext(new Uri("http://myservice.myserver.com/Dev/com.OData/IngressData.svc")))
    {
        var itemDetails = dc
            .ItemLineDetails
            .Where(d => d.ItemCode.Equals(itemCode) &&
                        ld.CommentDate == commentDate);

        ObsItemLineDetails = new ObservableCollection<ItemLineDets>();
    }
}

Then I update and save the data as shown below:
private void SaveItemDetails()
{
    using(var dc = new MyDataContext(new Uri("http://myservice.myserver.com/Dev/com.OData/IngressData.svc")))
    {
        foreach(var itemLine in ObsItemLineDetails )
        {
            var today = DateTime.Today.AddSeconds(-1);
            var newCommentDate = (Int32)(today.Subtract(new DateTime(1970, 1, 1,0,0,0))).TotalSeconds;

            var itemDetail = dc.ItemLineDetails.Where(d => d.ItemCode.Equals(itemLine.ItemCode) &&
                d.LineId == itemLine.LineId &&
                d.SearchDate == itemLine.SearchDate).FirstOrDefault();
            if (itemDetail != null)
            {
                itemDetail.CommentDate = newCommentDate;
                itemDetail.Comments = GetAutoComment();
                dc.UpdateObject(itemDetail);
            }
        }
        dc.SaveChanges();
    }
}

It raises an exception on the last line when SaveChanges is being called. Following is the IIS server log entry.
15:52:42.7823 Trace 20 com.OData.DataServiceBase`1 Received: http://myservice.myserver.com/Dev/com.OData/IngressData.svc/ItemLineDetails(ItemCode='001/152/0101',LineId=3,SearchDate=11070945856)
15:52:42.7823 Error 20 com.OData.DataServiceBase`1 Bad Request - Error in query syntax.
at System.Data.Services.RequestUriProcessor.ParsePath(Uri absoluteRequestUri, IDataService service)
at System.Data.Services.RequestUriProcessor.ProcessRequestUri(Uri absoluteRequestUri, IDataService service, Boolean internalQuery)
at System.Data.Services.DataService`1.HandleRequest()    at System.Data.Services.RequestUriProcessor.ParsePath(Uri absoluteRequestUri, IDataService service)
at System.Data.Services.RequestUriProcessor.ProcessRequestUri(Uri absoluteRequestUri, IDataService service, Boolean internalQuery)
at System.Data.Services.DataService`1.HandleRequest()

I think its probably the forward slashes in my ITEM_CODE field causing this problem.
If that's the case, is there any workaround for this.

A: try to add using on DataContext in the function instead of a global context object
like below
private void SaveItemDetails()
{

using(context dc = new context())
{
    foreach(var itemLine in ObsItemLineDetails )
        {
            var today = DateTime.Today.AddSeconds(-1);
            var newCommentDate = (Int32)(today.Subtract(new DateTime(1970, 1, 1,0,0,0))).TotalSeconds;

            var itemDetail = dc.ItemLineDetails.Where(d => d.ItemCode.Equals(itemLine.ItemCode) &&
                d.LineId == itemLine.LineId &&
                d.SearchDate == itemLine.SearchDate).FirstOrDefault();
            if (itemDetail != null)
            {
                itemDetail.CommentDate = newCommentDate;
                itemDetail.Comments = GetAutoComment();
                dc.UpdateObject(itemDetail);
            }
        }
        dc.SaveChanges();
}
}


text:
Q: AsyncTask and Services that uses onHandleIntent? I have a button click listener that's trigger a Service. that service fetches data from the web via onHandleIntent method.
This data is printed in my activity using a ListView
should i use asyncTask in my service(to fetch data from the web) or in my button listener or i shouldn't use it at all??
What are the best practices in my case?

A: If you are using an IntentService it will handle each Intent received in a worker thread, so there's no need to use an AsyncTask.

A: Service runs in main thread. Since you wanna fetch data by service, you should run AsyncTask in onHandleIntent method of service.


text:
Q: shell script to replace a word in a given sentence I Need a unix shell script that when executed accepts a sentence and replaces a given word with another word.

A: If you need a command to do this, try sed.
For example, to replace hello with goodbye in the sentence hello world:
$ sed 's/hello/goodbye/g' <<< "hello world"
goodbye world

If you want this in a bash script:
#!/bin/bash

if [[ $# -lt 3 ]]
then
     echo "Usage: $(basename $0) word replacement sentence" >&2
     exit 1
fi

word="$1"
replacement="$2"
sentence="$3"

echo "${3//$1/$2}"

Example:
$ replace.sh hello goodbye "hello world"
goodbye world

A: Use sed:
sed 's/source/destination/' file_with_sentence.txt

*

*source is the searched word

*destiantion is the replacement

*file_with_sentence... is sef explained

You can wrapp it into some unix shell script (you did not tell which shell are you using)
or even better:
echo "This is my sentence" | sed 's/source/destination/'


text:
Q: Specific input values convert to JSON Following form input values need to convert in JSON using Jquery, I will update this JSON data into mysql via AJAX. I need to convert specific input values (e.g: product id, product name, product price, discount reason, discount amount) to JSON format. I have tried myself:
$(document).ready(function(){
  var jsons = $('form').serializeJSON();
  console.log( jsons );
});

But, I can't maintain sequence and can't skip unwanted inputs.
PHP CODE:
    <form>
        First name: <input type="text" name="first_name" value="Addem">
        Last name: <input type="text" name="last_name" value="Smith">

        Product id: <input type="number" name="items[][cat_id]" value="18">

        Product name: <input type="text" name="items[][product_name]" value="Men's t-shirt">

        Product sku: <input type="text" name="item_sku" value="PBKL09509403">

        Date: <input type="text" name="date" value="2018-09-18">

        Product price: <input type="text" name="items[][product_price]" value="165.00">

        Discount reason: <input type="text" name="adjustments[][reason]" value="Special">
        Discount amount: <input type="text" name="adjustments[][amount]" value="20.00">

        Product total: <input type="text" name="total[price]" value="145.00">

    </form>

JSON Output (required):
{
   "items":[
      {
         "cat_id":18,
         "product_name":"Men's t-shirt",
         "product_price":165
      }
   ],
   "total":{
      "price":145
   },
   "adjustments":[
      {
         "reason":"Special",
         "amount":"20"
      }
   ]
}

A: To remove the unwanted inputs, you can use the delete operator.
var jsons = $("form").serializeJSON();
delete jsons.first_name;
delete jsons.last_name;

I'm not sure why it doesn't maintain the sequence properly. If that's true, it sounds like a bug in the serializeJSON plugin that you're using. There may be other implementations that work better.


text:
Q: Separating a string with PHP I am currently working on a VERY simple search feature for my website. The user types in their search query and then they are taken to a page that displays the results. In my case, the users are search for other users. My problem is, how do I separate a string into two variables?
Example Query:
Matt Morris
I would like my PHP to separate the string where the space occurs. How can I do that?
  <html>
    <form method="get" action="results.php">
        <input type="text" name="search"/>
    </form>

 </html>

<?php

    // code to explode the string into $fname and $lname
       if there is a space present

$fname= Matt
$lname= Morris

if (isset($fname) && isset($lname)) {
$search_query= "SELECT * FROM users WHERE fname LIKE %'".$fname."'% AND lname LIKE
%'".$lname."'%";
// code to run the query and display results
}
else if (isset($fname)) {
$search_query= "SELECT * FROM users WHERE fname LIKE %'".$fname."'%";
// code to run the query and display results
}
else if (isset($lname)) {
$search_query= "SELECT * FROM users WHERE lname LIKE %'".$lname."'%";
// code to run the query and display results
}

 ?>

Thanks

A: You could do it like this:
list($first, $last) = explode($name, ' ', 2);

A: You can use the php function explode
http://php.net/manual/en/function.explode.php
// Example 1
$pizza  = "piece1 piece2 piece3 piece4 piece5 piece6";
$pieces = explode(" ", $pizza);
echo $pieces[0]; // piece1
echo $pieces[1]; // piece2

A: $array = explode(' ', $string);


text:
Q: Reading csv file in c# method I am aiming to read a csv file in my c# method. this csv file is not defined and it can have n number of columns. One thing which will always remain constant is that there will be only two rows in csv file. one will be header row and other will be value row. My below method works fine when my values are string values but fails when one of my value is something like this [test,test1,test2]. I tried with Csv helper class but I am unable to do. can someone suggest me how should I approach?
metadata is list of lines I read from StreamReader
private void AddValuesToTable( DynamicTableEntity tableEntry, List<string> metadata )
        {

            var headers = metadata[0].Split( "," );
            var values = metadata[1].Split( "," );
            for( int i = 0; i < headers.Count(); i++ )
            {
                tableEntry.Properties.Add( headers[i].ToString(), EntityProperty.CreateEntityPropertyFromObject( values[i] ) );
            }
        }

Sample value:
columnA,columnB,columnC
valA,[testa,testb],valc

A: This is the code that I use to parse a CSV line.
private static string Peek(this string source, int peek) => (source == null || peek < 0) ? null : source.Substring(0, source.Length < peek ? source.Length : peek);
private static (string, string) Pop(this string source, int pop) => (source == null || pop < 0) ? (null, source) : (source.Substring(0, source.Length < pop ? source.Length : pop), source.Length < pop ? String.Empty : source.Substring(pop));

public static string[] ParseCsvLine(this string line)
{
    return ParseCsvLineImpl(line).ToArray();
    IEnumerable<string> ParseCsvLineImpl(string l)
    {
        string remainder = line;
        string field;
        while (remainder.Peek(1) != "")
        {
            (field, remainder) = ParseField(remainder);
            yield return field;
        }
    }
}

private const string DQ = "\"";

private static (string field, string remainder) ParseField(string line)
{
    if (line.Peek(1) == DQ)
    {
        var (_, split) = line.Pop(1);
        return ParseFieldQuoted(split);
    }
    else
    {
        var field = "";
        var (head, tail) = line.Pop(1);
        while (head != "," && head != "")
        {
            field += head;
            (head, tail) = tail.Pop(1);
        }
        return (field, tail);
    }
}

private static (string field, string remainder) ParseFieldQuoted(string line)
{
    var field = "";
    var head = "";
    var tail = line;
    while (tail.Peek(1) != "" && (tail.Peek(1) != DQ || tail.Peek(2) == DQ + DQ))
    {
        if (tail.Peek(2) == DQ + DQ)
        {
            (head, tail) = tail.Pop(2);
            field += DQ;
        }
        else
        {
            (head, tail) = tail.Pop(1);
            field += head;
        }
    }
    if (tail.Peek(2) == DQ + ",")
    {
        (head, tail) = tail.Pop(2);
    }
    else if (tail.Peek(1) == DQ)
    {
        (head, tail) = tail.Pop(1);
    }
    return (field, tail);
}

It correctly deals with quoted fields.


text:
Q: Easy way of creating tabs in a Liferay portlet? Ello there,
Does anyone know of an easy way to create tabs in a Liferay portlet? Been reading up on it and I just can't seem to find any suggestions on how to do this quite easily.
Would be great if someone that has experience with this could give me some pointers.
Thanks!

A: Use the Liferay UI TagLib!
First import the TagLib,
<%@ taglib uri="http://liferay.com/tld/ui" prefix="liferay-ui" %>

Now you can use this,
<liferay-ui:tabs
    names="questions,tags,users,badges,unanswered"
    param="tab"
    url="<%= myURL.toString() %>"
/>

*

*The name attribute is comma separated with the names of your Tab.

*The url attribute will be a URL where the param attribute will be appended to as a param.

Alternatively, you can explicitly set the URL for each tab.
<liferay-ui:tabs
    names="questions,tags,users,badges,unanswered"
    url1="<%= questionsURL.toString() %>"
    url2="<%= tagsURL.toString() %>"
    url3="<%= usersURL.toString() %>"
    url4="<%= badgesURL.toString() %>"
    url5="<%= unansweredURL.toString() %>"
/>


text:
Q: How to add virtual-host and how to change context root WAS DEV Maven i tried to create Maven project for WAS Liberty server.
mvn archetype:generate -DarchetypeGroupId=net.wasdev.wlp.maven -DarchetypeArtifactId=liberty-archetype-ear  -DarchetypeVersion=2.2  -DgroupId=com.test -DartifactId=test -Dversion=1.0-SNAPSHOT
Can you please tell me how to configure Context path and how to add the virtual-host.

A: Though the archetype template doesn't specifically provide a method for configuring these, you can easily start from the application and server config generated and configure the server "normally" from there.
Example using liberty-archetype-webapp archetype:

*

*Generate project:
mvn archetype:generate -DarchetypeGroupId=net.wasdev.wlp.maven -DarchetypeArtifactId=liberty-archetype-webapp -DarchetypeVersion=2.5 -DgroupId=com.test -DartifactId=test -Dversion=1.0-SNAPSHOT

*Create bindings file: src/main/webapp/WEB-INF/ibm-web-bnd.xml with contents:
<?xml version="1.0" encoding="UTF-8"?>
<web-bnd
    xmlns="http://websphere.ibm.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://websphere.ibm.com/xmk/ns/javaee   http://websphere.ibm.com/xml/ns/javaee/ibm-web-bnd_1_0.xsd"
    version="1.0">

    <virtual-host name="myVHost" />
</web-bnd>

*Configure virtual host (and context root) in server config at src/main/liberty/config/server.xml:
<server description="Sample Servlet server">

   <featureManager>
     <feature>jsp-2.3</feature>
   </featureManager>

  <httpEndpoint host="*" httpPort="9080" httpsPort="9443" id="defaultHttpEndpoint"/>

  <virtualHost id="myVHost">
    <hostAlias>myDomain.myHost.com:9080</hostAlias>
  </virtualHost>

  <webApplication id="test" location="test.war" name="test" contextRoot="ctxRoot"/>

 </server>

Note:
I noticed you specifically asked about the  liberty-archetype-ear archetype, so if the above doesn't meet your needs, please comment and mention this.
Also I upgraded the archetype version to 2.5, which also brings in a newer version of Liberty (actually Open Liberty), though it should also be fine at the 2.2 level.
You can


text:
Q: How to set the width of R console in terminal evoked from vim? I installed vim-r-plugin on my Linux computer. The below is the R console prompted by "\rf", but it seems too narrow to show all columns of the data though the terminal window has been wide enough. I am wondering how to make it wider just for the R console.

A: Install that package setwidth and put library(setwidth) in your ~/.Rprofile. Then the width of the R console adjusts to the width of your terminal (it will be the same width as the output of tput cols).
If you simply want a custom width, you can do options(width = 120), for example.
Edit:
The package setwidth has been removed from CRAN. Now you can get the desired result with: options(setWidthOnResize = TRUE)

A: The setwidth package doesn't work as advertised on my configuration (konsole 20.08.0, KDE Plasma 5.19.4), and it's been removed from CRAN:
https://cran.r-project.org/web/packages/setwidth/index.html
Fortunately, it is still available in the archive:
https://cran.r-project.org/src/contrib/Archive/setwidth/
So, you can install it via:
install.packages("https://cran.r-project.org/src/contrib/Archive/setwidth/setwidth_1.0-4.tar.gz")

(this is the most recent version, 2015 - not so young)
Now you can execute:
library(setwidth)

And this sets the width option once, to your terminal width.
Check it with:
getOption("width")

Unfortunately, after resizing nothing happens, despite having TERM='xterm-256color' in my environment.
But, putting library(setwidth) to my ~/.Rprofile at least works when I don't resize the terminal. Or, you can save the workspace and restart R.


text:
Q: Samsung Galaxy Tab 2 Native File Explorer app: "My Files" package name I am trying to make a button that when on click will change the view and open up the native file explorer on a tablet. I found a potential solution with code like this:
fileBrowseButton.setOnClickListener(new View.OnClickListener()
    {
        @Override
        public void onClick(View v)
        {
            PackageManager packageManager = getPackageManager();
            startActivity(packageManager.getLaunchIntentForPackage("com.My Files.android"));
        }
    });

The only issue I seem to have is I can't identify the name of the package that is the file explorer, I tried looking around in the app manager. I know on my Motorola phone its:
com.motorola.filemanager

Anyone know what the package name?
The possible workaround is downloading something like Astro and using that instead, but I would prefer the native app first.

A: I did some apk digging and found the package name for my device...
Now I know this will not work on other devices, I tested it on Motorola device and got an error (which was expected).
The package name for Samsung Galaxy Tab 2 native file browser turned out to work with the name:
"com.sec.android.app.myfiles"
Thanks

A: Android does not have a native File Manager, though most OEMs usually install one of their own, or one of a developer with whom they have an agreement.
You should either use an Intent to pick the file, and maybe even provide a small file manager yourself. This answer here should help with that.


text:
Q: IE7 automatically open xml file error Currently each link type http:monsite/monfichier.xml, the file will automatically open in IE without asking me to download it, the problem is that my file contains DTD so that it can not find a poster error "error opening file".
The problem persists even after changing the MIME server weblogic application / octet-stream
Is there a parameter change in IE? (for have download box directly)
Thank you in advance
i have change many option in securty (download no automatic etc..) but nothing

A: I think you can try to send the following header:
Content-Disposition: attachment; filename=filename.xml


text:
Q: Как мне создать метод transfer(), который удаляет игрока из одной команды и назначает игрока в другую команду? Указываем id игрока (которого хотим купить) и id команды (куда хотим вставить игрока). У игрока уже есть команда. Нам нужно сначала удалить его из команды, а затем вставить в другую команду. Что-то вроде этого кода). Spring Boot.
public void  buyPlayer(PlayerDTO playerDTO, TeamDTO teamDTO) {
        Team team2 = teamService.getOne(teamDTO.getId());
        Player player2 =  map(playerDTO);
        playerRepository.deleteById(playerDTO.getId());
        long cost = playerDTO.getFinalCost();
        long budget = teamDTO.getBudget() + cost;
        teamDTO.setBudget(budget);
        player2.setTeam(team2);

    }

A: Удаление игрока при помощи playerRepository.deleteById(playerDTO.getId()); явно некорректно.
В сущности Team имеет смысл хранить список игроков List<Player>, для которого следует реализовать пару методов addPlayer / removePlayer.  Тогда метод transfer может выглядеть так:
public void transfer(PlayerDTO playerDTO, TeamDTO teamDTO,) {
    Player player = map(playerDTO);
    Team oldTeam = player.getTeam();
    Team newTeam = teamService.getOne(teamDTO.getId());

    oldTeam.removePlayer(player);
    // старая команда получает деньги за переход, бюджет увеличивается
    oldTeam.setBudget(oldTeam.getBudget() + playerDTO.getFinalCost());

    newTeam.addPlayer(player);
    // новая команда платит деньги за переход, бюджет уменьшается
    newTeam.setBudget(newTeam.getBudget() - playerDTO.getFinalCost());
    // player.setTeam(newTeam);

    // суммарная стоимость игроков обеих команд должна пересчитаться после сохранения
    teamService.save(oldTeam);
    teamService.save(newTeam);
}


text:
Q: Show $(1,1)$ tensor acts as a map from vectors to vectors In Sean Carroll's Spacetime and Geometry book, pg. 22, it was stated that a (1,1) tensor acts as a map from vectors to vectors:
$${T^\mu}_\nu: V^\nu\rightarrow {T^\mu}_\nu V^\nu.$$
I tried showing this myself by considering the action of the $(1,1)$ tensor $T$ on a vector $V$:
$$T(0,V)={T^\mu}_\nu e_\mu\otimes e^\nu(0,V),$$
where $e_\mu$ and $e^\nu$ are the basis vectors for the vector space and the dual vector space respectively.
I then proceed on to get
$$\begin{equation}
T(0,V)={T^\mu}_\nu e_\mu(0)\times e^\nu(V) \\={T^\mu}_\nu e_\mu(0)\times e^\nu(V^\rho e_\rho)\\={T^\mu}_\nu e_\mu(0)\times V^\rho e^\nu( e_\rho)\\={T^\mu}_\nu e_\mu(0)\times V^\rho \delta^\nu_\rho\\={T^\mu}_\nu \times0\times V^\nu\\=0
\end{equation}$$
where I used $e_\mu(e^\rho)=\delta^\rho_\mu$ so $e_\mu(0)=0$.
The result is clearly not corret. What am I doing wrong?

A: A $(1,1)$ tensor is a multilinear map from $V^* \times V$ to the underlying field of scalars of V, which is typically $\mathbb{R}$. In you example, your first element in $(0, V)$ is $0 \in V^*$, and since the tensor is a linear map on $V^*$ it will always map $(0,v)$ to $0$ for any $v \in V$.
You can also think of a $(1,1)$ tensor $T$ as a linear map $T:V \rightarrow V$. If $T$ has components ${T^\mu}_\nu$ relative to a given basis and $V$ has compoonents $v^{\nu}$ relative to the same basis then the components of the vector $T(V)$ are $(T(V))^\mu = {T^\mu}_\nu v^{\nu}$.


text:
Q: excel sumifs how to convert a range value from a day into a date so that the criteria can test if the date falls between two dates I have a day field denoting which day of a month a debit comes out of an account. These are listed by start date end date and day number of withdrawal and value.
On a separate sheet I have a running fortnightly income and expenditure sheet and I want to include those fixed regular costs on the right fortnightly value.
I currently use the following sumifs statement:
=(SUMIFS(Fixed!$F:$F,Fixed!$C:$C,"Monthly",Fixed!$D:$D,">"&DAY('monthly forecast 2017'!H1),Fixed!$D:$D,"<"&DAY('monthly forecast 2017'!I1),Fixed!$B:$B,">"&H1,Fixed!$A:$A,"<"&'monthly forecast 2017'!I1))

The worksheet Fixed! is the sheet containing the fixed regular costs.
Fixed!$F:$F - the data being calculated in the sumifs
criteria range 1: Fixed!$C:$C -  include if row value is "monthly"
criteria range 2: Fixed!$D:$D,">"&DAY('monthly forecast 2017'!H1) - include if day number $D which is greater than the day number of the 'from' date of the fortnight column e.g. fortnight from H1 = 01-01-17  to H2 = 14-01-17
criteria range 3: Fixed!$D:$D,"<"&DAY('monthly forecast 2017'!I1) as above but if day number $D is less than the start of the next fortnight e.g. fortnight from I1 = 01-01-17  to I2 = 14-01-17
criteria range 4 & 5: just ensures the start and end date of this repeating bill does not after or before the fortnight respectively.
The problem is that where a fortnight is in 1 month and ends in another e.g. from column F the dates from 26-02-17 to 11-03-17 will fail to work as intended  when a bill falls on the 27th. As the criteria of range 3 fails to capture 2 different months. Therefore I tried to convert the day value to a date value based on the month in question e.g.
Criteria 2 becomes: DATE(year(F1),month(F1),day(Fixed!$D:$D),">"&'monthly forecast 2017'!F1 where F1 = start date of the forthnight. However this will not work due to improper use of the DATE() function on a range.
I need to either be able to convert a day to a specific date in order to check if the fixed bills falls between the two dates or I need to change the formula. I feel that latter but at the moment I cannot think of another method other than creating a VB script.
Example of fixed costs sheet
Example of calculated fortnightly costs (income/expenditure)
As you can see the first value should be in a column where the 27th day is in that fortnight. But it is not included when the fortnight ends in the next month.

A: I think you are overthinking your problem.
If the data in fixed is in date format (i.e. 01/02/2017 for example), excel sees it as a number. which means you can compare dates without any other calculation :
this will then be your formula (for one criteria, I'll let you put in the others):
sumif(fixed!$D1:$D10,"<"&'monthly forecast 2017'!I1)

For the fornight part, you then add the number of days to your criteria.
I may not have fully understood your problem, feel free to comment to help me get it.


text:
Q: correlation matrix to build networks I have used the MixOmics package in R for a two matrices (canonical correlation analysis) and I have a resultant correlation matrix. I would like to build a correlation network from the result obtained. I earlier thought of using the gene set correlation analysis package but I do not know how to install it and there are no sources over the internet to install it in R     (http://www.biostat.wisc.edu/~kendzior/GSCA/).
Also could you suggest what other packages I could use to build networks with correlation matrix as input ?? I thought of Rgraphviz but do not know if it is possible.

A: Copying this answer mostly from my previous answer at https://stackoverflow.com/a/7600901/567015
The qgraph package is mostly intended to visualize correlation matrices as a network. This will plot variables as nodes and correlations as edges connecting the nodes. Green edges indicate positive correlations and red edges indicate negative correlations. The wider and more saturated the edges the stronger the absolute correlation.
For example (this is the first example from the help page), the following code will plot the correlation matrix of a 240 variable dataset.
library("qgraph")
data(big5)
data(big5groups)
qgraph(cor(big5),minimum=0.25,cut=0.4,vsize=2,groups=big5groups,legend=TRUE,borders=FALSE)
title("Big 5 correlations",line=-2,cex.main=2)

You can also cluster strongly correlated nodes together (uses Fruchterman-Reingold) which creates quite a clear image of what the structure of your correlation matrix actually looks like:

For an extensive introduction take a look at http://www.jstatsoft.org/v48/i04/paper

A: You might also want to take a look at the network and sna packages on CRAN.  Both include tools for converting a matrix into a network data object.


text:
Q: Is It possible to sync MySQL table to SharePoint list through SharePoint Business Connectivity Service? I want know is it possible to connect MySQL table to SharePoint list ?
This question is asked in an interview for me.

A: Yes it is possible to connect MySQL with BDC using ODBC driver.
You can refer this Integrating SharePoint with MySQL using Business Data Catalog
Please let me know if it help you.
Thanks


text:
Q: The key was not found in the key ring. Unable to validate token I am getting weird error on identity server 4 after I added NGNIX Proxy infront of my application.

*

*My .net core identity server is running on Docker Container on port 8080

*Ngnix proxy(using https://github.com/nginx-proxy/nginx-proxy) is configured to route 443 to docker container 8080
After successfully authenticate on callback endpoint it fails to validate the forgery token.
The weird part is the whole scenario works for user that I seed when the .net core app is started. But fails for new one created via my API.
Any idea or taught is appreciated.

A: Your session cookie issued by ASP.NET core is encrypted using the Data Protection API.
The key used to sign the cookie is stored in a Key ring. If you now redeploy your application and if you haven't configured it correctly, then a new encryption key will be issued in a new key ring.
If the key that was used to encrypt the cookie can't be found, then this means that existing session cookie in the all clients browsers can't be decrypted anymore.
See this article about this API and this article about how to configure it.
This is both applicable to your IdentityServer and Client application as both uses the Data Protection API, so both needs to have a permanent key-ring in place. When you redeploy containers, the key-ring is lost unless you have placed the key-ring in some permanent volume on the file system or persisted it in some other way. The API supports many places to store the keyring, including database, redis, Azure Key Vault..


text:
Q: passing parameter without anonymous function in javascript In addeventlistener we must use anonymous function for passing parameter
for example
body.addeventlistener('click,function(){myfunc(str)});

why can't we use normal function for passing parameter??
for example
body.addeventlistener('click,myfunc(str));
function myfunc(str)
{
alert(str);
}

why does not this code work?


text:
Q: Known issues with Resharper 6 Im having real problems using Resharper-6 with VisualStudio-2008, specuially during debugging, as soon as click the "F5" to let it run, VS2008 crashes and restarts, is it a know issue, did anybody face such problems?
thank you

A: I haven't encountered that issue personally. It is definitely the fault of ReSharper? Does the problem go away if you uninstall ReSharper?
As for known issues try the following:

*

*ReSharper FAQ

*ReSharper Forum

*ReSharper Issue Tracker
If it's definitely down to ReSharper then I'd recommend adding a support request to the Issue Tracker.


text:
Q: Unable to call loaction.state inside componentDidMount in reactjs I am working on reactjs project where i have to get the data form Component B to Component A . i am successfully able to get the detail, after A component is fully mounted and perform some action such as click . I want the data to be returned when i mount my component in componentDidMoount or render function . I am unable to get the desired data how can i reslove this?. bellow is my code.
Component B (component which create's the data i need and pass it to edititeratoin)

<Redirect to={{ pathname: '/EditIteration',state: {editdata: userdata.userid , editstartdate:userdata.startdate , editenddate:userdata.enddate , editname:userdata.name} }} />

Componnet A

locationState()
  {
    console.log("Message",this.props.location.state.editdata);
  }

  componentDidMount()
  {
    // console.log("Message",this.props.location.state);
     this.locationState();
  }


text:
Q: Need compression utility which uses all CPUs and compresses the best I uses RAR since it was released a decade ago perhaps. However it is good for desktop applications I just found that on server where I need to compress a lot of text files every weekend it takes ages.
I looked into CPU usage and RAR takes around 15% of total CPU time. Nothing else is running alongside.
I have Xeon 8 threads (4 HT cores) and Windows 2008 R2.
Is there a compression software which zips no worse than RAR with option Best and takes advantage of all cores and HT ?
Thanks
P.S. Also has to have x64 version

A: On a single server, pigz is gzip compatible, which makes for trivial portability.  It will use as many cores as you have, to compress file(s).  I've found it quite useful, and significantly speeds up compression of a number of files. Usefully, pigz is installable directly from apt in Ubuntu 10.4.
Something else at a higher level that I have just seen today is Gnu Parallel that will run a program/script against multiple files either multiple times concurrently, and/or even more interestingly, on multiple machines.  http://www.youtube.com/watch?v=OpaiGYxkSuQ is a video demo (part 1) of its use.
These are both unfortunately primarily *nix based tools, though they may also be available via Cygwin.

A: Ok. I found the benchmark for many formats. It seems Winrar beats 7Zip on Best. And 7Zip with LZMA2 beats Winrar on Default...
So I am going to install 7Zip and compare it to Winrar side-by-side.
http://www.tomshardware.co.uk/archive-zip-compression,review-31831-8.html


text:
Q: Class inheritance under same instance I am trying to have multiple classes inherit from one class but use the same instance and not create a different instance each time.
class ClassA(object):
    def __init__(self):
        self.process_state = "Running"
        self.socket_list = []
    def method_a(self):
        print("This is method a")

class ClassB(ClassA):
    def __init__(self):
        super().__init__()

    def method_b(self):
        if self.process_state == "Running":
            self.socket_list.append("From Method B")
            print(self.socket_list)
            print("This is method b")

class ClassC(ClassA):
    def __init__(self):
        super().__init__()

    def method_c(self):
        if self.process_state == "Running":
            print(self.socket_list)
            self.socket_list.append("From Method C")
            print("This is method c")
            print(self.socket_list)

Functions ran:
CB = ClassB()
CB.method_b()
CB.method_b()

CC = ClassC()
CC.method_c()

Result:
['From Method B']
This is method b
['From Method B', 'From Method B']
This is method b
[]
This is method c
['From Method C']

Desired result:
['From Method B']
This is method b
['From Method B', 'From Method B']
This is method b
['From Method B', 'From Method B']
This is method c
['From Method B', 'From Method B', 'From Method C']

I am trying to have multiple class inherit from one class but use the same instance and not create a different instance each time.

A: One way you can achieve this is by making the socket list a static variable, though I'm not sure if this is recommended.
class ClassA(object):
    socket_list = []
    def __init__(self):
        self.process_state = "Running"
    def method_a(self):
        print("This is method a")

Output:
['From Method B']
This is method b
['From Method B', 'From Method B']
This is method b
['From Method B', 'From Method B']
This is method c
['From Method B', 'From Method B', 'From Method C']


text:
Q: Using wildcards (*) in REST API resource name Is it sensible to use * in REST API for a resource ID? I want to use it for searching. I'm using RESTEasy for developing my webservice.
Suppose I have resources that are user and user has Name and Age. Then my REST API looks like:
/users/{id}/name
/users/{id}/age

Now if I want to display all names I'm thinking on using the following:
/users/*/name

Is this correct or should I use another way of doing?
Edit 1: Adding subresources
As from an answer it is suggested to use a fields query param. But let's suppose I'm now want something that is a property of the sub-resource. For instance:
/user/*/name/full
/user/*/name/short

If I follow the fields option, I will have to do:
/user?fields=name-short
/user?fields=name-full

Which it is not nice as the properties of name are linked to the name class somehow.
Please do consider the example as that. Try to get the idea ;)

A: Query parameters
You can probably use wildcards, but not in the way you've shown in your question. What if you want to get more details besides the name in the same request?
You could use a query parameter to allow field selection for the users collection:
/users?fields=name

/users?fields=age

/users?fields=name,age

Or you can get some inspiration from how partial responses are handled in the Google Drive API:
/users?fields=name(short,full)

Alternatively, you could use dot notation:
/users?fields=name.short,name.full

Or use a mix of both, like in the Spotify API.
Custom media types
If you don't need field selection, you can use custom media type, returning a predefined set of fields.


text:
Q: How to initializeApp in HuaWei android messaging service In FirebaseApp, there is a initializeApp method to provide it's constants for firebase app. How about the related method in android app using HMS service?

A: Currently, HMS does not provide a unified codebased initialization, however, some kits individually do support codebased initialization by requesting APIkeys.


text:
Q: Can't install github desktop I get this error msg.
PLATFORM VERSION INFO
    Windows             : 10.0.14393.0 (Win32NT)
    Common Language Runtime     : 4.0.30319.42000
    System.Deployment.dll       : 4.6.1586.0 built by: NETFXREL2
    clr.dll             : 4.6.1637.0 built by: NETFXREL3STAGE
    dfdll.dll           : 4.6.1586.0 built by: NETFXREL2
    dfshim.dll          : 10.0.14393.0 (rs1_release.160715-1616)

SOURCES
    Deployment url          : https://github-windows.s3.amazonaws.com/GitHub.application
                        Server      : AmazonS3
    Application url         : https://github-windows.s3.amazonaws.com/Application%20Files/GitHub_3_3_4_0/GitHub.exe.manifest
                        Server      : AmazonS3

IDENTITIES
    Deployment Identity     : GitHub.application, Version=3.3.4.0, Culture=neutral, PublicKeyToken=317444273a93ac29, processorArchitecture=x86
    Application Identity        : GitHub.exe, Version=3.3.4.0, Culture=neutral, PublicKeyToken=317444273a93ac29, processorArchitecture=x86, type=win32

APPLICATION SUMMARY
    * Installable application.
    * Trust url parameter is set.
ERROR SUMMARY
    Below is a summary of the errors, details of these errors are listed later in the log.
    * Activation of https://github-windows.s3.amazonaws.com/GitHub.application resulted in exception. Following failure messages were detected:
        + The application binding data format is invalid. (Exception from HRESULT: 0x800736B2)

COMPONENT STORE TRANSACTION FAILURE SUMMARY
    No transaction error was detected.

WARNINGS
    There were no warnings during this operation.

OPERATION PROGRESS STATUS
    * [3/19/2017 7:14:58 PM] : Activation of https://github-windows.s3.amazonaws.com/GitHub.application has started.
    * [3/19/2017 7:14:59 PM] : Processing of deployment manifest has successfully completed.
    * [3/19/2017 7:14:59 PM] : Installation of the application has started.
    * [3/19/2017 7:15:00 PM] : Processing of application manifest has successfully completed.
    * [3/19/2017 7:15:08 PM] : Found compatible runtime version 4.0.30319.
    * [3/19/2017 7:15:08 PM] : Request of trust and detection of platform is complete.
    * [3/19/2017 7:19:30 PM] : Downloading of subscription dependencies is complete.
    * [3/19/2017 7:19:30 PM] : Commit of the downloaded application has started.

ERROR DETAILS
    Following errors were detected during this operation.
    * [3/19/2017 7:19:30 PM] System.Runtime.InteropServices.COMException
        - The application binding data format is invalid. (Exception from HRESULT: 0x800736B2)
        - Source: System.Deployment
        - Stack trace:
            at System.Deployment.Internal.Isolation.IEnumSTORE_ASSEMBLY.Next(UInt32 celt, STORE_ASSEMBLY[] rgelt)
            at System.Deployment.Internal.Isolation.StoreAssemblyEnumeration.MoveNext()
            at System.Deployment.Application.ComponentStore.CollectCrossGroupApplications(Uri codebaseUri, DefinitionIdentity deploymentIdentity, Boolean& identityGroupFound, Boolean& locationGroupFound, String& identityGroupProductName)
            at System.Deployment.Application.SubscriptionStore.CommitApplication(SubscriptionState& subState, CommitApplicationParams commitParams)
            at System.Deployment.Application.ApplicationActivator.InstallApplication(SubscriptionState& subState, ActivationDescription actDesc)
            at System.Deployment.Application.ApplicationActivator.PerformDeploymentActivation(Uri activationUri, Boolean isShortcut, String textualSubId, String deploymentProviderUrlFromExtension, BrowserSettings browserSettings, String& errorPageUrl)
            at System.Deployment.Application.ApplicationActivator.ActivateDeploymentWorker(Object state)

COMPONENT STORE TRANSACTION DETAILS
    No transaction information is available.

A: You should clear everything out of the Apps folder:

*

*Remove the 2.0 folder from %LocalAppData%\Apps
Also, turn off your firewall for private and public profile and then retry.
You can look at this link for more detail.


text:
Q: Перевести число в unsigned long = 83e58955 в строку char[9] = "83e58955" Всем привет. Требуется помощь с переводом unsigned long в char.
Пример:
Перевести
unsigned long out1 = 0x83e58955;

в строку
char out[9] = "83e58955".

Помогите с алгоритмом пожалуйста.