text:
Q: geany output to same terminal instance In Geany, the Menu > Build > Execute command can be configured to send output to a terminal window.
For example: With the following command in Build Commands and a Python script in the active window, the Execute command will send output from the script into an interactive Python session in a terminal window.
/usr/bin/python3 -i '%f'

However, with Geany as I've configured it so far, the output goes to a new instance of terminal each time I run. I will quickly accumulate an unwieldy number of windows and if I want to see the result of a previous run it is not always obvious which window is the one.
So is there any way of getting this all to happen in the same terminal instance each time I run?
This is not about multiple instances of Geany, but about one instance of Geany generating multiple instances of terminal. The behavior I'm looking for is that of IDLE's F5.

A: See Geany's manual on Virtual terminal emulator (VTE) page and check Execute programs in VTE option:

Execute programs in the virtual terminal instead of using the external terminal tool. Note that if you run multiple execute commands at once the output may become mixed together in the VTE.


text:
Q: CIColorMap doesn't apply gradient uniformly to input image I created a CIColorMap filter by loading the attached blue-to-red gradient image.

Then I tried to apply this to a gray scale input image, which is simply a linear gradient from black to white.

When I draw the out image of CIColorMap in a CIContext, the intention is to render black color in dark blue, white color in dark red, and mid gray in white. However the actual result looks like:

As you can see, the mid gray is actually mapped to light blue, instead of white as I have expected.
Below is the source code. I wonder if I have been using CIColorMap incorrectly given the very scarce documentation.
// Interface file
#import <Cocoa/Cocoa.h>
@interface ColorMapView : NSView
@end

// Implementation file
#import <QuartzCore/QuartzCore.h>
#import "ColorMapView.h"

static size_t imageWitdh = 512;
static size_t imageHeight = 125;

@implementation ColorMapView {
    CIImage *m_backgroundImage;
    CIImage *m_colorMapGradient;
    CIFilter *m_colorMapFilter;
    CIContext *m_ciContext;
}

- (instancetype)initWithCoder:(NSCoder *)coder {
    self = [super initWithCoder:coder];
    if (self) {
        [self initBackgroundImage];
        [self initColorMapGradient];
    }
    return self;
}

- (void)drawRect:(NSRect)dirtyRect {
    [super drawRect:dirtyRect];

    if (!m_ciContext)  {
        m_ciContext = [CIContext contextWithCGContext:[NSGraphicsContext currentContext].graphicsPort options:nil];
    }

    CGFloat x = (self.bounds.size.width - imageWitdh) / 2;
    CGFloat y = (self.bounds.size.height - imageHeight) / 2;

    // Drawing code here.
    [m_colorMapFilter setValue:m_backgroundImage forKey:kCIInputImageKey];
    [m_ciContext drawImage:[m_colorMapFilter valueForKey:kCIOutputImageKey] inRect:CGRectMake(x, y, imageWitdh, imageHeight) fromRect:m_backgroundImage.extent];
}

- (void)initBackgroundImage {
     CGColorSpaceRef colorSpace = CGColorSpaceCreateWithName(kCGColorSpaceGenericGray);
    CGContextRef context = CGBitmapContextCreate(NULL, imageWitdh, imageHeight, 8, imageWitdh, colorSpace, (CGBitmapInfo)kCGImageAlphaNone);
    CGFloat locations[2] = {0.0, 1.0};
    CGFloat components[4] = {0.0, 1.0, 1.0, 1.0};
    CGGradientRef gradient = CGGradientCreateWithColorComponents(colorSpace, components, locations, 2);
    CGContextDrawLinearGradient(context, gradient, CGPointMake(0, 0), CGPointMake(imageWitdh, 0), NO);
    CGImageRef gradientImage = CGBitmapContextCreateImage(context);
    CGContextRelease(context);
    CGGradientRelease(gradient);
    CGColorSpaceRelease(colorSpace);
    m_backgroundImage = [CIImage imageWithCGImage:gradientImage];
    CGImageRelease(gradientImage);
}

- (void)initColorMapGradient {
    NSString* imagePath = [[NSBundle mainBundle] pathForResource:@"blue_red_scale_gradient" ofType:@"png"];
    CGDataProviderRef dataProvider = CGDataProviderCreateWithFilename(imagePath.UTF8String);
    CGImageRef image = CGImageCreateWithPNGDataProvider(dataProvider, NULL, NO, kCGRenderingIntentDefault);
    m_colorMapGradient = [CIImage imageWithCGImage:image];
    CGImageRelease(image);
    m_colorMapFilter = [CIFilter filterWithName:@"CIColorMap"];
    [m_colorMapFilter setValue:m_colorMapGradient forKey:@"inputGradientImage"];
}

@end

A: It seems this is related to color management issue. If I set kCIContextWorkingColorSpace to NSNull when creating CIContext object, I will get expected result.
if (!m_ciContext)  {
    NSDictionary *options = @{kCIContextWorkingColorSpace : [NSNull null]};
    m_ciContext = [CIContext contextWithCGContext:[NSGraphicsContext currentContext].graphicsPort options:options];
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Use a CALayer to add a diagonal banner/badge to the corner of a UITableViewCell I'm trying to draw decorate a UITableViewCell in my table view with a text banner that looks like a stamp, diagonally across the top left corner of the cell.
I'm probably doing this in the wrong place entirely, but I'm overriding -layoutSubviews to add the layer. I tried to do it in -drawRect: but the banner ends up covered by the table view's imageView as the table renders (i.e. the layer is underneath the image view, as the image view is added later).
I'm really struggling to get the math right for this. I've calculated that, assuming the banner begins at 40 points from the top of the cell and 40 points from the left, angled at exactly -45º, the hypotenuse would be 56 points. So I'm making a CALayer 56 points wide, then rotating it -45º, which works. The problem is the position within the cell... it's sitting way out into the cell, instead of hard up against the edges of it.
Rather than me apply trial and error to get this in the right place, can somebody help me with the math? Obviously I need to move the layer and rotate it.
It feels like anchorPoint is what I need here, but that seems to actually move the layer around, so I must be missing the point (no pun intended).
- (void)layoutSubviews
{
    [super layoutSubviews];

    self.imageView.frame = CGRectMake(10, 10, 50, 50);

    if (self.hasBanner) {
        CALayer *banner = [CALayer layer];
        banner.backgroundColor = [UIColor colorWithRed:.5f green:.5f blue:.5f alpha:1.f].CGColor;
        banner.frame = CGRectMake(0, 40-15, 56, 15);
        banner.anchorPoint = CGPointMake(0, 1); // this just makes it worse
        banner.transform = CATransform3DMakeRotation(-45.0 / 180.0 * M_PI, 0.0, 0.0, 1.0);
        [self.layer addSublayer:banner];
    }
}

A: Where should the layer go?
Let's draw a diagram:

We could go further and do some trig, but let's stop here. It's pretty obvious that the middle-top point of the banner should be at (20,20).  We can tell Core Animation to do exactly that.
Positioning the layer
Think of it in terms of four separate steps:

*

*Set the size of the layer

*Decide what point in the layer is a convenient reference point

*Set the position of that reference point

*Rotate the layer around the reference point

These correspond to four properties: bounds, anchorPoint, position, and transform.
You don't want to touch the frame property, because its value is derived from the bounds, position, transform, and anchorPoint. If you try to set the frame, CALayer will try to invert the transform, apply that to the rect you gave, and then set the bounds and position. That may not give the results you want, so you're better off just ignoring it entirely -- less confusing that way.
(For more information, see the Core Animation Guide, specifically the section Layer Objects Define Their Own Geometry.)
In code, we will:

*

*Set bounds to the rect 0, 0, width, height. (I'm deliberately leaving width to you -- it's going to have to be more than 56.)

*Set anchorPoint to the point 0.5, 0. In other words, halfway along the width of the layer, and at the top of the layer.

*Set position to the point 20, 20.

*Set transform to rotate by 45°.

By the way, in the code below, I'm setting the affineTransform instead of the transform, just because it's slightly more convenient for simple 2-D transformations.
When to set up the layer
You're correct that -drawRect: is the wrong place to create and add layers. That method should draw into the content of the view (its CGContext) but do nothing else.
layoutSubviews will work, but it will get called more often than you might expect, and you don't want to create and add a new layer each time.
It looks like you just need to set the layer's geometry once, and never touch it again. Why not just create or destroy the layer when your hasBanner property is changed?
@interface MyTableViewCell ()

@property (nonatomic) BOOL hasLayer;
@property (nonatomic) CALayer* bannerLayer;

@end

- (void)setHasBanner:(BOOL)hasBanner
{
    if (hasBanner != _hasBanner) {
        _hasBanner = hasBanner;

        if (hasBanner) {
            CALayer* banner = [CALayer layer];
            banner.backgroundColor = [UIColor colorWithRed:.5f green:.5f blue:.5f alpha:1.f].CGColor;

            banner.bounds = CGRectMake(0, 0, 56, 15);
            banner.anchorPoint = CGPointMake(0.5, 0);
            banner.position = CGPointMake(20, 20);
            banner.affineTransform = CGAffineTransformMakeRotation(-45.0 / 180.0 * M_PI);

            // Add the layer to the view, and remember it for later
            [self.layer addSublayer:banner];
            self.bannerLayer = banner;
        } else {
            // Remove the layer from the view, and discard it
            [self.bannerLayer removeFromSuperlayer];
            self.bannerLayer = nil;
        }
    }
}


text:
Q: JDBC:MySql connection is not working in Ajax request -Java I have exactly same function in both Main method and other method JDBC connection is working fine. If I call the other function it throws error java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/wine:
I have included MySql Driver in library [Netbeans];
processRequest method:
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    String process = (String) request.getParameter("process");
    String name = (String) request.getParameter("process");
    String phone=(String) request.getParameter("phone");
    String email = (String) request.getParameter("email");
    String pwd = (String) request.getParameter("pwd");
    PrintWriter out = response.getWriter();
    out.println("Hello");
   signup(out,process,name,email,phone,pwd);

}

signup method:
private static int signup(PrintWriter out,String process,String name,String email,String phone,String pwd){
    Connection con = null;
    PreparedStatement stmt = null;
    ResultSet rs = null;
    try {
        con = DriverManager.getConnection("jdbc:mysql://localhost:3306/wine", "root", "");

        out.println("Process Not Found");
        if (process == "signup") {

            String query = "INSERT INTO user(name,phone,email,password,role) VALUES(?,?,?,?,1)";
            stmt = con.prepareStatement(query);
            stmt.setString(1, name);
            stmt.setString(2, phone);
            stmt.setString(3, email);
            stmt.setString(4, pwd);

            stmt.execute();

        } else {
            out.println("Process Not Found");
        }
    } catch (SQLException e) {
        // do something appropriate with the exception, *at least*:

        out.println(e);
        e.printStackTrace();
        return 0;
    }
    return 1;
}

