Q: Create Watchkit notification programmatically I'm looking to push a notification to the Apple Watch at a specific time. I was able to display a static message on the simulator using an apns file, but I'd like to set the data and time of the notification in the controller.
I heard I might not be able to do this on a simulator, but if I got a real phone and watch, how would it work?

A: So, you want to do something in the watch app extension and based on the results, schedule a UILocalNotification that will be sent to the phone at some point?
You cannot directly schedule a UILocalNotification from the watch because you don't have access to the UIApplication object. See Apple staff comment here.  However, using Watch Connectivity, you could send a message from the watch to the phone and have the phone app create and schedule it in the background. The watch will display the notification iff the phone is locked at the trigger time. The watch's notification scene will be invoked in that case.

A: Assuming you want to send the notification from the phone to the watch: You can use UILocalNotification to send a notification to the watch - but the watch must be locked to receive it.  There's also no guarantee when the Watch OS will turn on the watch to run the code that receives your notification, so your notification may arrive minutes or hours after it's sent.


Q: Log transform before bootstrapping? Background:
I’m exploring if hair cortisol levels (pg/mg) are related with executive functions like working memory (measured on WISC-scale), inhibition control (BRIEF-scale) and attention shifting (BRIEF-scale) with SPSS.  My sample sizes are 11 (group 1) and 21 (group 2). I want to study the groups together (are cortisol and executive functions related) and separately (is the relationship different in different groups). The hair cortisol values are positively skewed.
Questions:

*

*Other studies in this field have used log transformation of the (hair) cortisol without bootstrapping, but I want to use bootstrapping because of the small sample size and I’m now wondering whether to log transform the data before bootstrapping or not?

*Is the regression analysis right method for estimating the relationship between cortisol and executive functions? If not, what alternatives could you recommend? My hypothesis is that the relationship is U-shaped (very low and very high cortisol levels are related with more problems in executive functions), so I would add cortisol to the model in the first step, and squared cortisol in the model to the second step.

*I want to study if the sex, age and grouping variable have an impact on the relationship of working memory and cortisol.  Can I explore this with a general linear model?
I would really appreciate for any feedback!

A: Let $X_1$ be the indicator of group 1, and $X_2$ be hair cortisol levels. $Y$ be working memory. The model will be as following:
$Y=\beta_0 + \beta_1X_1 + \beta_2 X_2 +\beta_3X_2^2 +\beta_4X_1X_2+\beta_5X_1X_2^2 + \epsilon $
If $E(Y|X_2)$ and $\log(X_2)$ have better linear relation for given group, then transform it. Otherwise, do not.
You can delete the non-significant terms step by step.
Replace $Y$ with inhibition control and attention shifting, fit other two models.
Do not use bootstrapping because of small sample size. Bootstrapping is used for some difficult situations, but cannot increase the sample size.
Theoretically, you can add other factors such as gender into the model. But given the sample size is 32, I would not do it if I analyze these data.
Example of not using bootstrapping:
When you estimate the mean from a sample following normal distribution, then sample mean +/- t * SE is the best regardless the sample size. If you perform bootstrapping with 1,000,000 replica, you may get the same result.
Example of using bootstrapping:
You find a way to estimate parameter u with statistic T, but you cannot derive the variance of T mathematically, and of course you cannot estimate the variance of T from sample. Under this situation, bootstrapping can be used to estimate the variance of T.


Q: How to create an object in a class by passing a token to a constructor? What I am attempting to do is to take a .txt file that has multiple lines of people's information (Last name, First name, phone number, email) and display the information into a listbox so that a user could select a name in the listbox and display all of the selected person's information in a second form.  The instructions for my assignment say that the next thing I should do is Create your object by passing these tokens to your constructor. (Don’t pass the array but rather each element individually.) I have created a class called PersonEntry that constructs 4 strings containing the 4 pieces of information that's included in the .txt file. Here is where I'm at(the first one is my form1.cs code and the second is my PersonEntry.cs class code) and I don't know what to do next. Any help would be much appreciated!
namespace ChalabiMichaelProgram10
{
    public partial class chalabiMichaelProgram10 : Form
    {
        List<PersonEntry> personsList = new List<PersonEntry>;

        public chalabiMichaelProgram10()
        {
            InitializeComponent();
        }

        private void chalabiMichaelProgram10_Load(object sender, EventArgs e)
        {
            try
            {
                StreamReader inputfile;
                string line;
                int count;

                inputfile = File.OpenText("contacts.txt");

                while (!inputfile.EndOfStream)
                {
                    line = inputfile.ReadLine();
                    char[] delimiters = { ',' };
                    string[] tokens;
                    tokens = line.Split(delimiters);

                    for( count = 0; count < 4; count++)
                    {
                        tokens[count] = tokens[count].Trim();

                    }
                }
            }
        }
    }
}

namespace ChalabiMichaelProgram10
{
    class PersonEntry
    {
        //Constructor.
        public PersonEntry()
        {
            lastName = "";
            firstName   = "";
            phoneNumber = "";
            email       = "";
        }
        public string lastName { get; set; }
        public string firstName { get; set; }
        public string phoneNumber { get; set; }
        public string email { get; set; }
    }
}


Q: array used the same memory space? i have an array in the main program like this: (i am using C# to program in asp.net)
double[][] example= new double[][];

for this example lets imagine is an array of 10*2.
so next thing i will do is send this array to another function like this:
usedarray(example);
public double[][] usedarray(double[][]examplearray)
{

}

i know that a double array in each space has only 64 bit floating point number, so the array will have a 1280 bits for this example used memory, but when is send to the function it used the same space of memory? or it use a complete new set of memory space?

A: Arrays are reference types, not value types.  That means that the variable, examplearray doesn't actually contain 1280 bits of data, it just contains a reference (sometimes also referred to as a pointer) to the actual data, which is stored elsewhere (for the purposes of this post, it doesn't matter where "elsewhere" actually is).  Passing that variable to a method, as you have done there, is only copying that reference (which is 32 or 64 bits, depending on the system), not the underlying 1280 bits of data.


Q: onRestart() and onRefresh() Act Different with Same Code I have the exact same methods and calls in onRefresh() and onRestart(), but for some reason onRestart() does what I want exactly, yet onRefresh() acts differently. What I want to happen is for app to understand when the location is disabled while running.
onRestart() does this: I start the app, get the Forecast data, disable location from status bar, press the home button and open the app again. As expected, onRestart() tries to check for GPS status(with gpsTracker.getIsGPSEnabled()), sees that location is disabled, and sends the according Toast message.
onRefresh() does this: I start the app, get the Forecast data, disable location from status bar, even wait few seconds and then refresh the app. Unexpectedly, onRefresh() gives sends the "Data Refreshed" toast, even though it gets "null, null" as location latitude and longitude.
I could provide other codes as well, but if there was a problem with the rest of the code, why would onRestart() act the way I want? I'm not getting any errors. Any help would be highly appreciated. Thanks.
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    ButterKnife.bind(this);
    final GPSTracker gpsTracker = new GPSTracker(this);

    mSwipeRefreshLayout.setColorSchemeColors(Color.RED, Color.GREEN, Color.BLUE, Color.CYAN);
    mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    mSwipeRefreshLayout.setRefreshing(false);
                    if (gpsTracker.getIsGPSTrackingEnabled()) {
                        gpsTracker.getLocation();
                        getForecast(gpsTracker);
                        Toast.makeText(MainActivity.this, "Data Refreshed", Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(MainActivity.this, "Location is not enabled", Toast.LENGTH_LONG).show();
                    }
                }
            }, 3000);
        }
    });
}

@Override
protected void onRestart() {
    super.onRestart();
    final GPSTracker gpsTracker = new GPSTracker(this);
    new Handler().postDelayed (new Runnable ()
       @Override public void run() {
            gpsTracker.getLocation();
            if (gpsTracker.getIsGPSTrackingEnabled()) {
                getForecast(gpsTracker);
                Toast.makeText(MainActivity.this, "Data Refreshed", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(MainActivity.this, "Location is not enabled", Toast.LENGTH_LONG).show();
            }
        }
}, 3000);
}

A: onRestart you create a new instance of GPSTracker. try updating your GPSTracker handler in onRefresh.
give it a try

A:             @Override
            public void onRefresh() {
            final GPSTracker gpsTracker = new GPSTracker(MainActivity.this);
            new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                mSwipeRefreshLayout.setRefreshing(false);
                if (gpsTracker.getIsGPSTrackingEnabled()) {
                    gpsTracker.getLocation();
                    getForecast(gpsTracker);
                    Toast.makeText(MainActivity.this, "Data Refreshed", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(MainActivity.this, "Location is not enabled", Toast.LENGTH_LONG).show();
                }
            }
        }, 3000);
    }
});


Q: How to use jdt.ast to resolve polymorphism I'm working to get the override method binding through eclipse-jdt-ast.
Just like when we using eclipse, press Ctrl and click the method ,we can jump to the method implenmentation.
Although it's dynamic binging in java, but the following works well:
public class Father{
public void test(){}
}

And Son:
public class Son extends Father{
@Override
public void test(){}

   public static void  main (String[] arg){
    Father f=new Son();
    f.test();
   }
}

When we click the test in main, we can correctly jump to the Son.java
And I'm wondering how to do it. I tried to see the sources but didn't find the location because the code is too many.
And my code now is :
public class Main {
static  String filep="example/Son.java";
static String[] src={"example/"};
static String[] classfile={"example/"};

public static void main(String[] args) throws IOException,Exception{

    ASTParser parser = ASTParser.newParser(AST.JLS8);
    parser.setKind(ASTParser.K_COMPILATION_UNIT);
    parser.setSource(Files.toString(new File(filep), Charsets.UTF_8).toCharArray());
    // only setEnvironment can we get bindings from char[]
    parser.setEnvironment(classfile, src, null, true);
    parser.setUnitName(filep);
    parser.setResolveBindings(true);
    parser.setKind(ASTParser.K_COMPILATION_UNIT);
    CompilationUnit compilationUnit = (CompilationUnit) parser.createAST(null);
    if (compilationUnit.getAST().hasResolvedBindings()) {
        System.out.println("Binding activated.");
    }
    else {
        System.out.println("Binding is not activated.");
    }
    ASTNode node=compilationUnit.findDeclaringNode("f");
    compilationUnit.accept(new Myvisitor(compilationUnit));
}
}

And my visitor is:
public class Myvisitor extends ASTVisitor {
int i=0;
CompilationUnit compilationUnit;
Myvisitor(CompilationUnit compilationUnit){
    this.compilationUnit=compilationUnit;
}

@Override
public boolean visit(MethodInvocation node) {
    i++;
    System.out.println(i);
    IMethodBinding binding=node.resolveMethodBinding();

    ASTNode astNode=compilationUnit.findDeclaringNode(binding);
    System.out.println(astNode);
    return true;
}

}

It's a little long but simple, hope u can read here. Personally I guess the
findDeclaringNode method may do it. However, it returns null when I pass the binding. So do u have any ideas?
Thanks a lot

