text:
Q: Spring MVC RequestMapping I'm in the early stages of learning to use Spring MVC. I've created a controller and applied a RequestMapping annotation to it. When I run the project, the index page displays as expected at index.htm, but when I navigate to the URI that should be pointing to my controller, I get a 404 error, even though the controller seems to have been detected by Spring and started. Please help me understand what I am failing to grasp here:
Here is my web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>
<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
    <servlet-name>dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>dispatcher</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>
<session-config>
    <session-timeout>
        30
    </session-timeout>
</session-config>
<welcome-file-list>
    <welcome-file>redirect.jsp</welcome-file>
</welcome-file-list>

Here is my applicationContext.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns:context="http://www.springframework.org/schema/context"

   xmlns:p="http://www.springframework.org/schema/p"
   xmlns:aop="http://www.springframework.org/schema/aop"
   xmlns:tx="http://www.springframework.org/schema/tx"
   xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
   http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
   http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
   http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd>

    <context:spring-configured/>

<context:component-scan base-package="org.blah.blah"/>

Here is my dispatcher-servlet.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns:context="http://www.springframework.org/schema/context"
   xmlns:p="http://www.springframework.org/schema/p"
   xmlns:aop="http://www.springframework.org/schema/aop"
   xmlns:tx="http://www.springframework.org/schema/tx"
   xmlns:mvc="http://www.springframework.org/schema/mvc"
   xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
                       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
                       http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
                       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
                       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd">

<mvc:annotation-driven/>
<bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping"/>

<bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
    <property name="mappings">
        <props>
            <prop key="index.htm">indexController</prop>
        </props>
    </property>
</bean>

<bean id="viewResolver"
      class="org.springframework.web.servlet.view.InternalResourceViewResolver"
      p:prefix="/WEB-INF/jsp/"
      p:suffix=".jsp" />

<bean name="indexController"
      class="org.springframework.web.servlet.mvc.ParameterizableViewController"
      p:viewName="index" />

And, finally, here is my controller.
@Controller
@RequestMapping(value = "/hello")
public class Ctrl {

    @RequestMapping(method = RequestMethod.GET)
    @ResponseBody
    public String hello(){
    return "hello!";
    }

}

EDIT: This is what my browser displays:

A: I was half-wrong in the comments to gravityplanx' answer.
When you specify a <mvc:annotation-driven /> in your servlet configuration, Spring registers a RequestMappingHandlerMapping bean which is meant to collect and map all your @Controller handler methods, ie. those annotated with @RequestMapping.
It does this by looking at all the beans in the current context. Remember that when you load a context with DispatcherServlet, call it the servlet context, if a context was loaded by a ContextLoaderListener, call it the root context, the root context is made a parent of the servlet context. By default, the RequestMappingHandlerMapping bean does not look at the root context, which is a parent of the servlet context.
In your case, the @Controller beans are declared implicitly in the root context (your applicationContext.xml) because of the <context:component-scan/> which scans classes annotated with
 @Component or any of its specializations (@Controller for instance) and creates beans for them. So these beans are registered in the root context, where the RequestMappingHandlerMapping can't find them.
If instead you declare the <context:component-scan /> in the servlet context, then the @Controller (and other) beans are created in the servlet context where they are available to the RequestMappingHandlerMapping which can then register them to handle requests.
Note that <context:component-scan /> on its own doesn't do anything for the MVC stack. It needs further configuration, like <mvc:annotation-driven />. You should aim to specify packages that contain servlet specific beans in the servlet context and application wide beans in the root context.
Here's some literature:

*

*What is the difference between ApplicationContext and WebApplicationContext in Spring MVC?

*Difference between applicationContext.xml and spring-servlet.xml in Spring Framework

A: Your dispatcher servlet doesn't seem to be referenced correctly.
Replace:
<servlet>
    <servlet-name>dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>2</load-on-startup>
</servlet>

With:
<servlet>
    <servlet-name>dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>[insert the path to your dispatcher-servlet here]</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>

And then move:
<context:spring-configured/>

<context:component-scan base-package="org.blah.blah"/>

From applicationContext to dispatcher-servlet


text:
Q: Icons don't appear after build when opening on other computer I was working with JFrame in Netbeans, Java. I've made some buttons and added icons to them. When I build my project and open .jar file on my computer, I see the icons, but if I open that file on other computer, those buttons are empty. Where should I put the icons, so I could see them on another computer after build?

A: They should be inside your jar file, and loaded as resources.

A: Problem solved. What I had to do is to put those icons into my projects package folder, then select "Image within project" in button options and add them again.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why copyDatabase command still gives not authorized error message when 'dbAdminAnyDatabase'? The version is mongo 2.6.
I have created a user have role "dbAdminAnyDatabase".  But when copyDatabase still gives error message.
mongos> db.createUser({user:"hant",pwd:"abc",roles:["readWriteAnyDatabase","dbAdminAnyDatabase"]});
Successfully added user: {
    "user" : "hant",
    "roles" : [
        "readWriteAnyDatabase",
        "dbAdminAnyDatabase"
    ]
}

mongos> use admin;
switched to db admin
mongos> db.auth("hant","abc");
1
mongos>  db.copyDatabase("wlib007","wlib003");
{
    "errmsg" : "exception: nextSafe(): { $err: \"not authorized for query on wlib007.system.namespaces\", code: 13 }",
    "code" : 13106,
    "ok" : 0
}

But when checking wlib007.system.namespaces.find,
mongos> db.system.namespaces.find();
{ "name" : "admin.system.version" }
{ "name" : "admin.system.indexes" }
{ "name" : "admin.system.version.$_id_" }
{ "name" : "admin.system.users" }
{ "name" : "admin.system.users.$_id_" }
{ "name" : "admin.system.users.$user_1_db_1" }
{ "name" : "admin.system.profile", "options" : { "capped" : true, "size" : 1048576 } }

Why dbAdminAnyDatabase role doesn't work for copyDatabase?

A: Here is the official document describing roles of mongo:
https://docs.mongodb.org/manual/reference/built-in-roles/
Following the rules, "dbAdmin" has no permission to read/write. You can have a role test by client of mongodb such as Mongochef.

A: As you written:
mongos> db.auth("hant","abc");
db.copyDatabase("wlib007","wlib003");

{"errmsg" : "exception: nextSafe(): { $err: \"not authorized for query
  on wlib007.system.namespaces\", code: 13 }","code" : 13106,
  "ok" : 0 }

That you want

use wlib003

create user hant and grant those DB("wlib007","wlib003") authentication;
as followings.
It's a simple question.

*

*It's important that you must switch the target DB NOT admin.

use yourDB

*check your DB authentication by

*show users
If you get a {} empty object that is the question. You just need to type
db.createUser(
    {
      user: "yourUser",
      pwd: "password",
      roles: [ "readWrite", "dbAdmin" ]
    } )

or
db.grantRolesToUser('yourUser',[{ role: "dbAdmin", db: "yourDB" }])


text:
Q: How to compile the dynamic library(.so) when developing a MariaDB plugin? I clone MariaDB Server's source code from github, and I want to write an encryption plugin for it. But, I do not know how to get the dynamic library file of my plugin. Please help me.
MariaDB version: 10.8
OS: Ubuntu 18.04


text:
Q: function referencing inside sdf_pivot all:
I am having trouble referencing simple functions inside sdf_pivot. Can anyone help? Thanks!
This is the code that works, but not exactly what I need:
spark_disconnect_all();
sc <- spark_connect(master = "yarn-client")
mtcars_tbl <- sdf_copy_to(sc, mtcars, name = "mtcars_tbl", overwrite = TRUE)
mtcars_tbl %>%
  mutate(mpg = ifelse(mpg > 30, "High", "Low" )) %>%
  sdf_pivot(mpg+cyl ~ gear, fun.aggregate = list(hp = "mean"))

I want to calculate mean with NA removed and median calculated as well, ideally with NA removed as well. I cannot get the following codes to work though:
mtcars_tbl %>%
  mutate(mpg = ifelse(mpg > 30, "High", "Low" )) %>%
  sdf_pivot(mpg+cyl ~ gear, fun.aggregate = list(hp = "mean(na.rm=TRUE)"))
mtcars_tbl %>%
  mutate(mpg = ifelse(mpg > 30, "High", "Low" )) %>%
  sdf_pivot(mpg+cyl ~ gear, fun.aggregate = list(hp = "percentile(0.5)"))

This is the result I need:
  mpg     cyl `3.0` `4.0` `5.0`
  <chr> <dbl> <dbl> <dbl> <dbl>
1 Low       8  194.  NaN   300.
2 High      4  NaN    61   113
3 Low       4   97    85    91
4 Low       6  108.  116.  175

My data is 800 million rows and I'm just using a single example here for the purpose of easy replication. In reality, I cannot just collect it to a dataframe in R. All the calculation has to be on spark. A lot of things stop to work on Spark, median function is one. I can get percentile function to work but not median. But I can't figure out how to supply the extra parameters in this specific setting.


text:
Q: Sending POST data using the Firefox Request API Hello I'd be super grateful for help with this Firefox API question.
I have a webpage listening for a POST variable called sausage:
<!DOCTYPE HTML>
<body>
<?php
echo $_POST['sausage'];
?>

Using the Request API in the Firefox addon SDK, I've made a button which is supposed to load my webpage while sending the POST variable sausage:
var buttons = require('sdk/ui/button/action');
var tabs = require("sdk/tabs");
var Request = require("sdk/request").Request;

 var button = buttons.ActionButton({
    id: "mozilla-link",
    label: "Visit Mozilla",
    icon: {
        "16": "./icon-16.png",
        "32": "./icon-32.png",
        "64": "./icon-64.png"
        },
    onClick: handleClick
});

function handleClick(state)
{
    tabs.open({
        url: "http://localhost/home.php/",
        onOpen: runScript
    });
}

function runScript(tab)
{
    Request({
      url: "http://localhost/home.php/",
      content: { sausage: 'sausage' }
    }).post();
}

This is loading the target page, but not sending the POST variable, so the php echo function throws an error. Please can someone explain what's gone wrong. I especially would like to avoid using any of the lower level API functions because this looks like the kind of job Request should eat for breakfast. Thanks in advance!

A: The request api doesn't send the variable when opening the tab, it instead makes a second request to the same url. Check your server logs or the browser console, you should see two requests every time you click that button.


text:
Q: Export Lightning Component bundle I created some Lightning Components (*.cmp, *Controller.js, *Helper.js, *Controller.cls) and I wanted to export them to use them on other organisation.
How can I do this without taking care of Custom sObject ?

A: You can do that in 3 ways:

*

*If your orgs are connected (sandboxes etc.), use a changeset between them.

*Use Force.com migration tool (ant deploy).

*Use one of the Force.com IDEs like Eclipse or MavensMate