Main Method :
public static void main(String[] args) {

    Connection con = null;
    PreparedStatement stmt = null;
    ResultSet rs = null;
    String process = "signup";
    String name = "Test";
    String phone="45885";
    String email = "Test@gmail.com";
    String pwd = "dkjsdh";

    try {
        con = DriverManager.getConnection("jdbc:mysql://localhost:3306/wine", "root", "");

        if (process == "signup") {

            String query = "INSERT INTO user(name,phone,email,password,role,status) VALUES(?,?,?,?,1,1)";
            stmt = con.prepareStatement(query);
            stmt.setString(1, name);
            stmt.setString(2, phone);
            stmt.setString(3, email);
            stmt.setString(4, pwd);

            stmt.execute();

        } else {
            System.out.println("Process Not Found");
        }
    } catch (SQLException e) {
        // do something appropriate with the exception, *at least*:

        System.out.println(e);
        e.printStackTrace();
    }
}

A: There are two options that can be tried:
Class.forName("com.mysql.jdbc.Driver").newInstance() //older bug

and
Class.forName("com.mysql.jdbc.Driver");

In the comment I pasted the older bug solution when I meant to paste the second one.
Either way I am glad that it worked out for you


text:
Q: Android Studio - Unreachable statement in service I am trying to call a service, but inside the service Android Studio in the onStartCommand() Android Studio says unreachable statement when I register the LocationManager.
Which is weird because I call onStartCommand() in my MainActivity.
I have the service in the android manifest.
When I use the onCreate() method in the service there seems to be a name conflict with the onCreate() method in the MainActivity.
package com.example.gpstosqlite;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.widget.CompoundButton;
import android.widget.Switch;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    private TextView tv1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        tv1 = (TextView) findViewById(R.id.textView1);

        Switch switch1 = (Switch) findViewById(R.id.switch1);

        switch1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked == true) {
                    tv1.setText(R.string.switchOn);
                    Intent serviceIntent = new Intent();
                    serviceIntent.setAction("com.gpstosqlite.GPSservice");
                    startService(serviceIntent);
                } else {
                    tv1.setText(R.string.switchOff);
                }
            }
        });
    }
}

package com.example.gpstosqlite;

import android.app.Service;
import android.content.Intent;
import android.location.LocationManager;
import android.content.Context;
import android.os.Bundle;
import android.os.IBinder;

import androidx.annotation.Nullable;

public class GPSservice extends Service {
    LocationManager locationManager;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        stopSelf();
        return super.onStartCommand(intent, flags, startId);
        //the next line is underlined red
        locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
    }
}

A: The comments are correct, I had the return-statement return super.onStartCommand(intent, flags, startId); in the onStartCommand method before an instruction and thus this instruction was unreachable.


text:
Q: Steam>Warning: failed to init SDL thread priority manager: SDL not found — Amazon Linux 2 Following the documentation of Valve to install SteamCMD
I'm attempting to both install SteamCMD and run a gaming server on an EC2 instance using Amazon Linux 2 or Redhat.
Steps taken (after creating a user and granting it sudo right permissions):

*

*sudo yum install steamcmd

*sudo yum install glibc.i686 libstdc++.i686

*su - user

*mkdir ~/Steam && cd ~/Steam

*curl -sqL "https://steamcdn-a.akamaihd.net/client/installer/steamcmd_linux.tar.gz" | tar zxvf -

*./steamcmd.sh

Problem that occurs:
Steam>Warning: failed to init SDL thread priority manager: SDL not found

I then search for SDL packages, and have tried each one, but with no success.

A: The 32 bit SDL library would be provided by the SDL.i686 package:
yum install SDL.i686

If you also need the development libraries:
yum install SDL-devel.i686


text:
Q: filter array by its name inside an object var dictionary = {
  "english" : [{"key" : "1", "value" : "abc"}],
  "french" : [[{"key" : "1", "value" : "xyz"}]]
}

if I do this filter it is working  :
dictionary.english.filter ( obj => {return obj.value === "abc"})

but if mention the array name english in a variable and use the same filter it shows me undefined:
var language = 'english';
dictionary.language .filter ( obj => {return obj.value === "abc"})

what is the difference and how to fix it?

A: Try this

var dictionary = {
  "english": [{
    "key": "1",
    "value": "abc"
  }],
  "french": [
    [{
      "key": "1",
      "value": "xyz"
    }]
  ]
}

var language = 'english';
let _d = dictionary[language].filter(obj => {
  return obj.value === "abc"
})

console.log(_d)


text:
Q: PyQT signal from another script I have two python scripts. The first script contais a PyQt GUI which shows the status of my switch ports. To  display the status it consults a database that contains the full information of the ports. The second script is responsible for making the necessary changes to the database when the state of a port is altered.
I need to know how to send a signal or something similar when the database is updated.
PyQt script
  from PyQt4 import QtCore, QtGui
  import sqlite3
try:
    _fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
    def _fromUtf8(s):
        return s

try:
    _encoding = QtGui.QApplication.UnicodeUTF8
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig)

class MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName(_fromUtf8("MainWindow"))
        MainWindow.resize(300, 170)
        MainWindow.setMaximumSize(QtCore.QSize(300, 200))
        MainWindow.setStyleSheet(_fromUtf8("background-color: rgb(255, 255, 255);"))
        self.centralwidget = QtGui.QWidget(MainWindow)
        self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
        self.mac = QtGui.QLabel(self.centralwidget)
        self.port = QtGui.QLabel(self.centralwidget)
        self.ip_addres = QtGui.QLabel(self.centralwidget)
        self.name = QtGui.QLabel(self.centralwidget)
        self.actionUpdate = QtGui.QAction(MainWindow)
        self.actionUpdate.setObjectName(_fromUtf8("actionUpdate"))
        self.menuFile.addAction(self.actionUpdate)
        QtCore.QObject.connect(self.actionUpdate, QtCore.SIGNAL(_fromUtf8("activated()")), self.update)

        def update(self):

            con = sqlite3.connect("database.db")
            cursorObj = con.cursor()
            sql_query = "SELECT * FROM switch"
            cursorObj.execute(sql_consulta)
            row = cursorObj.fetchone()

            self.mac(_translate("MainWindow", row[0] None))
            self.ip_addres.setText(_translate("MainWindow", row[1], None))
            self.name.setText(_translate("MainWindow", row[2], None))
            self.port.setText(_translate("MainWindow", row[3], None))

if __name__ =="__main__":
    app =QtGui.QApplication(sys.argv)
    myapp = MainWindow()
    myapp.show()
    sys.exit(app.exec_())

The other script is executed when a change occurs in the switch and updates the database.
I need a way to update the interface when a change occurs, without the need to press the update button.
The other script
import sqlite3
import sys
if __name__ =="__main__":
    con = sqlite3.connect("database.db")
    cursorObj = con.cursor()
    sql_query = "UPDATE switch SET mac ='" + str(sys.argv[0]) + "', ip_addres = '" + str(sys.argv[1]) + "', name = '" + str(sys.argv[2]) + "', port ="  + str(sys.argv[3])
    cursorObj.execute(sql_update)
    con.commit()


text:
Q: Order of methods returned by typeof().GetMethods() in c# We read in MSDN that "The GetMethods method does not return methods in a particular order", but this is a general case for all types. I am interested in just interface types and need to enumerate interface methods in declaration order.
I realize that the safe way to do this is to add custom attribute to each method with some sort of sequence value, and then sort reflected MethodInfos by that sequence. However, I wonder whether it is really necessary. The reason for my doubts is the existence of [COMImport] interfaces that we know for sure MUST have the order of the members preserved in declaration order (otherwise correct vtable mapping cannot occur)
So my question is, which of the following approaches is better to ensure declaration order when doing typeof(interfacetype).GetMethods():

*

*Add custom property with seqence number and then sort returned methods by that sequence value

*Add [ComImport] with dummy [Guid] to the interface declaration in hopes that it actually makes any difference when methods are enumerated.

*Ignore MSDN and assume that the declaration order is preserved always for interface methods (which is what seems to be the actual case, from looking at the reference sources, unless I am missing something)

In my particular case I need only methods enumerated (no other members exist in the interface), only for interfaces, and the interfaces will never have any base interface.


text:
Q: Элементы с максимальной и минимальной суммой цифр С клавиатуры вводится кол-во элементов массива и сам массив чисел. Размер массива не больше 100 элементов. Нужно вывести элемент с минимальной суммой цифр в одну строку(если таких несколько, вывести минимальный из них). А во вторую, элемент с максимальной суммой цифр(если таких несколько, вывести максимальный из них)
В примере ниже: 11(1+1=2);  21(2+1=3);  111(1+1+1=3), 2-минимальная сумма, 3-максимальная, но т.к. элементов с суммой цифр равной 3м-два, то выводится максимальный из них т.е. 111
Подскажите, пожалуйста, алгоритм действий, поскольку у меня даже нет идей как выполнить поставленную задачу
Я знаю как найти сумму цифр числа, но как из массива взять число для проверки(и при этом, в случае если чисел с минимальной/максимальной суммой несколько, определить какое из них стоит выводить)-не понимаю
Пример
Вход
3
11 21 111
Выход
11
111

A: def digits_sum(num):
    return sum([int(x) for x in str(num) if x.isdigit()])

items = ['11', '21', '111', '-1']

min_ = min((digits_sum(x), int(x)) for x in items)[1]
max_ = max((digits_sum(x), int(x)) for x in items)[1]
print(min_)
print(max_)

вывод на экран:
-1
111

A: *

*Читаем длинну массива

*Читаем каждый элемент

*Ищем минимальный элемент в массиве a, где ключ - его сумма цифр

*Так же с максимальным.

n = input()
a = input().split()

def f(x):
    return sum(map(int, x if int(x) > 0 else x[1:])) - 0 if int(x) > 0 else int(x[1])

print(min(a, key=f))
print(max(a, key=f))


text:
Q: Select random image I've got two images and I am trying to use PHP to select one at random. I have the following code:
<?php

    $img_one = "http://www.domain.com/image-swap/image-one.png";
    $img_two = "http://www.domain.com/image-swap/image-two.png";

    $images = array( $img_one, $img_two);

    $rand_image =  array_rand($images, 1);

?>

<img src="<?php echo $rand_image ?>">

The problem with this code, is that the image's URL becomes a number: 1 or 2.

A: Try this way. $rand_image consists of randomly selected index number. So pass it inside the array as key value like <?php echo $images[$rand_image]; ?>
<?php

$img_one = "http://www.domain.com/image-swap/image-one.png";
$img_two = "http://www.domain.com/image-swap/image-two.png";

$images = array( $img_one, $img_two);

$rand_image =  array_rand($images, 1);

?>

<img src="<?php echo $images[$rand_image]; ?>">

A: change this:
<img src="<?php echo $rand_image ?>">

to this:
<img src="<?php echo $images[(int)$rand_image -1] ?>">


text:
Q: How can I highlight specific keywords on every appended paragraph? enter image description here
     $(`

                                              ${sentence.map((val, i) => `<div class="d-flex shadow_"><i class="fa fa-circle mt-1 " style="font-size: 10px;"></i>    <span class="m-0 text-gray font-14 fw-400 keyword-para" id="key_${i}" > ${val} </span></div>`).join("
")
                              }

                                    `).insertAfter(row);
                                   var search = keyword;

                                    $(".keyword-para:contains("+search+")").each(function () {
                                var regex3 = new RegExp("([' ]|^)"+search+"(?=[ ]|$|,|')", 'g');

                              $(this).html($(this).text().replaceAll(regex3,  `<span class='text-red'> ${search} </span>`));

                            });

