text:
Q: Update SQL Query not working ASP.NET Web Application Here is the code of my .aspx page,
When I click on update it runs the page doesn't show any errors and the row is not updated in my blog table.
The exception doesn't display anything, and i have a row with the id in my table.
The select command in the Page_Load() works perfectly.
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Blog
{
    public partial class update : System.Web.UI.Page
    {
        SqlConnection connection = new SqlConnection(##################);

        protected void Page_Load(object sender, EventArgs e)
        {
            string id = Request.QueryString["id"];
            string sql = "select * from blog where Id=@id";
            SqlCommand sqlCommand = new SqlCommand(sql,connection);
            sqlCommand.Parameters.AddWithValue("@id", id);
            connection.Open();
            SqlDataReader dataReader = sqlCommand.ExecuteReader();
            while (dataReader.Read())
            {
                DropDownListCategory.SelectedIndex = DropDownListCategory.Items.IndexOf(DropDownListCategory.Items.FindByText(dataReader["category"].ToString().Trim()));
                TextBoxTitle.Text = dataReader["title"].ToString();
                TextBoxDesc.Text = dataReader["description"].ToString();
            }
            connection.Close();
        }
        protected void Timer1_Tick(object sender, EventArgs e)
        {
            LabelDate.Text = DateTime.Now.ToString();
        }

        protected void Update_Click(object sender, EventArgs e)
        {
            try
            {
                int id = Convert.ToInt32(Request.QueryString["id"].Trim());
                string sql2 = "UPDATE blog SET title = @title , category = @category , description = @description , posteddate = @posteddate WHERE Id=@id";
                connection.Open();

                SqlCommand sqlCommand2 = new SqlCommand(sql2, connection);
                sqlCommand2.Parameters.AddWithValue("@id", id);
                sqlCommand2.Parameters.AddWithValue("@title", TextBoxTitle.Text);
                sqlCommand2.Parameters.AddWithValue("@category", DropDownListCategory.SelectedItem.Text.ToString());
                sqlCommand2.Parameters.AddWithValue("@description", TextBoxDesc.Text);
                sqlCommand2.Parameters.AddWithValue("@posteddate", DateTime.Now.ToString());
                sqlCommand2.ExecuteNonQuery();
            }
            catch(Exception ex)
            {
                Label1.Text = ex.Message;
            }
            connection.Close();
            //Response.Redirect("Default.aspx");
        }

    }
}

A: Added a if(!IsPostBack){} now works fine, Thank you
  protected void Page_Load(object sender, EventArgs e)
            {
                if (!IsPostBack)
                {
                    string id = Request.QueryString["id"];
                    string sql = "select * from blog where Id=@id";
                    SqlCommand sqlCommand = new SqlCommand(sql, connection);
                    sqlCommand.Parameters.AddWithValue("@id", id);
                    connection.Open();
                    SqlDataReader dataReader = sqlCommand.ExecuteReader();
                    while (dataReader.Read())
                    {
                        DropDownListCategory.SelectedIndex = DropDownListCategory.Items.IndexOf(DropDownListCategory.Items.FindByText(dataReader["category"].ToString().Trim()));
                        TextBoxTitle.Text = dataReader["title"].ToString();
                        TextBoxDesc.Text = dataReader["description"].ToString();
                    }
                    connection.Close();
                }
            }


text:
Q: Dio options.contentType vs header "Content-Type" I was trying to make a call to a REST service using the Dio plugin, but kept getting HTTP 400 response code. I thought I was doing everything right by setting the content type and response type options to JSON:
Response response = await Dio().get(
    'https://api.example.com/v1/products/$productId',
    queryParameters: {},
    options: Options(
        contentType: ContentType.json,
        responseType: ResponseType.json,
        headers: {'Authorization': 'Bearer $MY_API_KEY'}
    ),
);

However, it turns out that I needed to add a Content-Type header as well:
headers: {'Authorization': 'Bearer $MY_API_KEY'}, 'Content-Type': 'application/json' };

So now I'm confused - what exactly does the contentType option do? I thought it was analogous to setting the Content-Type header manually?

A: I've tried this locally using dio: ^3.0.10 and it seems that ContentType.json is an invalid value for contentType.

Digging through the documentation for dio, Headers.jsonContentType should be used.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why does "Q_FUNC_INFO "/" __FILE__" fail in Qt Creator/macOS? This compiles fine in Qt Creator/Windows:
foo(Q_FUNC_INFO "/" __FILE__);

But on the Mac, using Qt Creator as IDE/compiler, I get error:
error: expected ')'

These also fail on the Mac:
foo(Q_FUNC_INFO ## "/" ## __FILE__);
foo(Q_FUNC_INFO __FILE__);

Is there a way of concatenating function name and file name?

A: I don't know how OP defined foo() but (for the sake of simplicity) I will assume that it might be:
void foo(std::string_view text);

I must admit that I don't have experience with Mac OS but I heard the common compilers are clang or gcc.
I had a look on woboq.org to see how Q_FUNC_INFO is defined. There are a lot of nested #ifs and #elifs but after a while of digging, I came to the conclusion that the effective should be:
#elif defined(__GNU_C__)

…
#  define Q_FUNC_INFO       __PRETTY_FUNCTION__

So, the question is actually: How is __PRETTY_FUNCTION__ defined?
I couldn't find anything about clang but The GCC doc. is quite clear about this:

In C, __PRETTY_FUNCTION__ is yet another name for __func__, except that at file scope (or, in C++, namespace scope), it evaluates to the string "top level". In addition, in C++, __PRETTY_FUNCTION__ contains the signature of the function as well as its bare name.

…

These identifiers are variables, not preprocessor macros, and may not be used to initialize char arrays or be concatenated with string literals.

This explains why all the attempts of OP must have been failed.
The fix is actually simple:
foo(std::string(Q_FUNC_INFO) + "/" + __FILE__);

and I expect that this fix should work on other compilers as well.
MCVE:
#include <iostream>
#include <string>
#include <string_view>

#if defined(_MSC_VER)
#  define Q_FUNC_INFO __FUNCSIG__
#else
#  define Q_FUNC_INFO __PRETTY_FUNCTION__
#endif

void foo(std::string_view text) { std::cout << text << '\n'; }

int main()
{
  foo(std::string(Q_FUNC_INFO) + "/" + __FILE__);
}


text:
Q: Restful controller works in spring 3 doesn't work in spring 4 I have recently moved a project from spring 3 to spring 4 and my restful controllers don't work anymore.
My methods look like this:
@RequestMapping(value = "/app/barcode/generate", method = RequestMethod.POST)
@ResponseBody
public String doStuff(@RequestBody MyDTO dto) {
    return "Boo";
}

but when I call them from javascript I get this error:
Handler execution resulted in exception: Content type 'application/json' not supported
If I remove @RequestBody the param is always null.
My ajax calls are configured like this
$.ajax({
        url : url,
        type : 'POST',
        cache : false,
        contentType: "application/json",
        headers : {
            "Cache-Control" : "no-cache,no-store,must-revalidate",
            "Pragma" : "no-cache",
            "Expires" : "-1",
            "X-Content-Type-Options" : "NOSNIFF",
            "X-XSS-Protection" : "1",
            "X-Frame-Options" : "SAMEORIGIN"
        },
        dataType: 'json',
        data : requestData,
        beforeSend : function(xhr) {
            var token = $("meta[name='_csrf']").attr("content");
            var header = $("meta[name='_csrf_header']").attr("content");
            xhr.setRequestHeader(header, token);
        }
    });

This all worked completely fine in spring 3. The main difference is that I am now using Java Config.


text:
Q: Next.js event type error in arrow function I've created my handleChange() function with some event to handle event from my input. The problem is that I don't know what to add to solve the error.
Here below screenshot of this:

I'm using Next.js. In React I would never see something like that.
Thank you in advance for help.:)

