text:
Q: Android configuration file What is the best way and how do I set up a configuration file for a application?
I want the application to be able to look into a text file on the SD card and pick out certain information that it requires.

A: If you want to store the preferences of your application, Android provides SharedPreferences for this.
Here is the link to official training resource.

A: I met such requirement recently, noting down here, how I did it.

the application to be able to look into a text file on the sd card and
  pick out certain information that it requires

Requirement:

*

*Configuration value(score_threshold) has to be available at the sdcard. So somebody can change the values after releasing the apk.

*The config file must be available at the "/sdcard/config.txt" of the android hardware.

The config.txt file contents are,
score_threshold=60

Create a utility class Config.java, for reading and writing text file.
import android.util.Log;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;

public final class Config {

    private static final String TAG = Config.class.getSimpleName();
    private static final String FILE_PATH = Environment.getExternalStorageDirectory().getAbsolutePath() + "/config.txt";
    private static Config sInstance = null;

    /**
     * Gets instance.
     *
     * @return the instance
     */
    public static Config getInstance() {
        if (sInstance == null) {
            synchronized (Config.class) {
                if (sInstance == null) {
                    sInstance = new Config();
                }
            }
        }
        return sInstance;
    }

    /**
     * Write configurations values boolean.
     *
     * @return the boolean
     */
    public boolean writeConfigurationsValues() {

        try (OutputStream output = new FileOutputStream(FILE_PATH)) {

            Properties prop = new Properties();

            // set the properties value
            prop.setProperty("score_threshold", "60");

            // save properties
            prop.store(output, null);

            Log.i(TAG, "Configuration stored  properties: " + prop);
            return true;
        } catch (IOException io) {
            io.printStackTrace();
            return false;
        }
    }

    /**
     * Get configuration value string.
     *
     * @param key the key
     * @return the string
     */
    public String getConfigurationValue(String key){
        String value = "";
        try (InputStream input = new FileInputStream(FILE_PATH)) {

            Properties prop = new Properties();

            // load a properties file
            prop.load(input);
            value = prop.getProperty(key);
            Log.i(TAG, "Configuration stored  properties value: " + value);
         } catch (IOException ex) {
            ex.printStackTrace();
        }
        return value;
    }
}

Create another utility class to write the configuration file for the first time execution of the application,
Note: SD card read/write permission has to be set for the application.
public class ApplicationUtils {

  /**
  * Sets the boolean preference value
  *
  * @param context the current context
  * @param key     the preference key
  * @param value   the value to be set
  */
 public static void setBooleanPreferenceValue(Context context, String key, boolean value) {
     SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
     sp.edit().putBoolean(key, value).commit();
 }

 /**
  * Get the boolean preference value from the SharedPreference
  *
  * @param context the current context
  * @param key     the preference key
  * @return the the preference value
  */
 public static boolean getBooleanPreferenceValue(Context context, String key) {
     SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
     return sp.getBoolean(key, false);
 }

}

At your Main Activity, onCreate()
if(!ApplicationUtils.getBooleanPreferenceValue(this,"isFirstTimeExecution")){
           Log.d(TAG, "First time Execution");
           ApplicationUtils.setBooleanPreferenceValue(this,"isFirstTimeExecution",true);
           Config.getInstance().writeConfigurationsValues();
}
// get the configuration value from the sdcard.
String thresholdScore = Config.getInstance().getConfigurationValue("score_threshold");
Log.d(TAG, "thresholdScore from config file is : "+thresholdScore );

A: If your application is going to be released to the public, and if you have sensitive data in your config, such as API keys or passwords, I would suggest to use secure-preferences instead of SharedPreferences since, ultimately, SharedPreferences are stored in an XML in clear text, and on a rooted phone, it is very easy for an application to access another's shared preferences.

By default it's not bullet proof security (in fact it's more like
obfuscation of the preferences) but it's a quick win for incrementally
making your android app more secure. For instance it'll stop users on
rooted devices easily modifying your app's shared prefs. (link)

I would suggest a few other methods:
*Method 1: Use a .properties file with Properties
Pros:

*

*Easy to edit from whatever IDE you are using

*More secure: since it is compiled with your app

*Can easily be overridden if you use Build variants/Flavors

*You can also write in the config

Cons:

*

*You need a context

*You can also write in the config (yes, it can also be a con)

*(anything else?)

First, create a config file: res/raw/config.properties and add some values:
api_url=http://url.to.api/v1/
api_key=123456

You can then easily access the values with something like this:
package some.package.name.app;

import android.content.Context;
import android.content.res.Resources;
import android.util.Log;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public final class Helper {
    private static final String TAG = "Helper";

    public static String getConfigValue(Context context, String name) {
        Resources resources = context.getResources();

        try {
            InputStream rawResource = resources.openRawResource(R.raw.config);
            Properties properties = new Properties();
            properties.load(rawResource);
            return properties.getProperty(name);
        } catch (Resources.NotFoundException e) {
            Log.e(TAG, "Unable to find the config file: " + e.getMessage());
        } catch (IOException e) {
            Log.e(TAG, "Failed to open config file.");
        }

        return null;
    }
}

Usage:
String apiUrl = Helper.getConfigValue(this, "api_url");
String apiKey = Helper.getConfigValue(this, "api_key");

Of course, this could be optimized to read the config file once and get all values.
Method 2: Use AndroidManifest.xml meta-data element:
Personally, I've never used this method because it doesn't seem very flexible.
In your AndroidManifest.xml, add something like:
...
<application ...>
    ...

    <meta-data android:name="api_url" android:value="http://url.to.api/v1/"/>
    <meta-data android:name="api_key" android:value="123456"/>
</application>

Now a function to retrieve the values:
public static String getMetaData(Context context, String name) {
    try {
        ApplicationInfo ai = context.getPackageManager().getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA);
        Bundle bundle = ai.metaData;
        return bundle.getString(name);
    } catch (PackageManager.NameNotFoundException e) {
        Log.e(TAG, "Unable to load meta-data: " + e.getMessage());
    }
    return null;
}

Usage:
String apiUrl = Helper.getMetaData(this, "api_url");
String apiKey = Helper.getMetaData(this, "api_key");

Method 3: Use buildConfigField in your Flavor:
I didn't find this in the official Android documentation/training, but this blog article is very useful.
Basically setting up a project Flavor (for example prod) and then in your app's build.gradle have something like:
productFlavors {
    prod {
        buildConfigField 'String', 'API_URL', '"http://url.to.api/v1/"'
        buildConfigField 'String', 'API_KEY', '"123456"'
    }
}

Usage:
String apiUrl = BuildConfig.API_URL;
String apiKey = BuildConfig.API_KEY;

A: You can achieve this using shared preferences
There is a very detailed guide on how to use Shared Preferences on the Google Android page
https://developer.android.com/guide/topics/data/data-storage.html#pref


text:
Q: Get return Value from Object.keys I have a function that searches an object, to see if a value exist in it but I can't get the value from it when I try to log it.
searchValue(object,value){
    let valueExists = Object.keys(object).find(key => object[key].valueID === value );
    console.log(valueExists);
}

A: You could use Object(o).values like :
let valueExists = Object.values(object).find(val => val === value )
console.log(valueExists)

JS Example :

function searchValue(object, value) {

  let valueExists = Object.values(object).find(val => val == value)
  console.log(valueExists)
}

let user = {
  id: 12,
  name: "aaa",
  email: "aaaa@domain.com",

}

searchValue(user, "aaa")

A: If you already have value (as searchValue parameter) you don't need to "get" value because you already have it (below I simplify your implementation)

function searchValue(object, value) {
  return Object.values(object).includes(value);
}

let obj = {a: "xx", b: "yy"};
let val = "yy"

if(searchValue(obj,val)) {
    console.log("the object value exist and is:", val);
}

If you interest to find keys which are associated with value try this

function searchKeys(object, value) {
  return Object.keys(object).filter(k=>object[k]==value);
}

let obj = {a: "xx", b: "yy", c:"xx"};
let val = "xx"

console.log("Keys contains 'xx' value:", searchKeys(obj,val));

A: To achieve expected result, use below option of using Object entries and looping with forEach for value

function searchValue(object,value){
    Object.entries(object).forEach(v => {
      if(v.indexOf(value) !== -1) console.log("valueExists")
    });
}

let test = {
  id : 11,
  name: 'abc',
  location: 'usa'
}

searchValue(test, 11)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Api test case failed for user create view I am writing the test case here for CreateUser view but the test is failing. It is throwing the following error

profile_data = validated_data.pop('profile')  KeyError: 'profile'

What I am doing wrong here ?Am I doing wrong a=in my view/serializers or my test code is wrong?
It creates the users perfectly.
models.py
class Profile(models.Model):
    user = models.OneToOneField(get_user_model(),on_delete=models.CASCADE)
    address = models.CharField(max_length=250,blank=True,null=True)
    contact = models.CharField(max_length=250,blank=True,null=True)

serializers.py
class UserSerializer(serializers.ModelSerializer):
    profile = ProfileSerializer(required=False)
    email = serializers.EmailField(validators=[UniqueValidator(queryset=get_user_model().objects.all())])
    password1 = serializers.CharField(required=True, write_only=True)
    password2 = serializers.CharField(required=True, write_only=True)

    class Meta:
        model = get_user_model()
        fields = ['first_name', 'last_name', 'username', 'email', 'password1', 'password2', 'profile']

    def validate_password1(self, password):
        validators.validate_password(password=password)

    def validate_password2(self, password):
        validators.validate_password(password=password)

    def validate(self, data):
        if data['password1'] != data['password2']:
            raise serializers.ValidationError("The two password fields didn't match.")
        return data

    # def validate_username(self, validated_data):
    #     username = validated_data['username']
    #     print('usr',username)
    #     if len(username) < 6 and len(username) > 15:
    #         raise ValidationError('Username must be between 6 and 15 characters long')
    #     return username

    def create(self, validated_data):
        user = get_user_model().objects.create(
            username=validated_data['username'],
            email=validated_data['email'],
            first_name=validated_data['first_name'],
            last_name=validated_data['last_name'],

        )

        user.set_password(validated_data['password2'])
        user.is_staff = True
        user.save()
        profile_data = validated_data.pop('profile')
        Profile.objects.create(
            user=user, address=profile_data['address'], contact=profile_data['contact']
        )

        return user

views.py
class CreateUser(generics.CreateAPIView):
    serializer_class = UserSerializer
    queryset = get_user_model().objects.all()

tests.py
class UserCreateListTest(APITestCase):
    def setUp(self):
        self.client = Client()

    def test_create_user(self):
        url = reverse('users:create_user')
        user = {'first_name':'first','last_name':'last','username':'username','email':'email@email.com',
                'password1':'1234@password.com','password2':'1234@password.com',
                "profile": {
            "user": 1,
            "address": "add",
            "contact": "cc"
        },
               }
        response = self.client.post(url,data=user,format='json')
        print(response.status_code)
        print(response.json())
        return self.assertEqual(response.status_code,status.HTTP_201_CREATED)

A: In your test, replace Client class with rest_framework.test.APIClient

A:     def setUp(self):
        self.client = Client()

this is unnecessary. APITestCase already provides self.client which is APIClient


text:
Q: Converting table with columns as level into tree Hierarchy I have a table as shown in image and want to create a tree hierarchy out of it.