I wat to change color of all keywords that is appear on text
In jquery on api response I append the paragraphs, I want to highlight specific  keyword on every appended paragraph , but it can not work on all keyword what mistake i did on it


text:
Q: VB.Net httpwebrequest login and download page I want to login with my account to VyprVPN website.
So i logged in successfully with my code below, but i want to get number of remaining data, which is stored in this url: https://www.goldenfrog.com/controlpanel/vpn-remaining as pure html.
So basically what i'm trying to do is to download html from url after login.
My login code:
Dim username As String = "myusername"
Dim password As String = "mypassword"

Dim postData As String = "username=" & username & "&password=" & password & "&login=Login"
Dim tempCookies As New CookieContainer
Dim encoding As New UTF8Encoding
Dim byteData As Byte() = encoding.GetBytes(postData)

Dim postReq As HttpWebRequest = DirectCast(WebRequest.Create("https://www.goldenfrog.com/controlpanel/login"), HttpWebRequest) 'prva linija
postReq.Method = "POST"
postReq.KeepAlive = True
postReq.Timeout = 15000
postReq.CookieContainer = tempCookies
postReq.ContentType = "application/x-www-form-urlencoded"
postReq.Referer = "https://www.goldenfrog.com/login"
postReq.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:40.0) Gecko/20100101 Firefox/40.1"
postReq.ContentLength = byteData.Length

Dim postreqstream As Stream = postReq.GetRequestStream()
postreqstream.Write(byteData, 0, byteData.Length)
postreqstream.Close()
Dim postresponse As HttpWebResponse

postresponse = DirectCast(postReq.GetResponse(), HttpWebResponse)
tempCookies.Add(postresponse.Cookies)
logincookie = tempCookies
Dim postreqreader As New StreamReader(postresponse.GetResponseStream())

Dim thepage As String = postreqreader.ReadToEnd

What i tried (doesn't work, shows blank message box which is result of visiting that url without logging in, i probably failed to assign right cookie):
Dim request As HttpWebRequest = DirectCast(WebRequest.Create("https://www.goldenfrog.com/controlpanel/vpn-remaining"), HttpWebRequest)
request.CookieContainer = tempCookies
request.Method = "POST"
request.KeepAlive = True
request.CookieContainer = logincookie
request.ContentType = "application/x-www-form-urlencoded"
request.Referer = "https://www.goldenfrog.com/controlpanel"
request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:40.0) Gecko/20100101 Firefox/40.1"
request.ContentLength = byteData.Length

Dim postreqstream2 As Stream = request.GetRequestStream()
postreqstream2.Write(byteData, 0, byteData.Length)
postreqstream2.Close()
Dim postresponse2 As HttpWebResponse
postresponse2 = DirectCast(request.GetResponse(), HttpWebResponse)
tempCookies.Add(postresponse2.Cookies)
logincookie = tempCookies
Dim postreqreader2 As New StreamReader(postresponse.GetResponseStream())
Dim thepage2 As String = postreqreader.ReadToEnd

MsgBox(thepage2)

A: Dim request As HttpWebRequest = DirectCast(WebRequest.Create("url"), HttpWebRequest)
request.CookieContainer = logincookie
Dim response As HttpWebResponse = DirectCast(request.GetResponse(), HttpWebResponse)
Dim reader As New StreamReader(response.GetResponseStream())
Dim theusercp As String = reader.ReadToEnd


text:
Q: javascript textbox: enter text and it appears instantly in another textbox Javascripters, a 'puzzle':
Using a simple HTML form, make two textboxes. Whatever text you type (say, some random string of characters like asdfasdf ) into textbox #1 is IMMEDIATELY displayed, on the fly, without pressing any button or changing focus, into textbox #2.
Can it be done using getElementByID?

A: Simply:
<textarea id="text1" onkeyup="document.getElementById('text2').value = this.value"></textarea>
<textarea id="text2" onkeyup="document.getElementById('text1').value = this.value"></textarea>

A: If immediately is the most important word, you must handle the keypress event, then add the pressed key to your storage string. Then place that string into your result div or textarea.


text:
Q: do an action after a connection lapse time Hello everyone it's been a while since I'm looking for the solution to my problem I'm developing a web application and I'm blocking that day.
the objective is that after a time from the beginning of the connection of the user I make a precise action.
I will not give all the code is too long so I will try to be as simple as possible :
my first PHP script 1 validate the user login and create a session variable that takes the current time and then returns the user to the PHP script 2 :
 session_start();
 .
 .
 .// some code ....
 if(password_verify($password,$pass_sql))
        {

             $_SESSION['autorisation'] = 'oui';
             $_SESSION['ConnectOK'] = true;

             $_SESSION['login'] = $login;
             $_SESSION['debut'] = time(); // this is the variable of time

            header("Location:http://jawad.meswatts.fr/sous/meswatts.php");
        }

meswatts.php :
 <?php
 session_start();
 if(  !empty($_SESSION['autorisation']) AND  $_SESSION['autorisation'] =='oui' )
  {
      $t_navigation = time();
      if($t_navigation - $_SESSION['debut'] >= 12 )
        {
            echo " hello" ; // just exemple of action
        }
     .
     .
     .
     . //the rest of the code is only HTML that is not very important

   }
?>

and so in the second PHP script I still use the time function and I do a subtraction with the session variable that I created in the first page and so there will be an action after 12 seconds unfortunately it does not work not after the passage of 12 seconds nothing happens any help would be helpful !


text:
Q: What is the difference between initializing a static variable when it is declared vs initializing it in a static block? I have found this use in the link below, in step 5, in a guide for Service Locator design pattern
https://www.tutorialspoint.com/design_pattern/service_locator_pattern.htm
I don't understand why they used this structure.
public class ServiceLocator {
   private static Cache cache;

   static {
      cache = new Cache();
   }
}

vs
   private static Cache cache = new Cache();

A: In this particular instance the result is exactly the same. You can use static blocks if you need to apply more logic than just simple field initialization.
If you aim to improve code readability you should just initialize a static variable:
private static Cache cache = new Cache();


text:
Q: Binary in /usr/local/bin I look to see where the command is located:
xxx:~/mono/mono-2.6.7$ which mono
/usr/local/bin/mono

If I execute it directly, no problem:
xxx:~/mono/mono-2.6.7$ /usr/local/bin/mono -V
Mono JIT compiler version 2.6.7 (tarball Mon Aug  2 16:01:50 UTC 2010)
Copyright (C) 2002-2010 Novell, Inc and Contributors. www.mono-project.com
....

But if I execute the command without the path it cannot find it:
xxx:~/mono/mono-2.6.7$ mono
bash: /usr/bin/mono: No such file or directory

There is no mono file in /usr/bin:
xxx:~/mono/mono-2.6.7$ ls -l /usr/bin/mono
ls: cannot access /usr/bin/mono: No such file or directory

Here is my path:
xxx:~/mono/mono-2.6.7$ echo $PATH
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games

Doesn't it search each directory separated by the colons? So shouldn't it find mono in /usr/local/bin ?
If I log in as root, it works. I can execute mono on the command line and it finds it. The permissions are:
xxx:~/mono/mono-2.6.7$ ls -l /usr/local/bin/mono
-rwxr-xr-x 1 root root 8452592 2010-08-02 16:23 /usr/local/bin/mono

Is the user I am using not part of the right group?

A: Bash keeps a cache of command locations in memory, so that it doesn't have to do the whole PATH exploration each time you start a command. In your original bash session, bash had previously memorized that mono was /usr/bin/mono. Then you removed /usr/bin/mono and added /usr/local/bin/mono, but your running bash still had the old location in its cache.
You can manipulate the command location cache with the hash builtin. In particular hash -r clears the cache.
which is an external command, so it doesn't use bash's cache and performs a PATH lookup every time. You could also have used type, which is a builtin and therefore does use the lookup cache.

A: Maybe you have an alias defined for mono? Check out that the following files in your home directory: .bashrc, .profile, .login or .bash_profile
... does not contain something like this
 alias mono="/usr/bin/mono"

This can also be located in /etc/bashrc or /etc/profile.
Command alias shows all currently defined aliases.

A: I logged out, and then logged in again and it worked. I must have been doing something stupid. But, it works!


text:
Q: Problems in finding an integral basis in a ring of algebraic ntegers I have some problems with this paper.

*

*Firstly, with theorem 3.4: I don't know if this is the original formulation in the literature, but the statement seems rather trivial to me if one considers $0$ to be an algebraic integer. Moreover there are cases where a non trivial integer doesn't even exist as in the classical example of the ring of integers of  $\Bbb Q(\sqrt{d})$ where $d \in  \Bbb Z$ and $d \neq 1 \mod 4$.

*Secondly, in the algorithm that is based on this theorem. As an example I consider the polynomial $x^4+5x+5$. The Galois group of this polynomial over $\Bbb Q$ is the cyclic group of order $4$ abd its splitting field can be represented by its companion matrix $M = \left(\begin{smallmatrix}0 & 0 & 0 & -5\\1 & 0 & 0 & -5\\0 & 1 & 0 & 0\\0 & 0 & 1 & 0\end{smallmatrix}\right)$. Since $M$ is an algebraic integer one can take as a basis of integers for the splitting field the set $B = \{M^0,M,M^2,M^3\}$.The discriminant of this basis using $\Delta = \det(\operatorname{Tr}(B_iB_j))$ equals $5^3\dot 11^2$ (as does the discriminant of the polynomial). If I apply the algorithm I find an algebraic integer with coefficients $\frac{1}{11}\left [ 1, 3, 6,1\right ]$ (the minimal polynomial is $x^4+x^3+6x^2-4x+1$). If I replace in B the second element by this element I obtain a basis whose discriminant now is $5^33^2$, so we are nowhere nearer to an integral basis, on the contrary, one bastard goes out and another comes in.

*Conclusion: We know that the discriminant of an intergral basis divides that of a basis of integers so in out case it divides both discriminants so also their $\gcd, 5^3$. If only there was a way to calculate the $\gcd$ of two bases of integers.

A: Here is a formulation which makes more sense. First, recall some terms.

*

*There is the discriminant of the field $K$, given as follows: If $\alpha_i$ denotes an basis of $\mathcal{O}_K$ over $\mathbf{Z}$, then

$$\Delta_K = \Delta(\alpha_i):=\det \mathrm{Tr}(\alpha_i \alpha_j).$$

*If $\beta_i$ are $n = [K:\mathbf{Q}]$ elements of $\mathcal{O}_K$, one can also define:

$$\Delta(\beta_i):= \det \mathrm{Tr}(\alpha_i \alpha_j).$$

*As a special case, if $\beta \in K$ is the root of a polynomial $f(x)$ which generates $K$, and $\beta_1, \ldots, \beta_n$ are the powers $1$, $\beta, \ldots , \beta^{n-1}$, then $\Delta(\beta_i)$ is the discriminant of the polynomial $f$.

The key relation is that:
$$\Delta(\beta_i) = [\mathcal{O}_K:\mathbf{Z}[\beta_1,\ldots,\beta_n]]^2 \cdot \Delta_K.$$
From this, one can deduce the following:

*

*If $p$ divides the index of $\mathbf{Z}[\beta_1,\ldots,\beta_n]$ in $\mathcal{O}_K$, then $p^2$ divides $\Delta(\beta_i)$.