A: It looks like you've set up your Next.js project with TypeScript and your typescript configuration has noImplicitAny check enabled, that causes that error to be reported.
Easiest way to fix it would be to explicitly set event type to any.
const handleChange = (event: any) => {

Much better way to fix it would be to use a proper TypeScript type React.ChangeEvent
const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {


text:
Q: SWIFT 3: Capture photo with AVCapturePhotoOutput (Need another set of eyes to look over code, why isn't this working?) I have a custom camera, with AVCapturePhotoCaptureDelegate added to the class, and the following code to capture a still image:
Outlets, Variables, and Constants
@IBOutlet weak var cameraPreview: UIView!
@IBOutlet wear var takePhotoPreview: UIImageView!

private var cameraView: AVCaptureVideoPreviewLayer!
private var camera: AVCaptureDevice!
private var cameraInput: AVCaptureDeviceInput!
private var cameraOutput: AVCapturePhotoOutput!
private var photoSampleBuffer: CMSampleBuffer?
private var previewPhotoSampleBuffer: CMSampleBuffer?
private var photoData: Data? = nil

private let cameraSession = AVCaptureSession()
private photoOutput = AVCapturePhotoOutput()

Setup Camera Session
private func createCamera() {
    cameraSession.beginConfiguration()
    cameraSession.sessionPreset = AVCaptureSessionPresetPhoto
    cameraSession.automaticallyConfiguresCaptureDeviceForWideColor = true

    // Add Camera Input
    if let defaultCamera = AVCaptureDeviceDiscoverySession(deviceTypes: [.builtInWideAngleCamera], mediaType: AVMediaTypeVideo, position: .back).devices {
        camera = defaultCamera.first
        do {
            let cameraInput = try AVCaptureDeviceInput(device: camera)
            if cameraSession.canAddInput(cameraInput) {
                cameraSession.addInput(cameraInput)
                print("Camera input added to the session")
            }
        } catch { print("Could not add camera input to the camera session") }
    }

    // Add Camera View Input
    if let cameraView = AVCaptureVideoPreviewLayer(session: cameraSession) {
        cameraView.frame = cameraPreview.bounds
        cameraView.videoGravity = AVLayerVideoGravityResizeAspectFill
        cameraView.cornerRadius = 12.0
        cameraPreview.layer.addSublayer(cameraView)
        print("Camera view created for the camera session")
    } else { print("Could not create camera preview") }

    // Add Photo Output
    let cameraPhotoOutput = AVCapturePhotoOutput()
    if cameraSession.canAddOutput(cameraPhotoOutput) {
        cameraSession.addOutput(cameraPhotoOutput)
        cameraPhotoOutput.isHighResolutionCaptureEnabled = true
        print("Camera output added to the camera session")
    } else {
        print("Could not add camera photo output to the camera session")
        cameraSession.commitConfiguration()
        return
    }

    cameraSession.commitConfiguration()

    cameraSession.startRunning()
}

CaptureButton
@IBOutlet weak var cameraShutter: UIButton!
@IBAction func cameraShutter(_ sender: UIButton) {
    let photoSettings = AVCapturePhotoSettings()
    photoSettings.flashMode = .on
    photoSettings.isHighResolutionPhotoEnabled = true
    photoSettings.isAutoStillImageStabilizationEnabled = true
    if photoSettings.availablePreviewPhotoPixelFormatTypes.count > 0 {
        photoSettings.previewPhotoFormat = [ kCVPixelBufferPixelFormatTypeKey as String : photoSettings.availablePreviewPhotoPixelFormatTypes.first!]
    }
    cameraPhotoOutput.capturePhoto(with: photoSettings, delegate: self)
}

iOS Observing Camera Function
func capture(_ captureOutput: AVCapturePhotoOutput, didFinishProcessingPhotoSampleBuffer photoSampleBuffer: CMSampleBuffer?, previewPhotoSampleBuffer: CMSampleBuffer?, resolvedSettings: AVCaptureResolvedPhotoSettings, bracketSettings: AVCaptureBracketedStillImageSettings?, error: Error?) {
    if let photoSampleBuffer = photoSampleBuffer {
        photoData = AVCapturePhotoOutput.jpegPhotoDataRepresentation(forJPEGSampleBuffer: photoSampleBuffer, previewPhotoSampleBuffer: previewPhotoSampleBuffer)
        let photoDataProvider = CGDataProvider(data: photoData as! CFData)
        let cgImagePhotoRef = CGImage(jpegDataProviderSource: photoDataProvider!, decode: nil, shouldInterpolate: true, intent: .absoluteColorimetric)
        let newPhoto = UIImage(cgImage: cgImagePhotoRef!, scale: 1.0, orientation: UIImageOrientation.right)
        self.takePhotoPreview.image = newPhoto
        self.takePhotoPreview.isHidden = false
    }
        else {
        print("Error capturing photo: \(error)")
        return
    }
}

Alright, so here is the deal --  I put a breakpoint at cameraPhotoOutput.capturePhoto(with: photoSettings, delegate: self) and upon stepping into the line received the following error message:
Error Message
fatal error: unexpectedly found nil while unwrapping an Optional value
[runtime details] fatal error: unexpectedly found nil while unwrapping an Optional value
The code above is directly from Apple's example doc "AVCam" along with input from SO Q&As (link, link., and others which repeated these answers).  My end goal is to capture an image, and immediately push to image and user to a new ViewController to edit/post/save; however, I'm using a UIImageView currently just to confirm capture...which isn't working in the first place.
So SO, what is going on with this implementation???  It's been driving me nuts for days.
Swift 3, xCode 8

A: Try changing
cameraPhotoOutput.capturePhoto(with: photoSettings, delegate: self)

into
cameraOutput.capturePhoto(with: photoSettings, delegate: self as AVCapturePhotoCaptureDelegate)

A: Alright, figured it out.  El Tomato was on the right track with the problem child, but it wasn't the right prescription.  My createCamera() function was set to private which of course makes the contents not visible outside its body.  So while I was calling the correct AVCapturePhotoOutput(), the buffer feed didn't exist for the capturePhoto() call to execute...throwing the error described.
So this means the line:
cameraPhotoOutput.capturePhoto(with: photoSettings, delegate: self)
was correct, but it was simply the incorrect setup into execution.  To confirm proper execution I...

*

*changed my private let photoOutput = AVCapturePhotoOutput() constant

*to private let cameraPhotoOutput = AVCapturePhotoOutput()

*and called that constant directly in private func createCamera()
which immediately executed an image capture flawlessly.
Also replacing cameraPhotoOutput, an AVCapturePhotoOutput(), with cameraOutput, an AVCapturePhotoOutput!, was tried and simply reproduced the error.
If you are interested:  the cgImage creation process stayed the same in the func capture(_ : capture... function.  Within its bounds, I also determined the camera device's position, changed the image's orientation if front camera, and dispatched on the main queue the photo over to a var photoContent: UIImage? variable on the ReviewViewController.
Hope my mental error helps someone else :-)


text:
Q: Rails ActiveRecord has_one and belongs_to reloading association I have four models
class Votation
  belongs_to :quorum

  def calc
    return self.quorum.calc
  end

end

class Quorum
  has_one :votation
  ...
end

class NewQuorum < Quorum
  def calc
    do stuff and call
    self.votation.attribute_a
  end
end

class OldQuorum < Quorum
  def calc
    do stuff and call
    self.votation.attribute_b
  end
end

I have loaded the votation into a @votation object and eager loaded the associated Quorum.
The problem is that when I call @votation.calc, ActiveRecord execute a SQL select to load the votation again when it has to execute self.votation.attribute_a for example.
SELECT "votations".* FROM "votations" WHERE "votations"."quorum_id" = $1
how can I avoid this select from being executed?

A: You can use the :inverse_of option when specifying the association to prevent another select statement from being executed.
So your models would look like:
 class Votation
   belongs_to :quorum, inverse_of: :votation
 end

 class Quorum
   has_one :votation, inverse_of: :quorum
 end

Reference: http://apidock.com/rails/ActiveRecord/Associations/ClassMethods/belongs_to


text:
Q: Can I make a program reading from a piped stdin AND keyboard? Can I write a python program that read from a piped stdin and keyboard?
What I mean? I want to be able to use it in this way:
tail -f LOGFILE | myscript.py

see the log lines appearing in the screen and type commands with the keyboard?
This sounds like 2 stdin and that confuse me. Is it possible or is it conceptually wrong?
Thanks!

A: Possible solution would be to grab the users current tty and attach a file stream to the corresponding /dev/tty entry.
This may allow you to grab the keyboard input while using stdin as your piped log file.

A: Make your script take a file argument, then use bash's ability to create an anonymous fifo:
myscript.py <( tail -f LOGFILE )

bash translates this to (roughly):
mkfifo /tmp/UNIQUEFILENAME
tail -f LOGFILE > /tmp/UNIQUEFILENAME &
myscript.py /tmp/UNIQUEFILENAME

Have only the commands come through stdin.
<() and >(), especially when combined with tee, can be used anytime you want to create a "branch" in an either side of an arbitrary bash pipeline.

A: This might be hackable, but it is conceptually wrong seems weird to me. stdin is a single input stream. Issuing the command
... | program.py

changes stdin to be the stdout of whatever came before the pipe. But accepting keyboard input means reading the original stdin -- you can't have your cake and eat it too!
A hack would merge those two streams into one, but that's not a good way of doing it; it doesn't separate the data correctly. If your program really should accept keyboard input as well as piped data (are you sure that it should? that seems like an awfully counterintuitive thing to want!), the right way to do it is to spawn separate threads to handle each of the input streams.


text:
Q: Programatically fill inputs and submit AngularJS form after App is opened with URI Intent I have an Ionic 1 + AngularJS app, with cordova, that runs on Android.
I'm using this cordova plugin (https://github.com/darryncampbell/darryncampbell-cordova-plugin-intent) to get intent.extras when I open it with another App.
My question is: how can I fill the inputs and make the ng-submit programatically after the app is opened by another app?
If I fill the inputs with javascript, when I manually submit the form, the values that are submitted are the old ones.
window.plugins.intentShim.onIntent(function (intent) {
    console.log('Received Intent: ' + JSON.stringify(intent.extras));
    if (intent.extras){
        document.getElementById('field1').value = intent.extras.field1||"";
        document.getElementById('field2').value = intent.extras.field2||"";
        document.getElementById('field3').value = intent.extras.field3||"A";
        //apply the values on Angular context and submit
    }

});

A: I 'solve' my problem using document.getElementById('field1').value inside angular controller to get the input content instead of using angular ng-model value.


text:
Q: Transparent layer over img when hover ++ text I want to add an transparent layer over my img on a card when I hover over it, I have done that part but I want it to be cut to the img and not cover the footer on the card. If that makes sence?
this is the card with Hover. As u can see on the card, the img just covers like 90% of the card, I want the hover overlay to do the same
Card when not hover IMG
Card when hover IMG
   .card {
   position:relative;
   width: 350px;
   height: 335px;
   background-size: contain;
   background-repeat: no-repeat;
   background-color: #fff;
   border-radius: 5px;
   margin: 30px;
   float: left;
   }

   #card_oslo{
   background-image: url(img/oslo.jpg);
   }
   #card_oslo:hover{
   box-shadow: inset 0 0 0 1000px rgba(0,0,0,.7);
   transition: .5s;
   }

A: You should use a pseudo-element for this. Use :after or :before and set it as full size also set the parent with position:relative; then change the opacity of the pseudo element on hover.
Working Demo.

.box {
  position:relative;
}
.box:after {
  content:"";
  /* Set the element as full-size */
  position:absolute;
  left:0;
  top:0;
  width:100%;
  height:100%;
  /* Set bg and hide the element + animation */
  background-color:#000;
  opacity:0;
  transition: all 0.5s ease 0s;
}
.box:hover:after {
  /* Show the overlay on hover */
  opacity:0.5;
}

/* For the demo */
.box {
  width:200px;
  height:200px;
  background-color:red;
}

A: You can set the overlay to
position: absolute;
top: 0;
bottom: XXpx;
left: 0;
right: 0;

where XX is the footer height, then it will cover the whole card and leave the bottom x pixels free. You can also use % values instead of px.
If you want the overlay to contain text you need to put it into an extra div that you can then use as overlay.
I made a simplified version here https://jsfiddle.net/0L9fL1pj/

A: Been looking for a similar solution and since this thread never got a proper answer (neither proposed answer got me where I wanted and I doubt) but I got some important clues here and I thought I'd provide my current solution so anyone who has a similar problem can benefit.
I made a simple demo here: https://jsfiddle.net/Tdesign/2ynuajk0/14/
HTML:

CSS:
    #imgBox2 {
    position: relative;
    width: 500px;
}

    .shade:hover::after {
    content: "";
    position: absolute;
    top: 0;
    left: 0;
    height: 100%;
    width: 500px;
    background-color: rgba(0,0,0,0.5);
}


text:
Q: Loading class with interface from another class loader I have a class Foo which implements an IDoMagic interface.
The Foo class is loaded by the system classloader and the IDoMagic interface is defined in a third party component, which I think loads the interface in another class loader (Dynamic Classloader).
When I try to create a new instance of Foo, I'm getting a NoClassDefFound for IDoMagic. I assume that's because it is loaded by a different class loader.
I have tried to create a BridgeClassLoader (similar to the one used by Guice) and then load class Foo from the system class loader and all other classes from a different classloader which I think is the one used for IDoMagic but without any success.
Is there a way around it?