text:
Q: Dozer-Mapping.xml: Cannot find the declaration of element 'mappings' I am trying to implement Dozer mapper in my Spring Web Service Project.
I am getting below error:
EXCEPTION:
org.springframework.beans.factory.parsing.BeanDefinitionParsingException: Configuration problem: Failed to import bean definitions from relative location [dozer-mapping.xml]
Offending resource: class path resource [projectName/application-context.xml]; nested exception is org.springframework.beans.factory.xml.XmlBeanDefinitionStoreException: Line 4 in XML document from class path resource [folderName/dozer-mapping.xml] is invalid; nested exception is org.xml.sax.SAXParseException: cvc-elt.1: Cannot find the declaration of element 'mappings'.
Caused by: org.springframework.beans.factory.xml.XmlBeanDefinitionStoreException: Line 4 in XML document from class path resource [employeeelectionrs/dozer-mapping.xml] is invalid; nested exception is org.xml.sax.SAXParseException: cvc-elt.1: Cannot find the declaration of element 'mappings'.
    at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:396)
    at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:334)
    at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:302)
My Code:
Dozer-mapping.xml
<?xml version="1.0" encoding="UTF-8"?>
<mappings xmlns:ns="http://dozer.sourceforge.net"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://dozer.sourceforge.net
http://dozer.sourceforge.net/schema/beanmapping.xsd">
 <mapping>
<class-a>org.testing.ui.types.HistoryRequest</class-a>
<class-b>org.testing.api.types.HistoryReq</class-b>
<field>
    Status
    StatusCode
</field>
</mapping>
</mappings>

application-context.xml
<import resource="dozer-mapping.xml"/>
<bean id="dozerBeanMapper" class="org.dozer.spring.DozerBeanMapper">
    <property name="mappingFiles">
        <list>
            <value>dozer-mapping.xml</value>
        </list>
    </property>
</bean>

Dozer Jars Used:
- commons-beanutils-1.8.3.jar
- commons-lang-2.6.jar
- dozer-5.3.2.jar
- jcl-over-slf4j-1.6.6.jar
- log4j-1.2.15.jar
- slf4j-api-1.6.6.jar
- slf4j-log4j12-1.6.6.jar
I have got above jars from the Dozer official web page.
I have tried  n number of times but whenever  i am starting my Weblogic server, the above said exception is been thrown.
Kindly help/guide.

A: Remove the line with <import resource .. />. Why should the mapping configuration be loaded as part of the spring configuration file. The only bean interested in this configuration should be the DozerbeanMapper.
<bean id="dozerBeanMapper" class="org.dozer.spring.DozerBeanMapper">
    <property name="mappingFiles">
        <list>
            <value>dozer-mapping.xml</value>
        </list>
    </property>
</bean>


text:
Q: Height parameter not working with one of my images in HTML When adding images to a table, I was able to size the first image's width and height but for some reason the second image will not register the height in the image tag. The code is as follows:
<!DOCTYPE html>

The problem is with the height="200" that is not registering in my code.  I'm using SublimeText and the height also doesn't change to green like the height in my first image.
I can also post the CSS code if needed, but this is kind of a personal project so I want to post as little of it as I possibly can.

A: You're missing a closing quotation in your second image, after width.

Should be:


text:
Q: How can I select my version of python to use streamlit? I have an app.py and I have several versions of python installed on my machine. How can I select what version of python should run when I type:
streamlit run app.py

A: python --version

Output: Python 3.8.8

This will be the version that your streamlit app will run on. In my case 3.8.8.
If you want to have a different version of Python for streamlit, you can install it from python.org, use a virtual environment , or use conda to create a specific environment with conda install python 3.6.0


text:
Q: "Chains" of Dual Spaces I have seen examples of the following:

*

*A sequence of duals extending forever$$S \subset S^*  \subset S^{**}  \subset S^{***} \subset ... \\ S = L^0 $$

*A sequence of duals flipping between 2 spaces
$$S \subset S^*  \subset S  \subset S^{*} \subset ... \\ S = L^p $$

*A sequence of duals which is isometric to itself
$$S = S^* \\ S = H $$
Are there sequences of duals that "return" every third space or something? Is there some "deep" algebraic fact that these are the only 3 possibilities?


text:
Q: Windows Authentication not working for MVC 4 app on Windows Server 2008 with IIS 7.0 Getting this error:
HTTP Error 401.1 - Unauthorized
You do not have permission to view this directory or page using the credentials that you supplied.
I have successfully got Windows Authentication setup on my Windows 7 with IIS 7.5, just not on the test server (Windows Server 2008).  Test server is within the network and I have access.
Things I have tried:

*

*Turned on Windows feature, Windows Authentication

*In IIS (7.0) Authentication, set Windows Authentication to enabled & Anonymous Authentication to disabled.

*This is from the web.config file:

<system.web>
    <compilation debug="true" targetFramework="4.5"/>
    <httpRuntime />
    <authentication mode="Windows" />
    <authorization>
      <allow users="MyDomain\SomeUser" />
      <deny users="*" />
    </authorization>
    <pages controlRenderingCompatibilityVersion="4.0" />
  </system.web>

I can't think figure this out. Any ideas?

A: As I mentioned above, when I publish and browse to that application on my windows 7 computer the application works without a user/pass popup. But if I publish and browse to the application on the test server (Windows Server 2008) I keep getting a user/pass popup.
Here is the strange thing, browsing to the application from the test server doesn't work. However, browsing to the application from my own computer (Windows 7) to the application which is published on the test server works ONLY after entering user/pass in the pop.
I still don't know why I can't browse to the application while on the test server. It is a virtual machine so maybe it recognized me as something unexpected when I am logged in.


text:
Q: Return everything before the last "/" I would like a regular expression that will do the following:

*

*Given a directory, return the previous directory. So, basically remove the last "/" and everything after it. You can assume that the string will not end in "/something/" but instead will be "/something".

*Examples:

*

*
*

*Given: "/home/development"

*Return: "/home"

*
*

*Given: "/home/simulations/database"

*Return: "/home/simulations"

*
*

*Given: "/home/simulations/workingConfig/system/customer"

*Return: "/home/simulations/workingConfig/system"

*etc.

I've been playing around with a regular expression like /[^/]*$ and the command like:
expr match "/home/simulations/database" '\(/[^/]*$\)'
with no luck. Any help?