trying to do this using oracle sql.

A: I suggest you to change your table structure like this :
emp_id          emp_name          emp_emp_id (boss of emp_id)
1                    BigBoss          NULL
2                    Boss             1
3                    Emp1             2
4                    Emp2             2

The you can easyly use connect by Oracle KeyWord to recover the hierarchy tree.
Doc Here => http://docs.oracle.com/cd/B19306_01/server.102/b14200/queries003.htm

A: Let's take an example of SCOTT.EMP table to create the hierarchy.
SQL> SELECT empno,
  2    level,
  3    Lpad(ename,LENGTH(ename) + LEVEL * 10 - 10,'-') tree,
  4    job,
  5    mgr
  6  FROM emp
  7    START WITH mgr        IS NULL
  8    CONNECT BY PRIOR empno = mgr
  9  /

     EMPNO      LEVEL TREE                                JOB              MGR
---------- ---------- ----------------------------------- --------- ----------
      7839          1 KING                                PRESIDENT
      7566          2 ----------JONES                     MANAGER         7839
      7788          3 --------------------SCOTT           ANALYST         7566
      7876          4 ------------------------------ADAMS CLERK           7788
      7902          3 --------------------FORD            ANALYST         7566
      7369          4 ------------------------------SMITH CLERK           7902
      7698          2 ----------BLAKE                     MANAGER         7839
      7499          3 --------------------ALLEN           SALESMAN        7698
      7521          3 --------------------WARD            SALESMAN        7698
      7654          3 --------------------MARTIN          SALESMAN        7698
      7844          3 --------------------TURNER          SALESMAN        7698
      7900          3 --------------------JAMES           CLERK           7698
      7782          2 ----------CLARK                     MANAGER         7839
      7934          3 --------------------MILLER          CLERK           7782

14 rows selected.

SQL>

There are three important things to understand, START WITH, CONNECT BY PRIOR and LEVEL.
START WITH – Specifies the root of the hierarchy. To determine where to start parsing from.
CONNECT BY PRIOR – This explains the relationship between the parent and the child. CONNECT BY PRIOR empno = mgr means we are traversing from top to bottom. Reversing it would mean bottom to top.
LEVEL - It acts like a pseudo column that shows the level or rank of the particular row in the hierarchy.

A: You need to have parent-child hierarchy to perform that. I used the HR default schema to execute this query:
with t(val, lvl) as (
select sys_connect_by_path(employee_id, '/'), level lvl
  from employees
 start with manager_id is null
connect by manager_id = prior employee_id
), t_corr(bigboss, boss, employee) as (
select case
         when lvl > 1 then
           substr(val, instr(val, '/', 1, 1) + 1, instr(val, '/', 1, 2) - 1 - instr(val, '/', 1, 1))
         else
           substr(val, instr(val, '/', 1, 1) + 1)
       end bigboss
     , case
         when lvl = 1 then null
         when lvl = 2 then
           substr(val, instr(val, '/', 1, 2) + 1)
         else
       substr(val, instr(val, '/', 1, 2) + 1, instr(val, '/', 1, 3) - 1 - instr(val, '/', 1, 2))
       end boss
     , case
     when lvl in (1, 2) then null
         else substr(val, instr(val, '/', 1, 3) + 1)
       end employee
  from t
 where lvl < 4
)
select e1.last_name || ' ' || e1.first_name bigboss
     , e2.last_name || ' ' || e2.first_name boss
     , e3.last_name || ' ' || e3.first_name employee
  from t_corr
     , employees e1
     , employees e2
     , employees e3
 where t_corr.bigboss = e1.employee_id(+)
   and t_corr.boss = e2.employee_id(+)
   and t_corr.employee = e3.employee_id(+)
/

BIGBOSS              BOSS                 EMPLOYEE
-------------------- -------------------- --------------------
King Steven
King Steven          Kochhar Neena
King Steven          Kochhar Neena        Greenberg Nancy
King Steven          Kochhar Neena        Whalen Jennifer
King Steven          Kochhar Neena        Higgins Shelley
King Steven          De Haan Lex
King Steven          De Haan Lex          Hunold Alexander
King Steven          Raphaely Den
...
King Steven          Fripp Adam           Atkinson Mozhe
King Steven          Fripp Adam           Marlow James
King Steven          Fripp Adam           Olson TJ

29 rows selected.

If you want to make hierarchy from the table:
with t(a, b, c, d, e) as (
  select 'a', 'b', 'c', 'd', 'e1' from dual union all
  select 'a', 'b', 'c', 'd', 'e2' from dual union all
  select 'a', 'b', 'c', 'd', 'e3' from dual union all
  select 'a', 'b', 'c', 'd', 'e4' from dual union all
  select 'a', 'b', 'c', 'd', 'e5' from dual union all
  select 'a', 'b', 'c', 'd', 'e6' from dual union all
  select 'a', 'b', 'c', 'd', 'e7' from dual union all
  select 'a', 'b', 'c', 'd', 'e8' from dual
), tt (a, b, c, d, e) as (
  select a, lpad(b, 4, '-'), lpad(c, 8, '-'), lpad(d, 12, '-'), lpad(e, 16, '-') from t
)
select unique dd
  from tt
unpivot(
  dd for col1 in (a, b, c, d, e)
)
order by 1

DD
--------------------
a
---b
-------c
-----------d
--------------e1
--------------e2
--------------e3
--------------e4
--------------e5
--------------e6
--------------e7
--------------e8


text:
Q: Google Script for adding events from Sheets to Calendar not working I have the following code for adding Calendar events from Google Sheets, but it is not working. It is not showing any errors or anything, just that it is not updating the Calendar. Any ideas what I might have done wrong? I tried without the "new Date" on the Start and End dates as well.
function addEvent() {

var ss = SpreadsheetApp.getActiveSpreadsheet();
var calendar = ss.getSheetByName("Calendar");
var eventCal = CalendarApp.getCalendarsByName("Test");

var lr = calendar.getLastRow();
var data = calendar.getRange("A2:D"+lr).getValues();
for (i=0; i<data.lenght; i++){
  var taskTitle = data[i][0];
  var taskDesc = data[i][1];
  var startDate = new Date(data[i][2]);
  var endDate = new Date(data[i][3]);
  //Browser.msgBox('SPX'+':'+taskTitle+':'+startDate+':'+endDate+':'+taskDesc, Browser.Buttons.OK_CANCEL);
  eventCal.createEvent(taskTitle,startDate,endDate,{description: taskDesc});
}

}

Here is the sheet I am using.

Title
Description
Start Date
End Date

Test
Test
3/27/2021 13:00:00
3/27/2021 14:00:00

Test 1
Test 2
3/24/2021 13:00:00
3/24/2021 18:00:00

A: So this might be a good starting point to begin debugging again.
function addEvent() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var calendar = ss.getSheetByName("Calendar");
  var eventCal = CalendarApp.getCalendarsByName("Test");
  var lr = calendar.getLastRow();
  var data = calendar.getRange("A2:D" + lr).getValues();
  if (eventCal.length) {
    for (i = 0; i < data.lenght; i++) {//length is mispelled
      var taskTitle = data[i][0];
      var taskDesc = data[i][1];
      var startDate = new Date(data[i][2]);
      var endDate = new Date(data[i][3]);
      eventCal[0].createEvent(taskTitle, startDate, endDate, { description: taskDesc });//taking element zero in the array
    }
  }
}


text:
Q: Proving algebraically $a^2+b^2\ge a^{\alpha}b^{2-\alpha}$ for $0\le\alpha\le2$ and $a,b\ge0$ My Analysis professor showed this inequality and elegantly proved it using polar coordinates, saying that it can't be done algebraically. Instead, here's how I think I have handled it: firstly we see it's true for $ab=0$; dividing by the RHS we get $$\left(\frac{a}{b}\right)^{2-\alpha}+\left(\frac{a}{b}\right)^{-\alpha}\ge1, $$ or equivalently, setting $t=a/b$, $$t^2+1\ge t^\alpha$$ which holds because the LHS is $\ge t^2\ge t^\alpha$ for $t\ge1$ and $\ge1\ge t^\alpha$ for $0\le t<1$.
Am I missing something? Are there fancy algebraic (perhaps some linear algebra inequalities) ways to prove the inequality?

A: Turning my comment into an answer: I don't know whether you'll think this is cheating, but assuming without loss of generality that $a\geq b$, then $$a^2+b^2 \geq a^2 = a^\alpha a^{2-\alpha} \geq a^\alpha b^{2-\alpha}.  $$

A: Ask him to prove, using polar coordinates, that $$a^2+b^2\ge ka^{\alpha}b^{2-\alpha}\quad \forall 0\le\alpha\le 2, \forall a,b\ge 0$$
where
$$k=\frac{2}{\left(\alpha^{\alpha}(2-\alpha)^{(2-\alpha)}\right)^{1/2}}.$$
(Which is the best constant possible.)


text:
Q: How to add new port number to nginx server? I want to add new port number to nginx server or how to add new server block to nginx server.

A: Create a new file in the Nginx directory /etc/nginx/sites-enabled and add a new server block here (example shown below).
server {
       # Change me to change my port number
       listen 8080;

       server_name example.com;

       root /var/www/example.com;
       index index.html;

       location / {
               try_files $uri $uri/ =404;
       }
}

A: What you probably want is multiple "server" stanzas, each with a different port. You may want to read more into the documentation here.
Example:
server {
    listen       80;
    server_name  example.org  www.example.org;
    root         /var/www/port80/
}

server {
    listen       81;
    server_name  *.example.org;
    root         /var/www/port81/
}

You can use the same server_name, serving the "different" content appropriately within each one. If you want to have the same server_name and root, but multiple ports, another solution would be this:
server {
    listen 80;
    listen 81;
    server_name example.org;
    root /var/www/;
}

Cheers!


text:
Q: How to access value of variable in one custom directive in another custom directive I have made 2 custom directives and I use them in any HTML code like this

The first one renders a textbox and a button .When we click on button it returns an Object.I want to pass that object onto the second directive which takes the object and makes a table of it.Is it possible by any way in Angular JS.

A: Yes, use property on $scope that's shared from the parent scope.
I'm using a controller here as the parent scope:
module.controller('foo', function($scope) {
    $scope.bar = {};
});

module.directive('textboxComponent', function() {
return {
    ...
    scope: {
        sharedObj: '='
    },

    link: function($scope) {
        $scope.doSomething = function() {
            $scope.sharedObj.test = 'hello world!'.
        }
    }
};
});

// same definition using `scope` for gridComponent

And now you set that scope object:

        let us assume what follows inside is the template of this component

        click me

        let us assume what follows inside is the template of this component

        {{sharedObj.test}}

In the link function of gridComponent you can also do this if you need to know when sharedObj changes from outside (another directive):
$scope.$watch('sharedObj', function() {
    console.log($scope.sharedObj.test);
}, true);

You could also use $broadcast but that's plain wrong in this context...


text:
Q: Parallel using tasks I am currently creating an engine that will spin 10 new threads up that will do diffrent work. But i have found that my solution dose not run in Parallel.
public async Task Start(Func<string, Task> action)
{
   for (var i = 1; i <= config.threads; i++)
    {
        consumers.Add(getActionTask(action));
    }

    await Task.WhenAll(consumers);
}