A: Classloaders (CL) in Java work on a delegate strategy which means that the CL first will ask her parent, which also asks her parent, if she knows the defintion for class X. Only if neither the parent nor any of the ancestors or the current classloader knew the classdefinition for X then the current classloader will load the definition from the respective X.class file.
If a class Foo is loaded by the system classloader, any classes Foo is dependend on need also be loaded by either the system CL or by a parent of this CL. As IDoMagic is provided in an other JAR, you most likely need to add this JAR file to the classpath (java -cp ... or java -jar ...). Due to the delegation model, any CL which is a (grand-; and so forth)child of this CL will also gain access to the class definitions loaded by any of the parental CL.
If IDoMagic needs to be loaded by a custom CL, Foo must not be loaded by the system CL but with either the custom CL or a child of this CL in order for the delegation strategy to kick in and provide the definition for IDoMagic if Foo is loaded/instantiated.
There is a custom delegation CL model where shared classes are kept in a kind of common CL list/array which may be used by dependend CL. The dependend classes are not direct children of the common CLs but are children to a delegation CL which simply delegates calls to the common ones before asking the parent if neither of the children was able to execute the task. One solution here might be a structure like this:
bootstrap CL
- system CL
  - delegation CL
    - common CL
    - plugin CL
      - plugin 1 CL
      - plugin 2 CL

Here, the delegation CL needs to delegate an invocation of loadClass(...) and findClass(...) to its contained common CL (object composition) and only if it couldn't find a definition delegate the call to his parent. Similar to this still experimental class
This delegation loader enables to load IDoMagic with the common CL f.e. and the Foo class with one of the plugin loaders, which is not a direct child of the common CL. However, this requires that the delegation CL propagetes all calls to the common CL first before asking the parent. Also, this delegation loader brings some overhead to the table as it makes one of the adavandages of custom CL (the unloading of unused classes) more difficult.

A: If a class loader receives a class load request, it does not self-load
Instead, the request is delegated to the loader of the parent class. If the parent class loader still has its own parent class loader, it is further requested
The request will eventually reach the top-level starting class loader, and if the parent class loader can complete the class loading task, it will return successfully
If the parent loader is unable to complete the load task, the child loader will try to load it itself. This is the two-parent delegation model.


text:
Q: Change the order of the y-axis values I'm using the ggplot R package, I did this plot with the code below:
p3 = data.frame(cbind(c(1:70),
                      c("G1" ,  "G2" ,  "G1" ,  "G1" ,  "G1" ,  "G2"  ,   "G1" ,  "G1" ,  "G1" ,  "G1" ,  "G1" ,  "G1" ,  "G1",
                        "G1" ,  "G1" ,  "G1" ,  "G1" ,  "G1" ,  "G1" ,  "G1" ,  "G1" ,  "G2" ,  "G1" ,  "G2"  ,   "G1" ,  "G1"  ,
                        "G1" ,  "G1" ,  "G1" ,  "G2" , "G1" ,  "G1" ,  "G1" ,  "G1" ,  "G1" ,  "G1" ,  "G1" ,  "G1" ,  "G1"  ,
                        "G1" ,  "G1" ,  "G1" ,  "G1" ,  "G1" ,  "G1" ,  "G1" ,  "G1" ,  "G1" ,  "G1" ,  "G1" ,  "G1" ,  "G1" ,
                        "G1" ,  "G1" ,  "G1" ,  "G1" ,  "G2" ,  "G1" ,  "G1" ,  "G1" ,  "G1" ,  "G1" ,  "G1" ,  "G1" ,  "G1" ,
                        "G1" ,  "G1" ,  "G1" ,  "G1" ,  "G2"),
                      c(rep("B",35),rep("C",15),rep("A",20))
))

colnames(p3)=c("Num","L" , "G")

library(ggthemes)
library(ggplot2)

pp <- ggplot(p3, aes(Num, G)) +
  geom_tile(aes(fill = L), colour = "white")
pp + theme(legend.position="bottom", axis.text.x  = element_text(angle=90, size=7,vjust=0.5)) + # scale_fill_grey() + theme_classic()
  scale_fill_manual(values=c("#990000","#E69F00","#999999"))

I would like to change the order of y-axis values according to the number of bars (= variable G)
The expected plot:

Thanks a lot for your helps !

A: Change levels for p3$G according to sorted table of p3$G variable:
p3$G <- factor(p3$G, names(sort(table(p3$G))))

sort(table(p3$G))
# C  A  B
# 15 20 35

A: You can set how you want the G column of your dataframe to be ordered by setting it to type factor, and setting the levels. This can all be done with:
levels(p3$G) <- c("C", "A", "B")


text:
Q: Is there an infix version for routine invocation in perl 6? Say I want to apply an array of functions to an array of objects. Something like this:
my $a = sub ($) { $_ * 2 };
my $b = sub ($) { $_ / 2 };

my @funcs = ($a, $b);

my @ops = @funcs.roll(4);

I could do
say  ^10 ».&» @ops;

but .& is a postfix operator; same thing for >>., which could be used for a single function, however. Using
say  ^10 Z. @ops;

with . actually being the infix operator for calling a method, yields an error about mistaking it for the concatenation operator. I don't think I have any other option left. Any idea?

A: You could use the &infix:« o » / &infix:« ∘ » operator, combined with a lambda/closure factory.
sub lambda-factory ( +in ) {
  in.map: -> \_ { ->{_} }
}

my @funcs = (
  * * 2,
  * / 2
);

(@funcs X∘ lambda-factory ^10)».()
# (0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5)

(@funcs «∘» lambda-factory ^10)».()
# [0, 0.5, 4, 1.5, 8, 2.5, 12, 3.5, 16, 4.5]

( (|@funcs xx *) Z∘ lambda-factory ^10 )».()
# (0, 0.5, 4, 1.5, 8, 2.5, 12, 3.5, 16, 4.5)

A: If you have defined values, you can use the infix operator andthen.
    say (^10 »andthen» (* * 2, * / 2).roll(4))

A: If you roll your own infix equivalent of .& the construct you are trying to create seems to work fine.
$ perl6 -e 'my sub infix:<foo> ($a, $b) { $b($a) }; say ^10 Z[foo] (-> $_ { $_*2 }, -> $_ { $_/2 }).roll(4);'
(0 0.5 1 6)


text:
Q: pros and cons of incremental vs differential backup? Back In Time says it saves full copies of changed files. And it links unchanged files via hardlinks. So this is a incremental backup.
What are Pros and Cons of an incremental backup (like done with Back In Time) vs a differential backup?
When should I choose one over the other?

A: While your questions is out of policies on this site, I think it may be helpful for others, so I would try to clarify it a little.
Terms incremental and differential backups mostly are very misleading and hard to understand. There no exact answer to the question - which one method is better than other because of different backup technologies implemented by some particular software and also different needs for backups. Someone need to have full snapshot in time that includes all files at backup time but other need to save only files that was changed from last backup.
Also, different operation system has some filesystem's capabilities that doesn't exist on other systems so implementation of differential and incremental backup will be very differ.
Basically all differential backups saving only data that was changed since last FULL backup.  While backuping only new changes relatively to the full backup are small, over time it start growing more and more since there would be a big difference between original full backup and current stage.
In contrast to differential backup, - incremental backups also saving only changed data, but it only saving the data that has changed since the last backup — be it a full or incremental backup. Incremental backups aren't growing as crazy as differential ones that's why it isn't so critical to take often full backup over time. As far as full chain of backups that beginning from full backup up to the last incremental one kept unchanged then it isn't a problem to recover data to the stage in previous time without sacrificing space on a backup storage.
Advantage of differential backup is that you need only two backups, the full one and that differential one that you need to restore in previous time.
With incremental backups, one need to restore full chain of backups staring from full backup.
This is the primary difference between differential and incremental backup.
For example, take a look at tar that can do classic incremental backup. I posted no so long ago example of incremental backup here that using tar utility. tar in that script creating dedicated, separate file where it keeps all changes(include deletion). This file keeps stage of last incremental backup. It easy to check if one would open intermediate incremental backup file and will found only changed/new files and directories that happened since last backup only. This solution works very well to keep backups that wouldn't be accessed often (thanks to compression). To restore completely such archives, one need to unpack first (level=0) full backup and sequentially restore all incremental (level=1) backup in order as it was saved. A little longer process of restoration to compare with differential, but backups will be kept as small as possible.
BackInTime that you referenced in your question is basically a wrapper around rsync utility.
Here is example of incremental backup that utilize rsync capability to create incremental snapshots.
It is a little different to classic incremental backup because such solution creating a copy of the data as if it were frozen at a specific point in time, it includes all files and directories that were a subject of backup.
In comparison to tar, such solution create snapshots in time, so if you check any snopshot it will include the whole directories and files as it was at time of backup. While it looks like a full backup, in fact it isn't, because rsync don't copy/create files that already exist in previous backup, but instead rsync creates hard links to existing data that prevent wasting space on backup device. This way such snapshots will be incremental but it would looks like a full backup in the same time.
Such solution is very helpful if one need to access backuped data as soon as possible without spending time on unpacking and would see exact stage of snapshot in time that one needed.
I hope this information would help someone when one counting Pros and Cons regarding differential vs incremental backup.

A: I think "full-copy-backups" have these advantages:

*

*only corrupt files on the filesystem are lost, all others can be restored

*deleted files on the backup-drive can more likely be restored (I hope this can be understood)

*restoring files is faster

More answers are welcome .


text:
Q: Intel HDMI-1 disconnected Xrandr I did a fresh install of Lubuntu 20.04, I had to use "graphic safe mode". My monitor is showing the boot screen / BIOS. If I add nomodeset to GRUB, it works with 800x600 resolution. It's a touchscreen with built in PC from RC Stars.
I installed TeamViewer when using "nomodeset". The monitor is completely black but I can reach the computer through TeamViewer.
Answers for this questions I've found after a day of googling doesn't help and the answers is quite similar.
sudo lspci -v
00:02.0 VGA compatible controller: Intel Corporation HD Graphics 5500 (rev 09) (prog-if 00 [VGA controller])
    DeviceName:  Onboard IGD
    Subsystem: Intel Corporation HD Graphics 5500
    Flags: bus master, fast devsel, latency 0, IRQ 45
    Memory at f6000000 (64-bit, non-prefetchable) [size=16M]
    Memory at e0000000 (64-bit, prefetchable) [size=256M]
    I/O ports at f000 [size=64]
    Expansion ROM at 000c0000 [virtual] [disabled] [size=128K]
    Capabilities: [90] MSI: Enable+ Count=1/1 Maskable- 64bit-
    Capabilities: [d0] Power Management version 2
    Capabilities: [a4] PCI Advanced Features
    Kernel driver in use: i915
    Kernel modules: i915

xrandr
Screen 0: minimum 8 x 8, current 1024 x 768, maximum 32767 x 32767
eDP1 connected primary 1024x768+0+0 (normal left inverted right x axis y axis) 0mm x 0mm
   1024x768      60.00*+
   1024x576      59.90    59.82
   960x540       59.63    59.82
   800x600       60.32    56.25
   864x486       59.92    59.57
   640x480       59.94
   720x405       59.51    58.99
   640x360       59.84    59.32
   512x384       60.00
DP1 disconnected (normal left inverted right x axis y axis)
HDMI1 disconnected (normal left inverted right x axis y axis)

xrandr --output HDMI1 --auto --right-of eDP1
Doesn't do anything