A: When looking for all implementations of a given super method, the AST is of little help, as even with its bindings it only has references from sub to super but not the opposite direction.
Searching in the opposite direction uses the SearchEngine. If you look at JavaElementImplementationHyperlink the relevant code section can be found around line 218 (as of current HEAD)
You will have to first find the IMethod representing the super method. Then you prepare a SearchRequestor, an IJavaSearchScope, and a SearchPattern before finally calling engine.search(..). Search results are collected in ArrayList<IJavaElement> links.
A good tradition of Eclipse plug-in development is "monkey see, monkey do", so I hope looking at this code will get you started on your pursuit :)


Q: Close a MSI file handle after being downloaded from a website I have a vsto add-in for outlook. There is a code where I download a MSI file from a website:
Public Sub DownloadMsiFile()
    Try
        Dim url As String = "https://www.website.com/ol.msi"
        Dim wc As New WebClient()
        wc.Headers.Add(HttpRequestHeader.UserAgent, "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;")
        If File.Exists(My.Computer.FileSystem.SpecialDirectories.Temp & "\ol.msi") Then
            System.IO.File.Delete(My.Computer.FileSystem.SpecialDirectories.Temp & "\ol.msi")
        End If
        wc.DownloadFile(url, My.Computer.FileSystem.SpecialDirectories.Temp & "\ol.msi")
        wc.Dispose()
    Catch ex As Exception
        MessageBox.Show("File couldn't be downloaded: " & ex.Message)
    End Try
End Sub

And then I get the MSI version using the following function:
Function GetMsiVersion() As String
    Try
        Dim oInstaller As WindowsInstaller.Installer
        Dim oDb As WindowsInstaller.Database
        Dim oView As WindowsInstaller.View
        Dim oRecord As WindowsInstaller.Record
        Dim sSQL As String
        oInstaller = CType(CreateObject("WindowsInstaller.Installer"), WindowsInstaller.Installer)
        DownloadMsiFile()
        If File.Exists(My.Computer.FileSystem.SpecialDirectories.Temp & "\ol.msi") Then
            oDb = oInstaller.OpenDatabase(My.Computer.FileSystem.SpecialDirectories.Temp & "\ol.msi", 0)
            sSQL = "SELECT `Value` FROM `Property` WHERE `Property`='ProductVersion'"
            oView = oDb.OpenView(sSQL)
            oView.Execute()
            oRecord = oView.Fetch
            Return oRecord.StringData(1).ToString()
        Else
            Return Nothing
        End If
    Catch ex As Exception
        MessageBox.Show("File couldn't be accessed: " & ex.Message)
    End Try
End Function

And then I do the comparison with the current dll version to see if there is a need to download a newer version or not:
Public Sub CheckOLUpdates()
    Dim remoteVersion As String = GetMsiVersion()
    Dim installedVersion As String = Assembly.GetExecutingAssembly().GetName().Version.ToString
    If Not String.IsNullOrEmpty(remoteVersion) Then
        Try
            If String.Compare(installedVersion, remoteVersion) < 0 Then
                Dim Result As DialogResult = MessageBox.Show("A newer version is available for download, do you want to download it now?", "OL", System.Windows.Forms.MessageBoxButtons.OKCancel, MessageBoxIcon.Question)
                If Result = 1 Then
                    System.Diagnostics.Process.Start("http://www.website.com/update")
                Else
                    Exit Sub
                End If
            Else
                MessageBox.Show("You have the latest version installed!", "OL", MessageBoxButtons.OK, MessageBoxIcon.Information)
            End If
        Catch ex As Exception

        End Try

    End If

End Sub

This works pretty well if this ran once. However if I try again to check for update, I would get the following error which happens while trying to delete the file in DownloadMsiFile() :

The process cannot access the file %temp%\ol.msi because it is being used by another process

If I use the sysinternals handle.exe utility to check the handles on this file I get the outlook process having a handle lock on this file:
handle.exe %temp%\ol.msi
Nthandle v4.30 - Handle viewer
Copyright (C) 1997-2021 Mark Russinovich
Sysinternals - www.sysinternals.com

OUTLOOK.EXE        pid: 25964  type: File          4FC8: %temp%\ol.msi

I was wondering how can I close the handle to avoid this error? Any help is really appreciated

A: So here is what I have to do to close the handle. I have added the following lines after opening the MSI file:
            Marshal.FinalReleaseComObject(oRecord)
            oView.Close()
            Marshal.FinalReleaseComObject(oView)
            Marshal.FinalReleaseComObject(oDb)
            oRecord = Nothing
            oView = Nothing
            oDb = Nothing

So my final code looked like the following:
Function GetMsiVersion() As String
    Try
        Dim oInstaller As WindowsInstaller.Installer
        Dim oDb As WindowsInstaller.Database
        Dim oView As WindowsInstaller.View
        Dim oRecord As WindowsInstaller.Record
        Dim sSQL As String
        Dim Version As String
        oInstaller = CType(CreateObject("WindowsInstaller.Installer"), WindowsInstaller.Installer)
        DownloadMsiFile()
        If File.Exists(My.Computer.FileSystem.SpecialDirectories.Temp & "\ol.msi") Then
            oDb = oInstaller.OpenDatabase(My.Computer.FileSystem.SpecialDirectories.Temp & "\ol.msi", 0)
            sSQL = "SELECT `Value` FROM `Property` WHERE `Property`='ProductVersion'"
            oView = oDb.OpenView(sSQL)
            oView.Execute()
            oRecord = oView.Fetch
            Version = oRecord.StringData(1).ToString()
            Marshal.FinalReleaseComObject(oRecord)
            oView.Close()
            Marshal.FinalReleaseComObject(oView)
            Marshal.FinalReleaseComObject(oDb)
            oRecord = Nothing
            oView = Nothing
            oDb = Nothing
        Else
            Version = Nothing
        End If
        Return Version
    Catch ex As Exception
        MessageBox.Show("File couldn't be accessed: " & ex.Message)
    End Try
End Function


Q: What does this line of code means in javascript? function delay(n){
n = n || 2000
//other stuff
}

what does the first line do?
Thanks.

A: It means that if n, the argument passed to the function, is falsey, 2000 will be assigned to it.
Here, it's probably to allow callers to have the option of either passing an argument, or to not pass any at all and use 2000 as a default:

function delay(n){
  n = n || 2000
  console.log(n);
}

delay();
delay(500);

But it would be more suitable to use default parameter assignments in this case.

function delay(n = 2000){
  console.log(n);
}

delay();
delay(500);


Q: Setting tensorflow rounding mode I am working with small numbers in tensorflow, which sometimes results in numerical instability.
I would like to increase the precision of my results, or at the very least determine bounds on my result.
The following code shows a specific example of numerical errors (it outputs nan instead of 0.0, because float64 is not precise enough to handle 1+eps/2):
import numpy as np
import tensorflow as tf

# setup
eps=np.finfo(np.float64).eps
v=eps/2
x_init=np.array([v,1.0,-1.0],dtype=np.float64)

x=tf.get_variable("x", initializer=tf.constant(x_init))
square=tf.reduce_sum(x)
root=tf.sqrt(square-v)

# run
with tf.Session() as session:
    init = tf.global_variables_initializer()
    session.run(init)

    ret=session.run(root)
    print(ret)

I am assuming there is no way to increase the precision of values in tensorflow. But maybe it is possible to set the rounding mode, as in C++ using std::fesetround(FE_UPWARD)? Then, I could force tensorflow to always round up, which would make sure that I am taking the square root of a non-negative number.

What I tried: I tried to follow this question that outlines how to set the rounding mode for python/numpy. However, this does not seem to work, because the following code still prints nan:
import numpy as np
import tensorflow as tf

import ctypes
FE_TONEAREST = 0x0000 # these constants may be system-specific
FE_DOWNWARD = 0x0400
FE_UPWARD = 0x0800
FE_TOWARDZERO = 0x0c00
libc = ctypes.CDLL('libm.so.6') # may need 'libc.dylib' on some systems

libc.fesetround(FE_UPWARD)

# setup
eps=np.finfo(np.float64).eps
v=eps/2
x_init=np.array([v,1.0,-1.0],dtype=np.float64)

x=tf.get_variable("x", initializer=tf.constant(x_init))
square=tf.reduce_sum(x)
root=tf.sqrt(square-v)

# run
with tf.Session() as session:
    init = tf.global_variables_initializer()
    session.run(init)
    ret=session.run(root)
    print(ret)

A: Replace
ret=session.run(root)

with
ret = tf.where(tf.is_nan(root), tf.zeros_like(root), root).eval()

Refer tf.where


Q: Understanding LED driver circuit AC to DC conversion I am recently working on mains socket outlet type LEDs lights. They all have very similar AC to DC conversion circuit.

simulate this circuit – Schematic created using CircuitLab

*

*C1 is a X-2 type capacitor and I know it has Independence $$X_c= \frac{1}{2\pi fC} \approx 9.6 k\Omega$$
Thus, the AC current will be limited by this cap at 230/9.6k=23mA. But what the R1 does in the circuit?

*R2 is a big through hole resistor, does it act like a fuse or something?

*D1 is a Zener diode. I guess it is here to regulator the voltage to its breakdown voltage, like 5V or 12V. Am I right?

*This circuit doesn't have a transformer like 230V to 12v before the rectifier， would it be safe in practice?
Thanks a lot!

A: The circuit is safe so long as you can't touch it or any circuit connected to it, if there is inadequate protection between users and the circuit it is unsafe.
R1 bleeds the charge out of the capacitor when the circuit is unplugged
this makes the plug pins safe to touch very soon after it is unplugged.


Q: Is there any 40mV transistor's threshold value that is available in the market?
*

*Is there any 40mV transistor's  threshold value that is available in the market?
My UNO arduino only gives 40mV signal. That is very low. We do not want to use an op amp in order to get it high. We want to use a transistor that is applicable for this 40mV.

Also, if it is impossible to find one,

*I am measuring the signal output from the arduino pin and I am getting 40 mV. Wasn't I supposed to get 5V essentially?

A: Your team needs to get software version control as soon as possible. Losing your source code is unacceptable. Even if this is not a professional setting, losing the source code wastes your team's time. It doesn't matter who is at fault, it will happen again if you don't get some basic source control in place. Git, Subversion, Mercurial, any of these are better than nothing.
What if your Arduino Uno "blew up" and needs to be repaired or replaced? You will need to reload the firmware into the new board. If you suspect your board got fried, and the 5V power supply is still good, first thing to try is reloading the firmware. Sometimes that's enough to fix it if it was a disruption caused by power supply issues -- this is very possible if you're driving motors.
You don't need to mess around with trying to build a one-transistor amplifier: if your board is not driving valid logic output levels then it's defective, and trying to amplify a dead board won't get you anywhere. If your Arduino is dead, you can repair it by replacing the Atmega328 chip. If your Arduino isn't dead, it can already drive 5V logic levels out. This problem won't be solved by adding more transistors. ( unless the problem turns out to be, that the load requires more than 20mA. Then a transistor amplifier would help. )
And FYI just now I fired up my Arduino Uno, loaded some simple firmware (see below) and I measure 5.035VDC (no load) on my HP34401A DMM. So yes, indeed, an Arduino Uno does normally drive 5V levels on its digial output pins. As I think we already knew. This should be no surprise if you've read the Atmel ATmega328 microcontroller data sheet.
For VCC=5V, VOHmin is specified as at least 4.2V minimum, tested with 20mA output current. So if you're measuring 40mV, one of two things is happening.

