text:
Q: java.lang.RuntimeException: stub only when proguard enabled true I've written a sample app in which I'm getting data from localhost... created this app a year ago and last I used last week or max to max 2 weeks ago, and app was doing good, everything as per my expectation
UPDATE
Resolved this issue by disabling proguard, but I want to enable like, I've enabled earlier

Suddenly, app has stopped fetching data from localhost, can't see more, but this is what I found in Log:
2020-06-23 15:25:51.666 3751-3751/? W/RefBase: CallStack::getCurrentInternal not linked, returning null
2020-06-23 15:25:51.666 3751-3751/? W/RefBase: CallStack::logStackInternal not linked
2020-06-23 15:25:51.687 27221-27221/? W/ContextImpl: Calling a method in the system process without a qualified user: android.app.ContextImpl.startService:1631 android.content.ContextWrapper.startService:683 android.content.ContextWrapper.startService:683 com.sec.android.diagmonagent.sa.receiver.CFLogReceiver.sendCFLog:21 com.sec.android.diagmonagent.sa.receiver.CFLogReceiver.onReceive:13
2020-06-23 15:25:51.705 19718-19718/com.example.myapp W/System.err: java.lang.RuntimeException: stub
2020-06-23 15:25:51.705 19718-19718/com.example.myapp W/System.err:     at c.e.b.a.<init>(:36)
2020-06-23 15:25:51.705 19718-19718/com.example.myapp W/System.err:     at com.example.myapp.UserInfoActivity$e.<init>(:362)
2020-06-23 15:25:51.705 19718-19718/com.example.myapp W/System.err:     at com.example.myapp.UserInfoActivity.onCreate(:49)
2020-06-23 15:25:51.705 19718-19718/com.example.myapp W/System.err:     at android.app.Activity.performCreate(Activity.java:7955)
2020-06-23 15:25:51.705 19718-19718/com.example.myapp W/System.err:     at android.app.Activity.performCreate(Activity.java:7944)
2020-06-23 15:25:51.705 19718-19718/com.example.myapp W/System.err:     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1307)
2020-06-23 15:25:51.705 19718-19718/com.example.myapp W/System.err:     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3423)
2020-06-23 15:25:51.706 19718-19718/com.example.myapp W/System.err:     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3595)
2020-06-23 15:25:51.706 19718-19718/com.example.myapp W/System.err:     at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
2020-06-23 15:25:51.706 19718-19718/com.example.myapp W/System.err:     at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
2020-06-23 15:25:51.706 19718-19718/com.example.myapp W/System.err:     at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
2020-06-23 15:25:51.706 19718-19718/com.example.myapp W/System.err:     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2147)
2020-06-23 15:25:51.706 19718-19718/com.example.myapp W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:107)
2020-06-23 15:25:51.706 19718-19718/com.example.myapp W/System.err:     at android.os.Looper.loop(Looper.java:237)
2020-06-23 15:25:51.706 19718-19718/com.example.myapp W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:7807)
2020-06-23 15:25:51.706 19718-19718/com.example.myapp W/System.err:     at java.lang.reflect.Method.invoke(Native Method)
2020-06-23 15:25:51.706 19718-19718/com.example.myapp W/System.err:     at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
2020-06-23 15:25:51.706 19718-19718/com.example.myapp W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1047)

A: So basically, your classes, fields are being renamed during obfuscation hence leading to this error. The easiest way to solve this is to add the full class name of the class you don't wish to be obfuscated in the pro guard rules file. Refer: ProGuard - Obfuscating apk causing error


text:
Q: Git and Amazon EC2 public key denied I had git working before on /var/html/projectfolder and realized it was a security risk so I made a new folder /projects from the root folder and tried to replicate what I did and now it doesnt work.
Here is the backlog of what I did for my local machine and EC2 - server
Server-EC2
1.I added my public key to the authorized_user file in ~/.ssh folder
2.Create a bare repository
git init --bare

3.Change folder permissions to
sudo chgrp -R ec2-user *
sudo chmod -R g+ws *

Local Machine

*

*create a local repository with git init

*touch, add, commit readme file

*pointed origin master to ec2 via
git remote add origin ssh://ec2-user@remote-ip/path/to/folder
This is my output:
Permission Denied (publickey)
fatal: The remote end hung up unexpectedly

A: The easiest way to see what going on is to do a
 ssh -Tvvv  ssh://ec2-user@remote-ip/path/to/folder

Everything matter: the exact case of the path, or the user exact name.
But also the permission of the ~/.ssh directory (in which case, have a look at the sshd logs on the server, when you are doing your ssh command from the client, which might not be possible here for an amazon-ec2 server).
See also for illustration "Creating SSH keys for Gerrit and Hudson".

A: ok so with a little bit of tinkering around, I just instead of pushing I just did a clone of the repository..after I cloned the bare repository and pulled..it seemed to work. Thanks again for the help guys.

redpajama_set_name: RedPajamaStackExchange


text:
Q: embedded Jetty9 + Websockets . onWebSocketText says i'm not connected I'm using Jetty 9.0.2.v20130417 in my app (under Java 1.7)
The Servlet:
import org.eclipse.jetty.websocket.api.UpgradeRequest;
import org.eclipse.jetty.websocket.api.UpgradeResponse;
import org.eclipse.jetty.websocket.servlet.WebSocketCreator;
import org.eclipse.jetty.websocket.servlet.WebSocketServlet;
import org.eclipse.jetty.websocket.servlet.WebSocketServletFactory;

public class WSServletHandler extends WebSocketServlet
{

    private static final long serialVersionUID = 6600543852415589642L;

    public static class WSCustomCreator implements WebSocketCreator
    {
        @Override
        public Object createWebSocket(UpgradeRequest req, UpgradeResponse resp)
        {
            return new WSSocketHandler();
        }
    }

    @Override
    public void configure(WebSocketServletFactory factory)
    {
        factory.setCreator(new WSCustomCreator());
    }
}

The Websocket Handler:
import org.eclipse.jetty.websocket.api.Session;
import org.eclipse.jetty.websocket.api.WebSocketAdapter;
import org.eclipse.jetty.websocket.api.WebSocketException;

public class WSSocketHandler extends WebSocketAdapter
{
    public WSSocketHandler()
    {
        System.out.println("+++ Websocket class constructor");
    }

    public void onWebSocketConnect(Session sess)
    {
        System.out.println("+++ Websocket Connect from " + sess.getRemoteAddress().getAddress());
    }

    @Override
    public void onWebSocketError(Throwable e)
    {
        System.out.println("+++ Websocket Error " + e.getMessage());
        e.printStackTrace();
    }

    @Override
    public void onWebSocketClose(int statusCode, String reason)
    {
        System.out.println("+++ Websocket close " + statusCode + " , " + reason);
    }

    public void onWebSocketException(WebSocketException e)
    {
        System.out.println("+++ Websocket Exception " + e.getMessage());
        e.printStackTrace();
    }

    @Override
    public void onWebSocketBinary(byte[] payload, int offset, int len)
    {
        System.out.println("+++ ignoring binary message");
    }