private Task getActionTask(Func<string, Task> action)
{
    return Task.Run(async () =>
    {
        // Do something that returns a string
        String data = "Some string here";
        await action(data);
    }
}

Lets say i run 2 threads, and based on data will the first thread do a Task.Delay(TimeSpan.FromSeconds(30));
The second thread will print "Hello" on a loop.
It will never get the print loop before the Delay is over, what is wrong with my implementation?

A: The Task.WhenAll doesn't say that the tasks will run in parallel. It creates a Task that would be completed once all the tasks you pass as an argument to the WhenAll method would be completed.
If you want your code to run in parallel, you should make use of the Parallel class ForEach method.
Update
One important note as Scott pointed out below in his comment is that the functions in the Parallel class do not work with async methods. If you want to use async methods with it you must use TPL Dataflow instead.


text:
Q: SWT FileDialog is missing the navigation bar on windows 10 I have a small eclipse RCP application.
I have noticed that on windows 10 FileDialog doesn't have the path part available.
I have tried different combinations of Style flags during the initialization of the dialog but it didn't work.
It is worth mentioning that everything is alright on windows 7.
No navigation bar on windows 10:

Expected:

Further investigation of that issue I got to the following:
The dialog appears correctly with the navigation bar if I start it out of the WorkbenchAdvisor.
The code basically is like this:
@Override
public Object start(IApplicationContext context) throws Exception {
    try {
        int returnCode = PlatformUI.createAndRunWorkbench(display, new WorkbenchAdvisor() {

            @Override
            public void postStartup() {
                // THIS MAKES THE DIALOG APPEAR WITHOUT NAVIGATION BAR
                Display display = new Display();
                Shell shell = new Shell(display);
                FileDialog dialog = new FileDialog (shell, SWT.OPEN | SWT.MULTI);
                dialog.open();
                shell.close();
                while (!shell.isDisposed ()) {
                    if (!display.readAndDispatch ()) {
                        display.sleep ();
                    }
                }
            }

        });
        if (returnCode == PlatformUI.RETURN_RESTART) {
            return IApplication.EXIT_RESTART;
        }
        return IApplication.EXIT_OK;
    } finally {
        Display.getDefault().dispose();
    }
    return IApplication.EXIT_OK;
}

I need to be able to start the FileDialog correctly after starting my workbench.
If I do the following the dialog appears correctly with the navigation bar but this is not the desired:
@Override
public Object start(IApplicationContext context) throws Exception {
    // THIS MAKES THE DIALOG APPEAR WITH THE NAVIGATION BAR CORRECTLY
    Display display = new Display();
    Shell shell = new Shell(display);
    FileDialog dialog = new FileDialog (shell, SWT.OPEN | SWT.MULTI);
    dialog.open();
    shell.close();
    while (!shell.isDisposed ()) {
        if (!display.readAndDispatch ()) {
            display.sleep ();
        }
    }
    Display.getDefault().dispose();
    return IApplication.EXIT_OK;
}

I still can't figure out how to fix this or what is really happening.
Another piece of info is that if I start my RCP from eclipse using a launch configuration it works just fine, the file dialog appears with the navigation bar even if I start it inside the WorkbenchAdvisor.

A: I'd suggest you use the org.eclipse.ui.startup extension.  You declare it on your plugin.xml.
This extension requires you to provide a class that implements the IStartup interface.  This class' earlyStartup method runs after WorkbenchAdvisor.postStartup.
Maybe by this time the navigation bar appears.


text:
Q: Angular update 8.2->9.0 fails I am following the instructions set out in the Angular Update Guide but am experiencing problems at the first step.
On running
NG_DISABLE_VERSION_CHECK=1 npx @angular/cli@8 update @angular/core@8 @angular/cli@8

I got the following error message back:
Error: Cannot find module '../lib/init'

A: Please delete and add node module (npm i)
Then this will work.


text:
Q: Creating a live tile with the Iconic Tile Template I am trying to use the Iconic Tile Template to create a secondary live tile in my Windows Phone 8 app and I am getting an exception when creating the tile. The exception I am getting is:

A first chance exception of type 'System.InvalidOperationException'
  occurred in Microsoft.Phone.ni.dll
Additional information: initialData can be only of type
  StandardTileData.

the method I use to create the live tile is:
public void PinLock(Lock item)
{
    Uri smallIcon = new Uri(item.IsLocked ? LockedIcon : UnlockedIcon, UriKind.Relative);
    Uri largeIcon = new Uri(item.IsLocked ? LockedIcon : UnlockedIcon, UriKind.Relative);

    var tileData = new IconicTileData
    {
        IconImage = largeIcon,
        SmallIconImage = smallIcon,
        Title = item.Name
    };
    string tileUri = "/MainPage.xaml?Action=LockDetails&LockId=" + item.Id;
    ShellTile.Create(new Uri(tileUri, UriKind.Relative), tileData);
}

I have the live tile type set up in the WMAppManifest.xml like this:
<PrimaryToken TokenID="MyToken" TaskName="_default">
<TemplateIconic>
    <SmallImageURI IsRelative="true" IsResource="false">Assets\lock-icon.png</SmallImageURI>
    <Count>0</Count>
    <IconImageURI IsRelative="true" IsResource="false">Assets\lock-icon.png</IconImageURI>
    <Title>Locky</Title>
    <Message>
    </Message>
    <BackgroundColor>
    </BackgroundColor>
    <HasLarge>false</HasLarge>
    <LargeContent1>
    </LargeContent1>
    <LargeContent2>
    </LargeContent2>
    <LargeContent3>
    </LargeContent3>
    <DeviceLockImageURI IsRelative="true" IsResource="false">
    </DeviceLockImageURI>
</TemplateIconic>
</PrimaryToken>
</Tokens>

I can't find any good examples of the correct way to do this and I can't find anybody else on the internet running into this exception message.
Other things I have tried:

*

*First creating the secondary template using StandardTemplateTileData
and then when I update it try using IconicTileData. This throws an
exception.

*First creating the secondary template using
StandardTemplateTileData and then deleting it and replacing it with
one using IconicTileData. This didn't work (throws the same exception
as above)

Any help or good examples would be very much appreciated.

A: The answer is in your exception. When creating additional tiles on the start screen, only a class which derives from StandardTileData can be used. This limits you to that class or its one derived implementation, FlipTileData. IconicTileData and CycleTileData derive from the lower level ShellTitleData. This class is also the base for StandardTileData.
Some examples of creating FlipTileData can be found on the MSDN documentation, but as it derives from the same base class as your example above, you might be able to get away with simply changing the class name and patching up your XML a tiny bit.


text:
Q: Unable to sent email in java application deployed in azure we have a java application which we have deployed on the azure cloud. The email sent functionality is working fine before the deployment on azure. But when we deployed the application on azure the functionality is not working.
We have done two step verification in the google account for local machine and virtual machine too. But on the virtual machine or azure cloud these functionality is not working. Anyone do have solution for this please help me out. Thank you in advanced!!!!

A: short answer:the port 25 was blocked by Azure.
This is in place to prevent abuse of the service and stop spammers etc.

For all examples below, the process applies only to Virtual Machines & VM Scale Sets resources (Microsoft.Compute/virtualMachines & Microsoft.Compute/virtualMachineScaleSets). Sending email on Port 25 is unsupported from all Azure Platform-as-a-Service (PaaS) resources, including Azure App Service and Azure Functions.

Check this article for detail: https://learn.microsoft.com/en-us/azure/virtual-network/troubleshoot-outbound-smtp-connectivity


text:
Q: Get current preset Onvif Is there a way to get current preset using Onvif programming (using c#)?
I can set, remove, update and go to preset but I can't find a way to know if my PTZClient is positioned in a specific preset.

A: There is no method for that. But the device could emit the event tns1:PTZController/PTZPresets/Reached , see §5.11.1 of the PTZ Service specs.


text:
Q: Create sequence of additions I want to extract specific rows of my dataframe, following a sequence of rownumbers.
The sequence should be:
7, 14, 21, 31, 38, 45, 55, 62, 69.....until 8760.

So it always is starting from row 7 and then it goes +7 +7 +10 and this should be repeated until the end.
I know rep and seq, but I don't know how to deal with that +10 after the +7.
Any ideas?

A: Try
x <- rep(c(7, 10), c(2, 1))
out <- cumsum(c(7, rep(x, ceiling(8760 / sum(x)))))

Result
head(out, 10)
# [1]  7 14 21 31 38 45 55 62 69 79

tail(out)
# [1] 8726 8733 8743 8750 8757 8767

If you want out to end at 8760 you might do
c(out[out < 8760], 8760)

A: We can use rep
x1 <- rep(c(7, 10), c(2, 1))
out <- cumsum(c(7, rep(x1, 8760 %/% sum(x1)))))
out1 <- out[out < 8760]
head(out1, 10)
#[1]  7 14 21 31 38 45 55 62 69 79
tail(out1, 10)
#[1] 8685 8695 8702 8709 8719 8726 8733 8743 8750 8757


text:
Q: Finding sum of max and min elements of list Swi-prolog Please help, i new in Prolog trying to find  sum of max and min elements of  list , but this  code not works.
max([H|[]], Max) :- Max is H,!.
max([H|T], Max) :-
    max(T, Max1),
    Max1 > H,
    Max is Max1, !.
max([H|T], Max) :-
    max(T, Max1),
    Max1 < Head,
    Max is Head, !.

minlist([Head|[]], Min) :-
    Min is Head, !.
minlist([Head|List], Min) :-
    minlist(List, Min1),
    Min1 < Head,
    Min is Min1, !.
minlist([Head|List], Min) :-
    max(List, Min1),
    Min1 > Head,
    Min is Head, !.

sum([H|T],S) :-
    S is minlist([H|T],Min) + max([H|T],Max),
    !.

A: The cut at the end of each predicate clause definition is unnecessary. The purpose of the cut is to intentionally prune unwanted but otherwise valid solutions to a solution search.
In Prolog, there's a difference between an arithmetic function and a predicate. An arithmetic function returns a value (as do functions in other languages) and are only used with operators that evaluate arithmetic expressions (such as is/2, >/2, =:=/2, etc). SWI Prolog does not allow you to define your own arithmetic functions.
A predicate is a term that you query. They do not return a value as a function does. They merely succeed or fail and will instantiate variables in the arguments as needed to establish success. Further, on a query, Prolog will find as many different instantiations of variables as it can to succeed, thus possibly yielding multiple solutions. The the cut is intended to prune that process when desired. In Prolog, you can define your own predicates.
A simple example of the difference would be a predicate for minimum of two values:
min(A, B, A) :- A < B.
min(A, B, B) :- A >= B.

You would query this to get a result:
?- min(4, 2, M).
M = 2.

Prolog has a min/2 arithmetic function would would be used as follows:
?- M is min(4, 2).
M = 2.

In the case of your code, you have defined a predicate for the maximum value off a list. Here is your predicate, but rewritten to deal with the following issues:

*

*You're using is/2 as an assignment operator, which it isn't intended for. You want unification which can be done directly with the arguments (as shown below) or using =/2.

*You have a typo: using Head when you meant H.

*Rename to max_list to indicate it works with lists

Rewritten to avoid the cuts and the unnecessary use of is/2 to do "assignment":
max([H], H).               % The max of list [H] is H
max([H|T], Max) :-
    max(T, Max),
    Max > H.