*

*The Arduino is trying to drive logic high output, but something is drawing much more than 20mA from the digital output pin, possibly violating the Absolute Maximum (permanent damage) rating of 40mA per pin.

*The Arduino is actually driving a logic low when you're expecting logic high.

Since your source code is gone, it's impossible to tell for certain what your Arduino is trying to do. But you could try disconnecting the Arudino from your motor driver, and loading this new firmware, and see if you get the same result I did:
void setup() {
  // put your setup code here, to run once:
  pinMode(5, OUTPUT); // INPUT | OUTPUT | INPUT_PULLUP
  digitalWrite(5, HIGH); // HIGH | LOW
}
void loop() {
  // put your main code here, to run repeatedly:
}

With nothing else attached, digital pin 5 should be driven to logic high (5V). If this simple test doesn't work, your Arduino has failed.


Q: Getting "Error: Invalid or corrupt jarfile corda.jar" while bootstrapping the Corda netwrok While trying to bootstrap the Corda network getting below error.

Error: Invalid or corrupt jarfile corda.jar

Please find more details below.
root@domestic-lc:/home/POC_DomesticLC# java -jar corda-tools-network-bootstrapper-4.0.jar --dir build/nodes
Bootstrapping local test network in /home/POC_DomesticLC/build/nodes
Using corda.jar in root directory
Generating node directory for PartyB
Generating node directory for BankB
Generating node directory for Notary
Generating node directory for BankA
Generating node directory for PartyA
Nodes found in the following sub-directories: [PartyA, PartyB, BankB, BankA, Notary]
Found the following CorDapps: []
Not copying CorDapp JARs as --copy-cordapps is set to FirstRunOnly, and it looks like this network has already been bootstrapped.
Waiting for all nodes to generate their node-info files...
#### Error while generating node info file /home/POC_DomesticLC/build/nodes/PartyA/logs ####
Error: Invalid or corrupt jarfile corda.jar
#### Error while generating node info file /home/POC_DomesticLC/build/nodes/PartyB/logs ####
Error: Invalid or corrupt jarfile corda.jar
#### Error while generating node info file /home/POC_DomesticLC/build/nodes/BankA/logs ####
Error: Invalid or corrupt jarfile corda.jar
#### Error while generating node info file /home/POC_DomesticLC/build/nodes/BankB/logs ####
Error: Invalid or corrupt jarfile corda.jar
#### Error while generating node info file /home/POC_DomesticLC/build/nodes/Notary/logs ####
Error: Invalid or corrupt jarfile corda.jar
Error while generating node info file. Please check the logs in /home/POC_DomesticLC/build/nodes/PartyA/logs.

A: Did you get over this issue?
I've tried with bootstrap 4.0 but I didn't see any issue, so my suggestions are:

*

*check your java version, make sure it is 1.8.171+

*make sure the corda.jar (in your build /nodes/notary/corda.jar) is correct because bad network may cause the incomplete corda.jar downloaded

*make sure you've got the tools from official website instead of copying from other way where the bootstrap jar file might be broken

*last, as always, please try to use the latest version bootstrap: 4.3, to utilise the best Corda:
https://software.r3.com/artifactory/corda-releases/net/corda/corda-tools-network-bootstrapper/4.3/

A: I had a similar problem (not with that particular JAR file, but I'm using that file's name in my examples).  Here's how I worked out what was wrong.
These troubleshooting steps may help others who find this issue (but not the OP as the dates show it can't be this issue).
I started by trying to validate the JAR file by inspecting its contents:
$ jar -tf corda.jar

This showed me that it was indeed invalid.  In my case, I saw:
java.util.zip.ZipException: error in opening zip file
    at java.util.zip.ZipFile.open(Native Method)
    at java.util.zip.ZipFile.<init>(ZipFile.java:225)
    at java.util.zip.ZipFile.<init>(ZipFile.java:155)
    at java.util.zip.ZipFile.<init>(ZipFile.java:126)
    at sun.tools.jar.Main.list(Main.java:1115)
    at sun.tools.jar.Main.run(Main.java:293)
    at sun.tools.jar.Main.main(Main.java:1288)

I then looked at the size of the file:
$ ls -alh corda.jar

In my case, it was 133 bytes, which seems a bit small for a JAR file, so I cated it and saw this:
$ cat corda.jar

501 HTTPS Required.
Use https://repo1.maven.org/maven2/
More information at https://links.sonatype.com/central/501-https-required

It turned out that my script (a Dockerfile in fact) was downloading the file with curl -o but from a URL which was no longer supported.  As https://links.sonatype.com/central/501-https-required says:

Effective January 15, 2020, The Central Repository no longer supports insecure communication over plain HTTP and requires that all requests to the repository are encrypted over HTTPS.
If you're receiving this error, then you need to replace all URL references to Maven Central with their canonical HTTPS counterparts:
Replace http://repo1.maven.org/maven2/ with https://repo1.maven.org/maven2/
Replace http://repo.maven.apache.org/maven2/ with https://repo.maven.apache.org/maven2/
If for any reason your environment cannot support HTTPS, you have the option of using our dedicated insecure endpoint at http://insecure.repo1.maven.org/maven2/
For further context around the move to HTTPS, please see https://blog.sonatype.com/central-repository-moving-to-https.

This is fairly specific, but may help someone.


Q: Alterar a Status Bar para transparente em um Fragment dentro de uma Activity Tenho uma Activity a qual possui um tema para sua Status Bar, porém a mesma tem influência em um Fragment ao qual quero outra cor na Status Bar.
Existe alguma maneira de eu alterar a cor da Status Bar apenas quando aquele Fragment for aberto, e voltar ao normal quando for fechado?

A: Você pode alterar através do método setStatusBarColor():
context.getWindow().setStatusBarColor(Color.TRANSPARENT);

Lembre-se que esta função está disponível apenas a partir da API 21 (Lollipop), então faça uma verificação antes de utiliza-la:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
    context.getWindow().setStatusBarColor(Color.TRANSPARENT);
}

A: Com Status Bar, você se refere a Actionbar/Toolbar? Se sim, você pode mudar manualmente (código) com:
ActionBar bar = getActionBar();
bar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#CCFF0000")));

Dessa forma, quando o Fragment for criado você pode pegar a Activity, da Activity pegar o Fragment e mudar por código a cor da Actionbar.
EDIT:
Eu havia interpretado sua pergunta equivocadamente. A resposta do sicachester está correta.


Q: Is it more secure to go through a 3rd database to connect two databases using the same login? We have the following setup:

*

*Multiple production database containing private data which is used by desktop software

*A web database for a public website which needs some data from the private databases

*An intermediary database which contains a few views and stored procedures that pull data from the private databases

Currently the website logs in to web database, and the web database connects to intermediary database to pull data or execute stored procedures on the production databases. All the databases are on the same SQL instance, and the entire process uses the same user account.
The user account has full access to the web database and the intermediary database, but can only access specific views and stored procedures of and private database
Is this really more secure than just making the public database connect directly to the private ones?
It seems like the intermediary database is only there to complicates things since the same login is used to access data in all the databases, and it is already limited to just the views / SPs it needs in the private databases. I am hoping to remove it.

A: One thing jumps out here:

The entire process uses the same set of login credentials

Problem
So hypothetical userX (whether some meatsack using Excel, or IIS AppPool Identity) can see some views and code. It doesn't matter what database these views and code are in because userX is setup in 3 databases anyway.
However, you lose ownership chaining like this.
Let's say WebDB.dbo.SomeProc calls PrivateDB.dbo.SomeTable. UserX requires permissions on both objects. If this was OneDB.WebGUI.SomeProc using OneDB.dbo.SomeTable then only the OneDB.WebGUI.SomeProc needs permissions. Permissions on referenced objects with the same owner are not checked.
Note: I haven't looked too deeply at cross database ownership chaining. I only know plain old "ownership chaining" well
Now, as per comments you really have 2 databases that can be combined. Not 3 which was originally implied. However, the intermediate and web can be combined.
The other "private" databases can perhaps be combined, but that'll be a separate issue. See the bottom link for a fuller discussion of "one database or many"
Solution?
If the extra databases are code containers only, then schemas are a better idea.
This sounds like you've used "Database" where you should use "Schema" (in the SQL Server sense, not MySQL sense). I'd have a WebGUI schema, a Helper or Common schema (to replace Intermediate database) and Desktop schema. This way you separate permissions based on clients and just have one database
With one database (in addition to "ownership chaining") you can also start to consider indexed views, SCHEMABINDING (I use it always) and such that can't be done with seperate databases
For more on schemas, see these questions:

*

*Schema design - best practices?

*Over use/correct use of schemas?
Finally, there appears no reason to have separate databases based on "transactional integrity not required". See this question to explain this:
 Decision criteria on when to use a non-dbo schema vs a new Database

A: The answer is: it depends. If the private database is not accessed from outside internal LAN (or only through an VPN), this scheme adds security as someone using the credentials of the WebSite would have just limited access to that private DB Server (and will have some more work to get into your internal network - time that can be handy in discovering the intrusion and closing the hole).
If not, I don't think it adds anything except complexity.

EDIT:
Seems I've misread your question, so let's see if I understood correctly now: the IntermDb is a empty database just to connect to PrivateDB OR it is an DB which have views/procedure of its' own which connects to the PrivateDB to retrieve data?
In the first case, WTF? Rip it off. It's worthless, unless someone wants to audit it to profile access to the PrivateDB in a lazier way (and making WebApp developers work harder). SQL Profiler can filter using DB_ID...
In the second case, I sustain my previous answer.
EDIT: "I still don't see how this is more secure than connecting the private db directly to the public db since all 3 databases on on the same SQL instance and the login used for all 3 databases is the same, and can only access specific views and stored procedures in the private db anyways".
Having the intermediary means that invader would have to dig in your code know the existance of an IntermDB - and it have to dig your code on it to know that exists an PrivateDB.
If you put your PrivateDB on another server internal to your organization LAN/WAN (if possible), it can give enough time to the admin detect and block the attempt of invasion. If you use synonyms, this move is smooth as all you have is rebuild them to the existing code go to the right place.
Also you gain other advantages: since all code have to pass through IntermDB to access data in PrivateDB, no developer would be tempted to try bypass it - and that attempt can be easily spotted on SQL Server Profiler as the DB_ID of the request of PrivateDb data would be WebAppDb.


Q: how to add facebook comment to single page application? i have  website news  (single page application )
this code woks well in aspx page