    @Override
    public void onWebSocketText(String message)
    {
        System.out.println("+++ MESSAGE: " + message);

        if (isNotConnected())
        {
            System.out.println("+++ not connected");
            return;
        }

        try {
            getRemote().sendString("lallo");
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}

I can connect from javascript to the Jetty Server, and i can send a message from js to jetty. I see this message in the onWebSocketText function.
The problem: isNotConnected() is always true so nothing goes back to the Browser.
I dont get any errors in Jetty or Javascript in the Browser.
Jetty Logs: http://pastebin.com/Qq2EynFJ
I'm running out of ideas... i'm quite sure i miss something essential, but:
i have a similar test under java with exactly the same versions of jetty and java where this is working. The only difference is that the code above is part of a larger application whereas the short test is a standalone program.
thanks in advance

A: Not sure where you defined isNotConnected method, but you can do something like this based on your example.
public void onWebSocketConnect(Session sess){
        System.out.println("+++ Websocket Connect from " + sess.getRemoteAddress().getAddress());
        this.session=sess;
}

 public void onWebSocketText(String message){
    if(this.session.isOpen()){
    }
}

A: Doua is right.
If i get rid of onWebSocketConnect, everything is working.
when using onWebSocketConnect, you have to save Session somewhere (as Joakim showed in the first answer). After that, you have to use this.sess.
e.g.
this.sess.getRemote().sendString
or
this.sess.isOpen()
thanks for help :)

A: Try calling the parent's implementation for onWebSocketConnect inside the method
public void onWebSocketConnect(Session session){
     // your code here
     super.onWebSocketConnect(session);
}


text:
Q: How to verify a particular text is present inside a log (String format) in swift? let command = // some shell command execution that prints some log in terminal
command.description //This gives me the String representation
let textToSearch = "some string value "
//My approaches
let status = command.description.conatains(textToSearch)
XCTAssert(status, "The Text is not present!") // Fail
let status2 = command.description.range(of: textToSearch) != nil
XCTAssert(status, "The Text is not present!") // Fail

A: let command = Foo()
let description = command.description
let textToSearch = "some string value"
let status = description.localizedLowercase.contains(textToSearch.localizedLowercase)

XCTAssertTrue(status, "The Text is not present!")


text:
Q: How to parse a string into a Java Date? How do I parse a string like "Fri Feb 14 09:58:21 EST 2020" into a Date in Java ?
The closest example I can find is :
SimpleDateFormat formatter = new SimpleDateFormat("EEEE, MMM dd, yyyy HH:mm:ss a");
String dateInString = "Friday, Jun 7, 2013 12:10:56 PM";

try {

    Date date = formatter.parse(dateInString);
    System.out.println(date);
    System.out.println(formatter.format(date));

}
catch (ParseException e) {
    e.printStackTrace();
}

But it doesn't have the " EST " part, what's the right way to do it ?

A: Your pattern is not correct, it contain many problems :

*

*EEEE replace with EEE

*, remove this because your string not have comma

*, same thing for the second comma

*replace the position of yyyy and put in the end

*a remove as it is not used at all, and instead use z to match ETC

If you are using java-time you can parse your date using this pattern EEE MMM dd HH:mm:ss z yyyy :
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(
        "EEE MMM dd HH:mm:ss z yyyy",
        Locale.US);
ZonedDateTime zdt = ZonedDateTime.parse(str, formatter);


text:
Q: Java AWT - alt press detected every other occasion Consider test case for AWT frame where we print key press and release events
Frame frame = new Frame("Test");

frame.addKeyListener(new KeyListener() {
    @Override
    public void keyTyped(KeyEvent e) {}
    @Override
    public void keyReleased(KeyEvent e) {
        System.out.println("released " + e);
    }
    @Override
    public void keyPressed(KeyEvent e) {
        System.out.println("pressed " + e);
    }
});

frame.setVisible(true);

in case of CTRL and SHIFT modifiers, everything goes as expected and press followed by release is detected. In case of AltGr is detected double press with alt, and double release (I could get over that, at least it is somewhat consistent and detectable), but in case of ALT with subsequent "types" press -> release -> release -> press -> release -> release are detected.
Entire event prints:
    pressed java.awt.event.KeyEvent[KEY_PRESSED,keyCode=18,keyText=Alt,keyChar=Undefined keyChar,modifiers=Alt,extModifiers=Alt,keyLocation=KEY_LOCATION_LEFT,rawCode=18,primaryLevelUnicode=0,scancode=56,extendedKeyCode=0x12] on frame0
    released java.awt.event.KeyEvent[KEY_RELEASED,keyCode=18,keyText=Alt,keyChar=Undefined keyChar,keyLocation=KEY_LOCATION_LEFT,rawCode=18,primaryLevelUnicode=0,scancode=56,extendedKeyCode=0x12] on frame0
    released java.awt.event.KeyEvent[KEY_RELEASED,keyCode=18,keyText=Alt,keyChar=Undefined keyChar,keyLocation=KEY_LOCATION_LEFT,rawCode=18,primaryLevelUnicode=0,scancode=56,extendedKeyCode=0x12] on frame0
    pressed java.awt.event.KeyEvent[KEY_PRESSED,keyCode=18,keyText=Alt,keyChar=Undefined keyChar,modifiers=Alt,extModifiers=Alt,keyLocation=KEY_LOCATION_LEFT,rawCode=18,primaryLevelUnicode=0,scancode=56,extendedKeyCode=0x12] on frame0
    released java.awt.event.KeyEvent[KEY_RELEASED,keyCode=18,keyText=Alt,keyChar=Undefined keyChar,keyLocation=KEY_LOCATION_LEFT,rawCode=18,primaryLevelUnicode=0,scancode=56,extendedKeyCode=0x12] on frame0
    released java.awt.event.KeyEvent[KEY_RELEASED,keyCode=18,keyText=Alt,keyChar=Undefined keyChar,keyLocation=KEY_LOCATION_LEFT,rawCode=18,primaryLevelUnicode=0,scancode=56,extendedKeyCode=0x12] on frame0

Except for modifiers=Alt,extModifiers=Alt on released events are identical.
Is there anything I can do to achieve consistent behaviour? Am I doing something wrong? I want to display UI options with key bindings that use alt modifier when alt is pressed, but that is not really possible when I cannot hide these options consistently.
I have seen some suggestions with SWT input maps, but AWT usage is unfortunately a must.
Checked behaviour on java 10 and java 8, it is the same, but there is indeed a difference between operating systems. A linux distro produces correct behaviour, while windows 10 and 7 do not. Now the question remains, whether it is bug or a feature.
Edit 1: Listed code was swing frame, fixed to AWT, it has no influence on the problem.
Edit 2: Fixed swapped release/pressed (no effect on essence of the problem)


text:
Q: RStudio does not clear the workspace of a package project when doing "Install and Restart" I have an open project (a package) in RStudio and my workspace contains variables, eg.
a <- 1
When I choose the menu item Build > Install and Restart I can see (in the console) that the R session is restarted, but the workspace is not cleared (I can still see that a is 1):

Restarting R session...

> library(tryCatchLog)

What am I doing wrong?
Is this possibly only a "misnomer" (the menu item was called Build and Reload in older RStudio versions AFAIKR)?
PS: I am using RStudio 1.1.463 on Ubuntu with R 3.4.4 and can also reproduce this on Windows with RStudio 1.2.x and R 3.6.1
Edit 1: The Restore .RData option is not the reason for that:

Edit 2: I have opened an issue for that: https://github.com/rstudio/rstudio/issues/5639


text:
Q: Tensorflow core I run the code below on Tensorflow 1.0 using python 3.5
a = tf.placeholder(tf.float32)
b = tf.placeholder(tf.float32)
adder_node = a + b  # + provides a shortcut for tf.add(a, b)
sess = tf.Session()
print(sess.run(adder_node, {a: 3, b: 4.5}))
print(sess.run(adder_node, {a: [1, 3], b: [2, 4]}))

I got this error

print(sess.run(adder_node, {a:3, b:4.5}))
      Traceback (most recent call last):
        File "C:\Users\xxxx\AppData\Local\Continuum\Anaconda3\envs\tensorflow\lib\site-packages\tensorflow\python\client\session.py", line 1068, in _run
          allow_operation=False)
        File "C:\Users\xxxx\AppData\Local\Continuum\Anaconda3\envs\tensorflow\lib\site-packages\tensorflow\python\framework\ops.py", line 2708, in as_graph_element
          return self._as_graph_element_locked(obj, allow_tensor, allow_operation)
        File "C:\Users\xxxx\AppData\Local\Continuum\Anaconda3\envs\tensorflow\lib\site-packages\tensorflow\python\framework\ops.py", line 2787, in _as_graph_element_locked
          raise ValueError("Tensor %s is not an element of this graph." % obj)
      ValueError: Tensor Tensor("Placeholder_3:0", dtype=float32) is not an element of this graph.

During handling of the above exception, another exception occurred:
Traceback (most recent call last):
  File "", line 1, in
  File "C:\Users\xxxx\AppData\Local\Continuum\Anaconda3\envs\tensorflow\lib\site-packages\tensorflow\python\client\session.py", line 895, in run
    run_metadata_ptr)
  File "C:\Users\xxxx\AppData\Local\Continuum\Anaconda3\envs\tensorflow\lib\site-packages\tensorflow\python\client\session.py", line 1071, in _run
    + e.args[0])
TypeError: Cannot interpret feed_dict key as Tensor: Tensor Tensor("Placeholder_3:0", dtype=float32) is not an element of this graph.

>

Please help me debug this, not too sure where the error is coming from


text:
Q: How to get the Size (KB) of UIImage I am getting Image from didFinishPickingMediaWithInfo.
UIImage *originalImage = (UIImage*)[info valueForKey:UIImagePickerControllerOriginalImage];

I want to get the size of Image in Kb.

A:     UIImage *originalImage = (UIImage*)[info valueForKey:UIImagePickerControllerOriginalImage];
    NSData *imgData = UIImageJPEGRepresentation(originalImage, 1); //1 it represents the quality of the image.
    NSLog(@"Size of Image(bytes):%d",[imgData length]);
    imgData = nil;

A: I think the op's size (kb) is the memory size of originalImage, right?
Check out the usage about malloc_size under the ARC refer to this.
#import <malloc/malloc.h>

NSLog(@"Size of %@: %zd", NSStringFromClass([originalImage class]), malloc_size((__bridge const void *)originalImage));


text:
Q: Type mismatch error in java 8 I have the following class with the following method.
public class MyClass {

    public static <T> T getSomeThing(final int id, final java.lang.reflect.Type type, final Map<Integer, String> someThings) {
        final String aThing = someThings.get(id);
        if (aThing == null || aThing.isEmpty()) {
            return null;
        }
        return GsonHelper.GSON.fromJson(aThing, type);
    }

}

The GsonHelper provides me with some com.google.gson.GsonBuilder
public class GsonHelper {

    public static final com.google.gson.Gson GSON = getGsonBuilder().create();

    public static GsonBuilder getGsonBuilder() {
        return new GsonBuilder().setPrettyPrinting()
                .enableComplexMapKeySerialization()
                .registerTypeAdapter(new com.google.gson.reflect.TypeToken.TypeToken<byte[]>() {
                    // no body
                }.getType(), new Base64TypeAdapter())
                .registerTypeHierarchyAdapter(Date.class, new DateTypeAdapter())
                .registerTypeHierarchyAdapter(Pattern.class, new PatternTypeAdapter())
                .registerTypeAdapterFactory(new ListTypeAdapterFactory())
                .registerTypeAdapterFactory(new MapTypeAdapterFactory())
                .registerTypeAdapterFactory(new SetTypeAdapterFactory());
    }
}

Until Java 7 I was using this method like:
Map<Integer, String> allThings = new HashMap<>();
//FILL allThings with values

if(MyClass.getSomeThing(7, java.lang.Boolean.class, allThings)){
    //do something
}

This worked fine. cause the method will return a Boolean and I can use this inside "if". But when I change to Java 8 this is not possible anymore.
The compiler complains about:

Type mismatch: cannot convert from Object to boolean

 //while this is working but would throw a JsonSyntaxException
final String myString = "myInvalidJsonString";
if(GsonHelper.GSON.fromJson(myString, java.lang.Boolean.class)){
    //do something
}

I know that java.lang.Boolean can be null. And I could solve this issue with:
final Boolean b = MyClass.getSomeThing(7, java.lang.Boolean.class, allThings);
if(b){
    //do something
}

But I am curious about why this is working with Java 7 and NOT in Java 8. (not answered) What did they change? (not answered)
What is the reason for this compiler error when changing to Java 8? (answered)

A: Your method public static <T> T getSomeThing(final int id, final java.lang.reflect.Type t, final Map<Integer, String> someThings) does not guarantee to return a Boolean. It returns T which is defined by the caller and could be anything, which means Object.
The if statement can't know which type T will have and hence can't guarantee to convert it to a boolean.
Why not change the signature to boolean?
public static boolean getSomeThing(final int id,
                                   final java.lang.reflect.Type t,
                                   final Map<Integer, String> someThings)

Or are you in search of this?
public static <T> T getSomeThing(final int id,
                                 final Class<T> clazz,
                                 final Map<Integer, String> someThings)

Than this code will compile and work:
public static void main(String[] args) {
    if (getSomeThing(7, Boolean.class, emptyMap())) {
        System.out.println("It works!");
    }
}

public static <T> T getSomeThing(final int id,
                                 final Class<T> clazz,
                                 final Map<Integer, String> someThings) {
    ...
}