uname -a
5.8.0-45-generic #51~20.04.1-Ubuntu SMP Tue Feb 23 13:46:31 UTC 2021 x86_64 x86_64 x86_64 GNU/Linux

sudo xrandr --addmode HDMI1 1920x1080
xrandr: cannot find mode "1920x1080"

How do I troubleshoot to find out the problem? Windows installation works, but none of the Ubuntu distros/versions I've tried has worked


text:
Q: How to extract ul that comes after a particular tag (HTML Parsing) From the below HTML snippet I want to extract ul with all li (as highlighted) which comes just after h2 tag which has span id="See_also"

I am using Jsoup for HTML parsing in Java.

A: Well, after exploring the documentation of Jsoup I found the solution:
Elements ul= html.select("h2:has(span:contains(See Also))+ul");


text:
Q: Collections.synchronizedMap(Map) after migration to Linux - second Thread doesn't see new entry I have the following issue after trying to run my webapplication on Linux server.
When running on windows, everything works perfectly (simplified version) - call send() method, wait for JMS response on synchronizer object, send the response to client)...
When started on linux server (same JVM version - 1.7, bytecode - java 1.5 version), I get response only for the first message, and following error in log for the rest of the messages:
synchronizer is null /*my_generated_message_id*/

It looks like JMS message listener thread cannot see new entries (created in JMS sender Thread) in synchronizers map, but I don't understand why...
Synchronizers Map definition:
public final Map<String, ReqRespSynchro<Map>> synchronizers
    = Collections.synchronizedMap(new HashMap<String, ReqRespSynchro<Map>>());

Sending JMS request with active response awaiting:
@Override
public Map send(Map<String,Object> params) {
    String msgIdent  = ""/*my_generated_message_id*/;
    Map response = null;

    ReqRespSynchro<Map> synchronizer = synchronizers.get(msgIdent);
    if (synchronizer == null) {
        synchronizer = new ReqRespSynchro<Map>();
        synchronizers.put(msgIdent , synchronizer);
    }

    synchronized(synchronizer) {
        try {
                sender.send(params);
        } catch (Exception ex) {
            log.error("send error", ex);
        }

        synchronizer.initSendSequence();
        int iter = 1;
        try {
            while (!synchronizer.isSet() && iter > 0) {
                synchronizer.wait(this.waitTimeout);
                iter--;
            }
        } catch (Exception ex) {
            log.error("send error 2", ex);
            return null;
        } finally {
            response = (synchronizers.remove(msgIdent )).getRespObject();
        }
    }
    return response;
}

JMS onMessage response processing (separate thread):
public void onMessage(Message msg) {
        Map<String,Object> response = (Map<String,Object>) om.getObject();
        String msgIdent = response.getMyMsgID(); ///*my_generated_message_id*/

        ReqRespSynchro<Map> synchronizer = synchronizers.get(msgIdent);
        if (synchronizer != null) {
            synchronized (synchronizer) {
                msgSynchronizer.setRespObject(response);
                synchronizer.notify();
            }
        } else {
            log.error("synchronizer is null " + msgIdent);
        }
}

Synchronizer class:
public class ReqRespSynchro<E> {
    private E obj = null;

    public synchronized void setRespObject(E obj) {
        this.obj = obj;
    }

    public synchronized void initSendSequence() {
        this.obj = null;
    }

    public synchronized boolean isSet() {
        return this.obj != null;
    }

    public synchronized E getRespObject() {
        E ret = null;
        ret = obj;
        return ret;
    }
}

A: Your code bears the "check-then-act" anti-pattern.
ReqRespSynchro<Map> synchronizer = synchronizers.get(msgIdent);
if (synchronizer == null) {
    synchronizer = new ReqRespSynchro<Map>();
    synchronizers.put(msgIdent , synchronizer);
}

Here, you first check whether the synchronizers contains a particular mapping then you act by putting a new mapping when the mapping is not present, but by the time you act, there is no guaranty that the condition you have checked still holds.
While the map returned by Collections.synchronizedMap guarantees thread-safe put and get methods, it does not (and can't) guaranty that there won't be an update between subsequent invocation of get and put.
So if two threads execute the code above, there is the possibility that one thread puts a new value while the other already has performed the get operation but not the put operation and will therefore proceed with putting a new value, overwriting the existing. So the threads will use different ReqRespSynchro instances and so will the other threads get either of these from the map.
The correct use would be to synchronize the entire compound operation:
synchronized(synchronizers) {
    ReqRespSynchro<Map> synchronizer = synchronizers.get(msgIdent);
    if (synchronizer == null) {
        synchronizer = new ReqRespSynchro<Map>();
        synchronizers.put(msgIdent , synchronizer);
    }
}

It's a common mistake to think that by wrapping a map or collection into a synchronized one, every thread safety issue was solved. But you still have to think about access patterns and guard compound operations manually, so sometimes you're better off using manual locking only and resist the temptation of easy-to-use synchronized wrappers.

But note the ConcurrentMap was added to the Java API to address this use pattern (amongst others).
Change the map declaration to
public final ConcurrentHashMap<String, ReqRespSynchro<Map>> synchronizers
    = new ConcurrentHashMap<>();

This map provides thread safe put and get methods, but also methods allowing to avoid the "check-then-act" anti-pattern for updates.
Using the ConcurrentMap under Java 8 is especially easy:
ReqRespSynchro<Map> synchronizer = synchronizers
    .computeIfAbsent(msgIdent, key -> new ReqRespSynchro<>());

The invocation of computeIfAbsent will get the ReqRespSynchro<Map>, if there is one, otherwise the provided function will be executed to compute a value which will get stored, all with atomicity guaranty. The places where you simply get an existing instance need no change.
The pre-Java 8 code is a bit more convoluted:
ReqRespSynchro<Map> synchronizer = synchronizers.get(msgIdent);
if (synchronizer == null) {
    synchronizer = new ReqRespSynchro<>();
    ReqRespSynchro<Map> concurrent = synchronizers.putIfAbsent(msgIdent , synchronizer);
    if(concurrent!=null) synchronizer = concurrent;
}

Here, we can't perform the operation atomically, but we are able to detect if a concurrent update happened in-between. In this case, putIfAbsent will not modify the map but return the value already contained in the map. So if we encounter such a situation, all we have to do is to use that existing one instead of the one we attempted to put.

A: This could happen if your waitTimeout in send() method is too short. You only have one iteration set for the waiting cycle. So the msgIdent entry may be removed from the map in finally block in send before it can be read in onMessage(): wait timeout expires, iteration counter is decremented, thread exits the cycle and removes the entry from map.
Even if waitTimeout is long enough you may experience a so-called spurious wakeup:

A thread can also wake up without being notified, interrupted, or timing out, a so-called spurious wakeup. While this will rarely occur in practice, applications must guard against it by testing for the condition that should have caused the thread to be awakened, and continuing to wait if the condition is not satisfied.

By the way why don't you send response back via JMS without some cryptic synchronization? Here is an example for ActiveMQ message broker: How should I implement request response with JMS?


text:
Q: How to prove greedy is correct to uva 10026 The original program description is:

A shoemaker has N orders from customers which he must satisfy. The shoemaker can work on only one job in each day, and jobs usually take several days. For the ith job, the integer Ti ( 1$ \le$Ti$ \le$1, 000) denotes the number of days it takes the shoemaker to finish the job.
But popularity has its price. For each day of delay before starting to work on the ith job, the shoemaker has agreed to pay a fine of Si ( 1$ \le$Si$ \le$10, 000) cents per day. Help the shoemaker by writing a program to find the sequence of jobs with minimum total fine.
Input
The input begins with a single positive integer on a line by itself indicating the number of the test cases, followed by a blank line. There is also a blank line between two consecutive cases.
The first line of each case contains an integer reporting the number of jobs N, where 1$ \le$N$ \le$1, 000. The ith subsequent line contains the completion time Ti and daily penalty Si for the ith job.
Output
For each test case, your program should print the sequence of jobs with minimal fine. Each job should be represented by its position in the input. All integers should be placed on only one output line and each pair separated by one space. If multiple solutions are possible, print the first one in lexicographic order.
The output of two consecutive cases must be separated by a blank line.
Sample Input
1
4
3 4
1 1000
2 2
5 5
Sample Output
2 1 3 4

On Internet, I see the best solution is greedy on job's ratio of time and fine. But I don't think it is as simple as self-explanatory, so how to prove it strictly? Thanks!

A: Thanks, @mrmcgrep. I got the answer as this:
Let's say we have job 1, 2, ..., n, and they have time and fine as t1, f1, t2, f2, ..., tn, fn
and they are in the order of t1/f1 <= t2/f2 <= t3/f3 <= ... <= tn/fn
So this is the objective schedule. Now we change 1 with m (1 < m <= n)
By the original order, we need pay fine as much as:
F1 = t1 * (f2 + ... + fn) + t2 * (f3 + ... + fn) + ... + tm * (fm+1 + ... + fn) +  R
By the new order, we need pay fine as much as:
F2 = tm * (f1 + ... + fm-1 + fm+1 + ... + fn) + t1 * (f2 + ... + fm-1 + fm+1 + ... + fn) + ... + fm-1 * fm+1 + ... + fn) + R
F1 - F2 = (t1 + t2 + ... + tm-1) * fm - (tm * f1 + tm * f2 + ... + tm * fm-1)
As t1 * fm <= tm * f1, t2 * fm <= tm * f2, ..., tm-1 * fm <= tm * fm-1
F1 - F2 <= 0
So the original order is the best order.


text:
Q: What is a good book for self learning in geometry and topology and physics? I am a graduate student in physics. I want to self-study topology geometry and physics. I use the book of Nakahara with the same title. However, this book is not convenient for self-study in my opinion. I have the following problems while studying this book;

*

*There are not enough number of examples. When a mathematical definition is given, it is very easy to misunderstand it. And it is very hard to have an intuition on the idea presented. The definitions and the presentation are very concise, so in order have a feeling of what actually the presented ideas means, I usually need to address youtube to see whether someone explained already, however not everything is on youtube.

*There is an inconsistency on the notation, and there are also typos. So if you are learning it for the first time, this inconsistency can made some concepts impossible to grasp.

The good part of this book is, the topics covered are exactly what I need.
Thus do you have any book to complement this book with a more intuitive explanation, which is self-study friendly, and with more examples. Or even better, do you know any book that treats the same topic in a more pedagogical manner.
I specifically ask a book that covers same topics with  Nakahara's chapters 2-10  which is pedagogical and suitable for self-learning, or a book to complement this one.
the contents of the nakahara's book is here


text:
Q: read full database path on asp classic to new server Currently we use a windows 2003 (IIS 6.0) server with SQL Server 2008 R2 that runs perfectly a asp classic code. We are migrating to windows 2016 server with the same version of SQL Server. In most of the code it was necessary to put the full database path. The original that works on the other server, e.g.:

SELECT * from File

when changing to