but how to do  in View in SPA
which doesn't contain html or body tags just div
i use durandal in single page application

A: Late answer, but maybe it will help someone. For me the key to getting unique fb comments to render on a single page application was FB.XFBML.parse();
Each time I want to render unique comments:

*

*Change the url, each fb comments thread is assigned to the specific url
So I might have www.someurl.com/#123, www.someurl.com/#456, www.someurl.com/#789, each with its own fb comment thread. In AngularJs this can be done with $location.hash('123');

*Create a new fb-comments div, where 'number' equals '123', '456' or '789'

*Call a function that executes the fb SDK
function FBfun(path) {
  setTimeout(function() { // I'm executing this just slightly after step 2 completes
    window.fbAsyncInit = function() {
      FB.init({
        appId : '123456789123',
        xfbml      : true,
        version    : 'v2.2'
      });
    };

    (function(d, s, id){
      var js, fjs = d.getElementsByTagName(s)[0];
      if (d.getElementById(id)) {return;}
      js = d.createElement(s); js.id = id;
      js.src = "//connect.facebook.net/en_US/sdk.js";
      fjs.parentNode.insertBefore(js, fjs);
    }(document, 'script', 'facebook-jssdk'));

    FB.XFBML.parse(); // This is key for all this to work!
  }, 100);
}

A: i added the script to app.js like
   initializeFB: function () {
        if (!isFBInitialized.isInitialized) {

            FB.init({
                appId: 'xxxxxxxxxxxx',
                appSecret: 'xxxxxxxxxxxxxxx',
                // App ID from the app dashboard
                channelUrl: '//mysite//channel.html', // Channel file for x-domain comms
                status: true,                                 // Check Facebook Login status
                cookie: true, // enable cookies to allow the server to access the session
                xfbml: true                                  // Look for social XFBML plugins on the page to be parsed
            });

            (function (d, s, id) {
                var js, fjs = d.getElementsByTagName(s)[0];
                if (d.getElementById(id)) { return; }
                js = d.createElement(s); js.id = id;
                js.src = "//connect.facebook.net/en_US/all.js";
                fjs.parentNode.insertBefore(js, fjs);
            }(document, 'script', 'facebook-jssdk'));

            // Here we subscribe to the auth.authResponseChange JavaScript event. This event is fired
            // for any auth related change, such as login, logout or session refresh. This means that
            // whenever someone who was previously logged out tries to log in again, the correct case below
            // will be handled.
            FB.Event.subscribe('auth.authResponseChange', function (response) {
                // Here we specify what we do with the response anytime this event occurs.
                if (response.status === 'connected') {
                    // The response object is returned with a status field that lets the app know the current
                    // login status of the person. In this case, we're handling the situation where they
                    // have logged in to the app.
                    testFBAPI();
                } else if (response.status === 'not_authorized') {
                    // In this case, the person is logged into Facebook, but not into the app, so we call
                    // FB.login() to prompt them to do so.
                    // In real-life usage, you wouldn't want to immediately prompt someone to login
                    // like this, for two reasons:
                    // (1) JavaScript created popup windows are blocked by most browsers unless they
                    // result from direct user interaction (such as a mouse click)
                    // (2) it is a bad experience to be continually prompted to login upon page load.
                    FB.login();
                } else {
                    // In this case, the person is not logged into Facebook, so we call the login()
                    // function to prompt them to do so. Note that at this stage there is no indication
                    // of whether they are logged into the app. If they aren't then they'll see the Login
                    // dialog right after they log in to Facebook.
                    // The same caveats as above apply to the FB.login() call here.
                    FB.login();
                }
            });

            isFBInitialized.isInitialized = true;
        }
    },

and call it in viewattached
as
             app.initializeFB();

then it works well

A: Step 3 for my React app become (more linter friendly):
componentDidMount() {
    window.fbAsyncInit = () => {
        window.FB.init({
            appId: '572831199822299',
            xfbml: true,
            version: 'v4.0',
        });
    };

    (function (d, s, id) {
        const fjs = d.getElementsByTagName(s)[0];
        if (d.getElementById(id)) { return; }
        const js = d.createElement(s);
        js.id = id;
        js.src = '//connect.facebook.net/ru_RU/sdk.js';
        fjs.parentNode.insertBefore(js, fjs);
    }(document, 'script', 'facebook-jssdk'));

    setTimeout(() => {
        window.FB.XFBML.parse();
    }, 100);
}


Q: Can a black hole ever be the output of a Feynman diagram in momentum space? For a Feynman diagram representing a collision, particles come in from infinity with certain momenta, collide and then go off to infinite with other momenta. At collision vertices we integrate over all space-time.
It seems to me, that no in-coming or outgoing particles can be combined states if those states have any kind of half-life, because after infinite time they will decay. So even Feynman diagrams with protons incoming protons can only be approximate. (assuming proton decay)
Equally, if a black hole evaporates, can a black hole ever be one of the incoming or outgoing states?
As I read it, we could only have elementary particles as input and outputs, with perhaps a black hole forming during the collision which lasts for a certain amount of time (even a billion years) and then evaporating and elementary particles coming out.
In other words, in quantum gravity, should the S-Matrix contain only information about colliding elementary particles or include colliding black holes?

A: Let us be clear that any Feynman diagram of calculation implies quantization of gravity, for which there is no standard model yet.
That said, it is true that the standard model can be embedded in string theory models and also true that string theory  can accommodate quantization of gravity by including the  graviton in its string excitation.
Here micro black holes have been considered as a prediction of the extra dimensions of string theories, to be checked at LHC.

Such quantum black holes should decay emitting sprays of particles that could be seen by detectors at these facilities. A paper by Choptuik and Pretorius, published in 2010 in Physical Review Letters, presented a computer-generated proof that micro black holes must form from two colliding particles with sufficient energy, which might be allowable at the energies of the LHC if additional dimensions are present other than the customary four (three spatial, one temporal).

For example in this calculation they use semiclassical arguments to estimate the generation and decay of micro black holes at the LHC energies, based on the extra dimensions of string theories, thus connecting the standard model interactions with gravitational interactions.
The CMS experiment has been looking for them "Search for black holes and other new phenomena in high-multiplicity final states in proton-proton collisions"

Semiclassical black holes and string balls with masses as high as 9.5 TeV, and quantum black holes with masses as high as 9.0 TeV are excluded by this search in the context of models with extra dimensions, thus significantly extending limits set at a center-of-mass energy of 8 TeV with the LHC Run 1 data.

Various string model predictions are tested. If you read the links, it is not simple Feynman diagrams, but extensions of such calculations within string theory models. In this sense colliding black holes can be accommodated.All this is highly speculative of course, as only just limits are given at the moment.

A: Note that Feynman diagrams are generically used for theories with weak coupling. As such, the "in" and "out" states must be "free fields" (the fields one gets when canonically quantising the field). This means essentially that Feynman diagrams capture "weak effects" since the S-matrix expansion only works perturbatively (such that the expansion makes sense).
Now, when one thinks of the S-matrix of gravity, they're thinking of the scattering of gravitons perturbatively. In practice this means that you have to consider small fluctuations around flat space ("weak effects").
To answer your question now, black holes are a strong effect effect of gravity and thus cannot be represented by calculations involving weak effects, such as Feynman diagrams. The in/out states must be free fields (such as quarks, photons, or even gravitons if naively quantised) and since black holes are interactions between gravitons (which are by no means weak), they cannot be represented by free states in a Fock space.
Scattering amplitudes in string theory make sense at high-energy whereas those in quantum field theory may break down. Essentially this is how one can capture black holes in string theory, because it can describe those strong effects. But Feynman diagrams are not present in string theory and one usually integrates over the worldsheet of a certain process.
I'll summarise by answering more directly your questions.

*

*"Equally, if a black hole evaporates, can a black hole ever be one of the incoming or outgoing states?"
No, since it is not a free state. Even in practical S-matrix calculations for protons one approximates by using the composite quarks (approximation: the quarks are treated as free (but actually are not), so one can use them as in/out states). Even a small amount of time from our perspective is to captured well by us assuming the states are defined at +/- infinity (this is why decay etc. is not a huge problem for the S-matrix).

*"in quantum gravity, should the S-Matrix contain only information about colliding elementary particles or include colliding black holes?"
In general the S-matrix should only contain information regarding the states of the Fock space. In the case of quantum gravity, this would be graviton states (plus other matter states if your theory contains more fields), which will be well-defined on the Fock space. So the S-matrix will not contain information about black holes, only gravitons + matter. In one could somehow include gravity into the standard model then the S-matrix would contain information only about the elementary particles and gravitons.


Q: Unable to mount Galaxy Note 5 as MTP on 17.10 Did a clean install of 17.10 now Gnote 5 shows up in Nautilus but I cant browse the phone. Everytime I try The phone asks if I want to allow access. Tried for 2 days. Nothing seems to help.
Tried this as well
Problems Mounting Samsung Galaxy Note 5 16.04
Running Android 7.0 Everything is stock. Haven't rooted the phone.
Everything worked fine on 17.04.
dad@dad-System:~$ lsusb
Bus 002 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 004 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub
Bus 001 Device 002: ID 0424:2504 Standard Microsystems Corp. USB 2.0 Hub
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 003 Device 002: ID 062a:4101 Creative Labs Wireless Keyboard/Mouse
Bus 003 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub
Bus 008 Device 002: ID 0bda:0301 Realtek Semiconductor Corp. multicard reader
Bus 008 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hub
Bus 007 Device 016: ID 04e8:6860 Samsung Electronics Co., Ltd Galaxy (MTP)
Bus 007 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 006 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hub
Bus 005 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub

A: do the following :
sudo apt-get install go-mtpfs
sudo apt-get install libmtp
sudo apt-get install mtpfs mtp-tools

Plug in your phone and do:
mtp-detect

Note the VID and PID, they will be used later. Then sudo gedit /etc/udev/rules.d/51-android.rules and insert a line that says SUBSYSTEM=="usb", ATTR{idVendor}=="Insert VID here", ATTR{idProduct}=="Insert PID here", MODE="0666"
After that restart udev:
sudo service udev restart

If you want to get the contents of an external SD card, remove your phone, Shut down THE PHONE, remove the SD card, Turn on the phone without the SD card, Shut it down, put the SD card in again, turn the phone on, shut down your Ubuntu, then plug the phone in.


Q: Variable "Name" is not readable, how can I fix it? I was inserting some code to make a registration form, but iIfound this
class User {

    private String Nama;
    private String Kelas;
    private int NIM;

    public String getNama{
        return Nama;
    }
    public String setNama{

    }
}

The error message was all "variable is never read". Can someone explain why there is a message on this, and how I can fix it?

A: Though it is not clear where you use your codes, but the following is a java model class, with setter and getter method. Even it is not the direct answer of you question, but I have used this types of model class in my projects, one can find the idea of setter and getter from the following user class.
For using in various purposes You can create your User class as follows with constructors and setter and getter methods :
public class User {