A: The last version where the result of getSomeThing() is assigned to a Boolean variable can be inferred according to JLS 8, because in an assignment context the target type Boolean lets T to be inferred as Boolean, indeed. Here all compilers agree.
Regarding the original case, JLS 8 does not classify the condition of an if-statement as an assignment context. Outside assignment or invocation contexts, the invocation is not treated as a poly expression, but as a standalone expression (JLS 15.12 1st bullet). Standalone expressions have no target type. Without a target type inference in Java 8 falls back to inferring T to Object.
The Eclipse team has requested clarification in this regard even before Java 8 GA. Unfortunately, the resulting issue remains unresolved until today.
Ergo: JLS and the observed behavior of javac don't seem to agree. Likely, JLS is the entity that should be fixed.
Update: JLS is not going to change (confirmed via private email), hence accepting the program is a bug in javac.
Edit: Javac version 12 will propagate this bug even through a switch expression:
public class X {
    @SuppressWarnings("preview")
    public void foo(int i) {
        if (switch(i) { default -> magic(); })
            System.out.println("true");
    }
    <T> T magic() { return null; }
}

javac accepts this due to type inference with target type Boolean, but performing type inference in this location is illegal per JLS.


text:
Q: swift read write to firestore documents and collections from the IOS app i'm trying to update with new data 5 different "collection" in Firestore. I'm able to do that but to 1 collection only. I can't figure it out how to push the updates to all 5 collections at once. Any help is greatly appreciated.
import UIKit
import Firebase

class itemDataViewController: UIViewController {

    @IBOutlet var itemLabels: [UILabel]!
    @IBOutlet weak var testLabel: UILabel!

    @IBOutlet weak var firstItemField: UITextField!
    @IBOutlet weak var secondItemField: UITextField!
    @IBOutlet weak var thirdItemField: UITextField!
    @IBOutlet weak var fourthItemField: UITextField!
    @IBOutlet weak var fithItemField: UITextView!

    var docRef: DocumentReference!
    var infoListener: ListenerRegistration!

    @IBAction func updateData(_ sender: Any) {
        guard let firstItemText = firstItemField.text, !firstItemText.isEmpty else { return }
        guard let secondItemText = secondItemField.text, !secondItemText.isEmpty else { return }
        guard let thirdItemText = thirdItemField.text, !thirdItemText.isEmpty else { return }
        guard let fourthItemText = fourthItemField.text, !fourthItemText.isEmpty else { return }
        guard let fithItemText = fithItemField.text, !fithItemText.isEmpty else { return }

        let dataToSave: [String: Any] = ["firstItem": firstItemText]
        docRef.setData(dataToSave) { (error) in
            if let error = error {
                print("Oh no! Could not save: \(error.localizedDescription)")
            } else {
                print("Data Saved")
          }
        }
       }
   override func viewWillAppear(_ animated: Bool) {
            super.viewWillAppear(animated)
            infoListener = docRef.addSnapshotListener { (docSnapshot, error) in
                guard let docSnapshot = docSnapshot, docSnapshot.exists else { return }
                let myData = docSnapshot.data()
                let firstItemUpdate = myData?["firstItem"] as? String ?? ""
                self.firstItemField.text = "\(firstItemUpdate)"
            }
           }

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillAppear(animated)
        infoListener.remove()
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        docRef = Firestore.firestore().document("2/firstItem")

    (itemLabels as NSArray).setValue(10, forKey: "cornerRadius")

        // Do any additional setup after loading the view.
    }
}


text:
Q: I have 2 Service classes that both extend the same parent class with an autowired bean, I can use the bean in one class but not in the other I'm still pretty new to Spring, but I'm currently facing an issue of which I don't know the cause and I can't figure it out with only a nullpointerexception.
I have 2 classes that both implement the same Abstract class. InventoryService and InventoryMailService. All 3 are in the same package that is successfully being scanned with component-scan.  I'm trying to use my globalPrefService bean, which I can succesfully use in my InventoryService but somehow not in my InventoryMailService.
This is my AbstractService that I use to wire my services together:
package com.paperfoam.inventory.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service("abstractService")
public abstract class AbstractService {

    protected InventoryService inventoryService;
    protected FinancialCalculationService financialCalculationService;
    protected SupplierService supplierService;
    protected UserService userService;
    protected GlobalPrefService globalPrefService;

    @Autowired
    public void setGlobalPrefService(GlobalPrefService globalPrefService) {
        this.globalPrefService = globalPrefService;
    }

    @Autowired
    public void setInventoryService(InventoryService inventoryService) {
        this.inventoryService = inventoryService;
    }

    @Autowired
    protected void setFinancialCalculationService(FinancialCalculationService financialCalculationService) {
        this.financialCalculationService = financialCalculationService;
    }

    @Autowired
    protected void setSupplierService(SupplierService supplierService) {
        this.supplierService = supplierService;
    }

    @Autowired
    protected void setUsersService(UserService userService) {
        this.userService = userService;
    }

}

This is the the InventoryService (minus some non-related functions), when I try to call my GlobalPrefService it works just fine:
package com.paperfoam.inventory.service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.paperfoam.inventory.dao.InventoryDao;
import com.paperfoam.inventory.dao.InventoryLogItemDao;
import com.paperfoam.inventory.objects.InventoryItem;
import com.paperfoam.inventory.objects.InventoryLogItem;

@Service("inventoryService")
public class InventoryService extends AbstractService {

    private InventoryDao inventoryDao;
    private InventoryLogItemDao inventoryLogItemDao;

    public InventoryDao getInventoryDao() {
        return inventoryDao;
    }

    @Autowired
    public void setInventoryDao(InventoryDao inventoryDao) {
        this.inventoryDao = inventoryDao;
    }

    @Autowired
    public void setInventoryLogItemDao(InventoryLogItemDao inventoryLogItemDao) {
        this.inventoryLogItemDao = inventoryLogItemDao;
    }
    // This is the method where I succesfully use my GlobalPrefService
    public List<InventoryItem> getAllInventoryItems() {
        System.out.println(globalPrefService.getPreferenceValue("mailusername")); // this succesfully prints my preferenceValue to the console
        return inventoryDao.getInventoryList();

    }
}

However, I have my other class (same package) that extends the same AbstractService that returns a NullPointerException when I try to use it:
package com.paperfoam.inventory.service;

import java.io.File;
import java.util.logging.Logger;

import javax.mail.internet.MimeMessage;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.mail.MailParseException;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import com.paperfoam.inventory.config.JavaBeanConfig;
import com.paperfoam.inventory.objects.InventoryItem;
import com.paperfoam.inventory.objects.Supplier;

@Service("inventoryMailService")
public class InventoryMailService extends AbstractService {

    public void sendMessageWithAttachment(String to, String subject, String text, String pathToAttachment) {

        System.out.println(globalPrefService.getPreferenceValue("mailusername")); // NullPointerException on the globalPrefService!
        /*
        JavaBeanConfig javaBean = new JavaBeanConfig();
        JavaMailSender mailSender = javaBean.getJavaMailSender(globalPrefService);

        try {

        MimeMessage message = mailSender.createMimeMessage();

        MimeMessageHelper helper = new MimeMessageHelper(message, true);

            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(text);

        Resource file = new ClassPathResource(pathToAttachment);
        helper.addAttachment("hoera.png", file);

        mailSender.send(message);
        } catch (Exception e) {
            e.printStackTrace();
        }
        */
    }
}

The error I get:
SEVERE: Servlet.service() for servlet [paperfoam] in context with path [/bulletjournal] threw exception [Request processing failed; nested exception is java.lang.NullPointerException] with root cause
java.lang.NullPointerException
    at com.paperfoam.inventory.service.InventoryMailService.sendMessageWithAttachment(InventoryMailService.java:30) // This is the system.out line
    at com.paperfoam.inventory.controllers.InventoryController.showInventoryStatistics(InventoryController.java:165)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:114)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:624)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:317)
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:127)
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:91)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:114)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:137)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:111)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:170)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:63)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:200)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:116)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:64)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:56)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:105)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:214)
    at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:177)
    at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346)
    at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:262)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:110)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:506)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:169)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:962)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:445)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1115)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:637)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:318)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Unknown Source)

I have been staring at this for a while and I can't figure out what causes this. Everything is annotated in the same way, they extend the same class that autowires the bean in, they are in the same package that is being scanned and the access modifiers are also the same.
I also tried to clean/rebuild my project a few times, does anyone have any idea what I am missing here?
Thank you for reading.
In response to the comment:
My InventoryService gets Autowired in the controller.
protected InventoryService inventoryService;

@Autowired
    public void setInventoryService(InventoryService inventoryService) {
        this.inventoryService = inventoryService;
    }