A: Using an external command such as sed is needlessly inefficient; bash can do this built-in with parameter expansion:
s=${s%/*}

This does a non-greedy pattern match for /* at the end of your string and removes everything it finds. Thus:
$ s=/home/simulations/database
$ echo "${s%/*}"
/home/simulations

See also BashFAQ #100 ("How can I do string manipulations in bash?").

That said, if you really want to use a regular expression, bash can do that too with only built-in functionality:
$ s=/home/simulations/database
$ [[ $s =~ ^(.*)/[^/]*$ ]] && s=${BASH_REMATCH[1]}
$ echo "$s"
/home/simulations

A: You're looking for dirname
$ dirname /home/development /home/simulations/database /home/simulations/workingConfig/system/customer
/home
/home/simulations
/home/simulations/workingConfig/system

A: You may want to use sed for this, since it is pretty straight forward:
sed 's@/[^/]*$@@' <<< "string"

This removes everything from the last /.
Test
$ cat a
/home/simulations/workingConfig/system/customer
/home/simulations/database
/home/development

$ sed 's@/[^/]*$@@' a
/home/simulations/workingConfig/system
/home/simulations
/home


text:
Q: Getting Facebook API Error Code 191, but only in Internet Explorer I'm seeing this error in Internet Explorer (but not other browsers):

API Error Code: 191
  API Error Description: The specified URL is not owned by the application
  Error Message: redirect_uri isn't an absolute URI. Check RFC 3986.

My canvas URL is http://nintriva.com/_others/groupbuy/index.php?r=groupbuy/facebook/authenticate and my app is installed on the page http://www.facebook.com/nintriva?sk=app_241476069209769.
I have provided the site URL, http://www.nintriva.com/_others/groupbuy/index.php?r=groupbuy/facebook/authenticate, and the site domain www.nintriva.com.
I use this code to redirect to the Facebook fan page after the user gives permission:
$this->auth_url = "http://www.facebook.com/dialog/oauth?client_id=".Yii::app()->controller->module->app_id."&redirect_uri=".urlencode($session['page_link']."?sk=app_".Yii::app()->controller->module->app_id)."&scope=email,user_location";

where page_link is the user fan page link I get from a signed request.

A: Basically, Facebook sees URLs http://www.example.com as different from http://example.com
for the Facebook lo-gin to work you, your URLs must be exactly the way it is at Facebook.

A: Probably you got that error because the URL is constructed dynamically and it needs to be static.


text:
Q: android passing variable back from class I am trying to make a reusable UI class. I admit that I don't understand how it should work.  I want to have a class that I pass arguments into and when the user makes a selection it will return the selected value.  This will actually be a more complex, custom dialog that will be used.  For testing, I put together the following code from examples I found and it does everything but return the selected value back.
So, how can I get the user selected value back in the main routine?
Main module
    package com.mine.zd;
import android.app.Activity;
import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;

public class ZDialogActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        Button btn1 = (Button) findViewById(R.id.btn1);
        btn1.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View arg0){
                go();
            }
        });
    }

    private void go()
    {
       final String[] vOptions = { "One", "Two", "Three" } ;

       myOptions.getmenuOptions(
        ZDialogActivity.this, "Select Mode", vOptions,
            new android.content.DialogInterface.OnClickListener(){
               @Override
               public void onClick(DialogInterface dialog, int which) {
                  Log.w("TEST", "which=" + which );
               }
            }
       );
    }
}

called module
package com.mine.zd;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.util.Log;

public class myOptions {

    public static void getmenuOptions(Context context, String msg,
         String[] vOptions, OnClickListener neutralClickListener){

        new AlertDialog.Builder(context)
        .setTitle("Select Mode")
        .setItems(vOptions, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
                Log.w("TEST", "item=" + whichButton );
                dialog.dismiss();
            }
        })
        .setNeutralButton("Cancel", neutralClickListener )
        .create().show();
    }
}

I do get the returned "cancel" button value of -3, but I need the id of the option selected.

A: Here how about this:
import android.R;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

import com.your.package.MyOptions.MyDialogClickListener;

public class ZDialogActivity extends Activity implements View.OnClickListener, MyDialogClickListener {

    private MyOptions options;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        findViewById(R.id.btn1).setOnClickListener(this);

        String[] vOptions = { "One", "Two", "Three" };
        options = new MyOptions(vOptions, this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.btn1:
            go();
            break;
        default:
            Log.e("TEST", "Unhandled onClick");
            break;
        }
    }

    private void go() {
        options.getMenuOptions(this, "Select Mode");
    }

    @Override
    public void onMyDialogClick(String option){
        Log.d("TEST", "item=" + option);
    }
}

And your helper class:
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;

public class MyOptions implements OnClickListener {

    private final MyDialogClickListener listener;
    private final String[] options;

    public interface MyDialogClickListener {
        void onMyDialogClick(String option);
    }

    public MyOptions(String[] options, MyDialogClickListener listener) {
        this.options = options;
        this.listener = listener;
    }

    public void getMenuOptions(Context context, String msg)  {
        new AlertDialog.Builder(context)
            .setTitle(msg)
            .setItems(options, this)
            .setNeutralButton("Cancel", this)
            .create()
            .show();
    }

    @Override
    public void onClick(DialogInterface dialog, int which) {
        if(listener != null)
            listener.onMyDialogClick(options[which]);
        dialog.dismiss();
    }
}

1) Start your class names with uppercase
2) Dont use a static helper method, instantiate the class it's better practice in this scenario
3) You can then pass the non changing fields to the constructor
4) Use an interface to send message between classes (your Activity acts as a Listener on the dialog onClick event)
5) Don't use annoyomous onClick listeners let your class implement it and switch on the view id to pertain which was clicked
Hope that helps!


text:
Q: Disk Usage Very Strange Just today, my Ubuntu 11.04 started prompting me that my HDD is full ... I know I am filling up my HDD fast, but its the storage partition I expect to be filling up not my 60+GB OS Partition. So I did a Disk Usage Analysis and got the below:

/labs is actually the Storage partition
First, my home folder /home/jiewmeng is said to use 58.8GB? but the biggest few files, don't appear to sum up to that? Counting quickly, it looks like ~1.5GB only?
Looking at the 2nd image, my HDD doesn't seem to be all that full at all? Is it a mistake?
UPDATE (df -Th output)
Filesystem    Type    Size  Used Avail Use% Mounted on
/dev/sda1     ext4     68G   65G  4.0K 100% /
none      devtmpfs    3.9G  680K  3.9G   1% /dev
none         tmpfs    3.9G  220K  3.9G   1% /dev/shm
none         tmpfs    3.9G  392K  3.9G   1% /var/run
none         tmpfs    3.9G     0  3.9G   0% /var/lock
/dev/sda2     ext4    764G  561G  165G  78% /labs
/dev/sda3     ext4     69G  180M   65G   1% /ex

A: You could delete the .xsession-errors.old file entering sudo rm ~/.xsession-errors.old in terminal.
This file was the 99% of my drive space :)

A: Run df -h in a terminal window. The output should have the proper numbers.
/dev/sda2              16G  5,1G   10G  34% /
udev                  2,0G  4,0K  2,0G   1% /dev
tmpfs                 807M  896K  806M   1% /run
none                  5,0M  8,0K  5,0M   1% /run/lock
none                  2,0G  224K  2,0G   1% /run/shm
/dev/sda6              28G   14G   14G  51% /home

In my example the /home filesystem is located on /dev/sda6 and has 14GB used (3rd column) and 14GB free space (4th).
You can check the total disk usage of a directory by using du -hs. E.g:
$ du -hs /home/username
14G /home/username

You may have hidden directories accumulating large files. The first yellow block in the gparted window shows that the root partition (/dev/sda1) is almost full.

A: You should also check to make sure your .xsession-errors (not -old) is not growing quickly; this happens not infrequently.
I have set a cron job to delete it on a daily basis by making a cron file:
crontab -e

and putting this line in:
0 0 * * * rm /PATH-TO-HOME/.xsession-errors

(replacing PATH-TO-HOME with home/jiewmeng in this case )
There are a few other ways to prevent this (note that both of these methods disable logging, so if you're having any other oddities with your GUI, you may also lose useful logging info)
.xsession-errors file is huge. How can I disable?
modifies /etc/X11/Xsession to point the error logging to /dev/null
and http://ubuntuforums.org/showthread.php?t=1517991 simply removes the file and recreates it as a symlink to /dev/null.

A: First of all, 1 GB is 1,000,000,000 bytes, and 1 GiB is 1,073,741,824 bytes. You need to realise this when comparing number from Disk Usage Analyser and GParted, as they use different units. df uses the units G, M and K to mean GiB, MiB and KiB respectively. If you want to use multiple of ten units, pass --si to df.
Now on to your questions.

My home folder /home/jiewmeng is said to use 58.8GB? but the biggest few files, don't appear to sum up to that? Counting quickly, it looks like ~1.5GB only?

The output of Disk Usage Analyser only shows  directories. If your home directory is full of very large files, that will be included in the usage number of the home directory, but those large files won't get separate rows in the displayed table. This is probably what is happening in your case.

Looking at the 2nd image, my HDD doesn't seem to be all that full at all? Is it a mistake?

You have three partitions on your hard drive (not counting the swap partition), as shown by GParted. Your home directory is included in the partition /dev/sda1 mounted at /, since it isn't in its own partition. /dev/sda1 only has 3.45 GiB free space. Some of this free space (5%) is reserved for the root user by default. If you subtract that, you get what is known as the "available space", which is 4KiB according to the output of df. To double-check, run System Monitor and open the File Systems tab, you'll be able to compare the free space and the available space of each partition at once.
So, yes, the first partition is very full.

If I were you, I would boot a live CD of Ubuntu, make a backup of my data, shrink the /dev/sda2 partition, and grow the /dev/sda1 partition using GParted.

A: Chances are if the first few files don't add up, the disk analyzer is missing something, the filesystem is corrupt, or you have several hundred thousand 10mb files in there somewhere.
try:
- running fdisk

*

*looking manually into the folder with high usage and checking how many files there are.

*using a different usage analyzer that could show the hidden files or those with a bad entry in directory listings(try Jdiskreport)


text:
Q: the apple id you entered couldn't be found or your password was incorrect I am debugging my in-app purchase on ipad ( ios 7.0.3).
But when I enter my password, it always says "the apple id you entered couldn't be found or your password was incorrect".

*

*my developer id and the apple id registered on this ipad are different.

*when I intentionally enter wrong password, it displays a different message "Your Apple ID or password is incorrect".

*My in-app purchase is in review state. But I feel, it doesn't have any impact on sandbox testing

*I have restarted my device. I can use the same password for downloading/purchasing other apps from itunes.

I am not posting my in-app purchase code as this is out of our coding context.

A: In order to test in-app purchases before they are approved, you have to use test users, which you can create in iTunes Connect.
Once you sign in to iTunes Connect, you click where it says "Manage Users", which will let you create test users. Once you create a test user, you can use it within your development build of your app to test your in-app purchases. You can also create multiple test users if you need to repeatedly test non-consumable in-app purchases.

A: we have had same issue, spent whole day chasing rabbit at the end what solved issue was to set test account App Store Territory/country United states, in our case we have set country Pakistan on test account user causing issue

A: We also recently experienced this issue.
We "solved" it by using shorter email addresses for test users.
Emails longer than about 25 characters seemed to cause the error.


text:
Q: How can I write in a compact way $v_j = \max_i Q_{i,j}$ without using indexes? Let $Q$ be a matrix. I would like to write in a compact way (without indexing) $$\max_i Q_{*,i}$$ that should return a vertical vector $$v_j = \max_i Q_{j,i}$$
I need it because I have
$$Q = R + \gamma P \max_i Q_{*,i}$$
and I would like to have a matrix notation where there are no indexes. Now in my document I wrote something like
$$Q = R + \gamma P Q^*$$
making clear that $Q^* = \max_i Q_{*,i}$. But, if I find a more appropriate way to write this "operator" it will be great!
(Q is a matrix, R is a matrix, P is a 3-d matrix)


text:
Q: NodeJS & Jest : How to mock a service and repositories with a factory and dependency injection I would like to know how to mock a service and his repositories with Jest ?
I tried many stuff such as :
export default ({ quotationRepository }) => {

  const getQuotations = (runComputationData) =>
  Promise.resolve()
    .then(async () => {
      const promise = quotationRepository.runComputation(runComputationData);
      const quotationsResult = await Promise.all([promise]);
      const quotations = quotationsResult[0];

      return quotations;
    })
    .catch((error) => {
      throw error;
    });

  return {
    getQuotations,
  };
};

My quotationService test file :
import quotationRepository from 'src/infra/repositories/financing/quotation/index';
import quotationServices from 'src/domain/financing/quotation/quotationServices';
import mockedQuotations from './mockedQuotations';
import mockedRunComputationData from './mockedRunComputationData';

jest.mock('src/infra/repositories/financing/quotation/index', () => ({
  runComputation: jest.fn().mockResolvedValue(() => mockedQuotations)
}));

describe('getQuotations', () => {

  beforeAll(() => {
    jest.resetModules();
    jest.restoreAllMocks();
  });

  test('Test with mockResolvedValue', async () => {
    const runComputationData = await quotationServices.getQuotations(mockedRunComputationData);
    expect(runComputationData).toEqual(mockedRunComputationData);
  });
});

I always have the same issue :

I don't really know what's going on here. For me, it seems that jest.mock simulate a mock for the file we're passing in the first argument and the second is the behavior that the function (here runComputation) will have. Am I doing something wrong here ?
Thanks


text:
Q: Validate uniqueness of an item on individual user level I have a simple Rails 4 app calling the GitHub API to recreate, on a basic level, the Repositories page. On my calls to the API I am parsing the JSON and saving it in my database. The problem I'm having is that I want to validate the uniqueness of the repository name, but I only want the names to be unique for each user. As of now if I look at one user's page it saves everything fine, but if the next user I look at has anything named the same it will not save that repository to the database.
If anyone could point me in the right direction it would be great. Thanks.

A: validates_uniqueness_of :name, :scope => :profile_id

This will enforce uniqueness per profile, which it sounds like is what you're looking for.


text:
Q: Hibernate refresh? I am working with hibernate and mysql to abstract a database for use in a java driven website. I got all my queries to work out just fine using hibernate, but couldn't seem to figure out how to do the updates, inserts, and deletes with it so I ended up making my own bean that does those functions using regular mySQL methods.
The issue I am running into now is that when I do an update or insert using regular mysql, the persisted hibernate objects from the database do not get updated, but the data stored in the database does. How can I resynchronize or "refresh" the hibernate information to match the mysql information?
Or if it would be easier, how do I save/update modified objects from hibernate into msql. (obviously I'm new to hibernate) Any help would be appreciated. Thanks ahead of time!

A: Persisting the data back using standard SQL seems to somewhat defeat the purpose of using Hibernate.  My recommendation would be to change things so that you can do both retrieval and saving of data through Hibernate. Depending on your setup it could be as easy as getting a session from the session factory and calling the save method.
i.e.
  Session session = sessionFactory.getSession();
  session.save(hibernateObject);

In my experience the Hibernate documentation is quite good.  Skimming through it would probably be a worthwhile endeavor.  Particularly this section: Chapter 10: Working with Objects

A: Try
hibernateSession.refresh(yourObject)

http://docs.jboss.org/hibernate/orm/3.5/javadoc/org/hibernate/Session.html#refresh%28java.lang.Object%29


text:
Q: Is it possible to pivot a list without using SQL? What's the best way to pivot a list of lists?
I have a list of lists:
+-------+--------+-----+
| file1 | parama | 112 |
| file1 | paramb |  54 |
| file1 | paramd | 234 |
| file2 | paramb |  63 |
| file2 | paramd | 334 |
| file2 | paramz |  11 |
| file3 | parama |  34 |
+-------+--------+-----+

Can we pivot this list to get the following result:
+--------+-------+-------+-------+
|        | File1 | File2 | File3 |
| parama | 112   | -     | 34    |
| paramb | 54    | 63    | -     |
| paramd | 234   | 334   | -     |
| paramz | -     | 11    | -     |
+--------+-------+-------+-------+

What's the best way to pivot a list of lists?


text:
Q: C# app domain exception when "AddPermission", saying absolute path is require? I was just trying app domain and have this code:
        var perm = new PermissionSet(PermissionState.None);
        perm.AddPermission(
            new SecurityPermission(SecurityPermissionFlag.Execution));
        perm.AddPermission( // exception
            new FileIOPermission(FileIOPermissionAccess.NoAccess, "@d:\\"));

In fact the line "new FileIOPermission(FileIOPermissionAccess.NoAccess, "@d:\"));" throws exception, saying:
Unhandled Exception: System.ArgumentException: Absolute path information is required.
   at System.Security.Util.StringExpressionSet.CreateListFromExpressions(String[] str, Boolean needFullPath)
   at System.Security.Permissions.FileIOPermission.AddPathList(FileIOPermissionAccess access, AccessControlActions control, String[] pathListOrig, Boolean checkForDuplicates, Boolean needFullPath, Boolean copyPathList)
   at System.Security.Permissions.FileIOPermission..ctor(FileIOPermissionAccess access, String path)

Where did I get wrong, how to fix it?

A: You are writing the path in the wrong way.
change this "@d:\" to @"d:\" to make the string verbatim.
"@d:\\" -> @d:\
@"d:\"  -> d:\

More Info About String


text:
Q: How to make it more safe? I have following function:
isElemChar :: Char -> Bool
isElemChar x = elem x ['A'..'Z'] || elem x ['a'..'z']

When I try to use the function as follow:
isElemChar 5

Then I've got the exception:
<interactive>:73:12: error:
    * No instance for (Num Char) arising from the literal `5'
    * In the first argument of `isElemChar', namely `5'
      In the expression: isElemChar 5
      In an equation for `it': it = isElemChar 5
*Cipher Data.Char> isElemChar 'a'

How to make the function more safe? Which would be the right approach to make it to total function?
I could use the Maybe datatype, but do not know how to implement it.

A: Your function is safe. The "exception" you mention is actually a compile-time error, which is exactly the time you want errors.
This is slightly hidden by the fact you're at an interactive prompt, but if you wrote the program safe.hs....
isElemChar :: Char -> Bool
isElemChar x = elem x ['A'..'Z'] || elem x ['a'..'z']

main = print $ isElemChar 5

... and you tried to compile it...
ghc safe.hs

... you would get a similar error
safe.hs:5:27: error:
    • No instance for (Num Char) arising from the literal '5'
    • In the first argument of 'isElemChar', namely '5'
      In the second argument of '($)', namely 'isElemChar 5'
      In the expression: print $ isElemChar 5

A: There is no need to make the function more safe, this is not python, the functions params have a type, so your code will just give you a compile error.
If you are dealing with IO you will always get an IO([Char]) or a IO(Char).


text:
Q: How to install openCV on android emulator I have to install openCV on a emulator. Somebody wrote that is should use a certain command
adn install <...>/OpenCV-2.4.3.2-android-sdk/apk/OpenCV_2.4.3.2_Manager_2.4_x86.apk
but did not say where to put it? I did not see any command line do configure virtual device.

A: Installing the OpenCV Manager on emulator is like installing any other application. Here's a link on how to do that.

A: You can install it on a VirtualBox appliance.
http://dimitri-christodoulou.blogspot.com.es/2014/02/how-to-install-opencv-on-android-vm.html


text:
Q: Tensorflow: TypeError: run() got an unexpected keyword argument 'feedis_dict' I get this error when trying to add the feedis_dict to a self.sess.run command:
Traceback (most recent call last):
  File "spritegen.py", line 71, in <module>
    tf.app.run()
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/platform/app.py", line 44, in run
    _sys.exit(main(_sys.argv[:1] + flags_passthrough))
  File "spritegen.py", line 54, in main
    dcgan.train(FLAGS)
  File "/home/lewis/Documents/Sprite Generator/Sprite-Generator/dcgan.py", line 211, in train
    summary_str = self.sess.run([dis_optim, self.dis_sum],feedis_dict = {self.inputs: batch_images, self.z: batch_z})
TypeError: run() got an unexpected keyword argument 'feedis_dict'

Any suggestions as to why feedis_dict is unexpected ?
I believe im using tensorflow gpu 1.0.0


text:
Q: Layer error: ImageCollection.mosaic: Invalid type. (Earth Engine) An error occurred in raster to vector conversion:

Layer 1: Layer error: ImageCollection.mosaic: Invalid type.
  Expected type: Image.
  Actual type: FeatureCollection.

Why is the Map function trying to mosaic an image collection when I have a feature collection that is also a valid input to Map.
My code link is: https://code.earthengine.google.com/f14646de49f536d7ed4b4e0d5a9ccb21
  var elevation=SRTM;
  var sorted = L8.filter(ee.Filter.eq('WRS_PATH', 147))
  .filter(ee.Filter.eq('WRS_ROW', 38))
  .filter(ee.Filter.calendarRange(2013,2013,'year'))
 .filter(ee.Filter.calendarRange(7,10,'month'))
 .filterMetadata('CLOUD_COVER', 'less_than', 10)

var ndwi1 = sorted.map(
 function(img) {

   var ndwi = img.normalizedDifference(['B3','B5']);
   var slop = ee.Terrain.slope(elevation);
   var evi1 = ndwi.expression('(thr>0.25) && (slp<20)? 1 : 0' ,

      {  'thr' : ndwi,  'slp' : slop   });

   var evi = evi1.clip(table)

   var vectors = evi.addBands(evi)
     .reduceToVectors({
      geometry: table,
      crs: evi.projection(),
      scale: 30,
      geometryType: 'polygon',
      reducer: ee.Reducer.mean(),
      maxPixels: 1e8
                     });

 return vectors;
 })

 print(ndwi1)
Map.addLayer(ndwi1)

A: I can't run the code because the table asset is not shared. However, I think you will need to cast ndwi1 as an ee.FeatureCollection() and then flatten() it. Mapping over the sorted image collection returns a collection of feature collections, which cannot be added as a Map layer. Replace your last two lines with this:
var ndwiFc = ee.FeatureCollection(ndwi1).flatten()
print(ndwiFc)
Map.addLayer(ndwiFc)


text:
Q: How to replace all instances of "\n" in a string with linebreaks I am using data scraped from a website and making my bot display in separate lines. There is a particular string whose information has "\n" in between and I want to convert those into actual line breaks
I have tried replacing the '\n' with '+ "\n" +' but the output is still the same
This is an example of the issue I have, and not the actual bot code
import discord
from discord.ext.commands import Bot
from discord.ext import commands
import asyncio

Client = discord.Client()
client = commands.Bot(command_prefix = "!")

cardName = "Card Name"
rawCardText = "This is an ability\nThis is another ability"
cardText = rawCardText.replace('\n', '+ "\n" +')

fullText = cardName + "\n" + cardText
await client.send_message (message.channel, fullText)

I expected something like this:
Card Name
This is an ability
This is another ability
Instead what I get is:
Card Name
This is an ability\nThis is another ability

A: cardName = "Card Name"
rawCardText = "This is an ability\nThis is another ability"
cardText = rawCardText.split('\n')
fullText = fullText = (cardName + '\n' + '\n'.join(cardText))
print (fullText)

A: Write "\n" as raw string:
cardText = rawCardText.replace(r'\n', '+ "\n" +')


text:
Q: Pytest - custom output of test results I want to completely custom tests results output.
In unittest I can implement my own test runner by example of unittest.TextTestRunner. How can I do the same in pytest?

A: You'll need to work with pytest hooks:

py.test calls hook functions to implement initialization, running,
  test execution and reporting.

Also see:

*

*py.test code snippets

*pycon tutorial session (it also goes through using hooks)


text:
Q: Insert aws urls into an array I currently have a working audio player that uses paperclip attachments to upload to aws. I want to access all the urls for all tracks and insert them in an array or variable for use with my js audio player. Below is the following code that I have tried:
//incorrect code
 @tracks.each do |m|
  @tracks_url_list = m.audio
 end

I have also tried
//incorrect code
@tracks.each do |m|
  @tracks_url_list = Array[m.audio]
 end

When I implement
<% @tracks.each do |m| %>
  <%= m.audio %>
<% end %>

In the index.html.erb it displays
http://s3.amazonaws.com/musicstreamdata/tracks/audios/000/000/008/original/11_Acid_Rain_%28Prod._by_Jake_One%29_%28DatPiff_Exclusive%29.mp3?1457290530
and other track links show as well. However, when I try to store it inside a variable or array, it only shows one url for one track. I'm probably missing something obvious, but how do I get it so that I can store all the urls from my tracks in an array like this:
@track_url_lists = [track_one_url, track_two_url, track_three_url, etc. ]

I appreciate any help

A: Try one of following:
@tracks_url_list = @tracks.collect(&:audio)

or
@tracks_url_list = @tracks.inject([]) each do |url_list, track|
  url_list << track.audio
  url_list
end

Refer to Enumerable#inject for more info


text:
Q: Outputting a triangle Enter an odd value greater than zero -- I understand how to do that.
Print out a triangle that looks like the following if 5 is entered:
54321
 432
  3

If 11 is entered:
10987654321
 098765432
  9876543
 and so on

I see that we must divide the input by 10 and print the remainder but I'm having trouble printing the countdown.
for (i = n; i >= 1; i--)
  i = i - 1;

A: use a for loop (start at 0), and on each iteration print a substring from i to string.length()-1 an use the set width to increase the indent, following code below:
string num = "10987654321";

for (int i = 0; i < num.length(); ++i){
   cout << setw(i) << right << num.substr(i, num.length()-i) << endl;
}

This should give you your desired output. (if "<< right <<" doesn't work, swap "right" with "left")
ALSO
you need to include iomanip to use setw()

A: int num = 10987654321;
int numSpaces = 1;

cout << num << endl;

for (int i = 0; i >= 1; i--)
{
    for (int j = 0; j < numSpaces; j++)
    {
         cout << " ";
    }

    cout << num % 10 << endl;

    num = num / 10;

    numSpaces++;
}

Voila a beautiful triangle :)


text:
Q: How to block app using local proxy server in ios or redirect the network call to a nonexistant_invalid_url which match to proxy settings match domain I am trying to block app using proxy server.VPN is also working well,when i add this line
let config = URLSessionConfiguration.default
                            config.requestCachePolicy = .reloadIgnoringLocalCacheData
                            config.urlCache = nil
                            let session = URLSession.init(configuration: config)
                            let url = URL(string: "https://nonexistant_invalid_url")
                            let task = session.dataTask(with: url!) { (data, response, error) in
                            return

But got error is
2022-03-14 12:42:46.257048+0530 pushNotifications[1370:272455] invalid mode 'kCFRunLoopCommonModes' provided to CFRunLoopRunSpecific - break on _CFRunLoopError_RunCalledWithInvalidMode to debug. This message will only appear once per execution.
Starting
2022-03-14 12:42:55.375340+0530 pushNotifications[1370:272736] Connection 1: received failure notification
2022-03-14 12:42:55.375513+0530 pushNotifications[1370:272736] Connection 1: failed to connect 12:8, reason -1
2022-03-14 12:42:55.375574+0530 pushNotifications[1370:272736] Connection 1: encountered error(12:8)
2022-03-14 12:42:55.377315+0530 pushNotifications[1370:272736] Task .<1> HTTP load failed, 0/0 bytes (error code: -1003 [12:8])
2022-03-14 12:42:55.385009+0530 pushNotifications[1370:272737] Task .<1> finished with error [-1003] Error Domain=NSURLErrorDomain Code=-1003 "A server with the specified hostname could not be found." UserInfo={_kCFStreamErrorCodeKey=8, NSUnderlyingError=0x2827f6520 {Error Domain=kCFErrorDomainCFNetwork Code=-1003 "(null)" UserInfo={_NSURLErrorNWPathKey=satisfied (Path is satisfied), interface: en0, ipv4, ipv6, dns, kCFStreamErrorCodeKey=8, kCFStreamErrorDomainKey=12}}, NSURLErrorFailingURLSessionTaskErrorKey=LocalDataTask .<1>, NSURLErrorRelatedURLSessionTaskErrorKey=(
"LocalDataTask .<1>"
), NSLocalizedDescription=A server with the specified hostname could not be found., NSErrorFailingURLStringKey=https://nonexistant_invalid_url/, NSErrorFailingURLKey=https://nonexistant_invalid_url/, _kCFStreamErrorDomainKey=12}
View controller
class ViewController: UIViewController {

    var providerManager: NETunnelProviderManager!
    @IBOutlet weak var mySwitch: UISwitch!

    override func viewDidLoad() {
        super.viewDidLoad()

     }

    @IBAction func vpnConnectionSwitch(_ sender: Any) {

        if(mySwitch.isOn){
            self.loadProviderManager {
                //self.configureVPN(serverAddress: "hix",username: "JornVPN", password: "6ztbe85")
                self.configureVPN(serverAddress: "serveradress",username: "J", password: "6ztbe85")
            }
                }
                else {
                   print( "Switch is Off")
// Of on demand
                    let rule = NEOnDemandRuleDisconnect()
                    rule.interfaceTypeMatch = .any
                    self.providerManager?.onDemandRules = [ rule ]

                    self.providerManager?.saveToPreferences(completionHandler: { (error) in
                          if error == nil  {
                             self.providerManager.loadFromPreferences(completionHandler: { (error) in
                                 self.providerManager?.connection.stopVPNTunnel()
                                 print("Stop")
                             })
                          }
                    })

                }
    }

    func loadProviderManager(completion:@escaping () -> Void) {
       NETunnelProviderManager.loadAllFromPreferences { (managers, error) in
           if error == nil {
               self.providerManager = managers?.first ?? NETunnelProviderManager()
               completion()
           }
       }
    }

    func configureVPN( serverAddress: String,username: String, password: String) {

        guard
            let configurationFileURL = Bundle.main.url(forResource: "ios", withExtension: ".ovpn"),
                let configData = try? Data(contentsOf: configurationFileURL)
            else {
                fatalError()
            }

      self.providerManager?.loadFromPreferences { error in
         if error == nil {
            let tunnelProtocol = NETunnelProviderProtocol()

            tunnelProtocol.username = username
            tunnelProtocol.serverAddress = serverAddress
            tunnelProtocol.providerBundleIdentifier = "com.cloud.pushNotifications.tunnel" // bundle id of the network extension target
            tunnelProtocol.providerConfiguration = ["ovpn": configData, "username": username, "password": password]
            tunnelProtocol.disconnectOnSleep = false
            self.providerManager.protocolConfiguration = tunnelProtocol
            self.providerManager.localizedDescription = "JornVPN" // the title of the VPN profile which will appear on Settings
            self.providerManager.isEnabled = true
             self.providerManager.isOnDemandEnabled = true
    // VPN ON DEMAND
             let rule = NEOnDemandRuleConnect()
             rule.interfaceTypeMatch = .any
             self.providerManager.onDemandRules = [ rule ]

            self.providerManager.saveToPreferences(completionHandler: { (error) in
                  if error == nil  {
                     self.providerManager.loadFromPreferences(completionHandler: { (error) in
                         do {
                           try self.providerManager.connection.startVPNTunnel()

                             print("Starting")// starts the VPN tunnel.
                             let config = URLSessionConfiguration.default
                            config.requestCachePolicy = .reloadIgnoringLocalCacheData
                            config.urlCache = nil
                            let session = URLSession.init(configuration: config)
                            let url = URL(string: "https://nonexistant_invalid_url")
                            let task = session.dataTask(with: url!) { (data, response, error) in
                            return

                            }
                            task.resume()
                         } catch let error {
                             print(error.localizedDescription)
                         }
                     })
                  }
            })
          }
       }
    }

}

Packet Tunnel:
import NetworkExtension
import OpenVPNAdapter
import UIKit
import NEKit

class PacketTunnelProvider: NEPacketTunnelProvider {

    let proxyServerPort: UInt16 = 9090;
    let proxyServerAddress = "127.0.0.1";
    var proxyServer: GCDHTTPProxyServer!

    var startHandler: ((Error?) -> Void)?
    var stopHandler: (() -> Void)?
    var vpnReachability = OpenVPNReachability()

    var configuration: OpenVPNConfiguration!
    var properties: OpenVPNConfigurationEvaluation!
    var UDPSession: NWUDPSession!
    var TCPConnection: NWTCPConnection!

    lazy var vpnAdapter: OpenVPNAdapter = {
        let adapter = OpenVPNAdapter()
        adapter.delegate = self
        return adapter
    }()

    override func startTunnel(options: [String : NSObject]?, completionHandler: @escaping (Error?) -> Void) {
        print("Conneted \(options)")
        NSLog("Conneted \(options)")
        guard
            let protocolConfiguration = protocolConfiguration as? NETunnelProviderProtocol,
            let providerConfiguration = protocolConfiguration.providerConfiguration
            else {
                fatalError()
        }
        guard let ovpnFileContent: Data = providerConfiguration["ovpn"] as? Data else { return }
            let configuration = OpenVPNConfiguration()
            configuration.fileContent = ovpnFileContent
            do {
                properties = try vpnAdapter.apply(configuration: configuration)
            } catch {
                completionHandler(error)
                return
            }
        configuration.tunPersist = true

        if !properties.autologin {
            if let username: String = providerConfiguration["username"] as? String, let password: String = providerConfiguration["password"] as? String {
                let credentials = OpenVPNCredentials()
                credentials.username = username
                credentials.password = password
                do {
                    try vpnAdapter.provide(credentials: credentials)
                    print("vpnAdapter")
                } catch {
                    completionHandler(error)
                    return
                }
            }
        }

        vpnReachability.startTracking { [weak self] status in
            guard status != .notReachable else { return }
            self?.vpnAdapter.reconnect(afterTimeInterval: 5)
        }
        startHandler = completionHandler
        vpnAdapter.connect(using: packetFlow)

    }

    override func stopTunnel(with reason: NEProviderStopReason, completionHandler: @escaping () -> Void) {
        stopHandler = completionHandler
        if vpnReachability.isTracking {
            vpnReachability.stopTracking()
        }
        vpnAdapter.disconnect()
    }

    override func handleAppMessage(_ messageData: Data, completionHandler: ((Data?) -> Void)?) {
        if let handler = completionHandler {
            handler(messageData)
        }
    }

    override func sleep(completionHandler: @escaping () -> Void) {
        completionHandler()
    }

    override func wake() {
    }

}

extension PacketTunnelProvider: OpenVPNAdapterDelegate {
    func openVPNAdapter(_ openVPNAdapter: OpenVPNAdapter, configureTunnelWithNetworkSettings networkSettings: NEPacketTunnelNetworkSettings?, completionHandler: @escaping (Error?) -> Void) {
        networkSettings?.dnsSettings?.matchDomains = [""]

                // Set the network settings for the current tunneling session.
                setTunnelNetworkSettings(networkSettings, completionHandler: completionHandler)
        //proxy Server
        let settings = NEPacketTunnelNetworkSettings(tunnelRemoteAddress: proxyServerAddress)
        settings.mtu = NSNumber(value: 1500)

        let proxySettings = NEProxySettings()
        proxySettings.httpEnabled = true;
        proxySettings.httpServer = NEProxyServer(address: proxyServerAddress, port: Int(proxyServerPort))
        proxySettings.httpsEnabled = true;
        proxySettings.httpsServer = NEProxyServer(address: proxyServerAddress, port: Int(proxyServerPort))
        proxySettings.excludeSimpleHostnames = false;
        proxySettings.exceptionList = []
        proxySettings.matchDomains = ["https://www.facebook.com/","https://m.facebook.com/","https://www.google.com/","https://google.com/"]
        settings.dnsSettings = NEDNSSettings(servers: ["127.0.0.1"])
        settings.proxySettings = proxySettings;
        RawSocketFactory.TunnelProvider = self

        self.setTunnelNetworkSettings(settings, completionHandler: { error in
            guard error == nil else {
                completionHandler(error)
                return
            }
            let newProxyServer = GCDHTTPProxyServer(address: IPAddress(fromString: self.proxyServerAddress), port: Port(port: self.proxyServerPort))
            self.proxyServer = newProxyServer
            do {
                try self.proxyServer.start()
                completionHandler(nil)
            } catch let proxyError {
                completionHandler(proxyError)
            }
        })
    }

    func openVPNAdapter(_ openVPNAdapter: OpenVPNAdapter, configureTunnelWithNetworkSettings networkSettings: NEPacketTunnelNetworkSettings?, completionHandler: @escaping (OpenVPNAdapterPacketFlow?) -> Void) {
        setTunnelNetworkSettings(networkSettings) { (error) in
            completionHandler(error == nil ? self.packetFlow : nil)
        }
    }

    func openVPNAdapter(_ openVPNAdapter: OpenVPNAdapter, handleEvent event: OpenVPNAdapterEvent, message: String?) {
        switch event {
        case .connected:
            if reasserting {
                reasserting = false
            }
            guard let startHandler = startHandler else { return }
            startHandler(nil)
            self.startHandler = nil
        case .disconnected:
            guard let stopHandler = stopHandler else { return }
            if vpnReachability.isTracking {
                vpnReachability.stopTracking()
            }
            stopHandler()
            self.stopHandler = nil
        case .reconnecting:
            reasserting = true
        default:
            break
        }
    }

    func openVPNAdapter(_ openVPNAdapter: OpenVPNAdapter, handleError error: Error) {
        guard let fatal = (error as NSError).userInfo[OpenVPNAdapterErrorFatalKey] as? Bool, fatal == true else {
            return
        }
        NSLog("Error: \(error.localizedDescription)")
        NSLog("Connection Info: \(vpnAdapter.connectionInformation.debugDescription)")
        if vpnReachability.isTracking {
            vpnReachability.stopTracking()
        }

        if let startHandler = startHandler {
            startHandler(error)
            self.startHandler = nil
        } else {
            cancelTunnelWithError(error)
        }
    }

    func openVPNAdapter(_ openVPNAdapter: OpenVPNAdapter, handleLogMessage logMessage: String) {
        NSLog("Log: \(logMessage)")
    }

}

extension PacketTunnelProvider: OpenVPNAdapterPacketFlow {
    func readPackets(completionHandler: @escaping ([Data], [NSNumber]) -> Void) {
        packetFlow.readPackets(completionHandler: completionHandler)
    }

    func writePackets(_ packets: [Data], withProtocols protocols: [NSNumber]) -> Bool {
        return packetFlow.writePackets(packets, withProtocols: protocols)
    }

}
extension NEPacketTunnelFlow: OpenVPNAdapterPacketFlow {

}


text:
Q: Insert id from table to another table in laravel +vue.js first image
second image
I want to get Id from students table where   i want insert this id in differs table  . I don't really know how to explain it but maybe if you see my codes, you would understand. I have already finish making the relationship between this 2 tables already
my student controller
this my differ controller but I do not know any idea about if this code true or no

A: first: 'app\Differ'? but Differ is in App\Models
you can use hasOne(Differ::class); when Student model and differ in the same folder
the second thing you should know, when using functions of relationship in laravel such as hasOne, a foreign key should be named by student_id in Differ or
you show it in function like hasOne(Differ::class,'id_student','id')


text:
Q: Displaying both Traditional and Simplified Chinese in Java Is it possible to draw both Traditional and Simplified Chinese characters in the same Java application with logical fonts like "SansSerif"? I only get the traditional variety with CJK codepoints.
I've tried setting Locale.setDefault() and GraphicsEnvironment.preferLocaleFonts() before creating the font. I've tried using -Duser.language and -Duser.country on the command line when starting java.exe. Also tried creating the font with AttributedCharacterIterator.Attribute.LANGUAGE set on it. No effect.
I'm not using Swing or AWT. Just trying to draw into an off-screen BufferedImage. I'm on Windows 7 and I verified I have fonts installed that support Traditional and Simplified Chinese (MingLiU and SimSun). I also checked Java's font configuration file, and I see both of those fonts listed there.
What else should I be doing?

A: Yes, you can display both Simplified and Traditional Chinese text in Java, so long as you have a font that includes both sets of characters.
I wrote this brief program to demonstrate:
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

import javax.imageio.ImageIO;

public class ChineseFonts {

    public static final int GAP = 35;
    public static final int FONTS_PER_LINE = 2;

    public ChineseFonts(String s) {

        Rectangle rect = new Rectangle(0, 0, 1024, 768);
        BufferedImage bufferedImage = new BufferedImage((int) Math.ceil(rect.getWidth()), (int) Math.ceil(rect.getHeight()), BufferedImage.TYPE_4BYTE_ABGR);
        Graphics graphics = bufferedImage.getGraphics();
        graphics.setColor(Color.WHITE);
        graphics.fillRect(rect.x, rect.y, rect.width, rect.height);
        graphics.setColor(Color.BLUE);

        String title = "Chinese Fonts on " + System.getProperty("os.name") + ", version " + System.getProperty("os.version");
        int fontY = 30;
        printString(title, graphics, 0, fontY, new Font(Font.SERIF, Font.BOLD | Font.ITALIC, 28), false);
        fontY += GAP + 10;
        int counter = 0;
        for (String fontName : new String[]{Font.MONOSPACED, Font.SANS_SERIF, Font.SERIF}) {
            Font font = new Font(fontName, Font.PLAIN, 24);
            printString(s, graphics, counter++, fontY, font, true);
            if (counter % FONTS_PER_LINE == 0)
                fontY += GAP;
        }
        Font[] localFonts = GraphicsEnvironment.getLocalGraphicsEnvironment().getAllFonts();
        List<Font> chineseFonts = new ArrayList<Font>();
        String simplifiedAndTraditionalChinese = "????";
        for (int j = 0; j < localFonts.length; j++) {
            if (localFonts[j].canDisplayUpTo(simplifiedAndTraditionalChinese) == -1) {
                chineseFonts.add(localFonts[j].deriveFont(24F));
            }
        }
        for (Font font : chineseFonts) {
            printString(s, graphics, counter++, fontY, font, true);
            if (counter % FONTS_PER_LINE == 0)
                fontY += GAP;
        }
        graphics.dispose();
        try {
            ImageIO.write(bufferedImage, "png", new File("chineseFonts.png"));
        } catch (Exception e) {
            // ignored
        }
    }

    private void printString(String s, Graphics graphics, int counter, int y, Font font, boolean showFontDetails) {
        graphics.setFont(font);
        if (showFontDetails)
            s = font.getFamily() + " " + s;
        graphics.drawString(s, 20 + (counter % FONTS_PER_LINE) * 510, y);
        if (showFontDetails)
            System.out.println("Printing " + s + " using " + font.getName() + ", which is " + font.getFontName() + " in family " + font.getFamily());
    }

    public static void main(String args[]) {
        new ChineseFonts("S: 漢字 T: 汉字");
    }
}

The 2 simplified and 2 traditional Chinese characters used are from the wikipedia page on Chinese Characters. When you run it, all the fonts used are printed to stdout, and the image is output with the font names and the Chinese characters.
Here are the 3 logical fonts and the first physical font that worked:

*

*Monospaced

*SansSerif

*Serif

*Arial Unicode MS S


text:
Q: Identity the available range numbers when two range numbers are overlap If I have an existing range:
1-10
11-50

Then I will enter a new range from 1 - 60, How could I detect that the new range to be added overlaps to the previous entries? And how can I get the available range? In this case the available range is from 51-60.
Does anyone here have a great idea on this?
Thanks for helping.
Here's my current code:
$saved = array(
                            array(
                                    "start" => 1,
                                    "end"   => 10
                                ),
                            array(
                                    "start" => 10,
                                    "end"   => 50
                            )
                        );
            $new_range = array(
                                "start" => 1,
                                "end"   => 60
                            );
            $usable_range = array();
            $previous_from = 0;
            $previous_to = 0;
            foreach($saved as $value)
            {
                $range_start = 0;
                $range_end = 0;
                if($previous_from<$value['start'])
                {
                    $previous_from = $value['start'];
                }
                if($previous_to<$value['end'])
                {
                    $previous_to = $value['end'];
                }
                if($previous_from<=$new_range['start'])
                {
                    if($previous_to<$new_range['end'])
                    {
                        $range_start = $previous_to+1;
                        $range_end   = $new_range['end'];
                        $new_range['start'] = $range_start;
                    }
                 }
                else if($previous_from>=$new_range['start'])
                {
                    if($previous_to<$new_range['end'])
                    {
                        $range_start = $previous_to+1;
                        $range_end   = $new_range['end'];
                        $new_range['start'] = $range_start;
                    }
                }
                $usable[] =     array("range_start"=>$range_start,"range_end"=>$range_end);
            }

A: Call every interval (min,max)
1) Sort your list of intervals by their min.
2) Check to see if any max is greater than the next entry over's min. If they are, create the interval that is the smaller of their mins and the greater of their maxes, and add it back into the list in place of those two.
3) Whenever you get a new interval, binary search into the list to add it, sorted by min. Then, using similar logic as in 2), attempt to merge it with the entry one below and one above until no more merges are possible.

EDIT: A few changes.
First, since we're using integers not floats, if you have an interval like 1,10 and 11,20 then there is no 'gap' between the 10 and 11 - so we should consider this to be one larger interval, 1,20. Reflect this by, instead of checking to see if max > next min, if max >= next min - 1.
Second, if you want to find all intervals formed by overlap when merging a new interval into your list of intervals:
1) Since your list of intervals is known to be in a state where it is sorted by min and also sorted by max, binary search into it to find the lowest min just above your new min and the highest max just above your new max.
2) Iterate over min, max, min, max... etc in your array that are between your new min and new max. Below the lowest min, above the highest max and between each max/min you can compute the interval that is in the 'gap' there, and return them in e.g. an array.

For example if your list of intervals contains 13,16, 21,24 and 31, 38 and you want to calculate the non-overlap of the new interval 1,30:
1) We binary search into our list and find that 13 is the lowest min above 1 and 24 is the highest max above 30.
2) We iterate like so:

*

*Between our min and the lowest min is 1 and 13 - so this forms an interval 1,12 (inclusive bottom, exclusive top). Add onto the return array.

*Between max and the next min is 16 and 21 - so this forms an interval 17,20 (exclusive on both ends). Add onto the return array.

*Between max and our max is 24 and 30 - so this forms an interval 25,30 (exclusive bottom, inclusive top). Add onto the return array.

A: Finding overlap can be described as finding an intersection. Likewise finding the available range can be described as finding the difference. One way of doing this would be treating these sets as arrays and using the array_intersect [1] and array_diff [2] functions.
That is all I can come up with given your details.
[1] - http://php.net/manual/en/function.array-intersect.php
[2] - http://www.php.net/manual/en/function.array-diff.php


text:
Q: Java : clean up runnable object with socket I'm writing a multi-threaded server application in Java.
Everything works fine  , but there's one little problem.
When I'm stopping the runnable which listens for incoming connection request  , the socket keeps existing . So my question is : How do I stop a runnable object and clean up all the objects made in this runnable ?
The code for stopping the thread:
Runnable tr = new Worldwide() ;
        Thread thread = new Thread(tr) ;
        thread.start() ;
        online =  true ;

        while (core.getServerSate()) {
            try{
            Thread.sleep(200);
            } catch (Exception e ) {
                e.printStackTrace();
            }
        } ;
        thread.stop() ;
        thread.
        core.printToConsole("Server is offline now") ;

The Runnable code :
public class Worldwide implements Runnable  {

Core core = Core.getInstance()  ;

public Worldwide () {

}
@Override
public void  run() {

    try {
    ServerSocket server = new ServerSocket(port) ;

    core.printToConsole("Server is online") ;
    core.printToConsole ( "listening on port :" +  server.getLocalPort()) ;
    while (core.getServerSate() == true) {

        Socket client = server.accept() ;
        Runnable tr = new ClientCommunication(client) ;
        new Thread (tr).start() ;

    }

    }
    catch(Exception e ) {
        core.printToConsole ("An error occured while going online") ;
        e.printStackTrace() ;
    }
    }

Thanks  , Tom

A: You can close the socket from the main thread. This will break the call to accept and cause it to throw an IOException. You can then exit the accept thread's run method from the catch of the IOException.

A: You need to explicitly close the ServerSocket by calling the close -method of the socket. The best place to do this is in your Worldwide-class's run-method, in a finally-block (so the socket gets closed even if an exception occurs).


text:
Q: How to output values from a loop into a javascript array I'm building a custom shortcode in Wordpress. Essentially what I want this to do is the following:

*

*Dynamically pull values from a group of Advanced Custom Fields

*Output those values into a javascript array, comma-separated

Where I'm getting stuck is that I can successfully run a loop over the group of fields and grab all the values and output them on a page. However, when I attempt to store them into a variable to be pulled into a javascript array ($v is stored in the output variable which is referenced in the urls array), it only returns one of those values.
How can I get all the values from the foreach ( $value as $v) to list inside of the urls array, with comma separation? Any help would be appreciated :)
add_shortcode('training-player', 'training_player');
// Add shortcode for Diagnostic media playlist
function training_player() {
  $author_id = get_the_author_meta('ID');
  $fields = acf_get_fields(405);
  if( $fields ) {
    echo '

';
    foreach( $fields as $field ) {
      $value = get_field( $field['name'], 'user_'. $author_id );
      if(!empty($value)) {
        if ($value) {
          foreach ( $value as $v) {
            echo $v;
          }
        }
      }
    }
    echo "

    ";
  }
}

A: This is not really a Wordpress question.
However you probably need the implode php function, using a comma as glue.
foreach( $fields as $field ) {
  $value = get_field( $field['name'], 'user_'. $author_id );
  if(!empty($value)) {
    if ($value) {
      $v = implode(',', $value);
    }
  }
}

A: This might get your desired output:
<?php
add_shortcode('training-player', 'training_player');
// Add shortcode for Diagnostic media playlist
function training_player() {
    $author_id = get_the_author_meta('ID');
    $fields    = acf_get_fields(405);
    $js_values = [];

    if( $fields ) {
        echo '

';
        foreach( $fields as $field ) {
            $value = get_field( $field['name'], 'user_'. $author_id );

            if(!empty($value)) {
                if ($value) {
                    foreach ( $value as $v) {
                        $js_values[] = $v;
                    }
                }
            }
        }

        echo "

";
    }
}

We're storing the value of $v in the $js_values array, and then outputting it in a format workable with Javascript using wp_json_encode instead of trying to directly put it into Javascript.
For future reference, you may want to look at [wp_localize_script](https://developer.wordpress.org/reference/functions/wp_localize_script/) for getting values from PHP to Javascript "the WordPress way", and enqueue the rest of your JS using [wp_enqueue_script](https://developer.wordpress.org/reference/functions/wp_enqueue_script), but that's beyond the scope of this answer.


text:
Q: Win 8.1 SearchBox - binding suggestions We are writing a Windows 8.1 Store App that uses the new SearchBox XAML control. It looks like the only way to get suggestions into the dropdown list as the user types is to use the SearchBoxSuggestionsRequestedEventArgs and get the SearchSuggestionCollection from the event then append the suggestions to that.
We're using Prism for WinRT and want to separate the SearchBox and it's events from the ViewModel that is getting the list of suggestion strings.
I can't find anyway of binding a list of strings to the SearchSuggestionCollection or any way of adding them programatically that doesn't involve using the event args, which is making out unit testing very complex.
Is there a way of binding/adding the suggestions that doesn't involve the event args?

A: Okay, so I got obsessed with this question, and here is a solution for when using the SearchBox. I've uploaded a full sample on MSDN and GitHub
In short, use the Behavior SDK and and the InvokeCommand, and then use a converter to grab whatever data you need by using the new attributes InputConvert and InputConverterParameter.
XAML:
    <SearchBox SearchHistoryEnabled="False" x:Name="SearchBox" Width="500" Height="50">
        <SearchBox.Resources>
            <local:SearchArgsConverter x:Name="ArgsConverter"/>
        </SearchBox.Resources>
        <interactivity:Interaction.Behaviors>
            <core:EventTriggerBehavior EventName="SuggestionsRequested">
                <core:InvokeCommandAction
                    Command="{Binding SuggestionRequest}"
                    InputConverter="{StaticResource ArgsConverter}"
                    InputConverterLanguage="en-US"
                    InputConverterParameter="{Binding ElementName=SearchBox, Path=SearchHistoryEnabled}"/>
            </core:EventTriggerBehavior>
        </interactivity:Interaction.Behaviors>
    </SearchBox>

Converter:
 public sealed class SearchArgsConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, string language)
    {
        var args = (SearchBoxSuggestionsRequestedEventArgs)value;
        var displayHistory = (bool)parameter;

        if (args == null) return value;
        ISuggestionQuery item = new SuggestionQuery(args.Request, args.QueryText)
        {
            DisplayHistory = displayHistory
        };
        return item;
    }

    public object ConvertBack(object value, Type targetType, object parameter, string language)
    {
        return value;
    }
}

Mainpade codebehind - of course you want this in a VM :)
 public sealed partial class MainPage
{
    public DelegateCommand<string> Search { get; set; }
    public DelegateCommand<ISuggestionQuery> SuggestionRequest { get; set; }

    public MainPage()
    {
        InitializeComponent();
        Search = new DelegateCommand<string>(SearchedFor, o => true);
        SuggestionRequest = new DelegateCommand<ISuggestionQuery>(SuggestionRequestFor, o => true);

        DataContext = this;
    }

    private void SuggestionRequestFor(ISuggestionQuery query)
    {
        IEnumerable<string> filteredQuery = _data
            .Where(suggestion => suggestion.StartsWith(query.QueryText,
                StringComparison.CurrentCultureIgnoreCase));
        query.Request.SearchSuggestionCollection.AppendQuerySuggestions(filteredQuery);
    }

    private readonly string[] _data = { "Banana", "Apple", "Meat", "Ham" };

    private void SearchedFor(string queryText)
    {
    }
}

I wrote up a full walk through on my blog, but the above is all you really need :)


text:
Q: Comparing each row to a solutions vector with the correct answer and converting the orginal values based on the solutions in dplyr I have one data frame containing the original answers and one dataframe that has the solutions to these answers. I want to compare the answers with the solutions and convert the original ones to 1/0 (correct and incorrect, I could use a boolean but for this analysis I require a numeric datatype).
This can easily be done by just using ifelse in transmute I believe, but the problem is that my columns are dynamic. I'm trying to make my script dynamic, so it can adapt to the amount of columns that the test has. So I can't call the columns directly in a logical test.
answers <- data.frame(x1 = c(3, 2, 1), x2 = c(2, 1, 2), x3 = c(1, 3, 1))
  x1 x2 x3
  3  2  1
  2  1  3
  1  2  1

solution <- data.frame(x1 = 3, x2 = 2, x3 = 1)
  x1 x2 x3
  3  2  1

Goal:
  x1 x2 x3
  1  1  1
  0  0  0
  0  1  1

I can solve this with a loop in base R, like this:
while(i <= nrow(df)){
  z <- 1
  while(z <= ncol(df)){
    if(!is.na(df[i,z])){
      if(df[i,z] == solutions[1,z]){
        df[i,z] <- 1
      }else{
        df[i,z] <- 0
      }
    }
    z <- z + 1
  }
  i <- i + 1
}

But I think this is a pretty cumbersome way of achieving this result. I was wondering whether dplyr has an easier way to achieve this? I've looked into using apply, but this is still base R and I'd like to know if this is possible within dplyr.

A: You can use across.
df1 %>%
  mutate(
    across(everything(), ~ifelse(. == df2[[cur_column()]], 1, 0)
  )
)

Assuming that df1 and df2 are your dataframes. Including your data as reproducible dataframes will help people to answer your questions, even if they are simple.
Edit: Thanks @akrun for the correction

A: @SEcker's response is much more elegant, but another alternative would be to pivot the data frames from wide to long in order to make the comparison, although this uses functions from tidyr so it's not strictly a dplyr solution.
library(tidyverse)

#create some random data
df <- tibble(X1 = ceiling(runif(10) * 5),
             X2 = ceiling(runif(10) * 5),
             X3 = ceiling(runif(10) * 5))

solutions <- tibble(X1 = ceiling(runif(10) * 5),
                    X2 = ceiling(runif(10) * 5),
                    X3 = ceiling(runif(10) * 5))

#Add a column to track the row, then pivot from wide to long
df %>%
  mutate(row = row_number()) %>%
  pivot_longer(-row,
               names_to = "column",
               values_to = "answer") %>%
  #Merge with a similarly transformed solutions df
  inner_join({
    solutions %>%
      mutate(row = row_number()) %>%
      pivot_longer(-row,
                   names_to = "column",
                   values_to = "solution")
  }, by = c("row", "column")) %>%
  #Check whether the answer matches the soltion
  mutate(is_correct = as.numeric(answer == solution)) %>%
  #pivot back to wide
  select(row, column, is_correct) %>%
  pivot_wider(id_cols = row,
              names_from = column,
              values_from = is_correct) %>%
  #no longer need the row
  select(-row)

# A tibble: 10 x 3
X1    X2    X3
<dbl> <dbl> <dbl>
1     1     0     0
2     0     0     0
3     0     1     0
4     0     0     0
5     1     1     0
6     0     0     1
7     1     1     0
8     0     0     0
9     0     1     1
10     0     0     0


text:
Q: Append file names to the end of lines I have many fasta files and want to append name of files to the end of lines (header line). I know how to do it 1 by 1 by sed but looking for a better solution to do for many files.
File1.txt
>1
ACGTA

File2.txt
>2
GTCA

What expected:
File1.txt
>1_File1
ACGTA

File2.txt
>2_File2
GTCA

This works for a single file using sed in OSX:
sed -i.bak '/>.*$/ s/$/_File1/' File1.txt

Thanks

A: You may need to change the expression depending on your file names, but basically you want to iterate through all the files
    #!/bin/bash
    for file in *.txt
    do
      #just for echo the current 'file' var for testing
      echo "$file"
      sed -i.bak '/>.*$/ s/$/_"$file"/' $file
    done

A: You can use Perl's inplace editing capabilities:
perl -i.bak -p0e '$ARGV =~ s/\..*//; s/>.*/$&_$ARGV/' File*.txt

A: You can use this simple for loop:
for f in *.txt; do
   sed -i '' 's/^>.*/&_'"${f%.*}"'/' "$f"
done

"${f%.*}" will strip extension from filenames.


text:
Q: Не исполняются sql запросы в node.js? При попытке зайти на страницу, где есть sql запросы в nоde.js, в консоли выводится предупреждение:
(node:29843) [DEP0096] DeprecationWarning: timers.unenroll() is deprecated. Please use clearTimeout instead.
И sql запрос в итоге не исполняется.
Никаких модулей типа timers я не устанавливал.
Аргумент err в функции запроса возвращает PROTOCOL_CONNECTION_LOST
Кусочек кода
`
app.get("/news", function(req, res) {
    res.set('Content-Type', 'application/json');
    c.query("SELECT `id`, `title`, `time`, CONCAT(SUBSTRING(`text`, 1, 300), '...') AS `text` FROM `news` ORDER BY `id` DESC", function(err, result) {
        res.send(JSON.stringify({
            success: true,
            err: err,
            data: result
        }));
    });
});

`
Модули, которые я подключаю
`
const express = require("express");
const app = express();
const mysql = require("mysql");
const needle = require('needle');
const fs = require("fs");
const md5 = require("md5");
var bodyParser = require('body-parser');
app.use(bodyParser.json()); // support json encoded bodies
app.use(bodyParser.urlencoded({ extended: true })); // support encoded bodies

`
Буду очень благодарен за все!


text:
Q: Is there a general formula for number of integral points inside the circle $x^2+y^2=a^2$ for $a \in \mathbb Z^+$ I could work out a general formula for number of integral (lattice) points lying on or inside the circle $x^2+y^2=a^2$, $a \in\mathbb{Z}^+$
See this
I tried to work out a general formula for number of integral (lattice) points lying strictly inside the circle $x^2+y^2=a^2$, $a \in\mathbb{Z}^+$. Well, I can remove points lying on the circle when in my formula term inside the greatest integer is an integer, but i was wondering if there is any general formula possible for the same.

A: I don't think there's a neat formula for it.
This is called the Gauss circle problem. You can find more details here https://en.m.wikipedia.org/wiki/Gauss_circle_problem.


text:
Q: Group mongo collection based on a value if present else dont group, show it as it is I want to group the following collection by "Company" attribute, only if Company attribute is available else don't group show as it is
Here is my collection.
{
    "_id":"Wagon R",
    "type": "Car",
    "Company": "Suzuki"
},
{
    "_id":"Ertiga",
    "type": "Car",
    "Company": "Suzuki"
},
{
    "_id":"Accent",
    "type": "Car",
    "Company": "Hyundai"
},
{
    "_id":"Camry",
    "type": "Car",
    "Company": "Toyoto"
},
{
    "_id":"Corollo",
    "type": "Car",
    "Company": "Toyoto"
},
{
    "_id":"M 800",
    "type": "Car",
    "Company": ""
},
{
    "_id":"E 800",
    "type": "Car",
},
{
    "_id":"X 800",
    "type": "Car",
}

The sample output required.
{
    "_id":"Wagon R",
},
{
    "_id":"Accent",
},
{
    "_id":"Camry",
},
{
    "_id":"M 800",
},
{
    "_id":"E 800",
},
{
    "_id":"X 800",
}

I tried with grouping, but its giving the collection which only has company attribute. I also want the records which doesnt have company attribute
Can someone please help
    {
        "$match" : ----
    },

    {
      "$group": {
        "_id": "$Company",
        "doc": {"$first":"$$ROOT"}

      }
    },
    {
        "$replaceRoot": {"newRoot":"$doc"}
    }

A: I got it worked with help of this query:
db.getCollection('test999').aggregate([
    {
        $addFields: {
            groupCompany:
            {
                $switch: {
                    branches: [
                        { case : { $lt : ["$Company", null]}, then : "$_id"},
                        { case : { $ne : ["$Company", ""]}, then: "$Company"},
                        { case : { $eq : ["$Company",""]}, then : "$_id"}
                    ]
                    ,default: "default"
                }
            }
        }
    },
    {
        "$group": {
            "_id": "$groupCompany",
            "doc": { "$first": "$$ROOT" }
        }
    },
    {
        "$replaceRoot": { "newRoot": "$doc" }
    }
]);


text:
Q: javascript cannot add element into dictionary I want to create a structure of dictionary lineChartData{ datasets:[ {dataset },{dataset }...{ dataset} ] } and in each dataset, {data:[1,2,3,...]}. But whenever I try to print console, I always get "[object object]", can anyone help me out please??
var lineChartData = {}; //declare an object
lineChartData.datasets = [];
for (line = 0; line < symptomSet.size; line++) {
    y = [];
    dataset = {};
    dataset.data = [];
    for(i=0; i< Object.keys(dataMap).length ; i++) {
      if(dataMap[Object.keys(dataMap)[i]][symptoms[line]]==null) {
        dataset.data.push(0);
      } else {
        dataset.data.push(dataMap[Object.keys(dataMap)[i]][symptoms[line]]);
      }
    }
    console.log("dataset:"+dataset); //always print "[object object]"
    lineChartData[datasets].push(dataset);
}

A: Turning Derek 朕會功夫's comment into an answer:
Do console.log("dataset:", dataset) instead. Concatenating a string with an object will execute dataset.toString, which returns "[object object]".


text:
Q: What is the difference between a forefather and an ancestor? Stumbled upon this question today while going through synonyms of various terms. I was advised that they are not synonymous to each other.
Please advise.

A: "Ancestors" has only one meaning.  Your ancestors are your relatives several generations back who lived, and, it is commonly understood, had already died, by the time you were born.

"My ancestors arrived in Australia from Ireland in the 1790s."
"Hominids are our human ancestors."

English-speakers sometimes use "forefather" as a synonym for "ancestor."

"Our forefathers passed these customs down to us."

But it also has a more fanciful meaning, often referring to the originator of an idea or tradition, or a person who established an important precedent in some sort of field, like "forerunner."

"Alan Turing is the forefather of modern computing."

A: Ancestors and forefathers are terms used interchangeably in some instances, as when referring to a general shared historical past, and there is an implied assumption that the deceased persons being referenced are both blood-related ancestors, and "persons of an earlier historical period and with a common heritage with us" - i.e., forefathers.  Example:  "our Pilgrim ancestors," or alternatively, "our Pilgrim forefathers."  When one but not both of those factors are present, one word is more applicable than the other.
I like to think of the difference as this:  ancestor refers to individual and personal family tree predecessors (from whom we inherit DNA internal to ourselves), and forefathers refers to multiple persons and communal, regional, or national predecessors (from whom we inherit language, customs, etc. external to our individual selves). I would say "my ancestors," but not "my forefathers," and - unless I was at a family reunion, I would say, "our forefathers and mothers," not "our ancestors."
Stated another way, ancestors implies a blood and familial relation, and forefathers does not imply a blood and familial relation; forefathers implies a common cultural, regional heritage and roots, and ancestors does not imply a common cultural, regional heritage and roots.  Those of us Americans with immigrant roots have ancestors who lived and spoke in ways radically different from us, and were not our forefathers. And conversely, those of us Americans with immigrant roots are expected, as I was, to accept the Pilgrims as among our American forefathers as the history books portray them.  As an aside, I believe the range of persons who ought to be included in the American forefathers category should be broadly expanded to include at a minimum certain Native American peoples and African captives who were sold into slavery.   Just saying'


text:
Q: Cancel NSMutableRequest and XMLParsing method ObjectiveC I need to cancel a NSMutableRequest and a XMLParsing if the user choose another view
I do this on ViewDidLoad:
NSMutableURLRequest * req = [[NSMutableURLRequest alloc]initWithURL:[NSURL URLWithString:endereco]
                                                        cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:20.0f];

conn = [NSURLConnection connectionWithRequest:req delegate:self];

[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;

if(conn)
{
    receivedData = [[NSMutableData alloc]init];
    [DSBezelActivityView newActivityViewForView:self.view withLabel:@"Obtendo Lista..."];
}

I know i have to : [conn cancel]; on viewWillDisappear, but how i can check i the connection is ocurring so i can cancel it?
And the same happens to the parse method :
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;

    NSXMLParser * parser = [[NSXMLParser alloc]initWithData:receivedData];
    [parser setDelegate:self];
    [parser parse];
    [parser release];
    [receivedData release];
}

A: You can achieve this by using two flags(BOOL variables). One flag will keep track of connection activity(whether connection is still in progress or has finishedLoading).
So, for connection (BOOL isConnectionActive)
set isConnectionActive = YES in viewDidLoad
and set it isConnectionActive = NO in connectionDidFinishLoading or connectionDidFailWithError delegate methods.
and check
if(isConnectionActive)
{
if(con != nil)
{
 [con cancel];
}
  isConnectionActive=NO;
}

in viewWillApear: method.
similar thing you can do for xmlParsing. you will set isParsingCompleted=NO
- (void)parserDidStartDocument:(NSXMLParser *)parser method.
and isParsingCompleted=YES
- (void)parserDidEndDocument:(NSXMLParser *)parser;

- (void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError;

methods and you will use
if(!isParsingCompleted)
{
if (parser!= nil)
{
   [parser abortParsing];
}
 isParsingCompleted=YES;
}

in viewWillApear: method.[for this you will need a class level reference for parser.]
Thanks,


text:
Q: Interop C# .net 6.0 Excel system.IO.FileNotFoundException could not load I have a question about .net 6.0 and Excel, specifically about interop.
I had a look at this post which seems similar but it doesn't really answer my question.
Is it possible to use .net 6.0 with Excel/Interop? if so how do I deal with the following issue;
    System.IO.FileNotFoundException     HResult=0x80070002

Message=Could not load file or assembly 'office, Version=15.0.0.0,
Culture=neutral, PublicKeyToken=71e9bce111e9429c'. The system cannot
find the file specified.   Source=   StackTrace

The code example im working with, rough draft
                using Microsoft.Office.Interop.Excel;

                Console.WriteLine($"Processing: {FullPathToFile}");
                string nameOfFile = FullPathToFile.Split('\\').Last();
                string newLocation = $@"{ProcessedDir}\{nameOfFile}";

                if (File.Exists(newLocation))
                    File.Delete(newLocation);

                var application = new Application();
                var workbook = application.Workbooks.Open(FullPathToFile);
                var workBookName = workbook.Name;

                int worksheetcount = workbook.Worksheets.Count;
                if (worksheetcount > 0)
                {
                    Worksheet worksheet = (Worksheet)workbook.Worksheets[1];
                    string worksheetName = worksheet.Name;

                    var csvFileName = ($@"{PickUpFileDir}\{nameOfFile.Split('.').First()}.csv");

                    worksheet.SaveAs(csvFileName);
                    //worksheet.ExportAsFixedFormat((XlFixedFormatType)XlFileFormat.xlCSVWindows, csvFileName);

                    Console.WriteLine(worksheetName);

All I want to achieve is to open an excel/ods file, then export the first worksheet as a CSV file.
Would be more than happy with a .net core 6.0 example for the demonstrating how C# can expoert the CSV from an excel file.
Should I be using ExportAsFixedFormat() and if so how do I specify CSV. I had a look at some documentation, but didn't get far.
or should I just be using .SaveAs() and in which case, how do I specify CSV as the output format?
Thanks