    private String Nama;
    private String Kelas;
    private int NIM;

    public User() {
    }

    public User(String nama, String kelas, int NIM) {
        Nama = nama;
        Kelas = kelas;
        this.NIM = NIM;
    }

    public String getNama() {
        return Nama;
    }

    public void setNama(String nama) {
        Nama = nama;
    }

    public String getKelas() {
        return Kelas;
    }

    public void setKelas(String kelas) {
        Kelas = kelas;
    }

    public int getNIM() {
        return NIM;
    }

    public void setNIM(int NIM) {
        this.NIM = NIM;
    }
}


Q: Run a javascript on regex pattern match url (Blogger) I'm trying to load a javascript on several pages but I only on pages which the url matches with a specific pattern.
The following code works for specific pages but it doesn't accept any wildcard or regex
<b:if cond='data:blog.url == "https://mywebsite.com/yyyy/mm/article.html"'>
<script src='https://javascritp.js'/>
</b:if>

The closest thing I found is described here but since my website is running on Blogger I don't know how to use that code.
Any suggestion or help please?

A: Blogger conditional statements don't provide pattern matching capability. It would be easier to implement what you require via JavaScript directly in the Blogger template -
An example code would look like -
if(window.location.href.match(/Regex-Condition/){
    var script = document.createElement('script'); script.type = 'text/javascript';
    script.src = 'URL-Of-The-Script-You-Want-To-Load';script.async=true;
    var insertScript = document.getElementsByTagName('script')[0]; insertScript.parentNode.insertBefore(script, insertScript);
}

Other than this, you can also take a look at Lambda expressions (Refer to How to use Google Blogger Lambda Operators )

A: Hi and thank you for your feedback! While I was waiting for some reply I realized I've to use JavaScript as you said.
I was testing this code but it looks something is wrong:
<script type='text/javascript'>

var pattern = new RegExp('mywebsite\.com\/(200[8-9]|201[0-6])\/');
if (pattern.test(document.location.href)) {

}

</script>

I've two main concerns:

*

*if the regex is correct

*between the brackets I've to execute some code which includes Blogger conditional statements, div and plain JavaScript. Does this code need some special attention?

Thanks


Q: Split string using SUBSTR or SPLIT? I'm at a loss and hoping to find help here. What I'm trying to accomplish is the following:
I have a .csv file with 8 columns. The third column contains phone numbers formatted like so:
+45 23455678
+45 12314425
+45 43631678
+45 12345678
(goes on for a while)

What I want is:
+45 2345 5678
+45 1231 4425
+45 4363 1678
+45 1234 5678
(etc)

So just a whitespace after the 8th position (inc the + and whitespace). I've tried various things but it's not working. First I tried it with substr but couldn't get it to work. Then looked at the split function. And then I got confused! I'm new to perl so I'm not sure what I'm looking for but I've tried everything. There's 1 condition, all the numbers begin with (let's say) +45 and then a whitespace and a block of numbers. But not all the numbers have the same length, some have more than 10 digits. What I want it to do is take the first bit "+45 1234" (/+43\s{1}\d{4}/) and then the second part no matter how many digits it has. I figured setting LIMIT to 1 so it just adds the last bit no matter if its 4 digits or 8 long.
I've read http://www.perlmonks.org/?node_id=591988, but the part "Using split versus Regular Expressions" got me confused.
I've been trying for 3 days now and not getting anywhere. I guess it should be simple but I'm just now getting to know the basics of perl. I do have an understanding of regular expression but I don't know what statement to use for a certain task. This is my code:
@ARGV or die "Usage: $0  input-file output-file\n";

$inputfile=$ARGV[0];
$outputfile=$ARGV[1];

open(INFILE,$inputfile) || die "Bestand niet gevonden :$!\n";
open(OUTFILE,">$outputfile") || die "Bestand niet gevonden :$!\n";

$i = 0;

@infile=<INFILE>;

foreach ( @infile ) {
    $infile[$i] =~ s/"//g;
    @elements = split(/;/,$infile[$i]);

    @split = split(/\+43\s{1}\d{4}/, $elements[2], 1);

    @split = join ???

    @elements = join(";",@elements);            # Add ';' to all elements
    print OUTFILE "@elements";
    $i = $i+1;
}

close(INFILE);
close(OUTFILE);

A: There are several issues with your code, but to address your question on how to add a space after the 8th position in a string, I'm going to assume you have stored your phone numbers in an array @phone_numbers. This is a task well suited for a regex:
#!/usr/bin/env perl
use strict;
use warnings;
use Data::Dumper;

my @phone_numbers = (
    '+45 23455678',
    '+45 12314425',
    '+45 43631678',
    '+45 12345678'
);

s/^(.{8})/$1 / for @phone_numbers;

print Dumper \@phone_numbers;

Output:
$VAR1 = [
      '+45 2345 5678',
      '+45 1231 4425',
      '+45 4363 1678',
      '+45 1234 5678'
    ];

To apply the pattern to your script, just add:
$elements[2] =~ s/^(.{8})/$1 /;

or alternatively
my @chars = split//, $elements[2];
splice @chars, 8, 0, ' ';
$elements[2] = join"", @chars;

to alter phone numbers within your foreach loop.

A: Here is a more idiomatic version of your program.
use strict;
use warnings;

my $inputfile  = shift || die "Need input and output file names!\n";
my $outputfile = shift || die "Need an output file name!\n";

open my $INFILE,  '<', $inputfile   or die "Bestand niet gevonden :$!\n";
open my $OUTFILE, '>', $outputfile  or die "Bestand niet gevonden :$!\n";

my $i = 0;

while (<$INFILE>) {
    # print; # for debugging
    s/"//g;
    my @elements = split /;/, $_;
    print join "%", @elements;
    $elements[2] =~ s/^(.{8})/$1 /;
    my $output_line = join(";", @elements);
    print $OUTFILE $output_line;
    $i = $i+1;
}

close $INFILE;
close $OUTFILE;

exit 0;

A: use substr on left hand side:
use strict;
use warnings;

while (<DATA>) {
    my @elements = split /;/, $_;
    substr($elements[2], 8, 0) = ' ';
    print join(";", @elements);
}

__DATA__
col1;col2;+45 23455678
col1;col2;+45 12314425
col1;col2;+45 43631678
col1;col2;+45 12345678

output:
col1;col2;+45 2345 5678
col1;col2;+45 1231 4425
col1;col2;+45 4363 1678
col1;col2;+45 1234 5678

A: Perl one liner which you can use for multiple .csv files also.
perl -0777 -i -F/;/ -a -pe "s/(\+45\s\d{4})(\d+.*?)/$1 $2/ for @F;$_=join ';',@F;" s_infile.csv

A: This is the basic gist of how its done. The "prefix" to the numeric string is \+45, which is hard coded, and you may change it as needed. \pN means numbers, {4} means exactly 4.
use strict;
use warnings;

while (<DATA>) {
    s/^\+45 \pN{4}\K/ /;
    print;
}

__DATA__
+45 234556780
+45 12314425
+45 436316781
+45 12345678

Your code has numerous other problems:
You do not use use strict; use warnings;. This is a huge mistake. It's like riding a motorcycle and protecting your head by putting on a blindfold instead of a helmet. Often, it is an easy piece of advice to overlook, because it is explained very briefly, so I am being more verbose than I have to in order to make a point: This is the most important thing wrong. If you miss all the rest of your errors, it's better than if you miss this part.

Your open statements are two-argument, and you do not verify your arguments in any way. This is very dangerous, because it allows people to perform arbitrary commands. Use the three-argument open with a lexical file handle and explicit MODE for open:
open my $in, "<", $inputfile or die $!;

You slurp the file into an array: @infile=<INFILE> The idiomatic way to read a file is:
while (<$in>) {  # read line by line
    ...
}

What's even worse, you loop with foreach (@infile), but refer to $infile[$i] and keep a variable counting upwards in the loop. This is mixing two styles of loops, and even though it "works", it certainly looks bad. Looping over an array is done either:
for my $line ( @infile ) {  # foreach style
    $line =~ s/"//g;
    ...
}

for my $index ( 0 .. $#infile ) { # array index style
    $infile[$index] =~ ....
}

But neither of these two loops are what you should use, since the while loop above is much preferred. Also, you don't actually have to use this method at all. The *nix way is to supply your input file name or STDIN, and redirect STDOUT if needed:
perl script.pl inputfile > outputfile

or, using STDIN
some_command | perl script.pl > outputfile

To achieve this, just remove all open commands and use
while (<>) {  # diamond operator, open STDIN or ARGV as needed
    ...
}

However, in this case, since you are using CSV data, you should be using a CSV module to parse your file:
use strict;
use warnings;
use ARGV::readonly;  # safer usage of @ARGV file reading

use Text::CSV;

my $csv = Text::CSV->new({
        sep_char    => ";",
        eol     => $/,
        binary      => 1,
        });

while (my $row = $csv->getline(*DATA)) {  # read input line by line
    if (defined $row->[1]) {              # don't process empty rows
        $row->[1] =~ s/^\+45 *\pN{4}\K/ /;
    }
    $csv->print(*STDOUT, $row);
}

__DATA__
fooo;+45 234556780;bar
1231;+45 12314425;
oh captain, my captain;+45 436316781;zssdasd
"foo;bar;baz";+45 12345678;barbarbar

In the above script, you can replace the DATA file handle (which uses inline data) with ARGV, which will use all script argument as input file names. For this purpose, I added ARGV::readonly, which will force your script to only open files in a safe way.
As you can see, my sample script contains quoted semi-colons, something split would be hard pressed to handle. The specific print statement will enforce some CSV rules to your output, such as adding quotes. See the documentation for more info.

A: To add a space after the eighth character of a string you can use the fourth parameter of substr.
substr $string, 8, 0, ' ';

replaces a zero-length substring starting at offset 8 with a single space.
You may think it's safer to use regular expressions so that only data in the expected format is changed
$string =~ s/^(\+\d{2} \d{4})/$1 /;

or
$str =~ s/^\+\d{2} \d{4}\K/ /;

will achieve the same thing, but will do nothing if the number doesn't look as it should beforehand.
Here is a reworking of your program. Most importantly you should use strict and use warnings at the start of your program, and declare variables with my at the point of their first use. Also use the three-paramaeter form of open and lexical filehandles. Lastly it is best to avoid reading an entire file into an array when a while loop will let you process it a line at a time.
use strict;
use warnings;

@ARGV == 2 or die "Usage: $0 input-file output-file\n";

my ($inputfile, $outputfile) = @ARGV;

open my $in, '<', $inputfile or die "Bestand niet gevonden: $!";
open my $out, '>', $outputfile or die "Bestand niet gevonden: $!";

while (<$in>) {
  tr/"//d;
  my @elements = split /;/;
  substr $elements[2], 8, 0, ' ';
  print $out join ';', @elements;
}


Q: DOM reload after ajax form injection Ive tried similar questions to no avail.
My question is simply how to reload the DOM after an ajax request has been made?
Its not a question regarding event delegation, rather one concerning jquery selectors.
sample:
editUser : function(){
            var editItem = $("a.edit");

            editItem.on('click', function(e){
                e.preventDefault();

               //click the users tab & the edit tab
                var usersjq = $("li#users-jq");
                usersjq.find("a").eq(0).click();
                $("ul.tabs").find("a").eq(2).click();

                var uid = $(this).attr('id').split('_')[1];
                $(".three #users-edit").empty();

                $(".three #users-edit").load(BASE_PATH + 'users/admin/users/edit/' + uid, function(){
                   //loads a form with id of #form-users-edit

                }, 'html');

            });
        },
formEditUsers : function(){

            //#form-users-edit is not selectable

            //all of these just return jQuery ( )
            console.log($(".three #users-edit").find("#form-users-edit"));
            console.log($(document.forms));
            console.log($("form#form-users-edit"));

        }

Regards.

A: Passing formEditUsers() into the ajax success callback seems to work fine.


Q: Not full binding in knockout Knockout doesn't work as expected, im my interface.
I suppose my mistake. But I cannot understand it.
I have an album with genres included tracks with genres:
var initialData = [{
    title: 'Danny',
    genres: [
        {id: 21,
        title: 'Noise'},
        {id: 22,
        title: 'EBM'}],
    tracks: [
        {title: 'Pony',
        genres: [
            {id: 21,
            title: 'Noise'},
            {id: 22,
            title: 'EBM'}]},
        {title: 'Hungry',
        genres: [
            {id: 21,
            title: 'Noise'},
            {id: 22,
            title: 'EBM'}]}
    ]

}];

I want to create 1-way sync between album genres to tracks genres:

*

*If i add genre to album, this genre would be added to all tracks.

*If i delete genre from album, this genre would be deleted from all tracks.

*If i add genre to track, this genre would be added only to this track.

*If i delete genre from track, this genre would be deleted only from this track.

My sync works fine (except one case) with this functions:
self.addGenre = function(album) {
    var id = rand(),
        item = {
            id: id,
            title: ' genre #' + id
        };
    album.genres.push(item);

    if (album.tracks()) {
        $.each(album.tracks(), function (index, track) {
            track.genres.push(item);
        });
    }
};

self.removeGenre = function(genre) {
    $.each(self.albums(), function() {
        this.genres.remove(genre);
        if (this.tracks()) {
            $.each(this.tracks(), function (index, track) {
                track.genres.remove(genre);
            });
        }
    });
};

Exception is if I want to delete default (Noise, EBM, see initialData above ) genre from albums. it doesn't work.
I created an jsFiddle to show this case and include in it a lot of console.log() to debug

A: The problem is that when you use ko-mapping, it turns every property into an observable. The new genres you create are not the same kind of object as the initial objects, because they are just standard vanilla objects. So the genre you are trying to remove from the track is not the same one you removed from the album.
A simple way to fix your issue is to alter the remove function, as in this fiddle.
$.each(this.tracks(), function(index, track) {
    var toRemove = ko.utils.arrayFirst(track.genres(), function(item) {
        return ko.utils.unwrapObservable(genre.id) == ko.utils.unwrapObservable(item.id);
    });
    track.genres.remove(toRemove);
});

A better way would be to be a little more thorough in generating your initial viewmodel, the new genres, or both. This won't be easy.


Q: Transitioning Between Index Paths in a DetailViewController? Swift So using the code below, I've segued my CollectionViewCell indexPath into the new DetailViewController. now each `DetailViewController displays what is contained in the array of the indexPath selected.
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

    let animal: Animal!
    let anims: [Animal] = dataSource.anims

    animal = anims.filter{ $0.isDefault }[indexPath.row]

    DispatchQueue.main.async {
        self.performSegue(withIdentifier: "DetailVC", sender: animal)
    }
}

So that means the new DetailVCwill be able to pull the data from the array that corresponds with the selected indexPath.row, which it does.
Now here's the issue. Once I'm in the DetailVC, I want to make a button that lets me switch the displayed data to the previous or next indexPath.row. To explain it better, below is some Pseudo-Code that explains what I'm trying to do
@IBAction func nextIndex(_ sender: Any) {
     self.view.indexPath.row = self.view.indexPath.row +1
        or
     self.datasource = next datasource index
}

Now what would I need to do to transition between these indexPaths from inside the DetailViewController? Such as a "go to next" or "go to previous" or "go to [selected path]" button?
I feel there may be a simple answer to this that I'm not getting.

A: Easy solution: You can implement singleton, manager that will be responsible for this. e.g.
class AnimalManager: NSObject {

    static let shared = AnimalManager()

    private var animals = [Animal]()
    private var currentIndex: Int?

    .....
}

Now you can implement such methods like: current animal, next animal, revious, etc.


Q: Colour newly added bar in bar chart automatically when new data is received Following code basically put a colour in my bar graph based on cell D112 value. Now is there a way to automatically put colour as new data is available and new bar is added to my bar chart? For example, Cell D112 is the value for the month of Jan, now when i get value in cell D113 for the month of Feb, how do i colour the bar of that month automatically? I'm guessing there has to be some kind of a loop here right?
Sub ColorGraphs()

Dim ChrtObj As ChartObject
Dim Ser As Series
Dim SerPoint As Point

Set ChrtObj = ActiveSheet.ChartObjects("Chart 18")

Set Ser = ChrtObj.Chart.SeriesCollection(1)

Set SerPoint = Ser.Points(3)

With SerPoint.Format.Fill
    .Visible = msoTrue
    .Transparency = 0
    .Solid
End With

Select Case Range("D112").Value
    Case Is < 0.96
        SerPoint.Format.Fill.ForeColor.RGB = RGB(204, 0, 51)
        Range("P8").Interior.Color = RGB(204, 0, 51)

    Case 0.96 To 0.98
        SerPoint.Format.Fill.ForeColor.RGB = RGB(255, 102, 0)
        Range("P8").Interior.Color = RGB(255, 102, 0)

    Case Else ' larger than 0.98
        SerPoint.Format.Fill.ForeColor.RGB = RGB(0, 153, 102)
        Range("P8").Interior.Color = RGB(0, 153, 102)

End Select

End Sub

A: Try putting your code in Private Sub Worksheet_Change(ByVal Target as Range).
This Sub runs te code every time a cell is changed.


Q: Is there a data structure for a list ordered by value? I've got a JTable which shows the top 10 scores of a game. The data structure looks like the following:
    // {Position, Name, Score}
Object[][] data = {
    {1, "-", 0},
    {2, "-", 0},
    {3, "-", 0},
    {4, "-", 0},
    {5, "-", 0},
    {6, "-", 0},
    {7, "-", 0},
    {8, "-", 0},
    {9, "-", 0},
    {10, "-", 0}
};

I want to be able to add a new score to this array in the correct order (so if it was the 3rd highest, it would be put at index 2). I'll then truncate this list down to the top 10 again and update the table.
I know this is trivial to do by looping through and checking, but I'd like to know if there is an appropriate data structure that is better suited for data ordered by a value? Or is the simple two-dimensional array the only/best?

A: Use a TreeSet with a custom comparator.
Also, you should not work with Multi-dimensional arrays, use Maps (Name -> Score) or custom Objects

A: Hey, if your array is sorted, u can use the Collections.binarySearch() or Arrays.binarySearch() method to guide u at what index to make the insertion. The way these method work is to make a binary search after an existing element, and if the element cannot be found in the collection it will return a value related to the insertion point.
More info here Collections.binarySearch


Q: How to validate status code in robot framework i about to make a validation status code in robot framework. i create value in json with wrong password and i want to make validation code 400 bad request with this code.
login_negative_user

${json}     Load JSON From File     ${CURDIR}/../json/negativeuser.json
# Set Test Variable   ${JSON_SCHEMA}  ${json}
${resp}=    POST    ${base_url}/horde/v1/auth/login     json=${json}
${data}     Convert To String       ${resp.json()}
Status Should Be    400 ${resp}
Should Be Equal As Strings      ${resp.status_code}     400
${jsondata}     evaluate    ${data}
${poselang}=    Set Variable    ${jsondata['data']['token']}

Set Global Variable     ${poselang}
log to console  Get poselang token

But my log is this
login negativeuser                                                    | FAIL |

HTTPError: 400 Client Error: Bad Request for url: {secret api}
am i wrong to make validation with that code? sorry i cant tell the api because it is secret


Q: Is there a way to rename a similarly named column from two tables when performing a join? I have two tables that I am joining with the following query...
select *
  from Partners p
inner join OrganizationMembers om on p.ParID = om.OrganizationId
where om.EmailAddress = 'my_email@address.com'
  and om.deleted = 0

Which works great but some of the columns from Partners I want to be replaced with similarly named columns from OrganizationMembers.  The number of columns I want to replace in the joined table are very few, shouldn't be more than 3.
It is possible to get the result I want by selectively choosing the columns I want in the resulting join like so...
select om.MemberID,
       p.ParID,
       p.Levelz,
       p.encryptedSecureToken,
       p.PartnerGroupName,
       om.EmailAddress,
       om.FirstName,
       om.LastName
 from Partners p
inner join OrganizationMembers om on p.ParID = om.OrganizationId
     where om.EmailAddress = 'my_email@address.com'
       and om.deleted = 0

But this creates a very long sequence of select p.a, p.b, p.c, p.d, ... etc  ... which I am trying to avoid.
In summary I am trying to get several columns from the Partners table and up to 3 columns from the OrganizationMembers table without having a long column specification sequence at the beginning of the query.  Is it possible or am I just dreaming?

A: select om.MemberID as mem

Use th AS keyword. This is called aliasing.

A: Try this:
p.*,
om.EmailAddress,
om.FirstName,
om.LastName

You should never use * though. Always specifying the columns you actually need makes it easier to find out what happens.

A: You are dreaming in your implementation.
Also, as a best practice, select * is something that is typically frowned upon by DBA's.
If you want to limit the results or change anything you must explicitly name the results, as a potential "stop gap you could do something like this.
SELECT p.*, om.MemberId, etc..

But this ONLY works if you want ALL columns from the first table, and then selected items.

A:
But this creates a very long sequence
  of select p.a, p.b, p.c, p.d, ... etc
  ... which I am trying to avoid.

Don't avoid it. Embrace it!
There are lots of reasons why it's best practice to explicity list the desired columns.

*

*It's easier to do searches for where a particular column is being used.

*The behavior of the query is more obvious to someone who is trying to maintain it.

*Adding a column to the table won't automatically change the behavior of your query.

*Removing a column from the table will break your query earlier, making bugs appear closer to the source, and easier to find and fix.

And anything that uses the query is going to have to list all the columns anyway, so there's no point being lazy about it!


Q: can not read some string from struts.properties I have define variable error in struts.properties as follows:
error=this is an error

Now I can call this error as follows:
ErrorMsg = "<s:property value='getText(\"error\")'/>";

and it works, the result is: ErrorMsg=this is an error
How to get the text of variable instead of string?
I tried the following:
var m="error";
  error1 = "<s:property value='getText(m)'/>";
  error2 = "<s:property value='getText(\"m\")'/>";

I use firebug debugger and error1 and error2 are displyed as follows:
error1=""
error2=""

Any Idea?
thank you in advance

A: You appear to be mixing server side and client side code.
The s:property tags will be evaluated first on the server side, long before any value of m is valid, as that is client side JavaScript code.
If you post what you're trying to achieve then I or someone else may be able to help further.
HTH


Q: 'boost/multi_array.hpp' file not found error while building on Mac I am trying to build using Cmake on macOS Big Sur. Following is the makefile.
CMAKE_MINIMUM_REQUIRED(VERSION 3.5)

#------------------------------------------------------------------------------#
#                             Compiler setup
#------------------------------------------------------------------------------#

IF(CMAKE_SYSTEM_NAME=Windows)
  SET(ADDITIONAL_FLAGS "-DWIN32")
ENDIF(CMAKE_SYSTEM_NAME=Windows)

SET(CMAKE_CXX_COMPILER "g++")
SET(CMAKE_CXX_FLAGS "-std=c++17 -g -Wall -Wno-uninitialized")
SET(CMAKE_CXX_FLAGS_DEBUGALL "${CMAKE_CXX_FLAGS} -fsanitize=address,undefined -pthread" )
SET(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS} -O3 -DOPTIMIZE -pthread" ${ADDITIONAL_FLAGS} )
SET(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS} -O3 -DNDEBUG -DOPTIMIZE -pthread" ${ADDITIONAL_FLAGS} )
SET(CMAKE_CXX_FLAGS_RELWITHDEBINFO "${CMAKE_CXX_FLAGS} -O3 -g -DNDEBUG -DOPTIMIZE -pthread" ${ADDITIONAL_FLAGS} )

#SET(CMAKE_BUILD_TYPE Debug)
IF(NOT CMAKE_BUILD_TYPE)
  SET(CMAKE_BUILD_TYPE Release CACHE STRING "Choose the type of build: Debug Release RelWithDebInfo" FORCE)
ENDIF(NOT CMAKE_BUILD_TYPE)

#------------------------------------------------------------------------------#
#                             Required libraries
#------------------------------------------------------------------------------#

SET(Boost_DEBUG "ON")
SET(Boost_USE_STATIC_LIBS "ON")
SET(HOME_DIR ${CMAKE_CURRENT_SOURCE_DIR} CACHE INTERNAL "")
SET(CMAKE_MODULE_PATH ${HOME_DIR}/CMake)

FIND_PACKAGE(Boost COMPONENTS filesystem program_options timer chrono REQUIRED)
SET(EXTERNAL_INCLUDES ${Boost_INCLUDES})
SET(EXTERNAL_LIBRARIES ${Boost_LIBRARIES})

FIND_PACKAGE(Eigen3 3.3.4)
INCLUDE_DIRECTORIES(${EIGEN3_INCLUDE_DIRS})

#------------------------------------------------------------------------------#
#                             Directories for compiled libraries
#------------------------------------------------------------------------------#

INCLUDE_DIRECTORIES(src/Mesh)
INCLUDE_DIRECTORIES(src/Quadrature)
INCLUDE_DIRECTORIES(src/Common)
INCLUDE_DIRECTORIES(src/HybridCore)
INCLUDE_DIRECTORIES(src/Plot)
INCLUDE_DIRECTORIES(src/DDRCore)

ADD_SUBDIRECTORY(src/Mesh)
ADD_SUBDIRECTORY(src/Quadrature)
ADD_SUBDIRECTORY(src/Common)
ADD_SUBDIRECTORY(src/HybridCore)
ADD_SUBDIRECTORY(src/Plot)
ADD_SUBDIRECTORY(src/DDRCore)

#------------------------------------------------------------------------------#
#                             Directories for schemes
#------------------------------------------------------------------------------#

INCLUDE_DIRECTORIES(Schemes)
ADD_SUBDIRECTORY(Schemes)

While running make command I am getting
fatal error: 'boost/multi_array.hpp' file not found
#include <boost/multi_array.hpp>

I have boost installed with the help of brew. I also tried this https://stackoverflow.com/a/32929012/8499104 to verify my path is correct. Still not able to figure out why this is not able to find this library.


Q: Redirecting in react-router-dom v6 in a non-JSX context I'm trying to redirect a user from the route they are currently looking at to another route programatically. In my case, I am not in a JSX environment, and cannot use any kind of React hooks. How would I go about this?
I tried to use the code block below to redirect (tried using JSX), only to realize that it wouldn't work as it isn't in the context of the root router.
ReactDOM.render(<div>
    <Navigate to="/" />
</div>, document.getElementById("redirect"));

I also want to try and redirect without using window.location.href = as that would cause the whole page to refresh, something I don't want to happen.
EDIT: As requested, I am trying to redirect to a page from an event that is emitted by Tauri and is handled by some TypeScript code on the front end. Using window.location.href isn't an issue in any case.
Here is an example of what I'm trying to do:
/**
 * Sets up event listeners.
 */
export async function setupListeners() {
    console.log("Setting up link event listeners...");
    await listen("deeplink", onLinked);
}

/**
 * Invoked when a deep link call is received.
 * @param event The event.
 */
async function onLinked(event: Event<string>) {
    const { payload } = event;
    if (payload == "test:")
        // redirect("/testPage");
}

A: See redirect:
import { redirect } from "react-router-dom";

const loader = async () => {
  const user = await getUser();
  if (!user) {
    return redirect("/login");
  }
};

(from the docs)


Q: How does Doctrine generate:entities create getters and setter in symfony I have class User likr this
class user implements UserInterface {

protected id ,
protected username;

Then i have
class student extends user {

protected id ,
protected rollno;

Now when i run this
php app/console doctrine:generate:entities myBundle

Then propery username gets inserted in class student.
I want to know that is this ok or its error. Because then whats the use of extending from base class if my lass is going to be populated with all stuff

A: This isn't an error.
Symfony threats all classes as entities and if you're "mapping" them with doctrine you'll create the corrisponding tables onto database.
Now inheritance have to be taken into account: every "field" (property) into parent classe, will be extended or inherited by child.
So is perfectly clear that the corresponding parent field will be created into database.
To me the best way for solve this is to create a parent class and to migrate all commons (fields,methods and so on...) into it.
Then, you'll extend that new parent calss into user with specific fields (in that case username) aswell into student with student's specific fields.

A: Yeah, that's probably not an error, although I agree it can be annoying.
To see how exactly are they generated you can look into the command class.


Q: How to create a multicolored string? I'm interested in displaying a string composed from sub-strings of different colors.
Mathematica allows one to create a list comprising sub-strings of different colors, for example
{Style["Blue", Blue], Style["Red", Red]}

I would like to create a string looking like

StringJoin doesn't enable to tackle the problem

A: For display purposes you can use Row (as suggested by Szabolcs in comments).
Alternatively, you can use StringRiffle or StringTemplate after wrapping styled strings with ToString[#, StandardForm]:
StringRiffle[ ToString[#, StandardForm] & /@ {Style["Red", Red, 24],
    Style["Blue", Blue, 16]},""]

StringTemplate["````"] @@
 (ToString[#, StandardForm] & /@ {Style["Red", Red, 24], Style["Blue", Blue, 16]})

To get a string object you can use
str = StringJoin[
  ToString[#, StandardForm] & /@ {Style["Red", Red, 24], Style["Blue", Blue, 16]}]

Head[str]

String


Q: Double buffering with C# has negative effect I have written the following simple program, which draws lines on the screen every 100 milliseconds (triggered by timer1). I noticed that the drawing flickers a bit (that is, the window is not always completely blue, but some gray shines through). So my idea was to use double-buffering. But when I did that, it made things even worse. Now the screen was almost always gray, and only occasionally did the blue color come through (demonstrated by timer2, switching the DoubleBuffered property every 2000 milliseconds).
What could be an explanation for this?
using System;
using System.Drawing;
using System.Windows.Forms;

namespace WindowsFormsApplication1 {
    public partial class Form1 : Form {
        public Form1() {
            InitializeComponent();
        }

        private void Form1_Paint(object sender, PaintEventArgs e) {
            Graphics g = CreateGraphics();
            Pen pen = new Pen(Color.Blue, 1.0f);
            Random rnd = new Random();
            for (int i = 0; i < Height; i++)
                g.DrawLine(pen, 0, i, Width, i);
        }

        // every 100 ms
        private void timer1_Tick(object sender, EventArgs e) {
            Invalidate();
        }

        // every 2000 ms
        private void timer2_Tick(object sender, EventArgs e) {
            DoubleBuffered = !DoubleBuffered;
            this.Text = DoubleBuffered ? "yes" : "no";
        }
    }
}

A: I would just draw all of your items to your own buffer, then copy it all in at once.  I've used this for graphics in many applications, and it has always worked very well for me:
    public Form1()
    {
        InitializeComponent();
    }
    private void timer1_Tick(object sender, EventArgs e)
    {
        Invalidate();// every 100 ms
    }
    private void Form1_Load(object sender, EventArgs e)
    {
        DoubleBuffered = true;
    }
    private void Form1_Paint(object sender, PaintEventArgs e)
    {
        Bitmap buffer = new Bitmap(Width, Height);
        Graphics g = Graphics.FromImage(buffer);
        Pen pen = new Pen(Color.Blue, 1.0f);
        //Random rnd = new Random();
        for (int i = 0; i < Height; i++)
            g.DrawLine(pen, 0, i, Width, i);
        BackgroundImage = buffer;
    }

EDIT: After further investigation, it looks like your problem is what you're setting your Graphics object to:
Graphics g = CreateGraphics();

needs to be:
Graphics g = e.Graphics();

So your problem can be solved by either creating a manual buffer like I did above, or simply changing you Graphics object.  I've tested both and they both work.

A: Try setting the double buffered property to true just once in the constructor while you're testing.
You need to make use of the back buffer. Try this:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace DoubleBufferTest
{
    public partial class Form1 : Form
    {
        private BufferedGraphicsContext context;
        private BufferedGraphics grafx;

        public Form1()
        {
            InitializeComponent();

            this.Resize += new EventHandler(this.OnResize);
            DoubleBuffered = true;

            // Retrieves the BufferedGraphicsContext for the
            // current application domain.
            context = BufferedGraphicsManager.Current;

            UpdateBuffer();
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            this.Refresh();

        }

        private void OnResize(object sender, EventArgs e)
        {
            UpdateBuffer();
            this.Refresh();
        }

        private void UpdateBuffer()
        {
            // Sets the maximum size for the primary graphics buffer
            // of the buffered graphics context for the application
            // domain.  Any allocation requests for a buffer larger
            // than this will create a temporary buffered graphics
            // context to host the graphics buffer.
            context.MaximumBuffer = new Size(this.Width + 1, this.Height + 1);

            // Allocates a graphics buffer the size of this form
            // using the pixel format of the Graphics created by
            // the Form.CreateGraphics() method, which returns a
            // Graphics object that matches the pixel format of the form.
            grafx = context.Allocate(this.CreateGraphics(),
                 new Rectangle(0, 0, this.Width, this.Height));

            // Draw the first frame to the buffer.
            DrawToBuffer(grafx.Graphics);
        }

        protected override void OnPaint(PaintEventArgs e)
        {
            grafx.Render(e.Graphics);
        }

        private void DrawToBuffer(Graphics g)
        {
            //Graphics g = grafx.Graphics;
            Pen pen = new Pen(Color.Blue, 1.0f);
            //Random rnd = new Random();
            for (int i = 0; i < Height; i++)
                g.DrawLine(pen, 0, i, Width, i);
        }
    }
}

It's a slightly hacked around version of a double buffering example on MSDN.

A: No need to use multiple buffers or Bitmap objects or anything.
Why don't you use the Graphics object provided by the Paint event? Like this:
private void Form1_Paint(object sender, PaintEventArgs e)
{
    Graphics g = e.Graphics;
    Pen pen = new Pen(Color.Blue, 1.0f);
    Random rnd = new Random();
    for (int i = 0; i < Height; i++)
        g.DrawLine(pen, 0, i, Width, i);
}


Q: OnNotifyPropertyChanged not firing get I have a class which has an ObservableCollection called Items. That list should fill up a RadGridView. Even though the OC contains data, the list stays empty, and after a bit of debuggingg I noticed it has some odd behavior. I have a breakpoint in the Get and Set of the property. First it hits the Get. Then the Set, but it never hits the Get again. Shouldn't the NotifyChanged also trigger the get after that then, so it updates the list in the view?
Here is the code below of the class I am talking about:
public class PagedCollection<TEntity> where TEntity : class, INotifyPropertyChanged
{
    internal WorkflowEntities Context;
    internal DbSet<TEntity> DbSet;

    private ObservableCollection<TEntity> _items;
    public ObservableCollection<TEntity> Items
    {
        get
        {
            return _items;
        }
        set
        {
            SetField(ref _items, value, nameof(Items));
        }
    }

    public PagedCollection()
    {
        Context = new WorkflowEntities();
        DbSet = Context.Set<TEntity>();
    }

    public virtual IEnumerable<TEntity> Get(Expression<Func<TEntity, bool>> filter = null,
                                            Func<IQueryable<TEntity>, IQueryable<TEntity>> query = null,
                                            string includeProperties = "")
    {
        IQueryable<TEntity> value = DbSet;

        if (filter != null)
        {
            value = value.Where(filter);
        }

        value = includeProperties.Split(new[] {','}, StringSplitOptions.RemoveEmptyEntries).Aggregate(value, (current, includeProperty) => current.Include(includeProperty));

        return query?.Invoke(value).ToList() != null ? query(value).ToList() : value.ToList();
    }

    // boiler-plate
    public event PropertyChangedEventHandler PropertyChanged;
    protected virtual void OnPropertyChanged(string propertyName)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
    }
    protected bool SetField<T>(ref T field, T value, string propertyName)
    {
        if (EqualityComparer<T>.Default.Equals(field, value)) return false;
        field = value;
        OnPropertyChanged(propertyName);
        return true;
    }
}

The public virtual IEnumerable<TEntity> Get(...) is being triggered by another class, which fills up the Items. Like this: PagedCollection.Items = PagedCollection.Get();. This in turn fires the get, set, but not a get anymore, so my list stays empty in the view, even though there is data in PagedCollection.Items

A: Your class, PagedCollection, doesn't implement INotifyPropertyChanged.
public class PagedCollection<TEntity> where TEntity : class, INotifyPropertyChanged

What this says is that TEntity must be a class and implement INotifyPropertyChanged.
Try this instead:
public class PagedCollection<TEntity> : INotifyPropertyChanged where TEntity : class, INotifyPropertyChanged

A: You can't call PagedCollection.Get(); like that you have to instantiate something.

A: A change in a property of an object within a regular ObservableCollection does not trigger the CollectionChanged event.
Maybe you could use the TrulyObservableCollection class, derived from the former:
ObservableCollection not noticing when Item in it changes (even with INotifyPropertyChanged)

A: One thing is the ObservableCollection property itself.
When you run the program, it is get once when the view is loaded, and it is set once when you first initialize that property.
After that, when you populate the list, it's not the PropertyChanged event that is fired, since it would be fired only if you assign the whole OC property to another value (usually via Items = new ObservableCollection<TEntity>());
Thus, the event you should be watching is CollectionChanged, which is fired every time you add, remove, swap or replace elements.


Q: Can you prove p → p using only Deduction theorem? I've been asked to prove $\vdash p\rightarrow p$ using the Deduction theorem. We're usually given a list of axioms (page 20 of the book, 24 of the pdf) to use in our proofs but not this time.
Can you actually prove this tautology using the Deduction theorem and not repeating the proof in that same page? Since everything on the RHS has to be an axiom, I can't find find a different way of doing it, let alone using DT.
Thank you
Edit:
$p \vdash p \implies \vdash p \rightarrow p$ answered in the comments


Q: Lenovo Ideapad 530S - Heavy throttling making CPU stuck at 1.58GHz clock speed - Any solutions? I'm using a Lenovo Ideapad 530S, which has i5 8250U CPU and MX150 GPU.
Whenever I play a game such as Forza Horizon 3, the CPU clock starts with 3.38GHz, which is the maximum clock speed possible. The MX150 GPU usage rate shown in Task Manager also starts with 50~60%, which is adequate. However, after 1 or 2 minutes, the clock speed decreases heavily, and instantly, to 1.58GHz, as well as the GPU usage (%) decreases to around 30%. Of course the game starts to lag heavily, which makes me angry.
I tried undervolting the CPU using Intel XTU, to -100mV (over than that showed BSOD) which a lot of people recommended when I did some research on Google. Also, I found two settings in the BIOS menu called the DPTF (Dynamic Platform Thermal Framework) and System Performance, which were set as [Enabled] and [Quiet Mode] in default. I changed those settings to [Disabled] and [Performance Mode] and restarted the computer.
However, the throttling still occurs. Hopefully, I found this thread which shows an interesting(?) solution.
https://forums.lenovo.com/t5/Lenovo-Yoga-Series-Notebooks/CPU-Throttling-on-Intel-8th-Gen-Yoga-520/td-p/3917668
Therefore, for the final solution, I tried using ThrottleStop and set up the Speed Shift EPP value to 156 (default was 128), keeping the CPU voltage offset value. When I launched the game with ThrottleStop turned on, the CPU clock remained around 2.40GHz even after a few minutes, which was a good sign. However, the GPU still remains around 30% and the game speed is slower, compared to the moment when the CPU clock is 3.38GHz. I also tried using AfterBurner from MSI and increased the clock speed for the MX150 GPU, but it didn't work on increasing the game speed.
Any ideas to keep the CPU clock rate around the maximum rate, or disabling the thermal throttling??

A: The problem is the turbo boost power max. I found out that it is set to 8W at my 330s with the same CPU. With only 8W the CPU cannot do much more than 1,5Ghz. Check your temps and bring it close to 15W. And you can get arouns 2,5Ghz all core clock... But it comes at a price.. Called bad thermal (~80 °C)


Q: How can I color a graph (vertices and edges) with excel data? I'm have an excel file with mostly 0's and 1's and I want to use this information to color the vertices and edges of a graph. So like if a cell is 0, color the edge gray, but if the cell is 1, color it blue. And similarly for vertices.
Can anyone give me a suggestion for how to go about this? What should I use to make the graph? And how do I tell it how to color it?
THANKS!

A: Try using D3 graph. Visit https://d3js.org/
D3 uses javascript language. You can refer to multiple graphs.
Even you can take input data from excel file to create dynamic graphs.
You can refer to D3 network graph to understand how to change colour of vertex and edges of graph from given data http://christophergandrud.github.io/d3Network/

A: If you have the x and y values you can plot them directly on a worksheet.  The following is an example that randomly generates x and y coordinates for 5 points.  A small filled circle is drawn at each point.  A line is drawn between the previous and the next point forming a closed loop.
To demonstrate how you can select the line colors I alternately color them gray and blue to give you an idea of how to selectively color them based on some other criteria.
vbBlue is one of a preset color pallet (see this link) which is why it doesn't have to be declared - unlike vbGray.
Option Explicit

Sub drawALine(xFrm As Double, yFrm As Double, xTo As Double, yTo As Double, c As Long)
  With ActiveSheet.Shapes.AddLine(xFrm, yFrm, xTo, yTo).Line
    .DashStyle = msoLineDashDotDot
    .ForeColor.RGB = c
  End With
End Sub

Sub drawNode(r As Double, x As Double, y As Double, c As Long)
  With ActiveSheet.Shapes.AddShape(msoShapeOval, x - r / 2, y - r / 2, r, r)
    .Fill.ForeColor.RGB = c
  End With
End Sub

Sub ConnectedOverLappingLoop()
  Dim xMax As Double, yMax As Double, x1 As Double, y1 As Double
  Dim xFrm As Double, yFrm As Double, xTo As Double, yTo As Double
  Dim radius As Double
  Dim vbGray As Long, clr As Long

  xMax = 200
  yMax = 200
  radius = 5
  vbGray = RGB(150, 150, 150)

  xFrm = Rnd() * xMax
  yFrm = Rnd() * yMax
  x1 = xFrm
  y1 = yFrm
  clr = vbBlue

  drawNode radius, x1, y1, vbBlue

  Dim i As Integer
  For i = 1 To 5:
    xTo = Rnd() * xMax
    yTo = Rnd() * yMax

    drawNode radius, xTo, yTo, vbBlue
    drawALine xFrm, yFrm, xTo, yTo, clr
    xFrm = xTo
    yFrm = yTo

    If clr = vbBlue Then
       clr = vbGray
    Else
       clr = vbBlue
    End If

  Next
  drawALine xFrm, yFrm, x1, y1, clr

End Sub


Q: PHP sanitization question I was wondering how would you sanitize the $_SERVER['REQUEST_URI'], $_POST['email'] and $url code in the code snippets below using PHP.
I'm using PHP Version 5.2.14
Code Snippets.
<form method="post" action="<?php $_SERVER['REQUEST_URI']; ?>">
</form>

$email = $_POST['email']; //Grabs the email address

$page_url = $url; //Grabs the pages url address.

A: Use filter_var functions.
 // url
 filter_var($url, FILTER_VALIDATE_URL)
 // email
 filter_var('me@example.com', FILTER_VALIDATE_EMAIL)

A: Except in some very particular cases you should never 'sanitize' input - only ever validate it. (Except in the very particular cases) the only time you change the representation of data is where it leaves your PHP - and the method should be appropriate to where the data is going (e.g. htmlentities(), urlencode(), mysql_real_escape_string()....).
(the filter functions referenced in other posts validate input - they don't change its representation)