max([H|T], H) :-
    max(T, Max1),
    Max1 < H.

We can actually do a little better than this because your second and third clauses min([H|T], ...) which match the query min([H], ...) as does the first clause. That will result in unnecessary matching that can be avoided. You can handle this by ensuring lists in 2nd and 3rd clauses are at least two elements:
max_list([H], H).               % The max of list [H] is H
max_list([X,Y|T], Max) :-
    max([Y|T], Max),
    Max > X.
max_list([X,Y|T], H) :-
    max([Y|T], Max1),
    Max1 < X.

One further issue with this implementation is you will redundantly call max/2 depending upon whether Max > X succeeds or fails. The more "textbook" implementation for max_list, which avoids this issue and is tail recursive, would be:
max_list([X|Xs], M) :-
    max_list(Xs, X, M).

max_list([], M, M).
max_list([X|Xs], Xm, M) :-
    X > Xm,
    max_list(Xs, X, M).
max_list([X|Xs], Xm, M) :-
    X =< Xm,
    max_list(Xs, Xm, M).

You can define min_list/2 similarly.
Then sum/2 would be written as:
sum(L, S) :-
    min_list(L, Lmin),
    max_list(L, Lmax),
    S is Lmin + Lmax.


text:
Q: Finding the jsPlumb connection between two ids I am trying to remove the connection between two html elements. I have the ids of both elements, but I do not know how to find the connection in the jsPlumb instance that combines the two. How can I find the connection between two ids?

A: Select all Connections from "d1" and detach them
jsPlumb.select({source:"d1"}).detach();
select can take the following parameters :
[scope] String | String optional

[source] String | String optional

[target] String | String optional

[connections] Connection[] optional
an existing list of Connections. If you supply this, 'source' and 'target' will be ignored.

References :
https://jsplumbtoolkit.com/doc/querying.html#select
https://jsplumbtoolkit.com/apidocs/classes/jsPlumb.html#method_select


text:
Q: Function to generate random 8 Character Password I have this function in vb that had seemed to be working before to generate an 8 character password but now generates the same password for each user who registers to the website. I am unsure as to where I have went wrong as I have not fiddled with this piece of code (code was not written by me)? Any help would be appreciated.
function generatePassword()
  Dim i, newPassword
  newPassword = ""
  For i = 1 to 3
    newPassword = newPassword & Mid("ABCDEFGHJKLMNPQRSTUVWXYZ",randomInRange(1,24),1)
  Next
  For i = 4 to 7
    newPassword = newPassword & Mid("23456789",randomInRange(1,8),1)
  Next
  'For i = 1 to 8
  '  newPassword = newPassword & Mid("ABCDEFGHJKLMNPQRSTUVWXYZ23456789",randomInRange(1,32),1)
  'Next
  generatePassword = newPassword
end function

function randomInRange(lo,hi)
  randomInRange =(Int((hi - lo + 1) * rnd + lo))
end function

Dim newPassword = generatePassword()

            Dim strSql As String = "INSERT INTO Student(" & _
                             "StudentNo," & _
                             "Surname," & _
                             "FirstName," & _
                             "MiddleName," & _
                             "Gender," & _
                             "Pathway," & _
                             "[Level]," & _
                             "QubEmail," & _
                             "[Password]," & _
                             "HomeEmail," & _
                             "MobilePhone," & _
                             "HomeTown," & _
                             "PlacementYear," & _
                             "Status," & _
                             "DateEdited," & _
                             "HomePhone) " & _
                            "VALUES " & _
                            "( " & _
                             "'" & StudentNo.Text.Replace("'", "''") & "'," & _
                             "'" & Surname.Text.Replace("'", "''") & "'," & _
                             "'" & Forename.Text.Replace("'", "''") & "'," & _
                             "'" & MiddleName.Text.Replace("'", "''") & "'," & _
                            "'" & ddlGender.SelectedValue & "'," & _
                            "'" & ddlPathway.SelectedValue & "'," & _
                            "'" & ddlLevel.SelectedValue & "'," & _
                            "'" & QUBEmail.Text.Replace("'", "''") & "'," & _
                            "'" & newPassword & "'," & _
                             "'" & HomeEmail.Text.Replace("'", "''") & "'," & _
                            "'" & MobileNo.Text.Replace("'", "''") & "'," & _
                            "'" & HomeTown.Text.Replace("'", "''") & "'," & _
                            "" & PlacementYear & "," & _
                            "'Seeking Placement'," & _
                            " GETDATE() ," & _
                             "'" & HomeNo.Text.Replace("'", "''") & "' " & _
                            ")"

            Dim addStudent As OleDbDataReader = Database.DoSQLReturnDataReader(strSql)
            addStudent.Close()

A: There doesn't seem to be any code that is updating the rnd variable. This needs to update each time you call randomInRange to get different passwords.
I would suggest that you change randomInRange entirely to make it run more cleanly.
This is what you need to do:
Private rnd As Random = new Random()
Function randomInRange(lo As Integer, hi As Integer) As Integer
    Return rnd.Next(lo, hi + 1)
End Function

Making this change produces random passwords.

A: You should probably talk to the person that wrote the code if you're not a programmer yourself. Nevertheless, a Rnd is really not random, but only a sofisticated mathematical equation using a seed to calculate its value.
This seed is set to the time when the program runs. Without any involvement, the seed will stay the same which means that all randoms will actually be the same value; use Randomize at each generatePassword().
Function generatePassword()
    Randomize()

    /.../
End Function


text:
Q: Securing JAX-RS (Jersey) REST API via spring security oauth2? I have a REST API implemented with JAX-RS annotations with Jersey. I'd like to allow Facebook, GitHub, etc, logins via OAuth2.
Should I expect to get spring-security-oauth2 working with Jersey/JAX-RS without too much complication, or does spring-security-oauth2 really only work with a real spring web application (for instance, using spring-boot-starter-web)? I can't seem to find any example source code that does this.


text:
Q: How compare the orientation from one node to another I am trying to get a  node's point to connect to another node's point depending on the orientation of the first node. The problem is, I am having trouble thinking of the way a node call tell whether it is left, right , north or south given its X and Y positions and Width and Height.
Here is an image of the problem:
I have tried comparing the X and Y values, for example, if (child.Y > parent.Y) -> snap to southPoint, but it is too vague and will snap to north or south if it is placed right or left. Any idea on more specific conditions I can use to get the correct orientation? Thank you

A: You could do it by defining anchor points on your box:
public class UMLClassBox {
  private Point2D north;
  private Point2D east;
  private Point2D south;
  private Point2D west;
  public List<Point> getAnchorPoints() {
    ...
  }
}

As a second step you then can have a method to find the two nodes that are closest:
public Point2D[] findClosestNodes(UMLClassBox box1, UMLClassBox box2) {
  Point2D[] closest = new Point2D[2];
  double shortestDistance = Double.MAX_VALUE;
  for (Point2D anchorBox1 : box1.getAnchorPoints()) {
    for (Point2D anchorBox2 : box2.getAnchorPoints()) {
      double distance = anchorBox1.distance(anchorBox2);
      if (distance < shortestDistance) {
        shortestDistance = distance;
        closest[0] = anchorBox1;
        closest[1] = anchorBox2;
      }
    }
  }
  return closest;
}

While there is a chance that two anchor points pairs have the same distance, this should not matter in this case because either of those would be equally valid.


text:
Q: Listview not binding on inital load but works on RefreshCommand in xamarin Form My ListView does not load Data for clients as the app is Open but works fine when I swipe from top which call the RefreshCommand.
ClientViewModel.cs
public class ClientViewModel : BaseViewModel
    {
        private ObservableCollection<Client> _clients { get; set; }
        private IClientManager ClientManager { get; }
        public ClientViewModel(INavigationManager navigationManager, IClientManager clientManager)
            :base(navigationManager)
        {
            Title = "Client";
            Clients = new ObservableCollection<Client>();
            ClientManager = clientManager;
        }

        public ObservableCollection<Client> Clients
        {
            get => _clients;
            set
            {
                _clients = value;
                OnPropertyChanged();
            }
        }

        public Command LoadClientsCommand => new Command(async () => await ExecuteLoadClientsCommand());

        public Command SelectedItemCommand => new Command<Client>(OnClientSelected);

        //public Command AddClientCommand => new Command(() => OpenClientAddPage());

        private void OnClientSelected(Client obj)
        {
            NavigationManager.NavigateToAsync<ClientDetailViewModel>(obj);
        }

        public override async Task InitializeAsync(object data)
        {
            await ExecuteLoadClientsCommand();
        }

        private async Task ExecuteLoadClientsCommand()
        {
            if (IsBusy)
                return;

            IsBusy = true;

            try
            {
                Clients.Clear();
                Clients = (await ClientManager.GetAllClient()).ToObservableCollection();
            }
            catch (System.Exception)
            {
                throw;
            }
            finally
            {
                IsBusy = false;
            }
        }
    }

ClientPage.xaml
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:d="http://xamarin.com/schemas/2014/forms/design"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:local="clr-namespace:Scheduler.Behaviours"
             xmlns:localconverter="clr-namespace:Scheduler.Converters"
             mc:Ignorable="d"
             xmlns:utility="clr-namespace:Scheduler.Utility;assembly=Scheduler"
                  utility:ViewModelLocator.AutoWireViewModel="True"
             Title="{Binding Title}"
             x:Class="Scheduler.Views.ClientPage">
    <ContentPage.Resources>
        <ResourceDictionary>
            <localconverter:SelectedItemConverter x:Key="SelectedClient" />
        </ResourceDictionary>
    </ContentPage.Resources>

    <ContentPage.ToolbarItems>
        <ToolbarItem Text="Add"/>
    </ContentPage.ToolbarItems>

    <StackLayout>
        <ListView x:Name="ClientListView"
                  ItemsSource="{Binding Clients}"
                  VerticalOptions="FillAndExpand"
                  HasUnevenRows="true"
                  RefreshCommand="{Binding LoadClientsCommand}"
                  IsPullToRefreshEnabled="True"
                  IsRefreshing="{Binding IsBusy, Mode=OneWay}"
                  CachingStrategy="RecycleElement">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell>
                        <!--<ViewCell.ContextActions>
                            <MenuItem Clicked="OnDelete_Clicked" Text="Delete" CommandParameter="{Binding .}"/>
                        </ViewCell.ContextActions>-->
                        <StackLayout Padding="10">
                                   <Label Text="{Binding FullName}"
                                   d:Text="{Binding .}"
                                   LineBreakMode="NoWrap"
                                   Style="{DynamicResource ListItemTextStyle}" />
                        </StackLayout>
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
            <ListView.Behaviors>
                <local:EventToCommandBehaviour EventName="ItemSelected"
                                               Command="{Binding SelectedItemCommand}"
                                               Converter="{StaticResource SelectedClient}" />
            </ListView.Behaviors>
        </ListView>
    </StackLayout>
</ContentPage>

A: First of all, you are calling the same API twice here
Clients.Clear();
await ClientManager.GetAllClient();
Clients = (await ClientManager.GetAllClient()).ToObservableCollection();

it can literally be like
Clients.Clear();
Clients = (await ClientManager.GetAllClient()).ToObservableCollection();

Secondly, I do not see you calling the same
API in the constructor in that case where would the data come from? I would suggest you make the above API call in the previous page and pass it on here!