*If $p$ divides the index of $\mathbf{Z}[\beta_1,\ldots,\beta_n]$ in $\mathcal{O}_K$, then there is an algebraic integer of the form
$$\gamma = \frac{1}{p} \left(\lambda_1 \beta_1 + \ldots + \lambda_n \beta_n \right)$$
where $0 \le \lambda_i < p$ for all $i$ and not all of them are zero.
(This is the correct formulation of the statement you linked too --- one may insist that not all the $\lambda_i$ are zero, but this only exists if $p$ actually divides the index of the $\beta_i$ in $\mathcal{O}_K$, simply dividing $\Delta(\beta_i)$ is not enough. Of course, in practice, you can try this for all the possible $p$, and if you don't find a $\gamma$ then you have an integral basis.

*In practice, you start with an element $\beta$ and consider the set $\{1,\beta,\ldots,\beta^{n-1}\} = \{\beta_1,\ldots,\beta_n\}$. But the main point is that --- if you find $\gamma$ --- you don't replace the power basis of $\beta$ by the power basis of $\gamma$, but rather take:

$$\{\beta'_1,\ldots,\beta'_n\} = \left\{\beta_1,\ldots,\beta_{n-1},\frac{1}{p} \left(\lambda_1 \beta_1 + \ldots + \lambda_n \beta_n \right)\right\}.$$
This now has smaller index and you repeat. Edit: More carefully, you really want your new lattice to contain the old lattice. So you want the lattice generated by all the $\beta_i$ together with $\gamma$. You can ensure this as follows. At least one of the $\lambda_j$ will be non-zero modulo $p$ by construction. Replacing $\gamma$ by some multiple, one can first assume that $\lambda_j \equiv 1 \mod p$, and then, subtracting a multiple of $\beta_j$, one can assume $\lambda_j = 1$. Then the larger lattice $\{\beta_i,\gamma\}$ is generated by $\gamma$ and $\beta_i$ for $i \ne j$, and so this will have smaller index. End Edit
In your example, let $\beta$ be a root of $x^4 + 5x + 5$. You then discover a new integral element $\gamma$, for example,  your element:
$$\gamma = \frac{1}{11} \gamma^3 + \frac{6}{11} \gamma^2 + \frac{3}{11} \gamma + \frac{1}{11},$$
which does not lie in this basis. The next step is to consider $\{1,\beta,\beta^2,\gamma\}$. That will actually be a basis in this case. In fact, I compute the trace pairing matrix to be:
$$\left( \begin{matrix} 4 & 0 & 0 & -1 \\ 0 & 0 & -15 & -10 \\ 0 & -15 & -20 & -15 \\ -1 & -10 & -15 & -11 \end{matrix} \right),$$
which has discriminant $5^3$. Another computation at $5$ then shows this is an integral basis and one is done.
Warning! Not all fields have an integral basis given by powers of a single element (although this is true in degrees $1$ and $2$). Such fields are called monogenic, and, by certain measures, are rare. Determining if a field is monogenic or not can be quite non-trivial.
Of course, in your particular case, you can easily recognize the field from the fact that it is abelian and has discriminant $5^3$. Namely, it must be the field of fifth roots of unity. After you make this guess, you can compute that
$$\zeta = -\frac{3}{11} \beta^3 + \frac{4}{11} \beta^2 - \frac{9}{11} \beta - \frac{14}{11} = -1 + 0 \cdot \beta + 2 \cdot \beta^2  - 3 \cdot \gamma$$
does indeed satisfy $\zeta^5 = 1$.


text:
Q: Best way to get client browser latency? I have a custom web application, some clients are reported issue that they are not able to save the data.
So I would like to get connection speed between server and client machine...We have a PING command but we can't call it using javascript. I have tried to use IMAGE for that but I think this will not give accurate result.
So please let me know is there any other way to do this ?
Thanks,
Laxmilal


text:
Q: Trying to use KeyDown event in form to catch navigation arrowUp and arrowDown I have a flowlayoutPanel with about 50 userControl added dynamically.
I use this.KeyPreview = true in the form to be able to catch event in the form.
As it is now I use this eventhandler:
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
}

for KeyDown to be able to catch spacebar, the + character and the navigation key pageUp and pageDown. This works good.
I also need to catch the navigation arrowUp and arrowDown but the only working
solution for me is to use an event handler for KeyUp like this.
When I use event handler Form1_KeyUp event I can use the navigatiobn key arrowUp and arroeDown.
 private void Form1_KeyUp(object sender, KeyEventArgs e)
 {
 }

I tried to use this event handler
private void Form1_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
{
}

but this is never called when I click the navigation arrowUp and arrowDown.
I hope to be able to catch everything such as (pageUp, pageDown, spacebar, + character arrowUp and arrowDown) in the event handler for KeyDown
Any help is welcome.

A: It's simpler to just override the ProcessCmdKey function:
protected override bool ProcessCmdKey(ref Message msg, Keys keyData) {
  if (keyData == Keys.Up) {
    // do something here
    return true;
  } else {
    return base.ProcessCmdKey(ref msg, keyData);
  }
}


text:
Q: Detect the closure of an eclipse rcp application with taskkill I'm working on an eclipse rcp application and here is my question:
I have a WorkbenchWindowAdvisor with the method preWindowShellClose() (I know this method is called when somebody try to close the application) and this method displays a small window asking the user if he really wants to close the application ...
This is pretty standard but sometimes i need to close the application by a command line (without access to the interface), for example:
taskkill /IM example.exe
So with this command line the small window asking "Are you really sure..." appears and i don't want that! (I don't want to force the closure with something like that neither: taskkill /F /IM example.exe)
So I would like to detect if the application is being closed by pressing the "close window" button or by a taskkill.
Do you have any idea?
Thanks!


text:
Q: Woocommerce single product navigation: Bullets instead of thumbnails Can you help me substitute thumbnails navigation with bullets navigation?
I prefer it, because of mobile minimal functionality.
https://demo.woothemes.com/storefront/product/build-your-dslr/#camera-body

A: Add the following code snippet to your active theme's (or child theme if any) functions.php file.
add_filter('woocommerce_single_product_carousel_options', 'woocommerce_single_product_carousel_options_custom');
function woocommerce_single_product_carousel_options_custom($args){
    $args['controlNav'] = TRUE;
    return $args;
}

This will change the thumbnail navigation into an ordered list (numbered 1,2,3,... and so on) of navigation. You can change the display of this ordered list using CSS. An example CSS would be like this:
.flex-control-nav {
    position: absolute;
    bottom: -45px;
    list-style: none;
    display: block;
    padding: 0;
    margin: 0;
    width: 100%;
}
.flex-control-nav li {
    position: relative;
    display: inline-block;
    cursor: pointer;
    height: 1.5rem;
    width: 1.5rem;
    margin: 0;
    padding: .35714rem;
}
.flex-control-paging li a {
    border: 1px solid #2d2d2d;
    display: inline-block;
    margin: 0;
    padding: 0;
    position: relative;
    background: 0 0;
    outline: 0;
    line-height: 0;
    font-size: 0;
    text-indent: -99999px;
    color: transparent;
    cursor: pointer;
}
.flex-control-paging li a:before {
    content: " ";
    position: absolute;
    top: 0;
    left: 0;
    width: 20px;
    height: 20px;
    font-size: 60px;
    line-height: 20px;
    text-align: center;
    color: #2d2d2d;
    opacity: .6;
}
.flex-control-paging li a, .flex-control-paging li a:before {
    height: 1.07143rem;
    width: 1.07143rem;
    border-radius: 50%;
}
.flex-control-paging li a:before {
    display: block;
    transition: background .1s ease-out;
}
.flex-control-paging li a:focus, .flex-control-paging li a:hover {
    outline: 0;
}
.flex-control-paging li a:focus:before, .flex-control-paging li a:hover:before {
    opacity: .8;
}
.flex-control-paging li a:hover:before {
    background: #2d2d2d;
}
.flex-control-paging li a.flex-active:before {
    background: #666;
}


text:
Q: Node.js failed to connect azure-blob using SAS token when domain is customized Following the official doc, I write this script trying to connect a custom domain azure storage space:
const { BlobServiceClient } = require("@azure/storage-blob");

const account = "validaccount";
const sas = "sv=xxxx&.......";

const blobServiceClient = new BlobServiceClient(`https://${account}.blob.core.customdomain.name${sas}`);

//===============

async function main() {
  let i = 1;
  let containers = blobServiceClient.listContainers();
  for await (const container of containers) {
    console.log(`Container ${i++}: ${container.name}`);
  }
}

main();

I got error: Server failed to authenticate the request. Make sure the value of Authorization header is formed correctly including the signature.
I'm sure the SASURI is valid, I can use it in azure blob storage explorer, but in my code it doesn't work.
I tried some combinations like:

*

*https://${account}.blob.core.customdomain.name?${sas} //add a '?'

*https://${account}.blob.core.customdomain.name/abc?${sas}  //abc is a valid container name

*https://${account}.blob.core.customdomain.name/abc${sas} //remove '?' but keep container name

*https://${account}.blob.core.customdomain.name',sas //try to pass as two parameters.

But all failed.
I'm not sure there is another method.
I guess it maybe because the SAS token is only authorized to the abc container, it can't read the domains root.
but if so, why the 2nd combination was also failed.
I use @azure/storage-blob v12.3.0

A: I found the right answer.
The core of the problem is the SAS Token they gave me, was already bound to the container named "abc".
The SAS Token was not an authorization to everything under the domain, the token only authorized me to visit the container "abc".
So when I created the BlobServiceClient object, the "position" (if I can say so) was already under the container 'abc'. Since I'm already in a container, I can't list container anymore.
When I change the full path and try to connect the root, the token was actually not allowed. Of course the authorization failed.
Conclude:
The SAS token is already bounded to the specific container 'abc', so neither I can list the containers, nor I can visit the domain's root path.
I can only list the data of blobs in the specific container.
The blob-storage package's error message is not very clear.
Here't the code
const { BlobServiceClient } = require("@azure/storage-blob");
const account = "validaccount";
const sas = "sv=xxxx&.......";
const blobServiceClient = new BlobServiceClient(`https://${account}.blob.core.customdomain.name/abc?${SAS}`);

////====== just change 'list container' code to 'list blobs' code

const containerName = ""; //empty string, since you already in the container.

async function main() {
  const containerClient = blobServiceClient.getContainerClient(containerName);
  let i = 1;
  let blobs = containerClient.listBlobsFlat();
  for await (const blob of blobs) {
    console.log(`Blob ${i++}: ${blob.name}`);
  }
}

main();