SELECT * from [TABLE].[dbo].[File]

the new server can execute and read correctly.
In the part that the code itself has the legible queries is easy to understand. I do not know the asp classic well and the original code has variables with the same table name so I do not know if the called code item is actually the table or the variable.
I think it's something from the environment to set up. Would it be possible to resolve this without having to change the whole code?
I try to understand the error from logfile from IIS.

A: Maybe someone have the same situation, I solve this change the DSN connection (ODBC)
Dim rs
Dim conexao

Set conexao = Server.CreateObject("ADODB.Connection")
conexao.Open "DSN=database","sa","password1234"

I change the last line to use Provider too like example:
conexao.Open "Provider=SQLNCLI10;Server=nameserver\nameinstance;Database=namedatabase;UID=sa;PWD=password1234;"


text:
Q: How to deal with " RangeError: Maximum call stack size exceeded" I'm developping an express API. It runs well on my computer but on my server I meet the following exception:

RangeError: Maximum call stack size exceeded

The code consist in reading a file of ~400000 lines. Then it loops on each line and have a recursive call of depth 15 at most on it.
I read about setImmediate and process.nextTick but I'm not sure on how or where to use them.
Any idea of what's happening and how to fix it?
I already tried to change stack size (to the size of my file) but it it doesn't solve this problem. I suppose it's more a structural problem.
Sample code
const bigProcess = () => {
    const processLine = (line) => {
        let l = line && line.charAt(0);
        if (l) {
            if (line.length > 1) {
                processLine(line.substring(1));
            } else {
                console.log('line processed.');
            }
        }
    };

    var data = fs.readFileSync("myfile.txt", "utf-8");
    var lines = data.toString().split("\r\n");
    for (var line of lines) {
        processLine(line);
    }
};

Here is my full output:

RangeError: Maximum call stack size exceeded
      at String.charAt ()
      at processLine (/home/sinsedrix/myapi/bigprocess.js:7:30)
      at processLine (/home/sinsedrix/myapi/bigprocess.js:14:17)
      at processLine (/home/sinsedrix/myapi/bigprocess.js:14:17)
      at processLine (/home/sinsedrix/myapi/bigprocess.js:14:17)
      at processLine (/home/sinsedrix/myapi/bigprocess.js:14:17)
      at processLine (/home/sinsedrix/myapi/bigprocess.js:14:17)
      at processLine (/home/sinsedrix/myapi/bigprocess.js:14:17)
      at processLine (/home/sinsedrix/myapi/bigprocess.js:14:17)
      at processLine (/home/sinsedrix/myapi/bigprocess.js:14:17)
      at processLine (/home/sinsedrix/myapi/bigprocess.js:14:17)
      at processLine (/home/sinsedrix/myapi/bigprocess.js:14:17)
      at processLine (/home/sinsedrix/myapi/bigprocess.js:14:17)
      at processLine (/home/sinsedrix/myapi/bigprocess.js:14:17)
      at processLine (/home/sinsedrix/myapi/bigprocess.js:14:17)
      at processLine (/home/sinsedrix/myapi/bigprocess.js:14:17)
      at processLine (/home/sinsedrix/myapi/bigprocess.js:14:17)
      at processLine (/home/sinsedrix/myapi/bigprocess.js:14:17)
      at processLine (/home/sinsedrix/myapi/bigprocess.js:14:17)
      at processLine (/home/sinsedrix/myapi/bigprocess.js:14:17)
      at processLine (/home/sinsedrix/myapi/bigprocess.js:14:17)
      at processLine (/home/sinsedrix/myapi/bigprocess.js:14:17)


text:
Q: How do I add open graph tags? I'm using the Wordpress CMS. I don't have access to the theme's code etc..
So how do I update the opeh graph tags? I'm mainly looking to add an image to go along with it, as it's using the default WordPress image when I share on Facebook.
Thanks!

A: Do you have access to (installing) plugins?
There are several plugins that lets you add the Open Graph tags: http://wordpress.org/extend/plugins/search.php?q=open+graph

A: Here's the way I did after finding a solution via google.  This seems to work an pulls an image based on the featured image set on a post.  If it is a main page or a post/page with no featured image, there is a conditional statement which allows you to set a static image.
<!-- facebook integration -->
<meta property="fb:app_id" content="YOUR FACEBOOK APP ID" />
<meta property="fb:admins" content="YOUR FACEBOOK ADMIN CODE" />
<?php if (is_single() || is_author()) { ?>
<meta property="og:site_name" content="<?php bloginfo('name'); ?>" />
<meta property="og:url" content="<?php the_permalink() ?>"/>
<meta property="og:title" content="<?php wp_title(); ?>" />
<meta property="og:description" content="<?php echo strip_tags(get_the_excerpt($post->ID)); ?>" />
<meta property="og:type" content="article" />
<meta property="og:image" content="<?php if (function_exists('wp_get_attachment_thumb_url')) {echo wp_get_attachment_thumb_url(get_post_thumbnail_id($post->ID)); }?>" />
<?php } else { ?>
<meta property="og:site_name" content="<?php bloginfo('name'); ?>" />
<meta property="og:url" content="<?php the_permalink() ?>"/>
<meta property="og:title" content="<?php wp_title(); ?>" />
<meta property="og:description" content="<?php bloginfo('description'); ?>" />
<meta property="og:type" content="website" />
<meta property="og:image" content="LINK TO IMAGE TO USE FOR THUMBNAIL HERE" /> <?php } ?>

Sorry, just noticed you said you didnt have access to the code.  I guess a plugin is your only route.  If you can get access to the header, you can try my code snippet above.
Yes, a plugin that can do it:  http://wordpress.org/extend/plugins/facebook-open-graph-meta-in-wordpress/
And more info (another way of) doing this on this code route:  http://www.wpbeginner.com/wp-themes/how-to-add-facebook-open-graph-meta-data-in-wordpress-themes/


text:
Q: Ubuntu 14.04.1 - Unity Tweak Tool not working? I've been trying to use Unity Tweak Tool to apply the Numix icon and GTK themes, but it won't work at all.
The only thing I've even done in Ubuntu after installing it is just using Compiz to make the top bar transparent. Would this cause it?

A: Have same problem over here, tried with suggestion from http://ubuntuforums.org/showthread.php?t=2205981&page=2
After dist-upgrade, mostly seem to work.
Copied answer from thread:
sudo apt-get purge unity-tweak-tool
remove ppa if installed in repository
delete the contents of "var/cache/apt/archives/"
sudo apt-get update
sudo apt-get dist-upgrade
install unity-tweak-tool from Software Center


text:
Q: Syntax for selecting messages by Jms ID What is the correct syntax for selecting messages based on their corresponding JMS ID?
Currently I use:
String selector = "JMSMessageID='ID:305:1:5:1:1'";
messageConsumer = session.createConsumer(getRetryQueue(), selector);

The above syntax works in test with a mocked broker. But towards ActiveMQ the messages are not polled.
Original code:
@Override
public Message readMessageFromRetryQueueByJmsId(String jmsId) throws QueueingException {
    Connection connection = null;
    Session session = null;
    MessageConsumer messageConsumer = null;
    Message message = null;
    try {
        connection = getConnectionFactory().createConnection();
        session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        messageConsumer = session.createConsumer(getRetryQueue(), "JMSMessageID='"+jmsId+"'");
        message = messageConsumer.receiveNoWait();
    } catch (JMSException e) {
        throw new QueueingException("Failed to read message from MessageConsumer.");
    } finally {
        try { messageConsumer.close(); } catch (Exception e) { /* NOP */ }
        try { session.close(); } catch (Exception e) { /* NOP */ }
        try { connection.close(); } catch (Exception e) { /* NOP */ }
    }
    return message;
}

A: Messages were not read since the connection was never started.
Corrected code:
@Override
public Message readMessageFromRetryQueueByJmsId(String jmsId) throws QueueingException {
    Connection connection = null;
    Session session = null;
    MessageConsumer messageConsumer = null;
    Message message = null;
    try {
        connection = getConnectionFactory().createConnection();
        session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        connection.start();
        messageConsumer = session.createConsumer(getRetryQueue(), "JMSMessageID='"+jmsId+"'");
        message = messageConsumer.receiveNoWait();
    } catch (JMSException e) {
        throw new QueueingException("Failed to read message from MessageConsumer.");
    } finally {
        try { connection.close(); } catch (Exception e) {}
    }
    return message;
}


text:
Q: Why simple_form raises "undefined method `model_name' for NilClass:Class"? I'm studying how to use simple_form gem at index.html.erb from my user's folder. I have no success. The weird thing is that it is working at _form.html.erb. Why?
users_controller.rb