text:
Q: Which font is used in "Notices of the AMS"?
Possible Duplicate:
How do I find out what fonts are used in a document/picture?

I like the font in "What is ...?" of Notices of the AMS. For instance see this document http://www.ams.org/notices/201005/rtx100500608p.pdf. Does somebody know the name of this font? Is it free?

A: The font is Lucida Bright. It is not free.


text:
Q: How can I pass jquery variable as parameter to Java controller by href? This is my variable in javascript:
var dataid = dataInfo[i];

I want to pass the variable to my java controller through href:
 row = row + "
" + dataid + "	" +
       schoolid + "	" +
      "Details	"+
        ""+

";

but controller gets null value.
I am trying this using ajax:
        $.ajax({
            type: "GET",
            url:  "@{DataManagement.dataDetails}",
            data: {
                id: dataId
            },
            success: function(data) {
                console.log(data);

            }

        });

This is my controller:
public static void dataDetails(Long id) throws SQLException {

        Logger.info("id: "+ id);

        //dataId=dataId.trim();

        //Long iid = Long.parseLong(dataId);
        Data data = Data.findById(id);

        String totalStudent = Data.getTotalStudent(1L);

        Logger.info("totalStudent: " + totalStudent);

        renderArgs.put("totalStudent",totalStudent);

        render(data,totalStudent);

    }

But after ajax call it is not render the new page.
How can I do this?

A: It works!!!
I changed it to :
Details

A: You can send a json request with ajax and accept it on Controller.
Ajax Request:
$.ajax({
    type: "POST",
    contentType: "application/json",
    data: JSON.stringify(yourObject),
    url: "/path",
    success: function (msg) {
        console.log(msg);
        window.location = "/redirectTo";
    },
    error : function(e) {
        console.log('Error: ' + e);
    }

});

On Controller:
@ResponseBody
@CrossOrigin @RequestMapping(value = "/path", method = RequestMethod.POST, consumes=MediaType.APPLICATION_JSON_VALUE)
private ResponseEntity<YourObject> someMethod(@RequestBody YourObject obj){
        // do your coding here
        return new ResponseEntity<YourObject>(modifiedObject, HttpStatus.OK);
    } catch (Exception e) {
        return new ResponseEntity<YourObject>(HttpStatus.BAD_REQUEST);
    }
}


text:
Q: comparison between signed and unsigned integer expressions warning while make install? I am running my below code which checks whether data_timestamp is more than two weeks old or not. If it is more than two weeks old, then print hello otherwise prints world.
#include <boost/chrono/chrono.hpp>
#include <iostream>

int main()
{
    uint64_t data_timestamp = 1406066507000;

    const boost::chrono::system_clock::time_point now = boost::chrono::system_clock::now();
    boost::chrono::hours twoWeeks = boost::chrono::hours(24 * 14);
    boost::chrono::system_clock::time_point lastTwoWeeks = now - twoWeeks;

    boost::int_least64_t millis = boost::chrono::duration_cast<boost::chrono::milliseconds>(lastTwoWeeks.time_since_epoch()).count();

    std::cout << "Time stamp in milliseconds since UNIX epoch start: "<< millis << std::endl;

    if (data_timestamp < millis) {
        std::cout << "Hello";
    } else {
        std::cout << "World";
    }

    return 0;
}

And my above code is working fine but there is one warning on this if statement comparison -
if (data_timestamp < millis) {

And the warning I am seeing is -
warning: comparison between signed and unsigned integer expressions [-Wsign-compare]

How do I remove this warning? I would like to keep data_timestamp as uint64_t since in the actual code it is being used like that in other places as well.

A: You can cast millis to a uint64_t. The problem you're having is that millis is signed, so you can fix it by casting it to an unsigned type.
if (data_timestamp < (uint64_t)millis) {
    std::cout << "Hello";
} else {
    std::cout << "World";
}


text:
Q: Position:absolute; not working I'm pretty clueless on what the problem might be, but what works fine here does not here (login with 123/123)
CSS:
#drag {
    width: 700px;
    height: 400px;
    border: 1px solid #000;
    margin: 0 auto;
    position:relative;
}

.inside {
    width: 500px;
    height: 500px;
}
.drag {
    width: 700px;
    height: 400px;
    background: #333 url('bg.png');
}

I've tried to remove the .inside class, and also messed with the html a bit (re-checked the pos:relative part a million times)... with no results. Any idea?
[edit]
@Marcel Korpel : On the second one all islands end up in the upper left corner, despite having pos:absolute, top:x and left:x set

A: I used FireBug and it says that the #nr0, #nr1, ... divs just have a position:absolute;, but no left or top attribute


text:
Q: CSS drop down menu I want to make a drop down list with nice buttons that are long as the screen (compatible with more screens)....
I will use 3 images (left , middle and right) ... something like this (of course, smaller):

The middle part will repeat itself to "fill" the button. I want to get something like this:

There is no example with 3 images, all I could found is only 2 images.

A: my solution:
html:

text

css:
* {margin: 0px; padding: 0px;}
.clear {clear: both; height: 0px; font-size: 0px; line-height: 0px;}

.button {
    padding-right: 15px; /* right image width */
    background: url('right_image.jpg') no-repeat right top;
    height: 20px; /* images height */
}

.button .left {
    background: url('left_image.jpg') no-repeat right top;
    width: 15px; /* left image width */
    height: 20px; /* images height */
    float: left;
}
.button .inner {
    height: 20px; /* images height */
    background: url('middle_image.jpg') repeat-x right top;
    text-align: center;
}

jsFiddle Demo

A: It's very easy.
That's html:
<button>
   MENU
</button>

You should place all parts of your image in a very wide none-transparent(for transparent png method is harder a little bit) PNG(like it looks on design), trimmed to the image content. (one image wouldn't increase size much, but will make less http request to server). It called sprite.
button {  }
button span {
  padding:0 0 0 25px;
  background:url('image.png') left 0;
  display:inline-block;
  height:25px;
  line-height:25px;
}
button span span {
  padding:0 25px 0 0;
  background:url('image.png') right 0;
}

That's it. Of course you should place your image name, and your values of padding, height and line-height.

A: There are no examples with 3 images because you don't need 3 images. Create a small right images (like you have posted above) and create a left + center image with your maximum width (let's say 800px). Set the left sided / background image on a
 and hook the right side up to the .

   Link

A: Try this - this uses 3 background images which isn't compatible with IE8 and below, but you could use two inner divs to give you three containers and put one image in each - note the bottom image is listed last.
nav {
     height:75px; /* height of graphic elements */
      background:
        url(images/left_end.png) no-repeat 0px 0px,
        url(images/right_end.png) no-repeat right top,
        url(images/center.png); /* this images repeats */
}


text:
Q: Kotlin: How to check if enum contains a given String without messing with Exceptions? Why there is no contains method in enum classes (as well as in Java)? And how to implement it elegantly? Now I'm using this ugly approach:
val contains: Boolean =
    try {
        MyEnum.valueOf("some string")
        true
    } catch (e: IllegalArgumentException) {
        false
    }

A: enumContains
You can create an enumContains function similar to Hound Dog's answer but using reified type parameters instead.
You cannot create a JVM independent solution in Kotlin 1.0 but you can in Kotlin 1.1 using enumValues.
Kotlin 1.1
/**
 * Returns `true` if enum T contains an entry with the specified name.
 */
inline fun <reified T : Enum<T>> enumContains(name: String): Boolean {
    return enumValues<T>().any { it.name == name}
}

Kotlin 1.0
/**
 * Returns `true` if enum T contains an entry with the specified name.
 */
inline fun <reified T : Enum<T>> enumContains(name: String): Boolean {
    return T::class.java.enumConstants.any { it.name == name}
}

Usage
enumContains<MyEnum>("some string") // returns true or false

enumValueOfOrNull
If you also need the actual enum entry then you might consider creating an enumValueOfOrNull function instead.
Kotlin 1.1
/**
 * Returns an enum entry with the specified name or `null` if no such entry was found.
 */
inline fun <reified T : Enum<T>> enumValueOfOrNull(name: String): T? {
    return enumValues<T>().find { it.name == name }
}

Kotlin 1.0
/**
 * Returns an enum entry with the specified name or `null` if no such entry was found.
 */
inline fun <reified T : Enum<T>> enumValueOfOrNull(name: String): T? {
    return T::class.java.enumConstants.find { it.name == name }
}

Usage
enumValueOfOrNull<MyEnum>("some string")

A: You could do something like this:
fun <T : Enum<*>> KClass<T>.contains(value: String): Boolean {
    return this.java.enumConstants.any { it.name == value }
}

MyEnum::class.contains("some string")

A: You can just take values Array of your enum and use contains over it. For example:
Planets.values().map { it.name }.contains("EARTH")

But for this you need to have correct string value so you might uppercase it before search.
If you want to find enum by its value take a look at the Reverse Lookup for enums.
Edit:
As @JamesBassett suggested you can optimize it to stop looking once it finds a match.
Planets.values().any { it.name == "EARTH" }

A: or if you are really adventurous
enum MyEnum {
    MY_1, MY_2;

    companion object {

        fun isInEnum(someString: String) {
            return try {
                valueOf(someString)
                true
            } catch (e: Exception) {
                false
            }
        }
    }
}


text:
Q: How do you convert the image preview in finder for a grayscale image that was converted from a color image using Image Magick? I have a script to convert images into grayscale tiffs. All is working well except, when the file is complete, it is still showing a color image in mac's finder preview thumbnail. I am not sure if there is an option I am overlooking. I have played around with -preview type and it is updating the thumbnail preview but is creating a contact sheet. Not sure if I am going about it the right way with -preview or what actually controls this. Any help would be much appreciated.
for f in "$@"
do
    echo "$f"
    /usr/local/bin/convert -density 300 "$f"[0] -resize 1000x1000 -density 300 -type grayscale \
      -define tiff:endian=msb -compress LZW -format tif "${f%.*}_GS.tiff" && mv "${f%.*}_GS.tiff" /Done && rm "$f"

done


text:
Q: sed: Replace middle number pattern surrounded with single quotes I have hundreds of xml files containing below type of text
<Init dflt_value='1.00' max_value='1000000.00' diff_ele='1.0' new='Yes' />

where max_value element may have different values.
Issue: I need to replace value of max_value element to 100(for example) in all files. I tried doing something like below.
grep -rl 'max_value' | xargs sed -i "s/max_value='.*'/max_value='25'/g"

But nothing is working for me.
What might be the solution for it?

A: Don't parse XML/HTML with regex, use a proper XML/HTML parser and a powerful xpath query.
theory :

According to the compiling theory, XML/HTML can't be parsed using regex based on finite state machine. Due to hierarchical construction of XML/HTML you need to use a pushdown automaton and manipulate LALR grammar using tool like YACC.