text:
Q: BaseHTTPServer still writing although client lost network connection I've implemented a server which accepts requests and after some process the client connects to my server.
The server continuously sends data to client, but if the client lose the network connection (e.g. on my mobile I've disabled the internet access without exiting from the client program), then the server is still writing to the nothing.
I've attached my shortened version of my code logic. Monitoring the input data could be a good idea, but I have some cases when I don't have to wait for any input.
class CustomRequestHandler(BaseHTTPRequestHandler):
    def __init__(self, request, client_address, server):
        BaseHTTPRequestHandler.__init__(self, request, client_address, server)

    def do_GET(self):
        try:
            readable, writable, exceptional = select.select([self.rfile], [self.wfile], [self.rfile, self.wfile], 0)
            for s in readable:
                print (s.readline())
            for s in writable: #
                s.write(b"Data")
        except Exception as e:
            print(e)

    def finish(self, *args, **kw):
        print ("Do finish")

class CustomServer(socketserver.ThreadingMixIn, HTTPServer):
    pass

def start_server():

    httpd = CustomServer((HOST, PORT), CustomRequestHandler)

    try:
        httpd.allow_reuse_address = True
        httpd.serve_forever()
    except KeyboardInterrupt:
        pass
    httpd.server_close()

if __name__ == '__main__':
    start_server()

After a while writable   became an empty list, but how could I detect if on the client side a network lost occurred? How could I catch the network error?

A: Your socket is not closed when you cut the network connection. The sender will only get informed when the OS decides that the socket is timed out. This usually takes 30s+.
If on the other hand the receiver program is closed properly, the sender will get notified within milliseconds.
These left open but actually lost connections are a major problem in network programming. There are mitigations but there is no universal ultimate solution to it.


text:
Q: Expectation and variance on joint distribution problem Two continuous random variables $X$ and $Y$ have joint distribution $p(x,y)$. How do I show that

*

*$E[X] = E_Y[E_X[X|Y]]$

*$var[X] = E_Y[var_X[X|Y]] + var_Y[E_X[X|Y]]$

I'm not sure how to set up the integrals here and what properties to use.

A: For (1), we have that by definition of conditional expectations, we have
\begin{align*}
\int_B E_X(X \mid Y) dP = \int_B X dP
\end{align*}
for any $X \in \sigma(Y)$. Letting $B = \Omega$, we recover the tower property
\begin{align*}
\int_{\Omega} E_X(X \mid Y) dP &= \int_{\Omega} X dP  \\
\Rightarrow E_Y(E_X(X \mid Y)) &= E(X).
\end{align*}
I will edit this post to comment on Axolotl's comment about showing (2) using vector projections when I have more time.


text:
Q: Executing BCP from an Azure PHP web app Update: after a bunch of searching, it appears that Azure may restrict my ability to execute certain shell commands. I'm currently on a Standard 1 Web App plan - what do I have to do to be able to use the BCP utility through PHP?
So I have a PHP script running on my Azure web app and I've been trying to use BCP to upload data. I was able to run the command successfully via the Azure console but am having trouble running it through PHP.
PHP Code:
$upload_dir = '../uploads';
$test = shell_exec("bcp [database].[dbo].[Group] IN $upload_dir/working/Group.csv -S <server>; -T -f $upload_dir/format/Group.fmt -F2");
die($test);

When I run this, I receive no response from the script and querying the DB indicates that the upload was unsuccessful. When I try a simpler test using
$test = shell_exec("echo 'Hello World'");
die($test);

I receive the expected output, 'Hello World'.
For file structure, the PHP script is located in the wwwroot/scripts folder, and the CSV and FMT files are located in wwwroot/uploads/working/Group.csv and wwwroot/uploads/format/Group.fmt, respectively.
Is there something I'm missing when trying to execute shell commands through PHP? I'm pretty new to this, so I appreciate all the help!
Thanks!

A: According your description, it seems that you copied bcp.exe and bcp.dll to Azure Web Apps directory, and attempted to use shell env to execute the bcp commands. As the default directory path of Azure Console is the root directory of Azure Web Apps, so I suppose your application's structure will look like:
wwwroot/
       bcp.exe
       bcp.dll
       scripts/
       uploads/
       ...

According your code snippet, your php script in scripts folder cannot find the bcp command, so you got the blank page.
You can try to move the bcp.exe and bcp.dll files into the scripts folder, or modify the shell command e.g. ../bcp db.dbo.table in ...
If I have any misunderstanding of your question, please feel free to let me know.


text:
Q: extends Activity with Fragment in Android I am using Fragment for Sliding Menu. Now, I want to extend Activity to get reference of layout.xml and many more. But we can't bind Fragment and Activity together. So what is the way to solve this ?
Fragment Code :
public class FindPeopleFragment extends Fragment {

    public FindPeopleFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.becomeexpert, container,
                false);

        return rootView;
    }
}

If I am using extends Fragment then I can't use findViewbyId and many more things. So I am confused as I am using Fragment first time. Please help me regarding this.

A: Since you have the view inflated you can call rootView.findViewById(...)

A: I think this is what you are after:
public class FindPeopleFragment extends Fragment {

private View rootView;

private View myTextView;

public FindPeopleFragment() {
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

    rootView = inflater.inflate(R.layout.becomeexpert, container,
            false);

    myTextView = rootView.findViewById(R.id.my_textview);

    return rootView;
}

private void someFunction()
{
   View myButton = rootView.findViewById(R.id.my_button);
}

}
You can save a reference to the views that you need before onCreateView returns, or you can save a reference to the rootView and call findViewById on that later on if you need to.


text:
Q: How to find $\lim _{x\to \infty }(3-4x)e^{-x}$ without L'Hôpitals? $$\lim _{x\to \infty }(3-4x)e^{-x} = \lim _{x\to \infty }-\infty * 0  $$
Since I'm not allowed to multiply infinity by zero, how am I supposed to solve this limit?

A: For $x > e$ say, $e^x > x^2$ and $\displaystyle {1 \over e^x} < {1 \over x^2}$. Hence for $x > e$,
$$0 < \left| {3-4x \over e^x }\right| < \left|{3 - 4x \over x^2}\right|$$
Now squeeze.

A: $$\frac{3-4x}{e^x}=\frac{3}{1+x+\frac{x^2}{2}+...+\frac{x^n}{n!}+..}-\frac{4}{\frac{1}{x}+1+\frac{x}{2}+...+\frac{x^{n-1}}{n!}+...}$$


text:
Q: Finding deg(f) with invariant
Let $S = \{1,2,3,\ldots,n\}$. Consider a function $f\colon S\to S$. A subset $D$ of $S$ is said to be invariant if for all $x\in D$ we have $f(x)\in D$. The empty set and $S$ are also considered as invariant subsets. By $\deg (f)$ we define the number of invariant subsets $D$ of $S$ for the function $f$.
[b]i)[/b] Show that there exists a function $f\colon S\to S$ such that $\deg (f)=2$.
[b]ii)[/b] Show that for every $1\leq k\leq n$ there exists a function $f\colon S\to S$ such that $\deg (f)=2^{k}$.
Source

A: Hint: Find the $\deg$ of the two functions
$$f(x) = x$$ $$g(x) = \begin{cases}x+1 & \text{ if } x \neq n \\ 1 & \text{ if }x=n\end{cases}$$
One will give you the answer to part i), and if you combine what you've learned from both of them, you'll find the answer to part ii)

A: $ {S} =$ {$1,2,...,n$}
 .  $f:S \to f$
 .  $D\subset S$
1.consider a function f(x)=x+1 $\forall x \in S$ consider
   $n+1 \to 1$
Means a cyclical function.
So ,we can consideronly two sunsets A,B so that if $x\in A$ then $f(x)\in A$.
As it is easy to note that $S$ and $\Phi$ are both invariant under $f$.
2.now consider a subset $B={1,2,......,r} where r\le n$
We always get a function $f:S\to B $ now a subset of $S$ will invariant under $f$ if it consists $B$ also .so number of such subset is $2^{n-|B|}$.
So $deg (f)=2^{n-r}$.
 By similar arguement let $D\subset S$ so that $D$={$k+1,....,n$}.
and consider a function $g:s\to D$
$deg(g) = 2^k 1\ge k \le n$. $\square$                            QED


text:
Q: Rails cycle helper function isn't working I use the cycle helper function inside a loop to cycle between two CSS classes but it doesn't work. It always chooses the first CSS class in each iteration.
<% @projects.each do |project| %>

    <div class="<%= cycle("left-animate", "right-animate") + ' col-sm-6' %>"><%= image_tag project.screen_shot %>

    <div class="<%= cycle("right-animate", "left-animate") + ' col-sm-6 col-md-5' %>">

<%= project.title %>

      <%= raw project.description %>

<% end %>

Rails version is 5.2 and Ruby version is 2.5.1

A: Missing "name" parameter. Can you use it like this?
 <% @projects.each do |project| %>

            <div class="<%= cycle("left-animate", "right-animate, name:'image') + ' col-sm-6' %>"><%= image_tag project.screen_shot %>

            <div class="<%= cycle("right-animate", "left-animate",name:'summary') + ' col-sm-6 col-md-5' %>">

<%= project.title %>

              <%= raw project.description %>

        <% end %>

A: You're defining two cycles with the same [implicit] name, so they're cancelling each other out.
It sounds like you might want to use current_cycle in the second instance, to re-use the value from the preceding call.


text:
Q: DDD - Factory Method and Dependency Injection I'm a bit stuck on a piece of design. I am new to DDD and would like an opinion on how to solve this problem.
I have a Currency Value Object that needs to access a repository to get addditional data to make the class complete. The problem (or design issue) is that new instances of Currency can only be created via the Factory Method.
public class Currency
{
  internal Currency() {}

  public string Name { get; set; }

  public static Currency CreateCurrencyFromAlphaCode(string alphaCode)
  {
    Currency cur = new Currency();
    //Needs repository to set name etc
    return cur;
  }

  public static Currency CreateCurrencyFromCountryCode(string countryCode)
  {
    Currency cur = new Currency();
    //Needs repository to set name etc
    return cur;
  }

  public static Currency CreateCurrencyFromCountryName(string countryName)
  {
    Currency cur = new Currency();
    //Needs repository to set name etc
    return cur;
  }

}

I thought that if I need to inject a repository into the constructor then it will make the factory method pointless?
public class Currency
{
  public Currency(IRepoistory repository)
  {

  }
}

How should I design this class, given the dependency on the repository — must I make a param on each of the Factory Methods to accept a repository?

A: Why don't you move the currency building outside of the currency class? I don't like the name, but you might try something like CurrencyBuilder. It might look like this:
public class CurrencyBuilder {
  private IRepository repository;

  public CurrencyBuilder() : this(new DefaultRepository()) {
  }

  public CurrencyBuilder(IRepository repository) {
    this.repository = repository;
  }

  public Currency FromCountryCode(string countryCode) {
    string currencyName = repository.GetCurrencyNameByCode(countryCode);
    if (currencyName == null)
      throw new CurrencyCodeException(countryCode + " not found");

    Currency c = new Currency();
    c.Name = currencyName;

    return c;
  }
}

Using this setup, when you call 'new CurrencyBuilder()', it will use your default repository instance. However, for testing, you can pass a mock repository into the constructor.
Hope that helps, and stick with it. For what it's worth, this is not a great example where DI will help a lot. So, if you feel unsatisfied at the completion of this task, don't give up on DI straight away. As you get more comfortable with it, it's usefulness will become more apparent.

A: I responded to this on the DDD list where you asked it as well, but I'll repeat my concerns here too.
I think you're getting the roles of a Factory and a Repository confused here.
Your methods named, for example, CreateCurrencyFromAlphaCode, actually look like they should be, for example, FindCurrencyByAlphaCode and they should exist in a Repository, not in a Factory. A Factory is used for creating objects that don't already exist in your persistence layer (or for instantiating objects from data you've already received from your persistence layer).
Also, your AlphaCode actually sounds like an Identity, so, if you did want to continue retrieving Currencies from your persistence layer, then I'd suggest your Currency is most likely not a Value Object, but rather an Entity.
Without knowing more about your domain, it's hard to know if this is a correct design decision or not. I'm inclined to think that duffymo's response would serve you better and then you wouldn't need to worry about fetching from a data store each time at all.