def index
   @users = User.find_by_sql(["SELECT id, name, login, password
                               FROM users"])
end

users/index.html.erb
<%= simple_form_for @users do |f| %>

    <%= f.input :name %>

  .
  .
  .

    <%= f.button :submit %>

<% end %

It is raising this exception: undefined method `model_name' for NilClass:Class
Any ideas?

A: You are trying to create a form for an array of users, but simple_form_for takes a single record, not an array. If what you want is a list of forms, one for each user, then this would do that:
users/index.html.erb
<% @users.each do |user| %>
  <%= simple_form_for user do |f| %>

      <%= f.input :name %>

      <%= f.button :submit %>

  <% end %>
<% end %>

But this seems like a strange thing to do, shouldn't this form be on your new page, and not the index page?
Alternatively, if you want to have a form for a user alongside a list of users on your index page, you would need to create that user in your index action:
def index
  @users = User.find_by_sql(["SELECT id, name, login, password
                           FROM users"])
  @user = User.new
end

Then you can create the form with simple_form_for @user do |f| ... in the view, and also access the list of users with @users.


text:
Q: How to find out if a number is a perfect square without using sqrt function or ** in Python? I have to write a program that finds out whether or not a number is a perfect square. The terms are I don't use a sqrt function or an exponent (**)
I previously showed my teacher my solution using exponent (**) and she told me not to include that there.
num=int(input("Enter a positive integer: "))
base=1
while num/base!=base:
    base=base+1
if (num/base)%1==0:
    print(num,"is a square")
else:
    print(num,"is not a square")

It works fine with perfect squares but when they're not, it won't work because I can't find a way to get it out of the while loop even though it's not a perfect square.

A: You can iterate till finding a value bigger than you number:
You are sure the while will finish since you have a strictly increasing sequence.
def is_perfect_square(x):
    i = 1
    while i*i < x:
        i += 1
    return i*i == x

print(is_perfect_square(15))
# False
print(is_perfect_square(16))
# True

A: You have to change
while num/base!=base:

to
while num/base>base:

and it will work.

A: The sum of the first odd integers, beginning with one, is a perfect square.
See proof

1 = 1
1 + 3 = 4
1 + 3 + 5 = 9
1 + 3 + 5 + 7 = 16
and so on .....

So here, we can make use of this important fact to find a solution without using pow() or sqrt() in-built functions.
num = int(input("Enter a positive integer: "))
odd = 1

while num > 0:
num -= odd
odd += 2
if num == 0:
print('It is a pefect square')
else:
print('It is not a pefect square')

A: Instead of dividing and taking the remainder, multiply the base and see if it matches the number you are testing. For instance.
for i in range(1, num + 1):
    sq = i * i
    if sq == num:
        print(f"{i} squared is exactly {num}")
        break
    if sq  > num:
        print(f"{num} is not a perfect square")
        break

You might get a better mark if you do something more clever than increment from 1. A binary search would speed things up a lot for large numbers.

A: I guess it is not a place to answer such questions, but here is a super straightforward solution without using any tricks.
num=int(input("Enter a positive integer: "))
for i in range(num + 1): # in case you enter 1, we need to make sure 1 is also checked
    pow = i * i
    if pow == num:
        print('%d is a pefect square' % num)
        break
    elif pow > num:
        print('%d is not a pefect square' % num)
        break

A: Here is something that I came up with:
from math import *
num = eval(input('Enter a number: '))
sq = sqrt(num)
sq1 = sq%1 #here we find the decimal value and then..
if sq1 == 0.0: #if the value = 0 it is a perfect square else it is not, only perfect
squares will be whole numbers.
    print(f'{num} is a perfect square')
else:
    print(f'{num} is not a perfect square')

A: Hey Buddy Try This Code,
num=int(input("Enter a positive integer: "
base=1
while num/base>base:
    base=base+1
    if (num/base)%1==0:
        print(num,"is a square")
    else:
        print(num,"is not a square")

It should work I tried it
Jai hind jai bharat


text:
Q: Vertical align multiple image with different height I got a Carroussel script which display all the users of the site i'm working on. This carroussel displays the avatar of the users.
I try to align verticaly the avatar's but i can't get it right...
I also check the other subject on the internet (like http://codepen.io/chriscoyier/pen/oJeAK) , but nothing really match my needs...
Here is my CSS code :
#author-sorter {
    padding: 20px 30px;
    margin-right: 2px;
    width:900px;
}
#author-sorter > * {
    vertical-align: middle;
}
#author-sorter ul li {
    float: left;
}
#author-sorter ul li a {
    width: 48px;
    height:48px
}
#author-sorter ul li a:hover img, #author-sorter ul li.now a img {
    border: 1px solid #bcd001;
    width: 48px;
}
#author-sorter ul li.now {
    position:relative;
}

I made a live version here : http://jsfiddle.net/ev2wD/
Any tips ?

A: Here you go.
WORKING DEMO
The HTML:

The CSS:
#author-sorter {
    padding: 20px 30px;
    margin-right: 2px;
    width:900px;
}
#author-sorter > * {
    vertical-align: middle;
}
#author-sorter ul li {
    float: left;
}
#author-sorter ul li a {
    width: 48px;
    height:48px;
    display: table-cell;
vertical-align: middle;
}
#author-sorter ul li a:hover img, #author-sorter ul li.now a img {
    border: 1px solid #bcd001;
    width: 48px;
}
#author-sorter ul li.now {
    position:relative;
    vertical-align: middle;
display: table-cell;
}

Hope this helps.

A: I simplified the example to be used by other people:
add the CSS style display:table-row; and display:table-cell; to
 and
 respectively.


text:
Q: Is there some elegant way to manipulate my ndarray I have a matrix named xs:
array([[1, 1, 1, 1, 1, 0, 1, 0, 0, 2, 1],
       [2, 1, 0, 0, 0, 1, 2, 1, 1, 2, 2]])

Now I want to replace the zeros by the nearest previous element in the same row (Assuming that the first column must be nonzero.).
The rough solution as following:
In [55]: row, col = xs.shape

In [56]: for r in xrange(row):
   ....:     for c in xrange(col):
   ....:         if xs[r, c] == 0:
   ....:             xs[r, c] = xs[r, c-1]
   ....:

In [57]: xs
Out[57]:
array([[1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1],
       [2, 1, 1, 1, 1, 1, 2, 1, 1, 2, 2]])

Any help will be greatly appreciated.

A: If you can use pandas, replace will explicitly show the replacement in one instruction:
import pandas as pd

import numpy as np

a = np.array([[1, 1, 1, 1, 1, 0, 1, 0, 0, 2, 1],
              [2, 1, 0, 0, 0, 1, 2, 1, 1, 2, 2]])

df = pd.DataFrame(a, dtype=np.float64)

df.replace(0, method='pad', axis=1)

A: My version, based on step-by-step rolling and masking of initial array, no additional libraries required (except numpy):
import numpy as np

a = np.array([[1, 1, 1, 1, 1, 0, 1, 0, 0, 2, 1],
              [2, 1, 0, 0, 0, 1, 2, 1, 1, 2, 2]])

for i in xrange(a.shape[1]):
    a[a == 0] = np.roll(a,i)[a == 0]
    if not (a == 0).any():             # when all of zeros
        break                          #        are filled

print a
## [[1 1 1 1 1 1 1 1 1 2 1]
##  [2 1 1 1 1 1 2 1 1 2 2]]

A: Without going crazy with complicated indexing tricks that figure out consecutive zeros, you could have a while loop that goes for as many iterations as consecutive zeros there are in your array:
zero_rows, zero_cols = np.where(xs == 0)
while zero_cols :
    xs[zero_rows, zero_cols] = xs[zero_rows, zero_cols-1]
    zero_rows, zero_cols = np.where(xs == 0)


text:
Q: Testing Mobile Sites We are getting ready to launch a mobile site and are wondering what the best way of testing across as many mobile browsers as possible would be?
This could be a company that does this sort of thing, or a way in which to do it in-house, we're not being picky.

A: http://mobiready.com/launch.jsp?locale=en_EN
Emulators

*

*http://www.winwap.com/downloads.php

*http://developer.openwave.com/dvl/tools_and_sdk/phone_simulator/choosing.htm

*http://www.forum.nokia.com/info/sw.nokia.com/id/d57da811-c7cf-48c8-995f-feb3bea36d11/Nokia_Mobile_Internet_Toolkit_4.1.html

*http://msdn.microsoft.com/windowsmobile/downloads/tools/install/default.aspx

*http://emulator.mtld.mobi/emulator.php

*http://www.wapsilon.com/

A: It may be even more tricky than you think as operators may 'tweak' the look and feel of  phones in their network. Similarly they may use optimisers or content filters which will change how your site looks between networks (and even between APNs on the same network - i.e. a business APN may reduce picture resolution or block certain media types, while a normal consumer one would let everything through). I think this type of thing is becoming less prevalent as users with powerful smart phones and mobile broadband demand 'normal' wired like experience, but it does still exist and may be important for your site.
There is at least one company that offers a sort of virtual 'deploy anywhere' service so you can test your application or website on any phone type in any network (in theory, I am sure there are limits): http://www.deviceanywhere.com
Note I have nothing to do with these guys and have never used them, but the service they offer seems useful and I am sure they have some competitors you can look at also.

A: You may also want to try using Firefox and modifying the headers along with a user agent switcher.
Testing Mobile Web Sites Using Firefox

A: If you're about to launch, you've left it a bit late! Testing mobile web apps is a difficult job and should be done ongoing.  There are three things you can test:

*

*Assuming that you generate HTML specific to various mobile phones - you'll need to test your HTML generation. For this, use the Firefox UA switcher plugin. Note - this will do nothing to test how HTML is actually displayed on mobile devices, it will just test that your server side HTML generation is recognising different UA strings and rendering expected HTML

*Test mobile device browsers as much as possible. Somebody has already listed a bunch of emulators - I've had mixed results with these. They are a significant step up on just the Firefox UA switcher, but don't assume that these accurately emulate the mobile browser - think of it more as a useful guide

*Test mobile browser + mobile network. Someone else has also alluded to the fact that mobile carriers do funny things to the traffic. If your web app is targeted at a specific region, then get mobile phones from operators in that region and test on those operators networks. www.deviceanywhere.com is good for this, but limited in the regions it covers - namely North America & Western Europe.   Device Anywhere are not the only vendor in this area, but they are the only one's I've used.
In addition to this, try to identify the region & target audience for your app and from this come up with a short list of phones to cover.  e.g. If it is a business app, then think BlackBerry.  Also, make sure that your app is gathering statistics so you can see what devices are really accessing the site and ensure that these devices are on the list you test with in future.
Good luck!


text:
Q: Install postgis 2.2.1 on Ubuntu 18.04 Is it possible to install postgreSQL extension 'postgis' version 2.2.1 on Ubuntu 18.04 even if it is not listed anywhere in packages? The only version available is 2.4.4 and I have upgraded from Ubuntu 16.04 and there were not such issues.
I have tried aptitude and solution related to
Install PostGIS on Ubuntu 16.04 Xenial
And when somehow I have found the package, trying to install it returned similar errors, which are:
The following packages have unmet dependencies:

postgis : Depends: libgdal1h (>= 1.9.0) but it is not installable
          Depends: libgeos-c1 (>= 3.4.2) but it is not installable
          Depends: liblwgeom-2.3-0 (>= 2.0.0) but it is not going to be installed

I have also tried all commands like:
sudo apt-get update, upgrade, -f install  etc.

Has anyone encountered similar issue? Is there some kind of a workaround? I really need this particular version of postgis in order to run application. Using postgis 2.4.4 causes trouble with thegeom. For now the only solution I have is to install Ubuntu 16.04 again.


text:
Q: using VBA to find the last row of a merged cell I am trying to use find the last row of a merged cell with text and hide all rows beside that
For example:
A1:A5 is a merged cell with text "A", A6:A10 is a merged cell with text "B", etc
I want to write a code that would find the last row of the merged cell with text "B", and would hide any rows above or below the merged cell.
At the moment I am defining the rows to hide manually, but these change frequently so my method is not very efficient.
Any suggestions on how to find the last row instead?
Sub FindLastRow()

Dim ws As Worksheet

Set ws = ThisWorkbook.Sheets("Test")

'Hide all rows above B
ws.Rows("1:5").EntireRow.Hidden = True

'Hide all rows below B
ws.Rows("11:80").EntireRow.Hidden = True

End Sub

A: I guess you could try the following, making use of Range.Find and Range.MergeArea:
Sub Test()

Dim ws As Worksheet: Set ws = ThisWorkbook.Worksheets("Test")
Dim fullRng As Range, fndRng As Range

Set fullRng = ws.Range("A1:A80")
Set fndRng = ws.Range("A1:A80").Find(What:="B", Lookat:=xlWhole)

If Not fndRng Is Nothing Then
    fullRng.Rows.Hidden = True
    fndRng.MergeArea.Rows.Hidden = False
End If

End Sub


text:
Q: Help me! App crashes when selecting the check box Please look at my below code.
Is there any leaks or issues in my code since my application getting crashed when i select the check box.
Looking for any help...
Thanks!.
// checkbox at normal state
copyMailCheckbox = [[UIButton alloc] initWithFrame:CGRectMake( 150, 220,120 ,40 )];
UIImage *normalStateImage = [UIImage imageNamed:@"checkbox.jpg"];
[copyMailCheckbox setImage:normalStateImage forState:UIControlStateNormal];
[normalStateImage release];

// checkbox at selected state UIImage
UIImage *checkedStateImage = [UIImage imageNamed:@"checkbox-checked.jpg"];
[copyMailCheckbox setImage:checkedStateImage forState:UIControlStateSelected];   [checkedStateImage release];

// checkbox at highlighted state UIImage
UIImage *highlightedStateImg = [UIImage imageNamed:@"checkbox-pressed.jpg"];
[copyMailCheckbox setImage:highlightedStateImg forState:UIControlStateHighlighted];   [highlightedStateImg release];
[self addSubview:copyMailCheckbox];
[copyMailCheckbox release];

A: You have an allocation error here:
UIImage *normalStateImage = [UIImage imageNamed:@"checkbox.jpg"];
[copyMailCheckbox setImage:normalStateImage forState:UIControlStateNormal];
[normalStateImage release];

This UIImage object normalStateImage doesn't need you to call release on it. Remember the rule of allocations, if you call init, retain or copy, then you release the object. Otherwise, you should not do it because you don't have ownership on it.
PD:Also check please what sudo rm -rf is pointing.

A: This:
*checkedStateImage = [UIImage imageNamed:@"checkbox-checked.jpg"];

and this:
*highlightedStateImg = [UIImage imageNamed:@"checkbox-pressed.jpg"];

You're creating an unknown pointer or something.  I don't know how that got past the compiler warning, but you need to specify UIImage, for example...
   UIImage *highlightedStateImg = [UIImage imageNamed:@"checkbox-pressed.jpg"];

Also, I'd suggest that you use .png for images.  Although it's not required, it speeds up some image processing operations and is the generally recommended format for images.
Edit: It looks like your code was a typo, so please disregard this.


text:
Q: Orbeon - run batch file I need to run a kettle(ktr) file from the orbeon or more specifically from the xpl file. I was thinking of running a batch file but i cant find any step to do it. How can i run the batch/ktr file from within the xpl file?

A: To run external commands from XPL you van use the undocumented oxf:execute-processor, for instance (borrowed to XForms Unit):
<p:processor name="oxf:execute-processor">
    <p:input name="config" href="#control" transform="oxf:xslt">
        <exec executable="/home/vdv/projects/xformsunit/resources/apps/xformsunit/browser-run.sh"
            xsl:version="2.0">
            <arg
                line=" http://localhost:8080/orbeon/xformsunit/suite/{/*/name}/results?implementation=xsltforms&uid={/*/uid}"
            />
        </exec>
    </p:input>
    <p:output name="stdout" id="stdout" debug="stdout"/>
    <p:output name="stderr" id="stderr" debug="stderr"/>
    <p:output name="result" id="result" debug="result"/>
</p:processor>

AFAIK this processor hasn't been documented but you should be able to find more examples on the mailing list.


text:
Q: How to prove $\log A=V(\log A')V^{-1}$ https://en.wikipedia.org/wiki/Logarithm_of_a_matrix#Calculating_the_logarithm_of_a_diagonalizable_matrix
Suppose $A$ is a diagonalizable matrix, how to prove $\log A=V(\log A')V^{-1}$ where V is the matrix eigenvectors of $A$ and $A'$ is the diagonal matrix of corresponding eigenvalues?

A: First, each column of $V$ has to be orthnormal.
Comment: Each eigenvector can always be normalized, the key to notice is that, when there is a degeneracy, it's best to find the orthonormal basis of the degenerate state as well. The reason for this was to establish $VV^{-1}=I$
Second, $A=V(A')V^{-1}$, notice in the series expansion of $log(A)$, the term $(A-I)$ can be written as follow $(V(A')V^{-1}-I)=(V(A')V^{-1}-VV^{-1})=V(A'V^{-1}-IV^{-1})=V(A'-I)V^{-1}$, where it's power $(A-I)^n=V(A'-I)^nV^{-1}$.  Notice $(A'-I)$ is a diagonal matrix.
Thus $A=V log(A')V^{-1}$ as desired.


text:
Q: How make a 3 modules app, containing UI-Domain-Data layers Hi I was developing an App where I would like to use a 3 layer module app, but I don't really understand if I'm doing well.
What I want to do is a data-domain-ui arquitecture.
My arquitecture is the following:

So Am I doing well? and it's already a 3 layer app, or I should change in another way??
Thanks a lot in advance !


text:
Q: JSP hosting on Google App Engine? Any body hosted JSP in GoogleAppEngine...
I Expect the user experiences from GoogleAppEngine
Is it easy to maintain JSP/Servlet .
I have used another free webhosting service. But it wasn't nice to manage and use.

A: JSPs are a standard part of the Java GAE. So what exactly is you question?
What do you mean by your second sentence?

A: JSP and Servlet is still JSP and Servlet on Google App Engine. I have used it to call the Twitter API from the servlet and store it in their Memcache. It was just like writing any other application. However, when you deploy it, either it just works or you have no clue whats gone wrong. Bottomline - its very easy as long as it just works.

A: I've implemented an application based on a simple servlet serving JSON and storing/loading data directly using DataStore API (no JDO, JPA)


text:
Q: How to setup python 3.9 on my windows command prompt? It shows an error python not found I am trying since many hours, after watching several tutorials and reading many blogs I've setup variables as shown by them. Tried all of their methods to setup python3.9 on my windows cmd, but failed. I'm sharing some screenshots of my system variables and other things, please look into the problem and help me.

A: When you want to share on your post the errors you are getting, please insert them using the Code Sample function so that we can clearly read your errors and have a clear look at your situation.
Anyways, when you first install Python you have to option to automatically add Python to PATH, try uninstalling and checking that option.
If this doesn't work, paste inside your post the error you are getting.
EDIT: Can you share a screenshot of your Python directory?


text:
Q: Apply groups on already created menu I have developed a new module and in that module I have created a group in .xml file.
Now I want to apply that group in menus which are already created in other menu.
So can I apply groups to those menus?
I don't want to override the menu, I just want to apply groups in already created menus.
Thanks in advance.

A: Adding a group to an existing menu is done via the normal OpenERP record update mechanism. You don't actually have to fully redefine the existing menu record in your module, you just declare a <record> with the same ID, with only a value for the groups_id field:
    <record id="original_module.menu_id" model="ir.ui.menu">
        <!-- Use the special many2many value syntax to add a child record,
             and the `ref()` method to resolve the group XML ID -->
        <field name="groups_id" eval="[(4,ref('my_new_group_id'))]"/>
    </record>

You can find similar examples in the official OpenERP addons, such as the CRM module that makes the top-level Sales menu visible to some extra groups (l.48).

A: Instead of updating record, you can replace menuitem itself,
All you have to do is find menuitem that you want to override then add your code to it.
For example,
Already defined menu,
<menuitem id="menu_example" action="menu_action" name="Example Menu" parent="menu_example_parent" sequence="10"/>

Now suppose you want to add group to this menu,
<menuitem id="existing_module.menu_example" action="existing_module.menu_action" name="Example Menu" parent="existing_module.menu_example_parent" sequence="10" groups="group_example"/>

If it doesn't work then first delete that menu and after that write that menu again including your code.
For deleting menu,
<delete model="ir.ui.menu" id="module_name.menu_id" />

Hope this is helpful.

A: You can use this code for override groups list for a odoo menu :
    <function name="write" model="ir.ui.menu">
        <function name="search" model="ir.ui.menu">
            <value
            eval="[('id', '=', ref('module_name.menu_id'))]"
            />
        </function>
        <value eval="{'groups_id': [(6,0,[ref('module_name.group_example_1'), ref('module_name.group_example_2')])]}" />
    </function>


text:
Q: Get current URL in Nunjucks template? Seems like it should be pretty straightforward, but I'm having a really hard time finding an answer.
How do you find the current page's URL within a Nunjucks template?
Something like this would be perfect:
Some link

A: depends on attributes of your request obejct, if it's wsgi request from django, I simply print it as {{ request.build_absolute_uri }}

A: I find the following benefical if you have a single page URL that loads.
If you are building your gulp nunjucks projects with the help of browser-sync, you can build a relationship between the two, by accessing browser-sync's options through a callback.  Then pass that data back into a nunjucks environmental variable.
Here are the steps

*

*create an empty global variable

*user browserync's callback function to get a browsersync option for urls

*pass that value into the empty global variable in step 1

*now tell nunjucks to create an environmental variable that references the global variable from step 1.

*build the project.

*reference the nunjucks environmental variable in your template.

Below is an "idea" from your gulpfile.js file, but will require tweaking depending on your setup...

const browserSync = require('browser-sync');

//step 1
let mURL  = '';

//...

//step 4...
const manageEnvironment = function (environment) {
  environment.addGlobal('mURL', mURL);
}

function genNunJucks(cb) {
//...
   .pipe(nunjucksRender({
       manageEnv: manageEnvironment,
    });
//...
}

//...

const msync = browserSync.create();
function bSync(cb) {
msync.init({
        port: 49673,
        ui: {
            port: 3002,
        },
        listen: "gulp.wlc",
        browser: "default",
},
//step 2...
callbacks: {
    ready: function (err, bs) {
      //step 3...
      mURL = bs.options.getIn(['urls', 'local']);
    }
  }
});

//watch stuff...

}

//step 5
//npm start

//step 6...
/**
from witin your template, once the project is running,
you should have acces to {{mURL}},
and yes you can do Some link
all due to the help of browser-sync.
**/

A: Try something like this: {{ request.headers.referer }},
or this: {{ request.url }}.


text:
Q: i am trying to store my function call within an object i am trying to store my function call within an object, so when i refenence the property, it runs the function. this is the code i wrote, but its not working. this is my code so far.
html:
<!DOCTYPE html>
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Tetris(test)</title>
    <link rel="stylesheet" href="styleSheets/main.css">
    <script src = "https://code.jquery.com/jquery-3.4.1.js"></script>
    <script src = "js/jquery.1.js"></script>
    <script src = "js/main.js"></script>
  </head>
  <body>
      <svg id="container" width= "500" height= "650" style= "background-color: black" position= "relative">
      </svg>

  </body>
</html>

JS:
var svgNS = "http://www.w3.org/2000/svg";
var htmlNS = "http://www.w3.org/1999/xhtml";

function createShape1() {
    var elem = document.getElementById("container");
    var shape = document.createElementNS(svgNS, "rect");
        shape.id = "shape1";
        shape.style.width = "150px";
        shape.style.height = "50px";
        shape.style.fill = "orange";
        shape.style.y = "50px";
        shape.style.x = "150px"
        shape.style.position = "absolute"
        elem.append(shape);
    var shape2 = document.createElementNS(svgNS, "rect");
        shape2.id = "shape2";
        shape2.style.fill = "orange";
        shape2.style.x = "200px";
        shape2.style.width = "50px";
        shape2.style.height  = "51px";
        elem.append(shape2);
};
window.onload = randShape;
function createShape2() {
    var elem = document.getElementById("container");
    var shape = document.createElementNS(svgNS, "rect");
    shape.id = "shape1";
        shape.style.width = "100px";
        shape.style.height = "100px";
        shape.style.fill = "red";
        shape.style.x = "200px"
        shape.style.position = "absolute"
        elem.append(shape);
};
var shapes = {
    "shape1": createShape1(),
    "shape2": createShape2()
};
function randShape() {
    var x = Math.floor(Math.random() * 2);
    shapes.x;
}

so if you have any suggestions to get my code to generate a random property of shape, each of which should generate its own shape.

A: The problem was how to access the value and making the function call before accessing what function you wanted to call
var shapes = {
  "shape1": createShape1,
  "shape2": createShape2
};

function randShape() {
    var x = Math.floor(Math.random() * 2) + 1;
    (shapes["shape" + x]).call(shapes);
}

A: JS:
var svgNS = "http://www.w3.org/2000/svg";
var htmlNS = "http://www.w3.org/1999/xhtml";

function createShape1() {
    var elem = document.getElementById("container");
    var shape = document.createElementNS(svgNS, "rect");
        shape.id = "shape1";
        shape.style.width = "150px";
        shape.style.height = "50px";
        shape.style.fill = "orange";
        shape.style.y = "50px";
        shape.style.x = "150px"
        shape.style.position = "absolute"
        elem.append(shape);
    var shape2 = document.createElementNS(svgNS, "rect");
        shape2.id = "shape2";
        shape2.style.fill = "orange";
        shape2.style.x = "200px";
        shape2.style.width = "50px";
        shape2.style.height  = "51px";
        elem.append(shape2);
};
window.onload = randShape;
function createShape2() {
    var elem = document.getElementById("container");
    var shape = document.createElementNS(svgNS, "rect");
    shape.id = "shape1";
        shape.style.width = "100px";
        shape.style.height = "100px";
        shape.style.fill = "red";
        shape.style.x = "200px"
        shape.style.position = "absolute"
        elem.append(shape);
};
var shapes = [createShape1, createShape2]
function randShape() {
    var x = Math.floor(Math.random() * 2);
    shapes[x]()
}


text:
Q: If $u_n \rightharpoonup u$ in $L^2(\Omega)$, does $u_n^+ \rightharpoonup u^+$ in $L^2(\Omega)$? Let $\Omega$ be a bounded domain.
If $u_n \rightharpoonup u$ in $L^2(\Omega)$, does $u_n^+ \rightharpoonup u^+$ in $L^2(\Omega)$ where $u_n^+ = \max(0,u_n)$.
Note all convergences are weak.
My guess is no though I hope the answer is yes. I'm not sure at all how to prove it.

A: To summarize the comments: the answer is negative, and functions like $\sin nx$ or Rademacher functions $r_n$ provide counterexamples. They converge weakly to $0$, but the integral of the positive part does not tend to $0$.


text:
Q: How many solar panels do I need for a fully automatic Farm? Using a Farm and a Combine I have a sweet automatic farm set up, which churns out wheat and bread. The only problem is I have to go and fuel the engines (Hobbyist steam engines) every now and again to make the thing tick over.
I'd like to use solar power for an unattended farm. I'd use the solar to drive electrical engines. How many solar panels would I need? Is it possible to use only enough solar panels to power one machine, and alternate which engine is powered using redstone? (the turnover is slow, so alternating every few minutes between machines would be fine.)

A: How many solar panels you need is up to you. Even though Forestry farms drain a lot of power, they're A-OK with receiving very little, and in fact I'd recommend that because you get seriously diminishing returns if you power them fully.
The wheat farms especially, because it only has to harvest the crops and replant. Other farms have to do a lot more (such as harvest multi-blocks structures, replace soil blocks, gather loose items). The wheat grows on its own, and you're probably OK with the farm and harvester taking a bit to harvest and replant.
On Forestry easy mode, I'd say 1-2 MJ/t is enough between the two machines to keep things going, which means a single electrical engine (Choke upgrade or not). You don't have to alternate, a forked conductive pipe will do the trick. I recommend giving the electrical engine double its intake so it can run through the night (obviously you're gonna need a buffer like a BatBox as well). Maybe a bit more so it can cope with inclement weather.
Let's say you have that engine set up with Choke and Efficiency, which means 3 EU/t. Use 3 solar panels to have it running during the day, 6 and a buffer to have it run through the night as well, and maybe 7-8 if you don't want rain to slow it down too much. (Although day is a bit longer than night, so it should slowly build up a buffer even with 6 solar panels.)

A: I'm currently powering one Farm and Combine using an LV Solar Array. The Electrical Engine draws 4 EU/t (with an Iron Tube circuit board to make it Efficient). I suppose I could get away with four basic solar panels, but the constant 8 EU/t means that my batbox buffer collects some extra and keeps it all running a bit into the night. It also means alternating the BC power between the machines is unnecessary – there's plenty to go around.


text:
Q: Only add to select statement if logic is satisfied I'm trying to do something basically like this.
Pseudocode
DECLARE @logic BIT = 1

SELECT user_name,
user_id,
if @logic = 1
(
(SELECT first_name + ' ' + last_name FROM users y
WHERE x.user_id = y.user_id) AS 'Full name',
)
birth_dte FROM x

The intent is that if a bit is set, it will add additional results to the select query.  I believe this is doable with dynamic SQL but I'd like to avoid that if another solution exists.
The
CASE @logic WHEN 1 THEN...
method doesn't work here, because when @logic != 1, it will return a null column with no name.  I'd like it to simply not return that column at all, and just use the next one.
Is there any way to do this? Thanks!
Edit: I could do "if @logic then select... ELSE select..." but my use case will end up using multiple different logic bit checks.
If I need to compare against @logic_1, @logic_2, @logic_3, @logic_4, @logic_5 I end up with a lot of repetition that I'd like to avoid.  I'm thinking this may not be possible to integrate right in the select fields, but I figured others might have some tricks I'm unaware of.

A: if I understand your question you want something like this:
 DECLARE @logic BIT = 1;

IF @logic = 1
    BEGIN
       SELECT user_name
           , user_id
           , first_name+' '+last_name AS 'Full name'
           , birth_dte
       FROM   x
            INNER JOIN users y ON x.user_id = y.user_id;
    END;
ELSE
    BEGIN
       SELECT user_name
           , user_id
           , birth_dte
       FROM   x
            INNER JOIN users y ON x.user_id = y.user_id;
    END;

A: You could do something like below
DECLARE @logic BIT = 1

IF @logic = 1
BEGIN

SELECT user_name,
user_id,
(SELECT first_name + ' ' + last_name FROM users y
WHERE x.user_id = y.user_id) AS 'Full name',
)
birth_dte
FROM x

END
ELSE
BEGIN

SELECT user_name,
    user_id,
    birth_dte
    FROM x

END

A: DECLARE @logic BIT = 1
       ,@Sql NVARCHAR(MAX);

SET @Sql = N' SELECT   [user_name]
                     , [user_id] '
        + CASE WHEN @logic = 1 THEN
           N'     , first_name + '' '' + last_name AS Name ' ELSE N' ' END
        +  N' FROM [users] '

Exec sp_executesql @Sql


text:
Q: How to archive a message using ruby `net/imap` With the following ruby code, I can read a user's mail in an inbox via IMAP:
require 'net/imap'
imap = Net::IMAP.new('imap.gmail.com',993,true)
imap.login('user','passwd')
imap.select('INBOX')
mailIds = imap.search(['ALL'])
mailIds.each do |id|
  msg = imap.fetch(id,'RFC822')[0].attr['RFC822']
  puts msg
end
imap.logout()
imap.disconnect()

I want to know how I can archive and mark read emails. I want to move the emails out of the user's inbox.

A: Use store method
require 'net/imap'
imap = Net::IMAP.new('imap.gmail.com', 993, true)
imap.login('user', 'passwd')
imap.select('INBOX')
mailIds = imap.search(['ALL'])
mailIds.each do |id|
  msg = imap.fetch(id, 'RFC822')[0].attr['RFC822']
  puts msg
  imap.store(id, "+FLAGS", [:Seen])
end
imap.logout()
imap.disconnect()


text:
Q: tab-delimited string to XML with PHP I'm trying to write the tab-delimited content of a variable to XML like this:
$tsvData = str_getcsv($input, "\t");
foreach($tsvData as $line => $row) {
    if($line > 0) {
        $xmlWriter->writeElement('NAME', $row[0]);
        $xmlWriter->writeElement('CAKE', $row[1]);
        $xmlWriter->writeElement('BODYPART', $row[2]);
    }
}

But it's only writing one character per XML tag instead of everything between each tab. When I use SplFileObject, geting the same tsv data but from a file, it works.  What am I doing wrong with the str_getcsv function?
Thanks

A: The str_getcsv() function returns a 1-dimensional array, but you're treating it like it's returning a 2-dimensional array.
Edit:
To clarify, str_getcsv() has no concept of "lines".  Instead of doing this:
$tsvData = str_getcsv($input, "\t");

Thinking that you'll get an array of lines, each one containing an array of columns, you have to do something like this:
$lines = explode("\n", $input);
$tsvData = array();
foreach ($lines as $line) {
    $tsvData[] = str_getcsv($line, "\t");
}
// now $tsvData is a 2-dimensional array of lines/columns like you were wanting


text:
Q: Getting 'Conversion failed .. for varchar value to int' if I remove ORDER BY CLAUSE Getting a weird problem since a few days, which is preventing me from running any queries.
SELECT Empid as EmployeeId, EmpName,
CustomerName as 'Distributor Name', Customer.RSCode, markedFor as 'Date Marked For',
CASE WHEN Present = 0 THEN 'ABSENT' ELSE 'PRESENT' END AS Attendance, Reason
FROM EmployeeAttendance_Backup ea, Customer, Employee e, EmployeeMaster em
WHERE
ea.DistID = cast(Customer.RSCode as int)
AND e.EmployeeMasterID=em.Id
AND ea.Empid = em.EmployeeID
--ORDER BY markedFor

If I run the above query, I get ~160k - 190k records, before it terminates with the error:

Conversion failed when converting the varchar value 'Present
  500004862' to data type int.

I am not even selecting the field, for which it is throwing this error.
If I enable the ORDER BY clause, I do not get any records, and this error:

Conversion failed when converting the varchar value 'Hirannaiah K R' to data type int.

The EmployeeAttendance_Backup table has close to 2 lakh records. Is this causing any problems? I do not know how to look for solution. I tried going through the attendance table for this particular employee, to check if some records were incorrectly saved, but that is not the case. Did the same for Employee and EmployeeMaster for this particular employee.
Where do I start looking for problems?