realLife©®™ everyday tool in a shell :
You can use one of the following :
xmllint often installed by default with libxml2, xpath1 (check my wrapper to have newlines delimited output
xmlstarlet can edit, select, transform... Not installed by default, xpath1
xpath installed via perl's module XML::XPath, xpath1
xidel xpath3
saxon-lint my own project, wrapper over @Michael Kay's Saxon-HE Java library, xpath3
or you can use high level languages and proper libs, I think of :
python's lxml (from lxml import etree)
perl's XML::LibXML, XML::XPath, XML::Twig::XPath, HTML::TreeBuilder::XPath
ruby nokogiri, check this example
php DOMXpath, check this example

Check: Using regular expressions with HTML tags

Example using xpath with  xmlstarlet :
xmlstarlet ed -u '//Init/@max_value' -v '100' *.xml

If you want to edit in place, use -L switch :
xmlstarlet ed -L -u '//Init/@max_value' -v '100' *.xml

Example using xpath & python to edit in place
# edit in place XML
from lxml import etree
import sys
myXML = sys.argv[1]

tree = etree.parse(myXML)
root = tree.getroot()
code = root.xpath("//Init")
for i in code:
    if (i.attrib['max_value']):
        i.attrib['max_value'] = '100'

etree.ElementTree(root).write(myXML, pretty_print=True)

A: Your specific problem is that in sed, the .* is "greedy." That is, it matches as much as it possibly can which can cause it to merge two or more fields into one.
You want to be a little more careful about what you match. For replacing a number, try just matching numeric digits, maybe with a decimal point:
s/max_value='[0-9.]*'/max_value='25'/g

In general, what you want to do is use a negated character class of the closing quote:
s/'[^']*'/ ...

But in this specific case, 0-9 does the job, and is slightly more clear. (You would not want to try to match every possible character in a sentence using a positive pattern this way - far better to use a negative pattern and just say "everything except the end quote, followed by the end quote".

A: The problem is that you are including ' char in the .* subexpr.  Better use:
xargs sed "/max_value=/s/max_value='[^']*'/max_value='${new_value}'/g"

note
Beware that ' is special char for the shell (so I used double quotes around the whole sed command)
Also take into account that the expression can appear not only in the places you are seaching for.  As XML is not regular, it is not a good idea to parse it with a regular expression for matches.  Use of a full XML parser would allow you to change all occurrences in an xml attribute basis, instead of plain text search.  And take into account that grep(1) is a filter, you won't edit the files, you'll get that on standard output.
Case you want to edit the files, you can use ed(1) instead.
grep -rl max_value . |
while read file
do
    ed file <<EOF
    1,$s/max_value='[^']'/max_value='100'/g
    w
    q
EOF
done


text:
Q: Calculation of studentized deleted residuals I have a problem that asks me to calculate studentized deleted residuals from the following set of residuals:

From the original dataset:

The Hat matrix, diagonal elements hii, SSE/MSE, formula for studentized residuals, and final calculation of the residuals are below:
s

However, I cannot reproduce these results given the formula! For example, taking the square root of a negative residual in the numerator results in an imaginary number if x>0. Is there another way to calculate these residuals, or something I am I just not getting it? Thanks!

A: I believe this is simply a typo. The formula should be:
$$
\frac{e_i}{\sqrt{\operatorname{SSE}(1-h_{ii})-e_i^2}}
$$
or similarly:
$$
\operatorname{sign}(e_i)\left[
\frac{e_i^2}{\operatorname{SSE}(1-h_{ii})-e_i^2}
\right]^{1/2}
$$

A: The $i$-th (internally) studentized residual $r_i$ is given by
$$
r_i = \frac{e_i}{\sqrt{\mathrm{MSE}\left(1-h_{ii}\right)}},
$$
where the residual mean square $\mathrm{MSE}$ (for which a better abbreviation would be $\mathrm{MS}_{\mathrm{Res}}$) is given by $e^\top e /\left(n-p\right)$.
The $i$-th externally studentized residual $t_i$ is given by
$$
t_i = \frac{e_i}{\sqrt{S_{\left(i\right)}^2\left(1-h_{ii}\right)}},
$$
where $S_{\left(i\right)}^2$ is calculated as the usual unbiased estimator of the error variance but based on a data set with the $i$-th observation removed.
It is straightforward to show (see, e.g., Montgomery, Peck, & Vining, 2012, p. 593) that
$$
S_{\left(i\right)}^2 = \frac{\left(n-p\right)\mathrm{MSE} - e_i^2/\left(1-h_{ii}\right)}{n-p-1}.
$$
In terms of the $i$-th internally studentized residual we get
$$
\begin{align}
S_{\left(i\right)}^2
&= \frac{\left(n-p\right)\mathrm{MSE} - r_i^2\mathrm{MSE}}{n-p-1} \\
&= \frac{\left(n-p-r_i^2\right)\mathrm{MSE}}{n-p-1},
\end{align}
$$
and hence
$$
\begin{align}
t_i
&= \frac{e_i}{\sqrt{\frac{\left(n-p-r_i^2\right)\mathrm{MSE}}{n-p-1}\left(1-h_{ii}\right)}} \\
&= \frac{e_i}{\sqrt{\mathrm{MSE}\left(1-h_{ii}\right)}} \cdot \sqrt{\frac{n-p-1}{n-p-r_i^2}} \\
&= r_i \cdot \sqrt{\frac{n-p-1}{n-p-r_i^2}}.
\end{align}
$$

Reference
Montgomery, D. C., Peck, E. A., & Vining, G. G. (2012). Introduction to linear regression analysis (5th ed.). John Wiley & Sons.


text:
Q: clock skew detected: you build may be incomplete I've seen a bunch of these questions, most notable this one, which all say pretty much the same thing:  This error is caused by the modification time of the source files being in the future, which usually occurs on a mounted NFS when the server clock and client clock are not in sync.
I've tried to touch all the files in my directory, as many have suggested.  when that didn't work, I actually attempted copying all files out of the mounted drive and into a local drive, touching them again, then rerunning the build, and I still get the same error.  Is there any other way to solve this problem?

A: The NFS server and NFS client's system times are out of sync. The NFS server is probably drifting ahead.
Running make on an NFS mount is sensitive to the millisecond level so client/server system times must be tight as a drum. This can be done by having your NFS client(s) sync their time off of the NFS server's time using NTP at the highest rate allowed (usually 8 seconds). On a LAN this should get you sub-millisecond accuracy.

*

*Install NTP on both the NFS client(s) and the NFS server.

*On the NTP config file of the clients (ntp.conf in linux), comment out the entries starting with 'pool' or 'server' and add the line:

server [put address of the nfs server here] minpoll 3 maxpoll 3

... The '3' is a power-of-two in seconds for the polling interval, hence 8 seconds. The NFS server's NTP config file can probably be left alone.

*

*Restart the ntpd service on your client.

*Test that your client is syncing by using the linux command within the client:

ntpq -p

... the important part is that your 'reach' column is not zero for long as that means it cannot contact the server's NTP.

*

*If they don't sync, you may have to reboot the client and server. This may be the case with Synology NAS as the NTP server.

*Perform a full clean of your build (even nuke the directory and re-clone if convenient) and try again.
Similar answers are throughout the internet, but they suggest simply installing NTP to the machines. This wasn't good enough to solve the issue for me - they weren't synced tightly enough. A better way is to sync the clients' clocks to the server's clock on the local network at very frequent intervals. This is frowned upon with the internet but cheap on a LAN.
If this isn't possible, at least try to ensure NTP on the clients and server uses the same time servers in its pool/server entries.

A: If you are using Windows check if you compiling on a FAT file-system and if so try to switch.
FAT has a 2 second resolution, so its possible for your build to add to an archive, compile the next file, but detect that the archive is already up to date. Time resolutions for other file systems are listed in another answer.
If you must FAT consider the .LOW_RESOLUTION_TIME special target.


text:
Q: how to calculate next 5th working date form the current date in ios programmatically hi i have used NSDateComponents but could not calculate the 5th date
NSDate *now = [NSDate date];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];

NSDateComponents *dateComponents = [calendar components:NSWeekdayCalendarUnit | NSHourCalendarUnit fromDate:now];
NSInteger weekday = [dateComponents weekday];
NSLog(@"Week %ld",(long)weekday);

A: you can use NSDateComponent like this to get next date after some interval
NSDateComponents *dateComponents = [NSDateComponents new];
dateComponents.minute = 15; //to get time after 15 minutes
dateComponents.day = 5; //to get date after 5 days
//and similarly you can calculate date or time after hour, minute, seconds day, week, etc
NSDate *date = [[NSCalendar currentCalendar] dateByAddingComponents:dateComponents toDate:[formatterWithAM dateFromString:startTime.text] options:0]


text:
Q: How I change the origin of the x axis in ggplot to go from 'August to March' instead of 'Jan to March, August to December'? I want to plot temperature data over time, with the x axis: "08-01", "09-01", "10-01", "11-01", "12-01", "01-01", "02-01", "03-01"
Rather then: "01-01", "02-01", "03-01", "08-01", "09-01", "10-01", "11-01", "12-01", which R is doing.
My data looks like the following- my x axis uses the Month_day column. Unique values in this column are: "08-01", "09-01", "10-01", "11-01", "12-01", "01-01", "02-01", "03-01".
> head(upstream)
        Date daily_aveTempC Moving_Average_7day Year Month Day Month_day monthAbb Migration EmbryoDev
1 2007-08-01       13.49556            13.94947 2007    08  01     08-01      Aug  Upstream
2 2007-08-02       13.44325            13.74864 2007    08  02     08-02      Aug  Upstream
3 2007-08-03       12.93881            13.56086 2007    08  03     08-03      Aug  Upstream
4 2007-08-04       12.78937            13.41106 2007    08  04     08-04      Aug  Upstream
5 2007-08-05       13.13963            13.29029 2007    08  05     08-05      Aug  Upstream
6 2007-08-06       13.11844            13.19651 2007    08  06     08-06      Aug  Upstream

I have the following code that plots Month_day (x axis) vs Moving Average 7day (y axis).
png(paste0(read_out_final, "Migration_Upstream_7day_MovingAve_Sal_4.png"), res=300, width = 15, height = 8, units = "in")

ggplot(data=upstream, aes(x=as.factor(Month_day), y=factor(Moving_Average_7day, levels=upstream$Month_day), color=Year, group=Year)) +
  geom_line(size=1) +
  theme_bw() +

  scale_y_continuous(n.breaks = 20,
                     limits=c(1,20)) +

  scale_x_discrete(breaks = upstream$Month_day[grep("0*-01", upstream$Month_day)]) +

  theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1)) +

  labs(title="Salmon Creek 4: Upstream Migration from August to March",
       x="Date",
       y="Temperature (7-Day Rolling Average degrees C)")

dev.off()

This plots the data: "01-01", "02-01", "03-01", "08-01", "09-01", "10-01", "11-01", "12-01".
But I want the data plotted: "08-01", "09-01", "10-01", "11-01", "12-01", "01-01", "02-01", "03-01"

I've seen solutions to this issue using the plot() function, but not for ggplot.

A: Almost every question on ggplot2 that includes "order of ... axis" can be resolved by using factor(., levels=), and explicitly controlling the order of the levels.
dat <- data.frame(dt = seq(as.Date("2020-08-01"), as.Date("2021-04-01"), by="month"), y = 1:9)
dat$MonDay <- format(dat$dt, format = "%m-%d")
dat
#           dt y MonDay
# 1 2020-08-01 1  08-01
# 2 2020-09-01 2  09-01
# 3 2020-10-01 3  10-01
# 4 2020-11-01 4  11-01
# 5 2020-12-01 5  12-01
# 6 2021-01-01 6  01-01
# 7 2021-02-01 7  02-01
# 8 2021-03-01 8  03-01
# 9 2021-04-01 9  04-01