But I manually instantiate my InventoryMailService (and I'm starting to think thats the mistake) for debugging.
    @RequestMapping(value = { "/statistics", "/" })
    public String showInventoryStatistics(Model model) {

        Map<Integer, Long> calculated = financialCalculationService.getSuppliersWithTotalWorth();
        List<Supplier> allSuppliers = supplierService.convertSupplierHashmapToObjectList(calculated);

        List<InventoryItem> lowItems = inventoryService.getLowInventoryItems();
        List<InventoryLogItem> recentChanges = inventoryService.getRecentChanges();

        model.addAttribute("suppliers", allSuppliers);
        model.addAttribute("lowitems", lowItems);
        model.addAttribute("recentchanges", recentChanges);

        InventoryMailService mail = new InventoryMailService();
        System.out.println(mail.toString());
        mail.sendMessageWithAttachment("Redacted@gmail.com", "betere mail", "test123", "com/paperfoam/inventory/mail/success.png");

        return JspPage.INVENTORY_STATISTICS;
    }

I didn't even stop to think that that might affect the autowiring down the road, does that matter to spring?

A: For spring to handle dependency injection the entire dependency chain needs to be autowired, so you need to also autowire InventoryMailService in InventoryController.


text:
Q: React's Hook set function won't update array on submit export default function App() {

     const [arrayOne, setArrayOne] = useState([{name: 'A', age: 10,
                                       hobbies: [{name: soccer, experience: 12}]},
                                      {name: 'B', age: 6, hobbies: []}])
     const [newName, setNewName] = useState('')
     const [newAge, setNewAge] = useState(0)

     function handleSubmit(e) {
         e.preventDefault()
         const newEntry = {name: newName, age: newAge, hobbies: []}
         setArrayOne([newEntry, ...arrayOne])
         console.log(arrayOne)
     }

     return(

        <div>
            <form onSubmit={e => handleSubmit(e)}>
                  <input type="text" value={newName} onChange={e => setNewName(e.target.value)} />
                  <input type="number" value={newAge} onChange={e => setNewAge(e.target.value)} />
                  <input type="submit />
            </form>
        </div>

     )

}

For some reason arrayOne won't update after submit is pressed on the form, it always lags behind one submit click. Is there anyway I can make it so it updates immediately?

A: You can try this:
let copiedArray = [... arrayOne];

copiedArray.push(newEntry);

setArrayOne(copiedArray);

A: try setArrayOne((curr) => [...curr, newEntry])


text:
Q: Как использовать in в QueryBuilder? Никак не выходит сделать in условие для запроса в таблицу PostgreSQL с полем service (enum). Значения указываю существующие, в этом проблемы нет. Я пытался делать implode, но queryBuilder экранирует строку целиком, я пытался передать массив, но получаю array to string conversion и параметр Array вместо 'ACTIVE', 'ANOTHER'. Как правильно в queryBuilder сделать условие in для enum?
public function query()
{
    return $this->db()->createQueryBuilder();
}

public function getActiveSubscriberServices($msisdn)
    {
        $result = $this->query()
                ->select('id')
                ->from('subscriber.service')
                ->where('state in (?)')
                ->setParameter(0, [
                        'ACTIVE',
                        'ANOTHER',
                ])
                ->execute();
        return $result->fetchAll();
    }

An exception occurred while executing 'SELECT id FROM subscriber.service WHERE (state in (?))' with params [[\"ACTIVE\",\"ANOTHER\"]]:\n\nSQLSTATE[22P02]: Invalid text representation: 7 ERROR:  invalid input value for enum subscriber.service_state: \"Array\"

Пробую сделать вот так
->where($this->query()->expr()->in('state', [
    'ACTIVE',
    'ANOTHER',
]))

И получаю такой in: IN (ACTIVE, ANOTHER), что не работает, потому что значения внутри in должны быть экранированы.
Сейчас использую код, приведенный ниже, но это не гибко и немного костыльно.
$services = [Service::STATE_ACTIVE, Service::STATE_ACTIVATING];

$result = $this->query()
        ->select('*')
        ->from('subscriber.service')
        ->where($this->query()->expr()->in('state',
            array_map(function($item) {
                return '?';
            }, array_keys($services))))
        ->setParameters($services)
        ->andWhere('msisdn = ?')
        ->setParameter(count($services), $msisdn)
        ->execute();
return $result->fetchAll();

A: Можно использовать примерно вот такой код:
$services = [Service::STATE_ACTIVE, Service::STATE_ACTIVATING];

$result = $this->query()
        ->select('*')
        ->from('subscriber.service')
        ->where('state in (:services)')
        ->setParameter('services', $services, \Doctrine\DBAL\Connection::PARAM_STR_ARRAY);
        ->andWhere('msisdn = ?')
        ->setParameter(count($services), $msisdn)
        ->execute();
return $result->fetchAll();

A: Под рукой нет средств для проверки, овтет идет по документации:

// Example - $qb->expr()->in('u.id', array(1, 2, 3))
  // Make sure that you do NOT use something similar to $qb->expr()->in('value', array('stringvalue')) as this will cause Doctrine to throw an Exception.
  // Instead, use $qb->expr()->in('value', array('?1')) and bind your parameter to ?1 (see section above)

public function getActiveSubscriberServices($msisdn)
{
    $result = $this->query()
            ->select('id')
            ->from('subscriber.service')
            ->where($this->query()->expr()->in('state', [
                '?1',
                '?2',
            ]))
            ->setParameter(1, 'ACTIVE')
            ->setParameter(2, 'ANOTHER')
            ->execute();
    return $result->fetchAll();
}


text:
Q: Simulating WAves Nearshore and the use of triangle. Hei, I'm trying to get into SWAN and triangle, while not having any coding experience and I'm having a hard time since following designated guides do not give results. Does anybody have any idea how to use them?
SWAN questions:

*

*Is there a way to read input file with extension .swn? So that I can analyze test files.

*How to connect files with different extensions, is the .swn file responsible for it?

*How to post-process data? I guess that triangle does it? Many documents show figures of bathymetries with computed wave heights.

I probably misunderstood a lot.
As for triangle, I've been having issues just running this program.
I believe that I compiled it correctly (followed many guides), and I got a .exe file in the directory. I still cannot use the commands to run a mesh, or just to get a figure like said in its own guide.
Comments in "makefile"
makefile for Triangle and Show Me
Type "make" to compile Triangle and Show Me.
After compiling, type "triangle -h" and "showme -h" to read instructions for using each of these programs.
It says to simply type "make" and stuff.
For example, I'm trying to run the sample file A.poly. The command promt tells me that a command "triangle" is not found.
I don't know what to do, why can't some things just work ;D
I'm using Cygwin64 terminal for triangle and SWAN got its own on win10.
I installed gcc and stuff on cygwin.
If someone got a good tutorial for dummies, I would appreciate it.


text:
Q: jQuery mouseover/hover stopped working after few overs I use jQuery mouseover to do something. But if I move mouse over about 5-7 time - it freezed.
Why this problem appears?
I tryed mouseover and hover.
Code example:
$('span.info_icon').mouseover(function() {
    $('#info_box').show(600);
}).mouseout(function(){
    $('#info_box').hide(600);
});

Live example: http://dev.dolina-imeniy.ru/fotogalereya/kp_usadba_tishnevo (over red "I").

A: The problem: #info_box is overlapping the .info_icon which causes the mouseout event immediately to trigger. Therefore, it would be better if you give the info icon a higher z-index than the info box.

A: First of all, you have both jQuery and inline script defined:

Having both is going to cause issues.  (It will show twice, hide twice, etc).  This could eventually get things out of sync, but more importantly it is just plain redundant.
Also, your info_box covers the triggering span, so every time it shows, you trigger a mouseout.  This will end up toggling the info over and over.
The combination of these things will cause problems that may lead to what you are seeing.  Fix these issues first.


text:
Q: Empty output when populating 2D range with array I am trying to populate a 2D range with a 2D array.
At the moment I have this:
Sub populate()

Dim ws As Worksheet

Set ws = ThisWorkbook.Worksheets("Sheet1")

Dim Rows(2) As Variant

Rows(0) = [{1, 2, 3}]
Rows(1) = [{4, 5, 6}]
Rows(2) = [{7, 8, 9}]

With ws
    .Range(.Cells(1, 1), .Cells(3, 3)).Value = Rows
End With

End Sub

I do not get any errors ect., but the range remains empty after running the macro.
The weirdest thing is that I get the correct output when I go like:
With ws
    .Range(.Cells(1, 1), .Cells(3, 3)).Value = Application.Transpose(Application.transpose(Rows))
End With

I went through numerous articles and Microsoft Documents, but nothing came up to fix my problem.

A: I'm not following why you are interested in a 2D-array within a 2D-array, but (also as per @Rory his comment, you can try the following:
Sub populate()

Dim ws As Worksheet

Set ws = ThisWorkbook.Worksheets("Blad1")

Dim Rows(2, 0) As Variant

Rows(0, 0) = [{1, 2, 3; 4, 5, 6; 7, 8, 9}]
Rows(1, 0) = [{1, 2, 3; 4, 5, 6; 7, 8, 9}]
Rows(2, 0) = [{1, 2, 3; 4, 5, 6; 7, 8, 9}]

'Rows(0,0)(1,1) = "value" 'If you want to change. This example will change the first element of the 2D-array within the first element of your first 2D-array.

With ws
    .Range(.Cells(1, 1), .Cells(3, 3)).Value = Application.Transpose(Application.Transpose(Rows(0, 0))) 'Will transpose your first element in your initial 2D-array (not sure if this is put correctly in English)
End With

End Sub

You can implement a For x = Lbound(rows) to Ubound(rows) if you want to do the above operation for each element in your 2D-array.
In chat it becomes clear OP also wants to implement the following:
reasonArr(1, 0) = [{0,0,0,0,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,0,0,0,0,0,0}]

Which threw an error. This is because the provided line to Evaluate exceeds 255 characters.


text:
Q: Как в jquery отловить событие Ctrl + стрелочка влево/вправо? Как в jquery отловить событие "нажата клавиша Ctrl и одновременно стрелочка влево/вправо"?
A: $('#selector').keydown(function(event) {
  if ( event.ctrlKey && event.keyCode == 37 ) {
     //влево
  }
  if ( event.ctrlKey && event.keyCode == 39 ) {
     //вправо
  }
}


text:
Q: Android Constraint Layout doesn't stretch on full screen I have a problem with layout which won't stretch within high resolution like 1920x1080.
As root layout I use Constraint Layout with following style:
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:focusable="true"
android:focusableInTouchMode="true"
tools:context="njc.nhutrinhgold.MainActivity">

<ImageView
    android:id="@+id/imgNen"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:adjustViewBounds="true"
    android:scaleType="fitXY"
    android:visibility="visible"
    app:layout_constraintDimensionRatio="16:9"
    app:srcCompat="@drawable/xxhdpibg"
    tools:layout_editor_absoluteX="0dp"
    tools:layout_editor_absoluteY="0dp"
    tools:layout_width="match_parent" />

and in Manifest.xml
<supports-screens
    android:anyDensity="true"
    android:compatibleWidthLimitDp="960"
    android:largeScreens="true"
    android:largestWidthLimitDp="960"
    android:normalScreens="false"
    android:requiresSmallestWidthDp="960"
    android:resizeable="false"
    android:smallScreens="false"
    android:xlargeScreens="true" />

I want to stretch layout to any screen resolution but on emulator with high resolution it looks like this:

Actually I didn't figured out what is the problem

A: Do it like this, and tell me what are you getting, because this is the ideal way of doing this, since everybody is saying the same thing but do it like this. match_parent is generally the key
<android.support.constraint.ConstraintLayout
 xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:app="http://schemas.android.com/apk/res-auto"
 xmlns:tools="http://schemas.android.com/tools"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:focusable="true"
 android:focusableInTouchMode="true"
 tools:context="njc.nhutrinhgold.MainActivity">

<ImageView
   android:id="@+id/imgNen"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:scaleType="centreCrop"
   android:visibility="visible"
   app:layout_constraintDimensionRatio="16:9"
   app:srcCompat="@drawable/xxhdpibg"
   tools:layout_editor_absoluteX="0dp"
   tools:layout_editor_absoluteY="8dp"
   tools:layout_width="match_parent" />

Remove adjustViewBound and set the scaleType as centreCrop, you'll see the change
**NOTE : ** This is for the layout to take up the whole screen and adjust (stretching to the whole screen)

A: try this:
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:focusable="true"
    android:focusableInTouchMode="true"
    tools:context=".MainActivity">

<ImageView
    android:id="@+id/imgNen"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:adjustViewBounds="true"
    android:scaleType="fitXY"
    android:visibility="visible"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:srcCompat="@mipmap/ic_launcher"
    />

</android.support.constraint.ConstraintLayout>

A: Don't hardcode the height and width of Constraint layout and the ImageView inside it. Set it to match_parent and it will stretch full screen in any device.

A: You have given hardcoded width and height. It will never stretch if you keep working on hardcoded width and height.


text:
Q: The image of the topological embedding is locally closed I encountered the following statement in a book about the Lie groups.

Proposition. Let $M$ and $N$ be topological manifolds and let $\psi\colon N\to M$ be a topological embedding. Then $\psi(N)$ is locally closed in $M$. In other words, for every $y\in\psi(N)$ there is a neghbourhood $W$ of $y$ in $M$ such that $\psi(N)\cap W$ is closed in $W$.

This seems to be just a simple fact from topology, but I cannot figure out how to proceed.
Firstly, since $M$ is a topological manifold, then for $x=\psi^{-1}(y)$ there is an open neighbourhood $U$ of $x$ in $N$ and homeomorphism $\varphi\colon U\to\mathbb{R}^n$. Then the map $\psi\circ\varphi^{-1}\colon \mathbb{R}^n\to\psi(U)$ is also a homeomorphism. My guess would be that now  we can take the open set $W$ in $M$ such that $\psi(U)=W\cap \psi(N)$ (note that $\psi(U)$ is open in the induced topology on $\psi(N)$) and prove that $\psi(N)\cap W$ is closed in $W$ but I don't understand how to do it.
Perhaps we can use $\varphi^{-1}(B_{\varepsilon}(0))$ instead of $U$ and try to prove that $(\psi\circ\varphi^{-1})(\overline{B_{\varepsilon}(0)})$ is the closure of $(\psi\circ\varphi^{-1})(B_{\varepsilon}(0))$ in $M$, but I am not sure.
Any help would be appreciated.


text:
Q: try_again() Function is not working properly. At end of main function, no matter the entry it runs again # Tic-Tac-Toe
# Plays the game of tic-tac-toe against a human opponent
# global constants
X = "X"
O = "O"
EMPTY = " "
TIE = "TIE"
NUM_SQUARES = 9

# the display_instuct() function
def display_instruct():
    """ Display game instructions."""
    print(
    """
    Welcome to the greatest intellectual challenge of all time: Tic-Tac-Toe.
    This wil be a showdown between your human brain and my silicon processor.

    You will make your move known by entering a number, 0 - 8. The number
    will correspond to the board position as illustrated:

                    0 | 1 | 2
                    ---------
                    3 | 4 | 5
                    ---------
                    6 | 7 | 8

    Prepare yourself, human. The ultimate battle is about to begin. \n
    """
    )

# ask_yes_no() function
def ask_yes_no(question):
    """Ask a yes or no question."""
    response = None
    while response not in ("y", "n"):
        response = input(question).lower()
    return response

# ask_number() function
def ask_number(question, low, high):
    """Ask for a number within a range."""
    response = None
    while response not in range(low, high):
        response = int(input(question))
    return response

# pieces() function
def pieces():
    """Determine if player or computer goes first."""
    go_first = ask_yes_no("Do you require the first move? (y/n): ")
    if go_first == "y":
        print("\nThen take the first move. You will need it.")
        human = X
        computer = O
    else:
        print("\nYour bravery will be your undoing... I will go first.")
        computer = X
        human = O
    return computer, human

# new_board() function
def new_board():
    """Create new game board."""
    board = []
    for square in range(NUM_SQUARES):
        board.append(EMPTY)
    return board

# display_board() function
def display_board(board):
    """Display game board on screen."""
    print("\n\t", board[0], "|", board[1], "|", board[2])
    print("\t", "---------")
    print("\t", board[3], "|", board[4], "|", board[5])
    print("\t", "---------")
    print("\t", board[6], "|", board[7], "|", board[8])

# legal_moves() function
def legal_moves(board):
    """Create list of legal moves."""
    moves = []
    for square in range(NUM_SQUARES):
        if board[square] == EMPTY:
            moves.append(square)
    return moves

# winner() function
def winner(board):
    """Determine the game winner."""
    WAYS_TO_WIN = ((0, 1, 2),
                   (3, 4, 5),
                   (6, 7, 8),
                   (0, 3, 6),
                   (1, 4, 7),
                   (2, 5, 8),
                   (0, 4, 8),
                   (2, 4, 6))
    for row in WAYS_TO_WIN:
        if board[row[0]] == board[row[1]] == board[row[2]] != EMPTY:
            winner = board[row[0]]
            return winner
    if EMPTY not in board:
        return TIE
    return None

# human_move() function
def human_move(board, human):
    """Get human move."""
    legal = legal_moves(board)
    move = None
    while move not in legal:
        move = ask_number("Where will you move? (0 - 8):", 0, NUM_SQUARES)
        if move not in legal:
            print("\nThat square is already occupied, foolish human. Choose another.\n")
    print("Fine...")
    return move

# computer_move() function
def computer_move(board, computer, human):
    """Make computer move."""
# make a copy to work with since function will be changing list
    board = board[:]
# the best positions to have, in order
    BEST_MOVES = (4, 0, 2, 6, 8, 1, 3, 5, 7)
    print("I shall take square number", end=" ")
# if computer can win, take that move
    for move in legal_moves(board):
        board[move] = computer
        if winner(board) == computer:
            print(move)
            return move
# done checking this move, undo it
        board[move] = EMPTY
# if human can win, block that move
    for move in legal_moves(board):
        board[move] = human
        if winner(board) == human:
            print(move)
            return move
# done checking this move, undo it
        board[move] = EMPTY
# since no one can win on next move, pick best open square
    for move in BEST_MOVES:
        if move in legal_moves(board):
            print(move)
            return move

# next_turn() function
def next_turn(turn):
    """Switch turns."""
    if turn == X:
        return O
    else:
        return X

# congrat_winner() function
def congrat_winner(the_winner, computer, human):
    """Congratulate the winner."""
    if the_winner != TIE:
        print(the_winner, "won!\n")
    else:
        print("It's a tie!\n")
    if the_winner == computer:
        print("As I predicted, human, I am triumphant once more. \n"
              "Proof that computers are superior to humans in all regards.")
    elif the_winner == human:
        print("No, no! It cannot be! Somehow you tricked me, human. \n"
              "But never again! I, the computer, so swear it!")
    elif the_winner == TIE:
        print("You were most lucky, human, and somehow managed to tie me. \n"
              "Celebrate today... for this is the best you will ever achieve.")

# try_again() function
def try_again(question):
    t = main()
    q = input("\n\nPress Enter to Exit")
    response = None
    while response not in ("t", "q"):
        response = input(question).lower()
    return response

# main() function
def main():
    display_instruct()
    computer, human = pieces()
    turn = X
    board = new_board()
    display_board(board)
    while not winner(board):
        if turn == human:
            move = human_move(board, human)
            board[move] = human
        else:
            move = computer_move(board, computer, human)
            board[move] = computer
        display_board(board)
        turn = next_turn(turn)
    the_winner = winner(board)
    congrat_winner(the_winner, computer, human)

# start the program
main()
try_again(input("Press t to try again or q to quit: "))

I can't seem to get the try_again Function to work properly. No matter what the input it runs the main Function over again. Entering t or q just runs the main Function as though the input
was completely ignored. How do I fix this issue?

A: Firstly your try_again function call is passing the input from the user to it not the actual question.
Change it to:
try_again("Press enter to try again or q to quit: ")

Also your logic wasn't working in this function. To get it to work as expected I did this:
def try_again(question):
    response = None
    while response != "q":
        print("\n\n")
        response = input(question).lower()
        if response != "q":
            t=main()
        else:
            return response

Hope this sheds some light on your issue.


text:
Q: Append legends. Whats wrong with my code? I'm trying to add legends the plot when it adds a curve. I can't see whats wrong with my code, can someone please help? I'm using matlab r2015a on ubuntu.
x=1:5;
v=1:5;
plot(x,v)
[~,~,plots,str] = legend('1');

hold on
for i=4:10
pl=plot(x,v*i);
[~,~,plots,str]=legend([plots;pl],str,num2str(i))
end

when i run it i get:
plots =

  1x2 Line array:

    Line    Line

str =

    '1'    '4'

Error using vertcat
Dimensions of matrices being
concatenated are not
consistent.

So its means it works the first lap but not the second.

A: As discussed in the comment, the way Matlab handles legends is different than in earlier releases; they are now legend objects.
In any case, to solve your problem, which is a dimension mismatch problem, you can simply concatenate vertically the outputs you get using the transpose operator, because Matlab returns a horizontal array of line and text objects whereas you want a vertical array. Therefore, using plots.' and pl.' works fine. Also, it's good practice not to use i as a loop counter since it represents the imaginary unit.
clear
clc
close all

x=1:5;
v=1:5;
plot(x,v)
[~,~,plots,str] = legend('1');

hold on
for k=4:10
pl=plot(x,v*k);
[LegendObject,~,plots,str]=legend([plots.';pl.'],str,num2str(k));
end

%// Use the legend object to modify its properties/location
set(LegendObject,'Location','NorthWest');

Output:


text:
Q: How To Hide Polygons In Python Tkinter Canvas? The purpose of my code is to have a triangle replaces a cursor. However, I need a solution to delete the triangles which were drawn previously by previous cursor movements.
This is my original code:
from tkinter import*
tk = Tk()
tk.resizable(0,0)
tk.attributes('-topmost',True)
window = Canvas(width = 1300, height = 700, bg = 'black',\
            highlightthickness=0, relief='ridge')
window.pack()
window.config(cursor='none')

class Cursor:

    def __init__(self,canvas):

        self.canvas = canvas
        self.id = self.canvas.create_polygon(0,0,10,0,0,-10)

    def Move(self):

        self.Mousex = self.canvas.winfo_pointerx()
        self.Mousey = self.canvas.winfo_pointery()
        self.id = self.canvas.create_polygon(self.Mousex,self.Mousey,\
                                         self.Mousex+10,self.Mousey,\
                                         self.Mousex,self.Mousey-10,\
                                         fill = 'red')
Cursor1 = Cursor(window)

while 1:
    tk.update_idletasks()
    window.update()
    Cursor1.Move()

I have tried the following code, but then no triangles appear at all. In the following code I inserted a:
self.canvas.delete(self.id)

so that the code is:
from tkinter import*
tk = Tk()
tk.resizable(0,0)
tk.attributes('-topmost',True)
window = Canvas(width = 1300, height = 700, bg = 'black',\
            highlightthickness=0, relief='ridge')
window.pack()
window.config(cursor='none')

class Cursor:

    def __init__(self,canvas):

        self.canvas = canvas
        self.id = self.canvas.create_polygon(0,0,10,0,0,-10)

    def Move(self):

        self.Mousex = self.canvas.winfo_pointerx()
        self.Mousey = self.canvas.winfo_pointery()
        self.id = self.canvas.create_polygon(self.Mousex,self.Mousey,\
                                         self.Mousex+10,self.Mousey,\
                                         self.Mousex,self.Mousey-10,\
                                         fill = 'red')
        self.canvas.delete(self.id)

Cursor1 = Cursor(window)

while 1:
    tk.update_idletasks()
    window.update()
    Cursor1.Move()

A: Canvas already has a move method defined, which you can use instead:
from tkinter import*
tk = Tk()
tk.resizable(0,0)
tk.attributes('-topmost',True)
window = Canvas(width = 1300, height = 700, bg = 'black',\
            highlightthickness=0, relief='ridge')
window.pack()
window.config(cursor='none')

class Cursor:

    def __init__(self,canvas):

        self.canvas = canvas
        self.id = self.canvas.create_polygon(0,0,10,0,0,-10, fill='red')
        self.Mousex = 0
        self.Mousey = 0

    def Move(self):

        _new_x = self.canvas.winfo_pointerx()
        _new_y = self.canvas.winfo_pointery()
        self.canvas.move(self.id, _new_x - self.Mousex, _new_y - self.Mousey)
        self.Mousex = _new_x
        self.Mousey = _new_y
        #self.canvas.delete(self.id)

Cursor1 = Cursor(window)

while 1:
    tk.update_idletasks()
    window.update()
    Cursor1.Move()


text:
Q: KeyError: 'kivy.garden.graph' I just started on kivy recently but when I import from kivy.garden.graph import MeshLinePlot  it gives an error
 Traceback (most recent call last):
   File "<pyshell#0>", line 1, in <module>
     from kivy.garden.graph import MeshLinePlot
   File "<frozen importlib._bootstrap>", line 983, in _find_and_load
   File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
   File "<frozen importlib._bootstrap>", line 668, in _load_unlocked
   File "<frozen importlib._bootstrap>", line 640, in _load_backward_compatible
 KeyError: 'kivy.garden.graph'

I have installed Kivy using there installation guide for windows https://kivy.org/doc/stable/installation/installation-windows.html

A: You need to install kivy-garden module first:
pip install kivy-garden

Then install graph package from garden module:
garden install graph

See https://kivy.org/doc/stable/api-kivy.garden.html

A: You should install matplotlib if you didn´t
if the above doesn't work or still output Key Error kivy.garden.matplotlib
You should type the following in your command window
garden install matplotlib

I have already installed it you can view the picture here am using matplotlib 3.1.1 python 3.7

A: They have changed the installation method to pip install kivy_garden.graph
https://github.com/kivy-garden/graph
You should execute this, and then proceed to %python\Lib\site-packages\kivy_garden
Copy the \graph folder inside to this directory %python\Lib\site-packages\kivy\garden
This solved the issue for me.

*

*Python 3.8.1

A: If you find the above error in the Android log file when trying to compile deploy and run the Kivy app on Android using buildozer, then try this solution: https://github.com/kivy/buildozer/issues/1226
And remember to put matplotlib in the buildozer.spec requirements. Something like this, depending on your specific needs:
requirements = python3,kivy,pillow,matplotlib


text:
Q: Why the divs are overlapping in Bootstrap? I'm having a problem with my divs overlapping. When the window is resized, the block "bg2" overlaps the columns into "bg3". Can't seem to figure out why. I've tried putting clear: both; between the divs, it didn't help.
Here is my code.
<?php include('header.php'); ?>

            A Minecraft server ran by IT professionals

Stable optimized Spigot server

Highly effective DDoS solution

Strong anti-cheat solution

Non-abusive admin staff

NOT pay to win

Example body text

Nullam quis risus eget urna mollis ornare vel eu leo. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nullam id dolor id nibh ultricies vehicula.

This line of text is meant to be treated as fine print.

The following snippet of text is rendered as bold text.

The following snippet of text is rendered as italicized text.

An abbreviation of the word attribute is attr.

Example body text

Nullam quis risus eget urna mollis ornare vel eu leo. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nullam id dolor id nibh ultricies vehicula.

This line of text is meant to be treated as fine print.

The following snippet of text is rendered as bold text.

The following snippet of text is rendered as italicized text.

An abbreviation of the word attribute is attr.

Example body text

Nullam quis risus eget urna mollis ornare vel eu leo. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nullam id dolor id nibh ultricies vehicula.

This line of text is meant to be treated as fine print.

The following snippet of text is rendered as bold text.

The following snippet of text is rendered as italicized text.

An abbreviation of the word attribute is attr.

Here is my custom css (not bootstrap)
.bg1 {
background-image: url(../images/bg1.jpg);
clear: both;
width: 100%;
height: 400px;
margin: 0 auto;
padding: 0px;
-webkit-box-shadow: inset 0px -5px 15px 0px rgba(0,0,0,0.75);
-moz-box-shadow: inset 0px -5px 15px 0px rgba(0,0,0,0.75);
box-shadow: inset 0px -5px 15px 0px rgba(0,0,0,0.75);
}
.bg2 {
background-color: #fffeee;
clear: both;
width: 100%;
height: 300px;
margin: 0 auto;
padding: 0px;
}
.bg3 {
background-image: url(../images/bg3.jpg);
clear: both;
width: 100%;
height: 300px;
margin: 0 auto;
padding: 0px;
-webkit-box-shadow: inset 0px -5px 15px 0px rgba(0,0,0,0.75);
-moz-box-shadow: inset 0px -5px 15px 0px rgba(0,0,0,0.75);
box-shadow: inset 0px -5px 15px 0px rgba(0,0,0,0.75);
}
.bg4 {
background-color: #fffeee;
width: 100%;
height: 300px;
margin: 0 auto;
padding: 0px;
}
.content-container {
margin-right: auto;
margin-left: auto;
padding: 45px;
}
@media (min-width: 768px) {
.content-container {
width: 750px;
}
}
@media (min-width: 992px) {
.content-container {
width: 970px;
}
}
@media (min-width: 1200px) {
.content-container {
width: 1170px;
}
}
.bg1-text1 {
font-size: 30px;
color: #FFF;
}
.bg1-text2 {
font-size: 20px;
color: #FFF;
padding-top: 15px;
padding-left: 40px;
list-style: none;
}

Any help appreciated. Thank you!

A: You could remove the fixed value height:300px; on .bg1 .bg2 .bg3 .bg4.
Or, add either overflow:auto; or overflow:hidden; if you do need the fixed value.


text:
Q: XPages Custom Error Page - get error message and line I'm trying to generate a custom error page for my xpages. I googled a lot of solutions and so far I get an error page telling me, that an error occured.
But I can't get the information what exactly happened (in this case the error is, that an "doc" has to be saved, but i named the variable "docs" just to get error).
All I do is:
var errObj = requestScope.error;
output = errObj.getCause().getErrorPropertyId();
output = errObj.getCause().getComponentId();

As soon as I try to call getExpressionText() I get an error 500.
How do I get the information, where the error happened (line number) and the variable that caused the error? - just like I do using the standard error page.

A: Have a look at this XSnippet by Tony McGuckin: http://openntf.org/XSnippets.nsf/snippet.xsp?id=custom-error-page-cw-cause-and-stacktrace-information. It uses the following to output details on the error:
  var output = requestScope.error.toString()+"\n\n";
  if(requestScope.error instanceof com.ibm.xsp.exception.XSPExceptionInfo){
    var codeSnippet = requestScope.error.getErrorText();
    var control = requestScope.error.getErrorComponentId();
    var cause = requestScope.error.getCause();
    output += "In the control : " + control + "\n\n";
    if(cause instanceof com.ibm.jscript.InterpretException){
      var errorLine = cause.getErrorLine();
      var errorColumn = cause.getErrorCol();
      output += "At line " + errorLine;
      output += ", column " + errorColumn + " of:\n";
    }else{
      output += "In the script:\n";
    }
    output += codeSnippet;
  }
  return output;

A: The error line and details are not easily accessible from requestScope.error. If you look at the source code for the latest release of Mark Leusink's Debug Toolbar, you'll see he's parsing the stack trace to get the details.
However, you can access all the relevant information using the underlying Java class for the SSJS exception - com.ibm.jscript.InterpretException using getErrorLine(). The getLocalizedMessage() method gets the error detail that usually starts "Script interpreter error". The getExpressionText() method retrieves the line that threw the error.
If you take a look at the XPages OpenLog Logger project I put on OpenNTF, that's what I use to log full details to OpenLog. http://www.openntf.org/Internal/home.nsf/project.xsp?action=openDocument&name=XPages%20OpenLog%20Logger
You can see the source code of the OpenLogPhaseListener which uses those methods here: https://github.com/paulswithers/openlogjava/blob/master/OpenLogJava/WebContent/WEB-INF/src/com/paulwithers/openLog/OpenLogPhaseListener.java
Even if you're not a Java expert, from use of SSJS the key parts should be understandable. Line 84 captures uncaught exceptions - when XPages routes to the default error page. That uses the methods I mentioned.
Lines 98 to 105 are the ones that log out all the details if you just use a catch block, passing OpenLogBean.addError(e, this) where e is the error object and this is the component the error occurs on. error.getError() in the Java code retrieves that error object. To get the typeahead in SSJS you'll need to use catch(e:com.ibm.jscript.InterpretException) I believe.
I haven't tested this, I've just working back from what I used for the project on OpenNTF.

A: For now I've dealt with this problem by using the Debug Toolbar and the OpenLog Database.
If an error occurs the user only gets a custom error page (using the example of the Debug Toolbar) with the information, that something went wrong. So he does not have to bother with any other problems or even the Stack Trace. But at the same moment he gets the error page, the error is logged in our Log-Database with all informations needed (like line, exact error message etc.).
I've also implemented an "Report this problem" Link-Button to create a new E-Mail containing important information about the session the user is currently in.


text:
Q: 'Access-Control-Allow-Credentials' header in the response is ' ' when trying to send a POST request to an API using Axios I have a react app running in localhost:3000 and a nodeJS-express server on localhost:8000, I need to send a POST request to the jsreport API, but when I try to send the request I got the following error:

Access to XMLHttpRequest at 'http://localhost:5488/api/report' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Credentials' header in the response is '' which must be 'true' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.

Post request:
axios.defaults.withCredentials = true;

axios.post('http://localhost:5488/api/report',
{withCredentials: true, crossorigin: true},
{
  "template": {
    "content": "
Hello {{foo}}
",
    "engine": "handlebars",
    "recipe": "chrome-pdf"
  },
  "data": {
    "foo": "world"
  }
}).then((response)=> {
  fs.writeFileSync('/reports/report.pdf', response.content)
}).catch(function (error) {
  console.log('AXIOS error: '+ error);
  return 'errorReport'
})

Server.js:
var corsOptions = {
  origin: 'http://localhost:3000',
  credentials : true
 }
app.use(cors(corsOptions));
app.use((req, res, next) => {
  res.header('Access-Control-Expose-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
  res.header("Access-Control-Allow-Origin", "http://localhost:3000");
  res.header("Access-Control-Allow-Credentials", true);
  res.header("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  const err = new Error('Not Found');
  err.status = 404;
  next(err);
})

I don't understand why the credentials are empty If I use .withCredentials in axios and established the headers and the cors configuration in the server.

A: I used the next code instead of the axios request and it worked:
fetch('http://localhost:5488/api/report', {
  method: 'POST',
  body: JSON.stringify(data),
  headers:{
    'Content-Type': 'application/json'
  },
  credentials: "same-origin",
}

Set credentials to "same-origin" fixed the problem, but as I wanted to use jsreport I found a package to make this easier without using fetch or axios.
import jsreport from 'jsreport-browser-client-dist'
jsreport.serverUrl = 'http://localhost:5488'
jsreport.render(document.getElementById('reportPlaceholder'), data)

Using the jsreport methods I could show my report in the react component

there should be a report here...

A: Update Server.js as below

var corsOptions = {
  origin: 'http://localhost:3000',
  credentials : true
 }

app.use(cors(corsOptions));

app.use(function (req, res, next) {
    res.setHeader('Access-Control-Allow-Origin', 'http://localhost:3000');
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
    res.setHeader('Access-Control-Allow-Credentials', true);
    next();
});

A: i've been fiddling with persistent user sessions for a while and was having trouble stringing together passport / passport-local (for authentification), mongoose, express-session, and connect-mongo (for storing sessions in mongo).
@mshibl comment helped me get 1 step further, and setting these cors options for express finally had cookies being passed correctly. hopefully this helps someone else having a similar issue
app.use(cors({
  credentials: true,
  origin: "http://localhost:3000"
}));

A: This worked for me
export default function({ $axios, redirect }, inject) {
  // Base URL
  const base = process.env.API_URL

  // Sett withCredentials on $axios before creating instance
  $axios.defaults.withCredentials = true

  // Create a custom axios instance
  const api = $axios.create({
    baseURL: base,
    responseType: 'json',
    timeout: 10000,
    // withCredentials: true,
    headers: {
      'X-Requested-With': 'XMLHttpRequest',
      'Content-Type': 'application/json'
    }
  })

  // Inject to context as $api
  inject('api', api)

setting the defaults.withCredentials before creating my own instance solved it for me.


text:
Q: How to get the variable with its name in C# Want to use a variable based on its name. It is hard to describe. Here is the example
var sections = new[] { "Personnel", "General", "Medical" };

foreach (var s in sections)
{
    // want to retrieve the variable "lblPersonnel"
    (Label)Type.GetType(string.Format("lbl{0}", s)).Text = "Test";
}

so that we don't have to :
lblPersonnel.Text = "Test";
lblGeneral.Text = "Test";
lblMedical.Text = "Test";

So, is it possible for this kind of "reflection"?

A: Type.GetType expects a fully-qualified type name but you are trying to pass it name of the variable.And also it returns a Type instance so you can't cast it to Label.It seems you are confused about types,instances and variables. If you have labels and you want to access them you can use Controls collection of your Form.
foreach (var s in sections)
{
   var name = string.Format("lbl{0}", s);
   if(this.Controls.ContainsKey(name))
   {
       var currentLabel = this.Controls[name] as Label;
       if(currentLabel != null) currentLabel.Text = "Test";
   }
}

Edit: If you are devoloping an ASP.NET project then you can use FindControl method to get your labels by name:
foreach (var s in sections)
{
    var name = string.Format("lbl{0}", s);
    var currentLabel = FindControl(name) as Label;
    if(currentLabel != null) currentLabel.Text = "Test";
}

A: Why not just get the label using Controls?
var sections = new [] {"Personnel", "General", "Medical"};

foreach (var s in sections)
{
    // want to retrieve the variable "lblPersonnel"
    ((Label)(Controls["lbl" + s])).Text = "Test";
}

A: foreach (var s in sections)
{
    string name = string.Format("lbl{0}", s);
    FieldInfo fi = typeof(Form1).GetField(name);
    Label l = (Label)(fi.GetValue(this));
    l.Text = "Test";
}

This is assuming the Labels are public fields. If they are properties - use GetProperty , if they are private fields, use:
 GetField(name, BindingFlags.NonPublic | BindingFlags.Instance);


text:
Q: how to change domain of computer in many computer in all of our company? I would like to change abc domain to def domain for all computers on my network.
How do I change them all on the network and backup?
My server is Windows Server 2003 and it is used as an Active Directory and domain controller.
(Also, what about software that can be used in Active Directory?)

A: do you mean rename an Active Directory domain?
http://support.microsoft.com/?kbid=292541
or maybe
http://technet.microsoft.com/en-gb/windowsserver/bb405948.aspx
I think you need to elaborate a little more.  Although my powers of mental telepathy have improved since I first started answering questions on serverfault, they're not that good.

A: Or us the Active Directory Migration Tool if you prefer the GUI.

A: Make sure you have a very good business case for doing this... if you have applications in your environment that depend on Active Directory, they will likely break.  If you have Exchange 2003, it requires you to run a fix-up tool afterwards.  You cannot do it if you have Exchange 2007 or 2010 in your environment.  MOM/Operations Manager will need to be uninstalled before the domain rename and reinstalled afterwards.  SQL connection strings will need to be updated manually  (those are just off the top of my head).  You will need to test everything in a lab so that you find out what will/will not work in your own environment.
If, after all that, you decide to proceed... here is how to do it:
Windows Server 2003 Active Directory Domain Rename Tools & Documentation
http://www.microsoft.com/technet/downloads/winsrvr/domainrename.mspx
How Domain Rename Works
http://technet.microsoft.com/en-us/library/cc738208(WS.10).aspx and here: Introduction to Administering Active Directory Domain Renamehttp://technet.microsoft.com/en-us/library/cc816848(WS.10).aspx
Checklists for the Domain Rename Operation
http://technet.microsoft.com/en-us/library/cc816631(WS.10).aspx.
Webcasts
TechNet Support WebCast: Renaming domains when Microsoft Exchange Server 2003 is
in the Active Directory
http://support.microsoft.com/?id=838623
Support WebCast: Microsoft Windows Server 2003: Implementing an Active Directory
Domain Rename Operation
http://support.microsoft.com/default.aspx?scid=kb;en-us;819145
Another option would be to create a new domain and migrate over the users and computers using ADMT (guide here: http://technet.microsoft.com/en-us/library/cc974332(WS.10).aspx)

A: Use good network management software

A: you can script this using netdom.exe

NETDOM /Domain:def /user:adminuser /password:apassword MEMBER
      MYCOMPUTER /JOINDOMAIN


text:
Q: how to avoid null in json payload output in mulesoft dataweave transform My output :
   {
            "EmployeePositions": {
              "EmployeeID": "05383803",
              **"EmployeeName": null,**
              "Positions": [
                {
                  "PositionID": null,
                  "EffectiveDate": "2017-06-17",
                  "BusinessUnit": null,
                  "Customer": {
                    **"JobReqNumber": null,**
                    "CustomerID": "243720",
                    "CustomerName": "TEKGS UK@BANK OF AMERICA",
                    "CustomerOrderNumber": null
                  },
                  "WorkSiteLocaiton": {
                    "Address1": "BLUE SQUARES HOUSE",
                    "Address2": "PRIORS WAY",
                    "Address3": " ",
                    "Address4": " ",
                    "Number1": " ",
                    "Number2": " ",
                    "City": "BERKS",
                    "State": "BRACKNELL",
                    "Postal": "RG42 ING",
                    "Country": "GBR"
                  }
                },
                {
                  "PositionID": null,
                  "EffectiveDate": "2017-06-15",
                  "EffectiveStatus": "I",
                  "BusinessUnit": null,
                  "Customer": {
                    "JobReqNumber": null,
                    "CustomerID": "243721",
                    "CustomerName": "TEKGS UK@UK Bank",
                    "CustomerOrderNumber": null
                  },
                  "WorkSiteLocaiton": {
                    "Address1": "BLUE SQUARES",
                    "Address2": "PRIORS WAY",
                    "Address3": " ",
                    "Address4": " ",
                    "Number1": " ",
                    "Number2": " ",
                    "City": "BERKSS",
                    "State": "BRACKNEL",
                    "Postal": "RG42 ING",
                    "Country": "GBR"
                  }
                }
              ]
            }
          }

expected output:
   {
            "EmployeePositions": {
              "EmployeeID": "05383803",
              "EmployeeName": "John Smith",
              "Positions": [
                {
                  "PositionID": "",
                  "EffectiveDate": "2017-06-17",
                  "BusinessUnit": "",
                  "Customer": {
                    "JobReqNumber": "",
                    "CustomerID": "243720",
                    "CustomerName": "TEKGS UK@BANK OF AMERICA",
                    "CustomerOrderNumber": ""
                  },
                  "WorkSiteLocaiton": {
                    "Address1": "BLUE SQUARES HOUSE",
                    "Address2": "PRIORS WAY",
                    "Address3": " ",
                    "Address4": " ",
                    "Number1": " ",
                    "Number2": " ",
                    "City": "BERKS",
                    "State": "BRACKNELL",
                    "Postal": "RG42 ING",
                    "Country": "GBR"
                  }
                },
                {
                  "PositionID": "",
                  "EffectiveDate": "2017-06-15",
                  "EffectiveStatus": "I",
                  "BusinessUnit": "",
                  "Customer": {
                    "JobReqNumber": "",
                    "CustomerID": "243721",
                    "CustomerName": "TEKGS UK@UK Bank",
                    "CustomerOrderNumber": ""
                  },
                  "WorkSiteLocaiton": {
                    "Address1": "BLUE SQUARES",
                    "Address2": "PRIORS WAY",
                    "Address3": " ",
                    "Address4": " ",
                    "Number1": " ",
                    "Number2": " ",
                    "City": "BERKSS",
                    "State": "BRACKNEL",
                    "Postal": "RG42 ING",
                    "Country": "GBR"
                  }
                }
              ]
            }
          }

I want exactly the same same output instead of null i want ("") as an output
i tried (%output application/json skipNullOn="everywhere")  and also (when payload != null otherwise "") but i have to write this after every field. Do we have any better solution.
Any leads will be appreciated

A: This will work for you:
%dw 1.0
%output application/json

%function applyToValues(e, fn)
  e match {
    :object  -> $ mapObject {($$): applyToValues($, fn)},
    :array   -> $ map applyToValues($, fn),
    default  -> fn($)
  }

%function replaceNull(e, replacement="")
  applyToValues(e, ((v) -> replacement when (v == null) otherwise v))
---
replaceNull(payload)


text:
Q: How to make components in react native? I am new to react native and want to create three Components. for Increment Button, Decrement Button and to display Counter value.
State/Hook should remain in the App Component. I don't want to Modify that.
import React, {useState} from 'react';
import { Text, View, StyleSheet, Button } from 'react-native';

export default function App() {
const [getIncCounter, setIncCounter] = useState(0)
const inc = () => {
setIncCounter(getIncCounter + 1);
}
const dec = () => {
setIncCounter(getIncCounter - 1);
}
return (
<View style={styles.container}>
  <View style={{flexDirection: 'row'}}>
    <Button title="+" onPress={inc} />
    <Text> {getIncCounter} </Text>
    <Button title="-" onPress={dec} />
  </View>
 </View>
 );
}

const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
backgroundColor: '#ecf0f1',
padding: 8,
},
paragraph: {
margin: 24,
fontSize: 18,
fontWeight: 'bold',
textAlign: 'center',
},
});

A: Here is how you can create a separate component for increase/decrease buttons and a component for showing results.

import React, { useState } from 'react';
import { Text, View, StyleSheet, Button } from 'react-native';

export default function App() {
  const [getIncCounter, setIncCounter] = useState(0);
  const inc = () => {
    setIncCounter(getIncCounter + 1);
  };
  const dec = () => {
    setIncCounter(getIncCounter - 1);
  };
  return (
    <View style={styles.container}>
      <View style={{ flexDirection: 'row' }}>
        <ButtonComponent title={'+'} onClick={inc} />
        <ResultComponent result={getIncCounter} />
        <ButtonComponent title={'-'} onClick={dec} />
      </View>
    </View>
  );
}

const ButtonComponent = ({ onClick, title }) => {
  return (

      <Button title={title} onPress={onClick} />

  );
};

const ResultComponent = ({ result }) => {
  return (

      <Text> {result} </Text>

  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    backgroundColor: '#ecf0f1',
    padding: 8,
  },
  paragraph: {
    margin: 24,
    fontSize: 18,
    fontWeight: 'bold',
    textAlign: 'center',
  },
});

It's redundant though, but if you want to learn how to pass props and stuff it is fine. Button and Text are components themselves.
Expo Snack Example


text:
Q: Deny php execution in /wp-includes - using .htaccess in /wp-includes VS root folder Trying to secure my WP site. In an attempt to deny php execution from the wp-includes folder wondering if these two methods are effectively doing the same thing?
1) add new .htaccess file to root of wp-includes folder with following code:
<Files *.php>
deny from all
</Files>

but this disables tinymce.
2) add this code to top of existing .htaccess in root of WP install:
# Block the include-only files.
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^wp-admin/includes/ - [F,L]
RewriteRule !^wp-includes/ - [S=3]
RewriteRule ^wp-includes/[^/]+\.php$ - [F,L]
RewriteRule ^wp-includes/js/tinymce/langs/.+\.php - [F,L]
RewriteRule ^wp-includes/theme-compat/ - [F,L]
</IfModule>

Are these doing the same thing? Been using method #1 but need to make tinymce accessible now.


text:
Q: How to change Bootstrap width that triggers responsive? I have a code like this.
<!DOCTYPE html>

  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

                    Sidebar
                    Link
                    Link
                    Link
                    Link
                    Link

Main Area

Sriracha biodiesel taxidermy organic post-ironic, Intelligentsia salvia mustache 90's code editing brunch. Butcher polaroid VHS art party, hashtag Brooklyn deep v PBR narwhal sustainable mixtape swag wolf squid tote bag. Tote bag cronut semiotics,
                raw denim deep v taxidermy messenger bag. Tofu YOLO Etsy, direct trade ethical Odd Future jean shorts paleo. Forage Shoreditch tousled aesthetic irony, street art organic Bushwick artisan cliche semiotics ugh synth chillwave meditation.
                Shabby chic lomo plaid vinyl chambray Vice. Vice sustainable cardigan, Williamsburg master cleanse hella DIY 90's blog.

Ethical Kickstarter PBR asymmetrical lo-fi. Dreamcatcher street art Carles, stumptown gluten-free Kickstarter artisan Wes Anderson wolf pug. Godard sustainable you probably haven't heard of them, vegan farm-to-table Williamsburg slow-carb
                readymade disrupt deep v. Meggings seitan Wes Anderson semiotics, cliche American Apparel whatever. Helvetica cray plaid, vegan brunch Banksy leggings +1 direct trade. Wayfarers codeply PBR selfies. Banh mi McSweeney's Shoreditch selfies,
                forage fingerstache food truck occupy YOLO Pitchfork fixie iPhone fanny pack art party Portland.

Sriracha biodiesel taxidermy organic post-ironic, Intelligentsia salvia mustache 90's code editing brunch. Butcher polaroid VHS art party, hashtag Brooklyn deep v PBR narwhal sustainable mixtape swag wolf squid tote bag. Tote bag cronut semiotics,
                raw denim deep v taxidermy messenger bag. Tofu YOLO Etsy, direct trade ethical Odd Future jean shorts paleo. Forage Shoreditch tousled aesthetic irony, street art organic Bushwick artisan cliche semiotics ugh synth chillwave meditation.
                Shabby chic lomo plaid vinyl chambray Vice. Vice sustainable cardigan, Williamsburg master cleanse hella DIY 90's blog.

Sriracha biodiesel taxidermy organic post-ironic, Intelligentsia salvia mustache 90's code editing brunch. Butcher polaroid VHS art party, hashtag Brooklyn deep v PBR narwhal sustainable mixtape swag wolf squid tote bag. Tote bag cronut semiotics,
                raw denim deep v taxidermy messenger bag. Tofu YOLO Etsy, direct trade ethical Odd Future jean shorts paleo. Forage Shoreditch tousled aesthetic irony, street art organic Bushwick artisan cliche semiotics ugh synth chillwave meditation.
                Shabby chic lomo plaid vinyl chambray Vice. Vice sustainable cardigan, Williamsburg master cleanse hella DIY 90's blog.

https://www.w3schools.com/code/tryit.asp?filename=G6GLE5UA2TUM (You can press run to run code above)
This code moves left sidebar to top of the screen when the width of resolution goes less than about 580px. However, I want to change this behavior that it moves left side bar to top of the screen when the width of resolution goess less than 1024px, not 580px.
How can I do this with Bootstrap 4?

A: Just change the col-sm-* and flex-sm-column classes to col-lg-* and flex-lg-column... If you check Bootstrap documentation, the lg classes target the 1024px mark

<!DOCTYPE html>

  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

            Sidebar
            Link
            Link
            Link
            Link
            Link

Main Area

Sriracha biodiesel taxidermy organic post-ironic, Intelligentsia salvia mustache 90's code editing brunch. Butcher polaroid VHS art party, hashtag Brooklyn deep v PBR narwhal sustainable mixtape swag wolf squid tote bag. Tote bag cronut semiotics,
          raw denim deep v taxidermy messenger bag. Tofu YOLO Etsy, direct trade ethical Odd Future jean shorts paleo. Forage Shoreditch tousled aesthetic irony, street art organic Bushwick artisan cliche semiotics ugh synth chillwave meditation. Shabby
          chic lomo plaid vinyl chambray Vice. Vice sustainable cardigan, Williamsburg master cleanse hella DIY 90's blog.

Ethical Kickstarter PBR asymmetrical lo-fi. Dreamcatcher street art Carles, stumptown gluten-free Kickstarter artisan Wes Anderson wolf pug. Godard sustainable you probably haven't heard of them, vegan farm-to-table Williamsburg slow-carb readymade
          disrupt deep v. Meggings seitan Wes Anderson semiotics, cliche American Apparel whatever. Helvetica cray plaid, vegan brunch Banksy leggings +1 direct trade. Wayfarers codeply PBR selfies. Banh mi McSweeney's Shoreditch selfies, forage fingerstache
          food truck occupy YOLO Pitchfork fixie iPhone fanny pack art party Portland.

Sriracha biodiesel taxidermy organic post-ironic, Intelligentsia salvia mustache 90's code editing brunch. Butcher polaroid VHS art party, hashtag Brooklyn deep v PBR narwhal sustainable mixtape swag wolf squid tote bag. Tote bag cronut semiotics,
          raw denim deep v taxidermy messenger bag. Tofu YOLO Etsy, direct trade ethical Odd Future jean shorts paleo. Forage Shoreditch tousled aesthetic irony, street art organic Bushwick artisan cliche semiotics ugh synth chillwave meditation. Shabby
          chic lomo plaid vinyl chambray Vice. Vice sustainable cardigan, Williamsburg master cleanse hella DIY 90's blog.

Sriracha biodiesel taxidermy organic post-ironic, Intelligentsia salvia mustache 90's code editing brunch. Butcher polaroid VHS art party, hashtag Brooklyn deep v PBR narwhal sustainable mixtape swag wolf squid tote bag. Tote bag cronut semiotics,
          raw denim deep v taxidermy messenger bag. Tofu YOLO Etsy, direct trade ethical Odd Future jean shorts paleo. Forage Shoreditch tousled aesthetic irony, street art organic Bushwick artisan cliche semiotics ugh synth chillwave meditation. Shabby
          chic lomo plaid vinyl chambray Vice. Vice sustainable cardigan, Williamsburg master cleanse hella DIY 90's blog.