A: Without knowing some more about the context of your application it's difficult to be certain so forgive me if this is slightly off target, but it seems as though there are two potential issues with your design here.
Firstly you are injecting dependencies into a class that is presumably going to be used in your domain layer. Injecting dependencies into the domain layer or into dependencies of the domain layer is often seen as a symptom of a design flaw somewhere in your application.
Secondly, your currency object is taking on two responsibilities. Firstly it's being a currency (obviously), and secondly it is responsible for the creation of currencies.
To fix these issues, can you break the factory methods out of the currency class into a 'higher' layer of your application? If so you may find that everything starts to get easier as you can inject the repository dependencies into the factory with no problems. This may mean refactoring your domain layer code so you are passing 'ready built' currencies in there rather than currency codes, country codes etc, but I think that isn't a bad thing in itself. The domain layer should presumably care about a 'Currency', not necessarily about a 'Currency Code'.

A: If "repository" means "relational database", I'm not sure it should be your first choice here.  After all, the number of currency codes is relatively static.  They won't be changing that often, so I wouldn't think that you should have to pay the roundtrip to the database every time you create one.
I wonder if either a static data structure that's loaded on start-up from either a database or text file would be a more efficient choice.  It'd be one less dependency as well.


text:
Q: tree. Spacebar hotkey I want to use spacebar hotkey to expand/collapse nodes. It works perfectly well for enter, and it doesn`t work for space (just select/deselect node). here is my code:
 final Action actionEnter = new ShortcutAction("Select node",
            ShortcutAction.KeyCode.ENTER, null);
    final Action actionSpace = new ShortcutAction("Select node1",
            ShortcutAction.KeyCode.SPACEBAR, null);

    treePanel.addActionHandler(new Action.Handler() {

        @Override
        public void handleAction(Action action, Object sender, Object target) {
            if (action==actionEnter || action==actionSpace){
                Object curId = tree.getValue();
                expandCollapse(curId);
            }
        }

        @Override
        public Action[] getActions(Object target, Object sender) {
            return new Action[] { actionEnter, actionSpace };
        }
    });

What is the problem with space hotkey?

A: Add a KeyListener to the tree and then you can handle all of the events from there.


text:
Q: Can you permanently disable auto-calculate on specific sheets in a excel workbook I have a large excel workbook that has 23 sheets currently. The workbook takes about 100k lines of inventory and sorts it into 8 of the worksheets by inventory location, the other 15 sheets are used to tally numbers and move inventory as need. The 100k inventory is sorted by the 8 inventory sheets using around 400 sumifs and countifs formulas per sheet totaling around 3200 formulas. My workbook is starting to get serious lag as every time data is changed on one of the 15 working sheets the 8 inventory sheets recalculate. To breakdown what I am trying to find out, I need 15 sheets set to auto-calculate and 8 sheets set to manual calculate at the same time. Is there anyway to do this.  I have not included any code as this is a excel functionality question. I have searched extensively but all the literature I can find says that with the calculate function it is a all or nothing situation. But before rewriting the entire workbook to switch all the formula to VBA I thought I would see if anyone has found a work around.

A: You will need VBA to do this.

*

*Disable auto-calculation and calculate on save; this can be done in Excel or VBA with:
Application.Calculation = xlManual, Application.CalculateBeforeSave = False

*Make a list of all the sheets you want to "auto-calculate"

*Loop through the list, use Worksheets(1).Calculate or Sheets("Sheet1").Calculate to calculate a single sheet at a time

*You can set this to run every time you make a change in your notebook with the Worksheet.Change event, or personally I would make a button that runs the macro when clicked.

A quick prototype:
Sub customcalc
 Dim myarray As Variant
 myarray = Array("Sheet1", "Sheet2", "Sheet3")
 For Each s In myarray
  Sheets(s).Calculate
 Next s
End Sub


text:
Q: How to map poco to JSON using Automapper In my MVC 2 application I have a typical method that calls a web service, builds a JSON data object and returns it to the view.
Everything works fine, but I was wondering if there is a way to do the mapping with Automapper so I can remove the ugly code from my controller. Thanks in advance
Here is my Action method
public virtual ActionResult AllErrors(string sidx, string sord,
                                      int page=1, int rows=10)
    {
        var pageSize = rows;
        var pageNumber = page;
        var orderBy = string.Format("{0} {1}", sidx, sord);

        var result = errorService.GetPagedOpenErrors(pageSize, page, orderBy);
        var errors = new List<IngestionErrorDataContract>(result.IngestionErrors);
        var totalPages = (int) Math.Ceiling(result.TotalRows/(float) pageSize);

        int index = 0;
        var list = new List<object>();
        errors.ForEach(e => list.Add(
                                new {
                                        i = index++,
                                        cell = new[]
                                        {
                                            e.IngestionErrorId.ToString(),
                                            e.RunId.ToString(),
                                            e.ProcessDate.ToShortDateString(),
                                            e.Status,
                                            e.ErrorDetails
                                        }
                                    }));

        var jsonData = new
                           {
                               total = totalPages,
                               page = pageNumber,
                               records = result.TotalRows,
                               rows = list.ToArray()
                           };

        return Json(jsonData, JsonRequestBehavior.AllowGet);
    }

A: I solved it using the ConstructUsing method of AutoMapper.
Here is my map
public void CreateMap()
    {
        Mapper.CreateMap<List<IngestionErrorDataContract>, object[]>()
            .ConvertUsing(
                errors =>
                    {
                        int index = 0;
                        var list = new List<object>();
                        errors.ForEach(e => list.Add(
                            new
                                {
                                    i = index++,
                                    cell = new[]
                                               {
                                                   e.IngestionErrorId.ToString(),
                                                   e.RunId.ToString(),
                                                   e.ProcessDate.ToShortDateString(),
                                                   e.Status,
                                                   e.ErrorDetails
                                               }
                                }));
                        return list.ToArray();
                    });
    }

and here is my action method now
public virtual ActionResult AllErrors(string sidx, string sord, int page=1, int rows=10)
    {
        var pageSize = rows;
        var pageNumber = page;
        var orderBy = string.Format("{0} {1}", sidx, sord);

        var result = errorService.GetPagedOpenErrors(pageSize, page, orderBy);
        var errors = new List<IngestionErrorDataContract>(result.IngestionErrors);
        var totalPages = (int) Math.Ceiling(result.TotalRows/(float) pageSize);

        var jsonData = new
                           {
                               total = totalPages,
                               page = pageNumber,
                               records = result.TotalRows,
                               rows = mapper.Map<List<IngestionErrorDataContract>,object[]>(errors)
                           };

        return Json(jsonData, JsonRequestBehavior.AllowGet);
    }

Much better I think


text:
Q: Selector with context in jquery With jQuery, I do the following
MyCompaniesInfo = $('input[name^="Companies"]');

And the console gives me this (Firebug):
MyCompaniesInfo

Object[input b1280bf5...73a2a334, input#Companies_b1280bf5-102e-4592-a1b1-53e973a2a334__IsExist False, input#Companies_b1280bf5-102e-4592-a1b1-53e973a2a334__Type Company, 29 more...]

0 input#Companies_b1280bf5-102e-4592-a1b1-53e973a2a334__Name.text-box
1 input#Companies_b1280bf5-102e-4592-a1b1-53e973a2a334__phone.text-box
2 input#Companies_b1280bf5-102e-4592-a1b1-53e973a2a334__address.text-box
3 input#Companies_b1280bf5-102e-4592-a1b1-53e973a2a334__street.text-box
4 input#Companies_b1280bf5-102e-4592-a1b1-53e973a2a334__anotherthing.text-box
5 input#Companies_b1280bf5-102e-4592-a1b1-53e973a2a334__another.text-box
6 input#Companies_b1280bf5-102e-4592-a1b1-53e973a2a334__blabla.text-box
7 input#Companies_b1280bf5-102e-4592-a1b1-53e973a2a334__loremipsum.text-box

8 input#Companies_b1280bf52a1b1-53e973a2a334__Name.text-box
9 input#Companies_b1280bf5a1b1-53e973a2a334__phone.text-box
10 input#Companies_b1280bf5a1b1-53e973a2a334__address.text-box
11 input#Companies_b1280bf5a1b1-53e973a2a334__street.text-box
12 input#Companies_b1280bf5a1b1-53e973a2a334__anotherthing.text-box
13 input#Companies_b1280bf5a1b1-53e973a2a334__another.text-box
14 input#Companies_b1280bf5a1b1-53e973a2a334__blabla.text-box
15 input#Companies_b1280bf5a1b1-53e973a2a334__loremipsum.text-box

....
Now I want all fields that end in "Name", for example, so, I tried this:
$('input[name$="Name"]', MyCompaniesInfo).val('Name');

but that doesn't work.  How can I continue to select with jquery after MyCompaniesInfo = $('input[name^="Companies"]');?

A: The problem is that when you use the first selector MyCompaniesInfo = $('input[name^="Companies"]'); you'll store an array of elements in MyCompaniesInfo.
Then if you want to filter the elements you have to use filter, like the following.
$(MyCompaniesInfo).filter('input[name$="Name"]')

Why the following code won't work ?
$('input[name$="Name"]', MyCompaniesInfo)
Because it's the same of $(MyCompaniesInfo).find('input[name$="Name"]') and find only searches thrue the DOM tree, like it's being described on api.
Given a jQuery object that represents a set of DOM elements, the .find() method allows us to search through the descendants of these elements in the DOM tree and construct a new jQuery object from the matching elements.
Here you can see a demo.


text:
Q: Loss vs epoch plot in keras on time series forecasting epoch vs loss plot
I am getting above epoch vs loss plot while training on time series forecasting in keras 2.2.4. Model configuration 1 lstm layer, 1 dense layer, num epochs - 64. On some set of configuration I am getting right plot with just two curves one for validation set and one for training loss dataset while on some configuration I am getting this absurd plot shown in image. I am not able to understand why this is happening?
My code --
def train(trainingData, config):
    inputShape, numNode, numEpoch, batchSize = config
    if nDiff > 0:
            trainingData = np.array(difference(trainingData))
    trainX, trainY = trainingData[:, :-1], trainingData[:, -1]
    trainX = trainX.reshape((trainX.shape[0], trainX.shape[1], 1))
    model = Sequential()
    model.add(LSTM(numNode, activation = 'relu', input_shape = (inputShape, 1)))
    #model.add(Dense(4, activation = 'relu'))
    model.add(Dense(1))
    model.compile(loss = 'mse' , optimizer = 'adam')
    history = model.fit(trainX, trainY,  validation_split = 0.2, epochs = numEpoch, batch_size = batchSize, verbose = 0, shuffle = True)
    # summarize history for loss
    plt.plot(history.history['loss'])
    plt.plot(history.history['val_loss'])
    plt.title('model loss')
    plt.ylabel('loss')
    plt.xlabel('epoch')
    plt.legend(['train', 'test'], loc='upper left')
    plt.savefig(modelName + "ind")
    return model

A: Do you have metrics=['...'] in you model.compile() by any chance? If so, the graph probably shows the additional metric besides your original loss.

A: do
plt.close('all')

after you are done with the plotting of one plot or before you start each plotting
i.e.,
Replace
plt.savefig(modelName + "ind")

with
plt.savefig(modelName + "ind")
plt.close('all')


text:
Q: Flask JSON Custom Error Page is there any implementation exists on JSON as custom error page on Flask?

A: You can create a json response object using the "jsonify" helper from flask and then set the status_code of the response before returning it like this:
def not_found(error):
    response = jsonify({'code': 404,'message': 'No interface defined for URL'})
    response.status_code = 404
    return response

You can register this function as the handler by wrapping it in the errorhandler:
@app.errorhandler(404)
def not_found(error):
    ...

OR, setting it directly on the error_handler_spec:
app.error_handler_spec[None][404] = not_found


text:
Q: What's the point of these regex'es? I'm trying to solve a regex puzzle, and portions of the regexes keep consisting of pieces like this:
([^Xa-ehY]|[^f-zW])
or
([^2]|[^D-Za]|[D-Ze-f])
These confuse me.
Take the first one, for example: [^Xa-ehY]|[^f-zW]). Doesn't this mean "not Xa-ehY OR not f-zW"? And doesn't that equate to "any character"? Take e for example. It wouldn't match the first one, but it would match the second. W would not match the second, but it would match the first.
Same with ([^2]|[^D-Za]|[D-Ze-f]). This means "not 2 OR not D-Ze-f OR D-Ze-f", right? Which again amounts to "any character."
Am I missing something? Is this just a convoluted substitution for a single . regex?

A: I think there are some characters that overlap. E.g. in the first on the lowercase h wouldn't match either side.
Admittedly the second one looks like it is just "."

A: Since it is a puzzle you should look closer.
[^Xa-ehY]|[^f-zW] is not the same as . since they intersect at h (f-z contains h) so it would be the same as [^h]

A: You can throw a bunch of text at them in a regex tester to see if any characters overlap.  It's pretty crude, but your first example (\[^Xa-ehY\]|\[^f-zW\]) overlaps on the letter 'h'.  The second example does look like it should match anything.


text:
Q: Execute a job when node connect itself to Jenkins I have a Jenkins server and two nodes.
I want to execute a basic ip a command on a node when it first connect to the Jenkins server.
The problem is that when Node1 connect itself, the job trigger on Node 1 BUT
When Node2 connect to the server, the job trigger AGAIN on Node1...
Can you please help me ?
I use the java client for my nodes and a label called "Julien"
https://imgur.com/a/qnIX5Oo
Thanks

A: The question is quite old now, but I was facing same issue and wanted to share my settings to solve it.
I use the startup trigger plugin, as explained above, but by default, it was using any available node to do the job.
In order to make the new connected node run the job, I had to :

*

*Check "This project is parameterized"

*Add a "Node" parameter with "Name" set to "LAST_STARTED_NODE" (it can be anything else)

*Check "Build when job nodes start"

*In "Advanced", set "Node parameter name" to "LAST_STARTED_NODE" (same as above)

With this configuration, job is run on expected new node.

A: Hi you can use the startup trigger plugin which will trigger the jobs on startup of nodes and master. You can also restrict the nodes with there labels for triggering the job.
Also refer this link for more info.
I don't know how to select node for executing command but you can create another pipeline job and write pipeline script e.g.
pipeline {
    agent {label "${Node parameter name}"}
    stages {
        stage("some stage"){
          steps{
           bat "your command"
         }
      }
    }
}


text:
Q: Is there way to scan a registry hive on an attached USB drive? I have a hard drive with a virus that I removed from a PC. I can scan the file system of it as an attached USB drive. But how do I scan the registry of that USB drive since it is not booted up like a regular hard drive?
To clarify, the USB drive was a regular hard drive in a PC that got infected. I cannot boot into the OS to run a scan. I removed it to attach it to a working PC so I can scan its file system. But, I cannot scan the registry of that hard drive, because that drive is not booted up. The hard drive was a regular Windows XP hard drive install that I removed to scan as an attached drive (with an adapter to make it a USB drive).

A: Personally I recommend backing up the old disk and then wiping it
This way you don't have to worry about the virus remaining behind and it's more efficient too.
Note: the problem you're having right now is probably that the host OS (you're using right now) doesn't have access to the Windows folder of your infected guest OS. Using a Linux Live CD would allow you to "ignore" these permissions and restore whatever files you need.
Alternatively you could use a virus scanner within Linux to scan the drive as well, but I'm sure a clean install will give a better and more efficient result

A: What you want to do is called 'offline registry editing'. You can load the registry hives from the old hard disk drive into your registry editor. Here's a tutorial:
Load registry hive for offline registry editing
However, I'd recommend to use BartPE instead of your current Windows installation to do this:
How to edit the registry offline using BartPE boot CD?
BartPE will recognize your external USB hard disk drive connected.

A: RunAlyzer

*

*Autostart entries - RunAlyzer shows a bunch of places applications use to get themself started upon Windows start. This is good for tweaking your system as well as finding spyware, viruses or other malware.

*Analysis - RunAlyzer comes with a database of known entries and can do an online lookup to get the newest classifications of entries from our servers. Simple colors - green for good, red for bad - will give you the quick overview needed. Our detectives will even classify any unknown entries you submit to us through an easy function integrated into the application.

*Log functions - Should you want to get help from another place, RunAlyzer can export log files as would be created by Spybot-S&D or HijackThis - formats that many experts all over the world prefer.

*Windows x64 compatibility - RunAlyzer works on the new 64 bit versions of Windows as well - and allows you to view and change both 32 bit backward compatbility and new 64 bit entries there.

*WinPE compatibility - thanks to the multi platform code we use in many of our products, RunAlyzer also automatically detects Windows installations on other attached harddisks or partitions, and allows you to manage those. This can be extremly useful if for example you want to repair a system while booting from a BartPE (bootable Windows PE) CD.

Or ubcd4win has a tool called RunScanner that let you do offline registry scan with any scanners

A: You might not need to worry about scanning the registry file on the infected drive.
Removing the infected files by the scans you are able to run (antivirus and antimalware/spyware) will most likely kill the infections.  The registry entries will now point to missing files and so on... most likely.  Put the drive back in its original system.  I bet you can now boot to safe mode and run all the scans again locally... this time clearing out the registry of offensive entries, too. :)
My favorite approach has already been mentioned, though.  A bartPE disk with some nice, prebuilt plugins for loading offline registries and feeding those to the scanners.  This way, you don't remove the HD... you just boot a CD (or USB stick).   A hand-held method to making your own disk is at http://www.ubcd4win.com/  Good luck!

A: Disk drives do not have registries.  Your antivirus software should be able to scan a disk, which the USB drive should be recognized as.

A: Antivirus scanning of registry hive alone does not make sense, as there's no executable code in registry. There are only links to filesystem, and as long as filesystem is clean, registry is fine too.
But if you need to edit/search/replace something in the registry hive outside of Windows, or in the registry hive on USB HDD, you may use Emergency Boot CD ( http://www.prime-expert.com/ ) which contains standalone offline registry editor.


text:
Q: Entity Framework stored procedure Insert custom sequential number Please bear with me is a long explanation.
I have a set up a table in EF4 using mapped stores procedure for inserting data.
Example :
    id | location | type
    1  |     10   |  15
    5  |     10   |  16

What the SP does is to check in another table the next id that corresponds by location and type.
So in this example the next id would be

*

*2 for location 10 and type 15

*6 for location 10 type 16

This works by mapping a result column in EF.
It works ok except when two different keys have the same sequential number example:
    id | location | type
    1  |     10   |  11
    1  |     10   |  10

Edit: this error occurs when I am creating both new rows at the same time.
The next value for both of them is 2, the data is saved to the database but the application fails with this message:

The changes to the database were committed successfully, but an error occurred
  while updating the object context. The ObjectContext might be in an
  inconsistent state.
  Inner exception message:
  AcceptChanges cannot continue because the object's key values conflict with another
  object in the ObjectStateManager.
  Make sure that the key values are unique before calling AcceptChanges.

Any advice?
Edit
Stored procedure example

declare @nextNumber int
SELECT @nextNumber = value + 1  FROM SEQUENTIAL_TABLE WHERE location = @location and type=@type
INSERT INTO TABLE (location, type, id ,......) VALUES (@location, @type,@nextnumber, .......)
UPDATE SEQUENTIAL_TABLE SET value = @nextNumber WHERE location = @location and type=@type
SELECT @nextNumber as [NextNumber]

A: Without knowing more about the design; you could modify your table so that ID is not a primary key, but rather use the set of ID/Location/Type as a composite key.

A: It sounds like you're mis-using the id column to not just mean "auto-incrementing int".

A: The "bogus negative numbers" is a great trick, and worked very nicely in the DataSet / TableAdapter days.  If that doesn't work, perhaps this is a race condition, and you need to place the details in a transaction such that no other threads / rows can get the next id until you're done incrementing and inserting yours.


text:
Q: scrollbar is appearing for element having height lesser than max-height I'm having a div containing the list (unordered) and I have set the max-height of the list as 300px and overflow-y as auto but even if the list is not exceeding 300px, I can see the scroll bar.

abc

xyz

mno

pqr

stu

lmn

wxy

note:list is dynamic
and css for class dynamicList
.dynamicList{
  max-height:300px;
  overflow-y:auto
}

A: <!DOCTYPE html>

<title>Page Title</title>

Listbox

abc

xyz

mno

pqr

stu

lmn

wxy

Can you try this code? There is max height but no default height.


text:
Q: SQL Query for a specific Result Set
I could not format the text for better readibility. Hence, putting it up as an image.
Please suggest a way to devise a query.
Thanks

A: SELECT
COUNT(SELECT * FROM EMP WHERE EMP.EMPNO != EMP_MIRROR.EMPNO) as DIFF_EMPNO,
COUNT(SELECT * FROM EMP WHERE EMP.AGE != EMP_MIRROR.AGE) as DIFF_AGE

FROM EMP
JOIN EMP_ERROR

Try that

A: Try this:
SELECT
SUM(CASE WHEN EMP.EMPNO <> EMP_ERROR.EMPNO THEN 1 ELSE 0 END) AS DIFF_EMPNO,
SUM(CASE WHEN EMP.AGE <> EMP_ERROR.AGE THEN 1 ELSE 0 END) AS DIFF_AGE
FROM EMP
JOIN EMP_ERROR ON EMP.ID = EMP_ERROR.ID


text:
Q: How to write domain logic for a domain model in Domain Driven Design? I am stucked in writing domain logic for domain model.
I am new to DDD and have read some articles for DDD. I have collected some of the domain objects for our project, but I can't figure out what does domain logic mean?
I have a domain model class named "Account".
As the user register for their new account, they have to select one of the two types of account in our Project.
Let's say one account type is Personal and the another is Business.
The Account model class is shown below:
public class Account
    {
            private AccountType _accountType;
            private string _userRole;
            private Address _address;
            private BusinessInfo _businessInfo;
            private string _contactPhoneNumber;
            private string _citizenshipCountryCode;
            private DateTime _dateOfBirth;
            private string _emailAddress;
            private string _preferredLanguage;
            private string _registrationType;
            private DateTime _createdDateTime;
    }

I have not posted my full class, but above are the attributes of Account domain.
If the user selects the business account, he had to fill business info details else no need.
Based on my situation how could I select the domain logic for account domain class.
What are the ideas or how should I select the domain logic basically?
Any help would be appreciable.

A: 2 me it sounds as if you have different types of accounts and they all have some common parts but also some parts specific to each type.
Have you thought about making an base account class with the common stuff and create specific account types that inherit from this base class instead?
The base class may take all necessary information as arguments in its constructor
and expose common operations..
Likewise the specialized class (BusinessAccount?) could take whatever necessary on top of the common stuff as arguments in its constructor..

A:
but I can't figure out what does domain logic mean?

Everything that's directly related to problems you are dealing with. And with problems I mean that part of problems Your customer is talking about.
Technical things like 'how to display this account?' or 'how to retrieve account data from by database?' should be separated from domain logic such as 'is this account expired?', 'does this account has special privileges?', 'stuff that happens when we close an account' etc.
Hardest part of writing domain logic is finding ways on how to decouple this technical part which for your customer makes not much more sense than MAGIC. In some sense - it will be just a model after all, you need some means to reflect it (programming language itself for example).
What you should end up with is neatly written rule set that closely follows language your customer is speaking in.

A:
Based on my situation how could I select the domain logic for account
  domain class.
What are the ideas or how should I select the domain logic basically?

My general rule:
Everything that is related to Target Domain of the software and isn't an infrastructure  (Data Access or Application layers) or GUI (Presentation Layer) could be considered as Domain Logic.
Domain logic can be placed into Entities, Value Objects, Aggregates, Domain Services, Domain Events, Factories.
According to the Domain-Driven Design by Eric Evans there are building blocks of DDD:

*

*Layered Architecture. It is used to isolate Domain Model and Domain Logic from Persistence Layer and Presentation Layer

*Entities (building block of your Domain Model that implements Domain Logic)

*Value Objects (building block of your Domain Model that implements Domain Logic)

*Domain Events (Domain Logic that is performed by 'experts' when they are notified)

*Services (Domain Logic that is not responsibility of any entity)

*Modules

*Aggregates (building block of your Domain Model that implements Domain Logic)

*Repositories. They provides an illusion of in-memory collections.

*Factories. Domain Logic that is responsible for creating instances of complex objects.

So, I would design it the following way:

*

*Account is an abstract class and PersonalAccount and BusinessAccount classes inherit it.

*AccountFactory is used in order to create complex object (either PersonalAccount or BusinessAccount).

*UI or Application Logic use AccountFactory to create an Account using data provided by user.

*you can also introduce additional Value Objects in order group properties of you Account more naturally for business users and use ubiquitous language for it.

A: Basically you need a AccountingProcessingRules Class  that accept different type Account class and process accordingly. When you do this you can specify two sets of rules for each account type, one for personal and one for business.


text:
Q: CNAME file not copied in gh-pages branch after npm run deploy I have a react app deployed with git hub pages, using gh-pages plugin. My package.json entry look like this.
"scripts": {
    "predeploy": "npm run build",
    "deploy": "gh-pages -d build",
     .....
   }

Eveything worked fine until I tried to use a custom domain.

*

*I configured the required A and CNAME entry in my domain provider DNS settings.

*I created the CNAME file in the develop branch. That is the branch that I have checked out on my local machine.

*I run npm run deploy on develop branch on local machine.

*plugin pushed the build code to gh-pages branch on remote.

*the gh-pages branch on remote does not contain the CNAME file.

*after every deploy I have to manually add the custom-domain from github settings pages section, which eventually create a CNAME file. And then every works.
Is there a configuration requied in package.json to force gh-pages plugin to copy the CNAME file ?


text:
Q: Downgraded from Big Sur to Mojave on Macbook Air, Photos app won't open On my Macbook Air, I downgraded from Big Sur to Mojave, and the Photos app won't open. Photos are located on an SD card and not on the MacBook HD. The reason I downgraded was because the essential software I constantly used did not work on Big Sur.
I simply restored from a backup I had made on Mojave before I got the local Mac service people to install a new (larger) hard drive. It may be (I don't recall) I opened the Photos app when Big Sur was installed, and if so, it may have altered the database setup.

A: It's not truly surprising. Apple frequently makes format/database changes with upgrades. The resulting files are almost never convertible 'downhill', there is simply no provision to be able to do that.
There appears to be a 'get out of jail free' card for Photos, though, using iCloud as an intermediary. There is a long [& outdated] explanation on Downgrading a Photos Library to a Previous Version of Photos with the Help of iCloud Photos which I have never tested, so cannot comment on whether it will still work from Big Sur right the way back to Mojave.
I can confirm that deleting the Big Sur Library, creating a new Photos Lib, making it your System Library and turning on iCloud Photos will download a new Mojave compatible library.
This does rather emphasise the need for a solid backup strategy, to prevent issues like this in future. Personally, not only do I keep backups of everything, but before I do any major OS upgrade, I clone my entire boot drive as a 'belt & braces' for if I decide to go back. There are frequently issues trying to go 'downhill' using Time Machine, so I consider this to be a vital step.

A: I believe I found the answer. Go to Finder, then Pictures, then right click Photos library and select Show Package Contents. Select Originals folder and drag to left column of Finder under Pictures or wherever in that column. Open folder and all photos are in numbered folders. Then go to App Store and located in your account there should be the iPhoto app, download and boot it, then under File menu select "Import to Library' and select the 'Original' folder mentioned above and all your photos/videos load into the iPhoto app. I tried doing the same in the "Photos' app but it didn't work. iPhoto will do for me for the moment, the only difference "Photo" app syncs your pics with other Apple devices, which I'm not interested in. But at least I was able to restore all my inaccessable photos and I'm back in business on my Mac. Possibly when I upgrade to next macOS Photos app will be able to access my pics also.


text:
Q: Piping StdOut adds more text I am running a simple command (some Kafka related stuff):
curl localhost:8083

Its output is very simple:
root@debian:/etc/kafka# curl localhost:8083/
{"version":"0.11.0.0-cp1","commit":"6a8cf706ddc9ab6a"}root@debian:/etc/kafka#

But now, when I use utility tool jq to format json, more lines get added:
root@debian:/etc/kafka# curl localhost:8083/ | jq
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100    54  100    54    0     0   1492      0 --:--:-- --:--:-- --:--:--  1500
{
  "version": "0.11.0.0-cp1",
  "commit": "6a8cf706ddc9ab6a"
}

Same happens if I pipe it to less or cat in the expected way curl ... | less. So this has nothing to do with jq itself.
My knowledge of all the stdin, stdout, stderr, pipes (that are just joins of stdout to sdtin), file redirects > < 2>, etc.. doesn't explain this behaviour. :(

A: As many UNIX tools, the output of curl depends upon what type of device stdout is attached to. In this case, piping the ourput through jq changes the type from TTY to pipe, resulting in unwanted additional output.
curl has a command-line switch -s, that silences this additional output, so running curl -s localhost:8083/ | jq shold solve the issue.


text:
Q: SQL : remove last comma in string I have a text memo field in SQL table that I need to remove the last character in the field if it's a comma.
So, for example, if I have these rows, I need to remove the commas from rows 2 and 4.
  INETSHORTD
1  94
2  85,
3  94, 92
4  89, 99, 32,

The output would be:
  INETSHORTD
  94
  85
  94, 92
  89, 99, 32

Any ideas?

A: Using REVERSE and STUFF:
SELECT
    REVERSE(
        STUFF(
            REVERSE(LTRIM(RTRIM(INETSHORTD))),
            1,
            CASE WHEN SUBSTRING((REVERSE(LTRIM(RTRIM(INETSHORTD)))), 1, 1) = ',' THEN 1 ELSE 0 END,
            ''
        )
    )
FROM tbl

First, you want to TRIM your data to get rid of leading and trailing spaces. Then REVERSE it and check if the first character is ,. If it is, remove it, otherwise do nothing. Then REVERSE it back again. You can remove the first character by using STUFF(string, 1, 1, '').
SQL Fiddle

A: Use case statement if the particular string is ending with , take the substring with LEFT function and lenght - 1
Select
    CASE
        WHEN INETSHORTD LIKE '%,'  THEN LEFT(INETSHORTD, LEN(INETSHORTD)-1)
        ELSE INETSHORTD
    END
From yourtable

example fiddle

A: Not sure if the syntax was available in 2015 but I would think this is a more elegant solution.
SELECT TRIM(',' from INETSHORTD) FROM TABLE

A: Here's a more elegant / readable way:
SET @string = REPLACE(@string + '<END>', ',<END>', '')

if you can't be sure if last comma appear in string, use this:
SET @string = REPLACE(REPLACE(@string + '<END>', ',<END>', ''), '<END>', '')

A: Using CHARINDEX (https://msdn.microsoft.com/en-us/library/ms186323.aspx) AND LEN (https://msdn.microsoft.com/en-us/library/ms190329.aspx) you should be able to do it like this:
SELECT IIF( CHARINDEX( ',', tmp.SHORTD, LEN( tmp.SHORTD ) ) > 0
          , LEFT( tmp.SHORTD, LEN( tmp.SHORTD ) - 1 )
          , tmp.SHORTD )
  FROM tmp

This SQL Fiddle shows it at work: http://sqlfiddle.com/#!3/a99c8/7.

A: declare @t table (id varchar(20))
insert into @t(id)values ('94,'),('85,'),('94, 92'),('89, 99, 32,')

SELECT  REVERSE(SUBSTRING(  REVERSE(id),    PATINDEX('%[A-Za-z0-9]%',REVERSE(id)),
    LEN(id) - (PATINDEX('%[A-Za-z0-9]%',REVERSE(id)) - 1)   ) )
FROM    @t


text:
Q: If $f: \mathbb{R}^2 \to \mathbb{R}$ is a continuous function with zero integral over every rectangle of area $1,$ then $f = 0.$
If $f: \mathbb{R}^2 \to \mathbb{R}$ is a continuous function with zero
integral over every rectangle of area $1,$ prove $f = 0.$

Using induction and a shifting argument for the base case, I managed to show that if $ABCD$ is a rectangle with integer area, then $$f(A) + f(C) = f(B) + f(D) \, \, (*)$$ I think this almost solves the problem, I just need to draw the right diagram now. Unfortunately, I'm having difficulties coming up with a diagram that works.
I drew a $2 \times 2$ square with vertices $A, B, C, D, E, F, G, H, I,$ applied $(*)$ on all sorts of squares within this square, summed the results, and then tried to cancel as many terms on both sides as possible. However, no matter which sums I took, I would always end up with either $0 = 0$ or a trivial result of the form $(*).$ How do I find the right diagram? I tried drawing $3 \times 3, \sqrt{2} \times \sqrt{2}$ and even $\sqrt{3} \times \sqrt{3}$ squares, but ran into the same problem (at one point, I thought I had proven that $f(x,y) = f(x+\sqrt{3},y) = f(x+\sqrt{2},y),$ which would show $f$ is constant after employing the density of $\{a\sqrt{2}+b\sqrt{3} : a, b \in \mathbb{Z}\}$ in $\mathbb{R},$ but it turned out I made a mistake when adding terms in both cases). Any ideas?