library(ggplot2)
ggplot(dat, aes(MonDay, y)) + geom_point()

This is because ggplot2 looks to order its variables; if numeric or integer, it's easy; if character, then it sorts it lexicographically, and it seems clear that "08-01" comes after "04-01" (despite the fact that the strings were formed from an object that had the opposite ordering).
dat$MonDay <- factor(dat$MonDay, levels = unique(dat$MonDay[order(dat$dt)]))
ggplot(dat, aes(MonDay, y)) + geom_point()


text:
Q: Check if a CIDR contains public IP addresses - In Java Given a CIDR string, i would like to test whether or not this CIDR contains IP addresses that are not reserved as private addresses (i.e. is whitin one of the following ranges :)
192.168.0.0 - 192.168.255.255
172.16.0.0 - 172.31.255.255
10.0.0.0 - 10.255.255.255

A: Parse it into an InetAddress, then check its bytes.
int slash = cidr.indexOf('/');
String ip = cidr.substring(0, slash);
InetAddress address = InetAddress.getByName(ip);
byte[] bytes = address.getAddress();
boolean privateAddress =
    (bytes[0] == 10) ||
    (bytes[0] == (byte) 172 && (bytes[1] >= 16 && bytes[1] < 32)) ||
    (bytes[0] == (byte) 192 && bytes[1] == (byte) 168);

Or, you could just check the string directly:
boolean privateAddress =
    cidr.startsWith("10.") || cidr.startsWith("192.168.") ||
    cidr.matches("172\\.(1[6-9]|2[0-9]|3[01])\\..*");

Personally, I would opt for the first approach;  shorter isn't aways better.  I'd rather rely on a parser that handles every corner case of IPv4 address notation.

A: Ended up defining static CIDR blocks for private ranges and using the following code to see if it overlaps with a given CIDR -
https://gist.github.com/nacx/8837081716c5b333d7edc8bec4684482


text:
Q: Magento First Line Whitespace Basically i have a magento collection list which i am converting to xml output.
When i try to validate the XML/page output if fails because the first line is just white space, and for XML to be valid in needs to be the start of the document.
Line 1 :
line 2 :<!DOCTYPE html>
line 3 :<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
line 4 :<head>
line 5 :<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
line 6 :<title>Seak Ecommerce Group</title>
     etc...

Further validation (HTML)(page source) of general pages etc this seems to be magento wide and also includes the last line as well.
Has anyone else seen this and/or know how this can be fixed
cheers

A: Have you looked into index.php on the document root ? I was having the same issue, and i checked disabling all modules one by one, removing BOM and everything as suggested in various forums. But before giving up, I tried opening index.php and found that this was the culprit. There were blank lines in the top of the file. I removed it and the issue was resolved.


text:
Q: How to navigate through routing on button click in react. react-router": "^6.2.1 How to navigate through routing on button click in react.
I am trying to acess some other class using routing ( "react-router": "^6.2.1",) in reactJS. When I am clicking I am getting this error.

Cannot read properties of undefined (reading 'push')

Here is my class
import React, { Component } from "react";
import { withRouter } from 'react-router-dom';
import { useHistory } from "react-router-dom";
import Button from "@mui/material/Button";

class MyBar extends Component {
constructor(props) {
    super(props);

        this.state = {};
        this.createNew = this.createNew.bind(this);
}

createNew () {
   this.props.history.push('/new');
}

render() {
    return (

                    <button type="create" class="btn btn-outline-primary"  onClick={this.createNew}> Create Post </button>

    );
  }
}
export default MyBar;

Here is my dependency
"dependencies": {
    "@emotion/react": "^11.8.1",
    "@emotion/styled": "^11.8.1",
    "@mui/material": "^5.4.3",
    "@testing-library/jest-dom": "^5.16.2",
    "@testing-library/react": "^12.1.3",
    "@testing-library/user-event": "^13.5.0",
    "axios": "^0.26.0",
    "bootstrap": "^5.1.3",
    "draft-js": "^0.11.7",
    "font-awesome": "^4.7.0",
    "react": "^17.0.2",
    "react-bootstrap": "^2.1.2",
    "react-dom": "^17.0.2",
    "react-draft-wysiwyg": "^1.14.7",
    "react-icons": "^4.3.1",
    "react-pro-sidebar": "^0.7.1",
    "react-router": "^6.2.1",
    "react-router-dom": "^6.2.1",
    "react-scripts": "5.0.0",
    "web-vitals": "^2.1.4"
  },

But in other version( "react-router-dom": "^5.2.0",) of app by using this in the export
export default withRouter(ListOfEmployee);

I was easily able to navigate.
Can anybody help me here.
PS: I know there are multiple answer but none of them are its working and not getting much from the git and offcial docs.

A: In v6 you can use useNavigate:
const navigate = useNavigate()
navigate('/new')

A: It should work
class Login extends Component {
    nextPath(path) {
    this.props.history.push(path);
  }
    render() {
        return (

        <button type='button' onClick={() => this.nextPath('/yourpath') } >Button</button>

        );
}


text:
Q: django featured content field Sent a question yesterday but I wasn't too clear on what I am attempting. I'm struggling to find any useful tutorials on how best to achieve this so a nudge in the right direction would be greatly appreciated.
I've set up a model which references django_content_type. My idea is to use this model to reference other models so that they can be marked as "featured" content, without me having to put a new "isFeatured" field on every model.
All I want to be able to do is have a check box appear on the forms of my admin for each model, which indicates if the content is featured or not.
class FeaturedContent(models.Model):
    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    content_object = generic.GenericForeignKey('content_type', 'object_id')

Firstly, is this the right approach?
Do I need to create a custom form/model field? and how do I introduce this field to the admin template?
I've been looking inside of (django.contrib.contenttypes) generic.py and you can clearly see where the template data is being loaded and also which template is being used. I'm wondering if perhaps I need to extend this class rather than write my own field?
Thanks for any help,
James

A: In my view this isn't the right approach. You're better off using abstract base classes with a BooleanField, like this:
class FeaturedModel(models.Model):
    is_featured = models.BooleanField(default = False)

    class Meta:
        abstract = True

class Foobar(FeaturedModel):
    title = models.CharField(max_length = 200)
    ...

That way you get all the goodness of each model having it's very own is_featured field that you can play with, and none of the complication of content types.


text:
Q: Active Objects: Cannot handle method. It is not a valid getter or setter and does not have an implementation supplied I am getting the error:
java.lang.IllegalArgumentException: Cannot handle method. It is not a valid getter or setter and does not have an implementation supplied. Signature: public abstract ...
in a unit test run with ActiveObjectsJUnitRunner.
The project is an Atlassian Jira plugin with Active Objects.

A: The problem was that some my colleague wrote the getter as:
import net.java.ao.0neToMany;

@OneToMany
Collection<NdaProtectedItem> getNdaProtectedItems();

while it should have been:
@OneToMany
NdaProtectedItem[] getNdaProtectedItems();

The result must be a plain array, ActiveObjects do not support collection getters!


text:
Q: How to update UI from one form to another form I have Form1 which contains a combobox which show some number saved in Database and it also contain a button(butn2) which on click popups a another form and another button(butn1) which updates the combo from database.
Here on this form (Form2, Child form of some sort)i try to updat the data of the combobox of previous form(parent one) on button click by creating object of Form1
But when i open and see the combobox it still show the same data(it is not updated).
Is it possible to update the UI from combobox from one form to another ? My code is
Form1 code:
public Form1()
{
  InitializeComponent();
}

Form1.Designer.cs:
Button butn1;
Button butn2;
ComboBox cmb1;
private void InitializeComponent()
 {
  cmb1 = new ComboBox();
  butn1 = new Button();
 }
this.butn1.Click += new System.EventHandler(this.button_Save_Click);
this.butn2.Click += new System.EventHandler(this.button_Save_Click2);

public void button_Save_Click(object sender, System.EventArgs e)
{
  UpdateComboBoxFromMySQL.InsertdataInCombo(this.cmb1 ); //Here i add data in combox through database, the code is correct i verfied it
}
public void button_Save_Click2(object sender, System.EventArgs e)
 {
    Form2 frm2 = new Form2();
    frm2.show();
 }

Form2 code:
Button butn2 = new Button();
//first i add some data to database, which are added i have seen the table-columns by opening DB. Now i want to update the Combobox from that data
Form1 obj1 = new Form();
this.butn2.Click += new System.EventHandler(obj1 .button_Save_Click); //It calls the function button_Save_Click, i saw on debugging but still it do not update the data.

How to update this combobox of Form1 from Form2 button click?

A: Let's suppose that the name of your first Form is Foobar. In that case, instead of
Form1 obj1 = new Form();
this.butn2.Click += new System.EventHandler(obj1 .button_Save_Click);

which creates a new Form object, you need this:
Form obj1 = null;
for (int i = ((obj1 == null) && (Application.OpenForms.Count - 1)); i >= 0; i--)
{
    if (Application.OpenForms[i].Name == "Foobar")
        obj1 = Application.OpenForms[i];
}
if (obj1 != null)
{
    this.butn2.Click += new System.EventHandler(obj1 .button_Save_Click);
}

Explanation: obj1 is initialized with null. A cycle is created to find the Form you want to find, the end sign being either completed iteration or the Form being found. If the Form is found, then obj1 is initialized. After the cycle, if obj1 was initialized, then you can use it, its members and methods, including, but not limited to button_Save_Click.

A: You also can show form2 with parent form1
public void button_Save_Click2(object sender, System.EventArgs e)
 {
    Form2 frm2 = new Form2();
    frm2.Show(this);
 }

Then you can access to form1 through the Owner property of form2.
this.butn2.Click += new System.EventHandler(Owner.button_Save_Click);


text:
Q: How to stop animation using animeJs - Reactjs how can i remove this animation in the else statement please ?
i have a form with 2 inputs (email, pwd) and a button.
if both of  inputs have length < 6  i should animate the button, otherwise, i have to remove completly the animation (i.e. keep the button where it is currently)
  const btnRef = useRef(null);
  const inputs = useRef([]);

  const [emailSize, setEmailSize] = useState(null);
  const [pwdSize, setPwdSize] = useState(null);

  const addInputs = (el) => {
    if (el && !inputs.current.includes(el)) {
      inputs.current.push(el);
    }
  };

  const handleEmail = () => {
    setEmailSize(inputs.current[0].value.length)
  }
  const handlePwd = () => {
    setPwdSize(inputs.current[1].value.length)
  }
      useEffect(() => {
        if (btnRef) {
          handleEmail();
          handlePwd();
          console.log("size email: ", emailSize)
          console.log("size pwd: ", pwdSize)
          const animateMove = (element, prop, pixels) =>
          anime({
            targets: element,
            [prop]: `${pixels}px`,
            easing: "easeOutCirc",
          });

          const getRandomNumber = (num) => {
            return Math.floor(Math.random() * (num + 1));
          };
          if ((emailSize && pwdSize) < 6) {
            ["mouseover"].forEach(function (e) {
              console.log("HOVER")
              btnRef.current.addEventListener(e, function (event) {
                const top = getRandomNumber(
                  this.parentElement.offsetHeight - this.offsetHeight - 1
                );
                const left = getRandomNumber(
                  this.parentElement.offsetWidth - this.offsetWidth - 1
                );

                animateMove(this, "left", left).play();
                animateMove(this, "top", top).play();
              });
            });
          }
          else if ((emailSize && pwdSize) >= 6) {
             // remove animation
           });
          }
        }
      }, [inputs, emailSize, pwdSize]);


text:
Q: Replace Action bar with toolbar I'm using a Toolbar to replace the ActionBar. All is going well before replacing.
after replacing it gives me error:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.oi.mmg/com.oi.mmg.EventDetailsScreenActivity}: java.lang.IllegalStateException:
This Activity already has an action bar supplied by the window decor. Do not request Window.FEATURE_ACTION_BAR and set windowActionBar to false in your theme to use a Toolbar instead.

A: In the style used by your Activity you have to add:
<style name="MyTheme" parent="Theme.AppCompat.Light">
    .....
    <!-- Both of these are needed -->
    <item name="windowActionBar">false</item>
    <item name="windowNoTitle">true</item>
</style>

A: Without knowing your code I would suggest using this parent theme for your application:
Theme.AppCompat.Light.NoActionBar

The property "windowActionBar" is then "false" by default.
And if you are using AppCompat your activities should then extend from "AppCompatActivity".


text:
Q: After taking the picture from CameraX, how can we preview our latest photo so I am making a different project, I'm making an app that has a normal camera using CameraX. My goal is when the photo is taken to go to a preview to see the latest photo directly before saving, examples such as "Messanger, Viber, Whatsapp and etc." does anyone has any idea how? Here is the code so far:
Manifest
<uses-permission android:name="android.permission.CAMERA"/>
<uses-feature android:name="android.hardware.camera2"/>
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE"
     tools:ignore="ScopedStorage" />

Gradle implementation
implementation 'androidx.camera:camera-camera2:1.1.0-alpha01'
implementation 'androidx.camera:camera-lifecycle:1.1.0-alpha01'
implementation 'androidx.camera:camera-view:1.0.0-alpha21'

main_activity.xml
<androidx.constraintlayout.widget.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:orientation="vertical" >

    <androidx.camera.view.PreviewView
        android:id="@+id/previewView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <com.google.android.material.floatingactionbutton.FloatingActionButton
        android:id="@+id/camera_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="15dp"
        android:importantForAccessibility="no"
        app:backgroundTint="#B8AEAE"
        app:borderWidth="5dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

MainActivity.kt
package com.example.watermarkbitmap2

import android.Manifest
import android.annotation.SuppressLint
import android.content.pm.PackageManager
import android.graphics.*
import android.graphics.Color.BLACK
import android.graphics.Color.RED
import android.graphics.Paint.ANTI_ALIAS_FLAG
import android.graphics.Paint.DITHER_FLAG
import android.net.Uri
import android.os.Bundle
import android.util.Log
import android.widget.TextView
import android.widget.Toast
import androidx.annotation.ColorInt
import androidx.appcompat.app.AppCompatActivity
import androidx.camera.core.CameraSelector
import androidx.camera.core.ImageCapture
import androidx.camera.core.ImageCaptureException
import androidx.camera.core.Preview
import androidx.camera.lifecycle.ProcessCameraProvider
import androidx.camera.view.PreviewView
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.google.android.material.floatingactionbutton.FloatingActionButton
import java.io.File
import java.text.SimpleDateFormat
import java.util.*
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors

class MainActivity : AppCompatActivity() {
    /**watermark private variables**/
    private var paint = Paint()
    private val config = Bitmap.Config.ARGB_8888
    private val width = 15
    private val height = 15
    private var bitmap = Bitmap.createBitmap(width, height, config)

    /**Camera variables**/
    private var imageCapture: ImageCapture? = null
    private lateinit var cameraExecutor: ExecutorService
    private lateinit var outputDirectory: File

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        /**Checking for all permissions to be granted through method,
         * if so it will start the camera, if not checks for a request with permissions and request code**/
        if (allPermissionsGranted()) {
            startCamera()
        } else {
            ActivityCompat.requestPermissions(this, REQUIRED_PERMISSIONS, REQUEST_CODE_PERMISSIONS)
        }

        // Making a variable, connecting to the button and setting up a listener to initiate taking a photo through a method
        val imageCaptureBtn = findViewById<FloatingActionButton>(R.id.camera_button)
        imageCaptureBtn.setOnClickListener {
            takePhoto()
        }

        // Connecting the late init variable with a new method to get output directory
        outputDirectory = getOutputDirectory()
        cameraExecutor = Executors.newSingleThreadExecutor()
    }

    private fun getOutputDirectory(): File {
        val mediaDir = externalMediaDirs.firstOrNull().let {
            File(it, "BitmapWatermark").apply { mkdirs() } }
        return if (mediaDir.exists())
            mediaDir else filesDir
    }

    private fun takePhoto() {
        val photoFile = File(outputDirectory, SimpleDateFormat(FILENAME_FORMAT, Locale.ENGLISH).format(System.currentTimeMillis()) + ".jpg")
        val outputOptions = ImageCapture.OutputFileOptions.Builder(photoFile).build()

        imageCapture?.takePicture(
            outputOptions, ContextCompat.getMainExecutor(this), object  : ImageCapture.OnImageSavedCallback {
                override fun onImageSaved(outputFileResults: ImageCapture.OutputFileResults) {
                    val saveUri = Uri.fromFile(photoFile)
                    val msg = "Photo capture succeeded: $saveUri"

                    Toast.makeText(baseContext, msg, Toast.LENGTH_SHORT).show()
                    Log.d(TAG, msg)
                }

                override fun onError(exception: ImageCaptureException) {
                    Toast.makeText(baseContext, "Photo capture failed: ${exception.message}", Toast.LENGTH_SHORT).show()
                    photoFile.delete()
                }

            }
        )

    private fun startCamera() {
        val viewFinder = findViewById<PreviewView>(R.id.previewView)
        val cameraProviderFuture = ProcessCameraProvider.getInstance(this)
        cameraProviderFuture.addListener({
            // Used to bind the lifecycle of cameras to the lifecycle owner
            val cameraProvider: ProcessCameraProvider = cameraProviderFuture.get()

            // Preview
            val preview = Preview.Builder()
                .build()
                .also {
                    it.setSurfaceProvider(viewFinder.surfaceProvider)
                }

            imageCapture = ImageCapture.Builder()
                .build()

            // Select back camera as a default
            val cameraSelector = CameraSelector.DEFAULT_BACK_CAMERA

            try {
                // Unbind use cases before rebinding
                cameraProvider.unbindAll()

                // Bind use cases to camera
                cameraProvider.bindToLifecycle(
                    this, cameraSelector, preview, imageCapture)

            } catch (exc: Exception) {
                Log.e(TAG, "Use case binding failed", exc)
            }

        }, ContextCompat.getMainExecutor(this))
    }

    private fun allPermissionsGranted() = REQUIRED_PERMISSIONS.all {
        ContextCompat.checkSelfPermission(
            baseContext, it) == PackageManager.PERMISSION_GRANTED
    }

    @SuppressLint("SetTextI18n")
    fun drawBitmap(bitmap: Bitmap, left: Float, top: Float, paint: Paint?) {
        val paintText = Paint()

        paintText.textAlign
        paintText.textSize = 14F
        paintText.color = RED

        paintText.getTextPath(textText.toString(), 1, 10, 12f, 12f, path)
    }

    fun addWatermark(
        bitmap: Bitmap,
        watermarkText: String,
        options: WatermarkOptions = WatermarkOptions()
    ): Bitmap {
        val result = bitmap.copy(bitmap.config, true)
        val canvas = Canvas(result)
        val paint = Paint(ANTI_ALIAS_FLAG or DITHER_FLAG)

        paint.textAlign = when (options.corner) {
            Corner.TOP_LEFT,
                Corner.BOTTOM_LEFT -> Paint.Align.LEFT
            Corner.TOP_RIGHT,
                Corner.BOTTOM_RIGHT -> Paint.Align.RIGHT
        }

        val textSize = result.width * options.textSizeToWidthRatio
        paint.textSize = textSize
        paint.color = options.textColor

        if (options.shadowColor != null) {
            paint.setShadowLayer(textSize / 2, 0f, 0f, options.shadowColor)
        }

        if (options.typeface != null) {
            paint.typeface = options.typeface
        }

        val padding = result.width * options.paddingToWidthRation
        val coordinates = calculateCoordinates(watermarkText, paint, options, canvas.width, canvas.height, padding)
        canvas.drawText(watermarkText, coordinates.x, coordinates.y, paint)
        return result
    }

    private fun calculateCoordinates(
        watermarkText: String,
        paint: Paint,
        options: WatermarkOptions,
        width: Int,
        height: Int,
        padding: Float
    ): PointF {
        val x = when (options.corner) {
            Corner.TOP_LEFT,
            Corner.BOTTOM_LEFT -> {
                padding
            }
            Corner.TOP_RIGHT,
            Corner.BOTTOM_RIGHT -> {
                width - padding
            }
        }

        val y = when (options.corner) {
            Corner.BOTTOM_LEFT,
            Corner.BOTTOM_RIGHT -> {
                height - padding
            }
            Corner.TOP_LEFT,
            Corner.TOP_RIGHT -> {
                val bounds = Rect()
                paint.getTextBounds(watermarkText, 0, watermarkText.length, bounds)

                val textHeight = bounds.height()
                textHeight + padding

            }
        }
        return PointF(x, y)
    }

    enum class Corner {
        TOP_LEFT,
        TOP_RIGHT,
        BOTTOM_LEFT,
        BOTTOM_RIGHT,
    }

    data class WatermarkOptions(
        val corner: Corner = Corner.BOTTOM_RIGHT,
        val textSizeToWidthRatio: Float = 0.04f,
        val paddingToWidthRation: Float = 0.03f,
        @ColorInt val textColor: Int = Color.WHITE,
        @ColorInt val shadowColor: Int? = Color.BLACK,
        val typeface: Typeface? = null
    )

    companion object {
        private const val TAG = "ExampleCameraPreview"
        private const val FILENAME_FORMAT = "dd.MM.yyyy-HH:mm:ss"
        private const val REQUEST_CODE_PERMISSIONS = 10
        private val REQUIRED_PERMISSIONS = arrayOf(Manifest.permission.CAMERA)
        private var path: Path = Path() // this gets us the new image
    }
}


text:
Q: MySQL 1:10 fixed relationship. How to implement it at database level? Is it possible to implement a 1:N relationship that has 10 rows of the many referencing 1 row from the one table at most?
// ID int
INSERT INTO one VALUES (1);
// ...
INSERT INTO one VALUES (25);

//ID int, one_id int
INSERT INTO many VALUES (1,1);
// ...
INSERT INTO many VALUES (1,10);
INSERT INTO many VALUES (1,11); // ERROR!

INSERT INTO many VALUES (2,11); // working
// ...
INSERT INTO many VALUES (2,20); // working
INSERT INTO many VALUES (2,21); // ERROR!

A: You can do this with a trigger:
create trigger trg_mytable_max10 before insert on mytable
for each row
begin
  declare cnt int;
  set cnt = (select count(*) from mytable where col1 = new.col1);
  if cnt = 10 then
    signal sqlstate '45000' set message_text = 'only 10 records per col1 allowed';
  end if;
end;

http://rextester.com/EORH56497