text:
Q: multiple where clauses in redbeanphp I'm using readbeanphp as ORM for my php project. I'm trying to load a bean with an additional where clasue. But i'm not sure how to do this.
Normally i'd get a 'bean' like this:
$book = R::load('book', $id);

Which is basically like saying:
SELECT * FROM book WHERE id = '$id'

But i need to add another condition in the where clause:
SELECT * FROM book WHERE id = '$id' AND active = 1

How can i do this with redbeanphp?

A: R::find() and R::findOne() is what you are looking for:
$beans=R::find("books","active=? AND id=?",array(1,1));

Or if you want a single bean only:
$bean=R::findOne("books","active=? AND id=?",array(1,1));

R::find() will return multiple beans, while R::findOne() returns just a single bean.
You technically could use R::load() but would have to use PHP to check the active field after the bean is loaded to test if it is valid:
$bean=R::load("book",$id);
if($bean->active==1){//valid
   //do stuff
}else{//not valid
   //return error
}

Hope this helps!

A: RedBean_Facade::load is using for primary key only.
if you want get beans by a complex query
use
R::find like,
$needles = R::find('needle',' haystack = :haystack
                                  ORDER BY :sortorder',
    array( ':sortorder'=>$sortorder, ':haystack'=>$haystack ));

Read more about R::find
http://www.redbeanphp.com/manual/finding_beans
try to use getAll to write your query directly with parameters
R::getAll( 'select * from book where
id= :id AND active = :act',
array(':id'=>$id,':act' => 1) );

Read more about queries,
http://www.redbeanphp.com/manual/queries

A: these answers are fine but can be simplified. What you should use is:
$book = R::find('books', id =:id AND active =:active, array('id' => $id, 'active' => 1));

And then you can do your standard foreach to loop through the returned array of data.


text:
Q: Entity Framework Oracle connection I use entity framework but I can not connect to the oracle database
using System.Data.Entity;
using Oracle.ManagedDataAccess.Client;
public class EShopContext :DbContext
{
    public EShopContext(bool oracle) : base(new OracleConnection("User Id=ETICARET;Password=medoc; DATA SOURCE=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=192.168.1.202)(PORT=1522))(CONNECT_DATA=(SERVER =192.168.1.202)(SID=XE)))"),true)
    {

    }
    public EShopContext() : base("Server=.;Database=ETicaret;User Id=sa;Password=a93c85y85") //sql connection String
    {

    }
    public virtual DbSet<Admin> Admins { get; set; }
}

protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);
        using (var context = new EShopContext(true))
        {
            try
            {
                context.Database.CreateIfNotExists();
            }
            catch (Exception ex)
            {
            }
        }

    }

context.Database.CreateIfNotExists();

throw exception => {"An error occurred accessing the database. This usually means that the connection to the database failed. Check that the connection string is correct and that the appropriate DbContext constructor is being used to specify it or find it in the application's config file. See http://go.microsoft.com/fwlink/?LinkId=386386 for information on DbContext and connections. See the inner exception for details of the failure."}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Parsing JSON data containing unicode characters I have UTF8 encoded a json file containing unicode characters stored in AWS S3 storage. To be able to download that file from my React project, I've created AWS Gateway API and Lambda function. In the project, I used Axios library to download that file and it seems to be downloaded properly (I check the content with console.log). However, when I parse the file using JSON.parse, I get "bad control character in string literal" error. Checking the content with JSON validators return positive and the http-response header from API Gateway is set properly to "content-type:application/json" and "charset:utf-8". JSON.parse only works when I delete all UTF8 unicode characters from my file. When I remove sections that contain unicode characters, I don't even need to use JSON parse. I can access it as an object from my script. This is the content of my json file
{
  "en": [
    {
      "Question": "Question 1",
      "Choice": [ "Strongly  Agree", "Agree", "Neither Agree Nor Disagree", "Disagree", "Strongly Disagree" ]
    },
    {
      "Question": "Question 2",
      "Choice": [ "Strongly  Agree", "Agree", "Neither Agree Nor Disagree", "Disagree", "Strongly Disagree" ]
    },
    {
      "Question": "Question 3",
      "Choice": [ "Strongly  Agree", "Agree", "Neither Agree Nor Disagree", "Disagree", "Strongly Disagree" ]
    },
    {
      "Question": "Question 4",
      "Choice": [ "Strongly  Agree", "Agree", "Neither Agree Nor Disagree", "Disagree", "Strongly Disagree" ]
    }
  ],
  "fr": [
    {
      "Question": "Question 1",
      "Choice": [ "Tout À Fait d'Accord", "d'Accord", "Ni En Désaccord Ni d'Accord", "Pas d'Accord", "Pas Du Tout d'Accord"]
    },
    {
      "Question": "Question 2",
      "Choice": [ "Tout À Fait d'Accord", "d'Accord", "Ni En Désaccord Ni d'Accord", "Pas d'Accord", "Pas Du Tout d'Accord"]
    },
    {
      "Question": "Question 3",
      "Choice": [ "Tout À Fait d'Accord", "d'Accord", "Ni En Désaccord Ni d'Accord", "Pas d'Accord", "Pas Du Tout d'Accord"]
    },
    {
      "Question": "Question 4",
      "Choice": [ "Tout À Fait d'Accord", "d'Accord", "Ni En Désaccord Ni d'Accord", "Pas d'Accord", "Pas Du Tout d'Accord"]
    }
  ],
  "pt": [
    {
      "Question": "Questão 1",
      "Choice": [ "Concordo Plenamente", "Aceita", "Não Concordo Nem Discordo", "Discordar", "Discordo Fortemente" ]
    },
    {
      "Question": "Questão 2",
      "Choice": [ "Concordo Plenamente", "Aceita", "Não Concordo Nem Discordo", "Discordar", "Discordo Fortemente" ]
    },
    {
      "Question": "Questão 3",
      "Choice": [ "Concordo Plenamente", "Aceita", "Não Concordo Nem Discordo", "Discordar", "Discordo Fortemente" ]
    },
    {
      "Question": "Questão 4",
      "Choice": [ "Concordo Plenamente", "Aceita", "Não Concordo Nem Discordo", "Discordar", "Discordo Fortemente" ]
    }
  ],
  "my": [
    {
      "Question": "မေးခွန်း ၁",
      "Choice": [ "အပြည့်အ၀ထောက်ခံတယ်", "ထောက်ခံတယ်", "ထောက်ခံတယ်လည်းမဟုတ်ဘူး မထောက်ခံတယ်လည်းမဟုတ်ဘူး", "မထောက်ခံဘူး", "အပြည့်အ၀မထောက်ခံဘူး" ]
    },
    {
      "Question": "မေးခွန်း ၂",
      "Choice": [ "Strongly  Disagree", "Somewhat Disagree", "Agree", "Somewhat Agree", "Strongly Agree" ]
    },
    {
      "Question": "မေးခွန်း ၃",
      "Choice": [ "Strongly  Disagree", "Somewhat Disagree", "Agree", "Somewhat Agree", "Strongly Agree" ]
    },
    {
      "Question": "မေးခွန်း ၄",
      "Choice": [ "Strongly  Disagree", "Somewhat Disagree", "Agree", "Somewhat Agree", "Strongly Agree" ]
    }
  ]
}

EDIT
This is code responsible for downloading and parsing that file :
    let request = {
        host: process.env.AWS_HOST,
        method: 'GET',
        url: process.env.AWS_URL,
        path: process.env.AWS_PATH
    }

    let signedRequest = aws4.sign(request, {
        secretAccessKey: process.env.AWS_SECRET_KEY,
        accessKeyId: process.env.AWS_ACCESS_KEY
     });

    axios(signedRequest)
        .then(response => {

            console.log(response.data);

            JSON.parse(response.data); // Error!

        })
        .catch((error) => {
            console.log("error",error);
        });

EDIT
I corrected the title to reflect the question I'm asking.

A: I just figured out that it was my lambda function causing this issue. The function  reads the file from s3 bucket and encode the data as ascii before returning as response. Fixing it to utf-8 resolve the issue. Thanks @Tomalak for your time.
const done = (err, res) => callback(null, {
    statusCode: err ? '400' : '200',
    body: err ? err.message :  res.Body.toString('utf-8'), // <<-- this line
    headers: {
        'Content-Type': 'application/json',
        'Charset': 'utf-8',
        "'Access-Control-Allow-Methods": "GET, POST, OPTIONS"
    },
});


text:
Q: Sudden "Cannot contact site at the specified url" error for no apparent reason I have a SharePoint site with a few subsites.
I also have a C# program which connect to one of these subsites and import files to SharePoint. A few days ago, I installed this program on a Windows Server 2008 R2 SP1 Standard server (since it was mostly for test purposes, I just copied my project's bin/Release to the server).
It worked flawlessly for a day, then, for no apparent reason, it stopped working. There has been no known changes on the server.

I did some research, and conclude the issue could be linked to the DLL Microsoft.SharePoint.Client and Microsoft.SharePoint.Client.Runtime, since they were not initially distributed with my program.
The program still runs fine on another server and on my machine, and I can access the SharePoint sites from the server using a internet browser, and of course from any other machine.
What I did try:

*

*Including the DLL in my program's folder

*Deleting these DLLs from the GAC

*Reinstalling in the GAC

*Tried older versions of my program

*Checked for outdated password
What I haven't/couldn't try:

*

*Edit web.config: I have no idea how to access it, since I don't have any known access to the site. Then again, the program works fine on other machines, so I guess the issue isn't website-sided.

*Reinstall .NET framework: If I can avoid doing this, I'm OK, but if there's no choice left...

The error remains the exact same:
à Microsoft.SharePoint.Client.ClientContext.EnsureFormDigest()
à Microsoft.SharePoint.Client.ClientContext.ExecuteQuery()
à MyNamespace.MyClass.getLibraries()
à MyNamespace.Forms.MainWindow.<>c__DisplayClass9.<doConnection>b__4()
Microsoft.SharePoint.Client/Void EnsureFormDigest()/Cannot contact site at the specified URL
https://mydomain.sharepoint.com

Any idea on this issue? I will edit if more information is needed.

A: "Cannot contact site at the specified URL https://mydomain.sharepoint.com" <-- the domain here is a generic one which leads me to believe that one of your libraries (dll's) is not being loaded correctly and a Default domain value is being used (like an internal static reference)
I recommend you update the service pack on the R2 server to the latest release you can find and then re-deploy your app to /Release and try again.
as a sanity check, look at the version numbers of the Microsoft.SharePoint.Client and Microsoft.SharePoint.Client.Runtime dll files on any server that is working and then try to get the same files over to the r2 server.


text:
Q: Retrieve Contact name from phone number I've been looking everywhere since the past few days to find a way to retrieve a contact name using a phone number I already have stored in a variable, unfortunately everything I found so far seems to be using deprecated functions/calls.
Of Course, I tried doing it my own way but I feel like my Android/JAVA knowledge is not good enough to understand this concept yet, keep getting some errors or force close when I try to run anything.
So far the best thing I could find was something like this:
public String getContactName(final String phoneNumber)
    {
        Uri uri;
        String[] projection;

        if (Build.VERSION.SDK_INT >= 5)
        {
            uri = Uri.parse("content://com.android.contacts/phone_lookup");
            projection = new String[] { "display_name" };
        }
        else
        {
            uri = Uri.parse("content://contacts/phones/filter");
            projection = new String[] { "name" };
        }

        uri = Uri.withAppendedPath(uri, Uri.encode(phoneNumber));
        Cursor cursor = context.getContentResolver().query(uri, projection, null, null, null);

        String contactName = "";

        if (cursor.moveToFirst())
        {
            contactName = cursor.getString(0);
        }

        cursor.close();
        cursor = null;

        return contactName;
    }

But by using this code, Eclipse tells me: context cannot be resolved.
A lot of the codes and explanations I found were using this Context thing, but I still don't understand it even after reading this: What is 'Context' on Android?
Any help will be greatly appreciated,
Thank you very much

A: If you're using this inside an activity, then a context is what you get by using this. So basically here, instead of calling context.getContentResolver(), call this.getContentResolver() or simply just getContentResolver().
Eclipse complains basically because you're trying to call a method of something called context which Eclipse doesn't know because it hasn't been declared anywhere. It would work if you previously did something like Context context = this;, but that's really useless.
getContentResolver() is a method declared and defined by Activity which is a class that your activity extends, therefore you can call it just like that.
I hope it helps. As to what this context really is, I am sorry, but I can't help you with that as I am not even sure I understand it correctly.
Also, please notice, that I haven't checked the code you posted and I don't know if it works for obtaining a contact's name from a phone number. Just wanted to help you with getting rid of the context cannot be resolved error.


text:
Q: Phonegap - can't add plugin using CLI When trying to add a plugin, I get the following error:
   phonegap local plugin add https://git-wip-us.apache.org
    /repos/asf/cordova-plugin-device.git
    [phonegap] adding the plugin: https://git-wip-us.apache.org/repos/asf/cordova-pl
    ugin-device.git

    fs.js:427
      return binding.open(pathModule._makeLong(path), stringToFlags(flags), mode);
                     ^
    Error: ENOENT, no such file or directory 'C:\DOCUME~1\k\USTAWI~1\Temp\plugma
    n-tmp1379488251610\plugin.xml'
        at Object.fs.openSync (fs.js:427:18)
        at Object.fs.readFileSync (fs.js:284:15)
        at Object.module.exports.parseElementtreeSync (C:\Documents and Settings\k\Dane aplikacji\npm\node_modules\phonegap\node_modules\cordova\node_modules\pl
    ugman\src\util\xml-helpers.js:107:27)
        at C:\Documents and Settings\k\Dane aplikacji\npm\node_modules\phonegap\
    node_modules\cordova\node_modules\plugman\src\util\plugins.js:67:39
        at C:\Documents and Settings\k\Dane aplikacji\npm\node_modules\phonegap\
    node_modules\cordova\node_modules\shelljs\shell.js:1707:7
        at ChildProcess.exithandler (child_process.js:641:7)
        at ChildProcess.EventEmitter.emit (events.js:98:17)
        at maybeClose (child_process.js:735:16)
        at Process.ChildProcess._handle.onexit (child_process.js:802:5)

I tried to solve that problem using advice from here , but it does not change anything.
Will be really grateful for any suggestions how to solve that issue.

A: If anybody had similar problem with PhoneGap on Windows - installing the latest Git version solves all the problems...


text:
Q: Equivalent condition for Cauchy Sequences I am trying to prove the following :
Let $E$ be a topologic vector space. $(x_n)\subset E$ is a Cauchy sequence in $E \ $ iff $\ \lim_{k\to\infty}(x_{m_k}-x_{n_k})=0$ for any $n_k, m_k$ pair of strictly increasing sequences of $\Bbb N$.
I know that $x_n$ is a Cauchy sequence in $E \ $ means
$\forall V\in\mathscr V_0 \ \ \ \exists n_0\in \Bbb N \ \ \textrm{such that} \ \ \forall n,m\geq n_0 \ \ x_n-x_m\in V$ where $\mathscr V_0 $ is collection of nbds of zero.
I am sorry for this easy question but I even don't know how should I start because it seems as if there is nothing to prove.  Thanks in advance for any help for any direction of this proposition.
I appreciate any help.

A: "It seems as if there is nothing to prove" - this is not true, but it is not difficult.

*

*Let $(x_n)$ be a Cauchy sequence in the sense of your definition. Let $V\in\mathscr V_0$ and $(m_k), (n_k)$ be two strictly increasing sequences of integers. We know that $x_m - x_n \in V$ for $n \ge n_0$. Since $(m_k), (n_k)$ are strictly increasing, there exists $k_0$ such that $m_k , n_k \ge n_0$ for $k \ge k_0$. Hence $x_{m_k}-x_{n_k} \in V$ for $k \ge k_0$. This shows that  $ \lim_{k\to\infty}(x_{m_k}-x_{n_k})=0$ .

*Let the limit condition be satisfied. Let $V\in\mathscr V_0$. Assume that
for all $n_0$ there exist $m,n \ge n_0$ such that $x_{m}-x_{n} \notin V$. This can be used to construct inductively strictly increasing sequences of integers such that $x_{m_k}-x_{n_k} \notin V$ for all $k$.Then certainly $(x_{m_k}-x_{n_k})$ cannot have the limit $0$, a contradiction.


text:
Q: ImageView fills different screen sizes, but maintaing the aspect ratio I have a rectangular image in an image view. I want to fit the image in the screen for different screen sizes while maintaining the aspect ratio.
In smaller screen its working fine, but its not getting stretched in biggerscreens. Some gap remains in the bottom of the image.
This is my code:
LayoutParams params = new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT);
LayoutParams params1 = new LayoutParam(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);

mMainLayout = new LinearLayout(context);
mMainLayout.setLayoutParams(params);

backgroundImage = new ImageView(context);
backgroundImage.setId(0);
backgroundImage.setAdjustViewBounds(true);
backgroundImage.setScaleType(ScaleType.FIT_CENTER);
backgroundImage.setLayoutParams(params1);
backgroundImage.setImageResource(R.drawable.background_circles_en);

mMainLayout.addView(backgroundImage);

I have used many combinations of fill_parent, wrap_content with multiple scaleTypes: fitCenter, centerInsideand they all draw the images in the right aspect ratio, but none of them actually scale the images up and the ImageView itself, resulting in either the TextViews get pushed all the way down off the screen, blank spaces inside the ImageView, or image not scaled.
Please give a right combination so that it will work properly for different screen sizes.

A: Privide ScaleType FIT_XY, it will scale image to x and y dimensions, irrespective of aspect ratio.


text:
Q: Difference between the Kohana's Request cookie(), Response cookie() and the Cookie class? I'm working on a program dealing with cookies under the kohana's HMVC structure, and I find that Kohana has 3 ways to get/set the cookie. They are
Request::current()->cookie(), Response->cookie(), and the cookie class (Cookie::set(), get())
And PHP has a native setcookie() function and $_COOKIE to deal with cookies too.
Could anyone explain their differences and, what are the situations that they should be used respectively.

A: Request::cookie() prior to calling Request::execute() on the same object is used to set the cookies that will be send (or have been sent in case of the initial request) along with the rest of the request.
Request::cookie() during a Request::execute() will replace $_COOKIE.
Response::cookie() during a Request::execute() will replace setcookie().
Response::cookie() after a Request::execute() is used to get the cookies set back by the server.
The Cookie helper will sign your cookies and is used by HTTP_Header to set cookies set to the Response object in your initial Request object (see Response::send_headers() in index.php).
You probably do not want to use it yourself directly if you are trying to code HMVC safe.


text:
Q: Blank Windows Feature list when loading through C# I want to be able to open the "Windows Features" menu in my C# application, but for some reason, it'll show a blank Windows Features list, but only on some machines. I've ran this on another Windows 7 VM and it worked perfectly fine, but when doing this on my machine (and my friends machine), it left us with a blank list.
Here's the code I use to open "Windows Features". If I run this with CMD manually it works files however - only in the C# application will it cause problems.
Process.Start("OptionalFeatures.exe");

The same problem will happen if I use this as well
Process.Start("control.exe", "appwiz.cpl,,2");

Any ideas on why this is happening..?

A: Try specifying a platform target corresponding to your OS platform.
I assume the computers that run into this problem are 64 bit machines and your application runs in 32bit mode. So try specifying either platform target = AnyCpu AND disable the checkbox "prefer 32 bit" or set the platform target to 64bit.


text:
Q: Open .rda file in a Shiny app uploaded to shinyapps.io I am trying to achieve the following:

*

*Deploy a Shiny app to shinyapps.io

*On open, the app connects to Sharepoint

*Downloads and opens a .rda file stored there. That file contains proprietary data where only people with the relevant credentials can get access to.

This allows me to separate access to the app from access to the data (only if you have the relevant credentials you can get the data file - the .rda). It also means an upload of a much slimmer set of information to the shinyapps.io servers.
It all works fine within R-studio as the download operation sticks the .rda into the local folder and the load operation takes the objects serialized there into the environment.
It fails (predictably) once the app is deployed to shinyapps.io: I suspect the "download" stops meaning anything.
Ideally there should be a "open" action which opens the .rda and then takes the relevant objects into the environment. I really couldn't find it.
This is the code that works within R-Studio (I cannot obviously share the precise details of the Sharepoint site), any help figuring out the correct workflow strategy so it could work on shinyapps.io would be really appreciated.
library(Microsoft365R)

site <- get_sharepoint_site(site_id = "idOfTheSharepointSite")
docs <- site$get_drive()

docs$download_file("Stuff/DelSet.Rda", overwrite = T)

load("DelSet.Rda")

EDIT
The actual problem is not the management of the file itself (the comment below should address that). It's the autentication on Sharepoint within Shinyapps.io.
This barebone app fails as well (while working as expected on R-studio).
library(shiny)
library(Microsoft365R)

site <- get_sharepoint_site(site_id = "IDofMySite")
docs <- site$get_drive()

ui <- fluidPage(h5("Hello world!"))

server <- function(input, output) {}
shinyApp(ui = ui, server = server)

A: Normally when you call the Microsoft365R functions like get_sharepoint_site(), they authenticate using a builtin app registration ID that assumes the code is running on your local machine. This won't work when your code is on a remote server, like shinyapps.io. Instead you have to register your app with Azure, and use the resulting app ID when authenticating.
The process is basically:

*

*Create an app registration that contains information about your site, including the redirect URI (your site address), and who is allowed to use it (everyone or only people in your org). You can do this in the Azure portal, or with the CLI.

*Give the app registration the necessary permissions for working with MS365. They are all Microsoft Graph permissions, and the scopes have the base URI https://graph.microsoft.com/*.

*In your Shiny UI script, call build_authorization_uri with the required scopes, your tenant, and your app ID

*In the server script, call get_azure_token and pass it the authcode, as shown in the AzureAuth Shiny vignette

*Use the token in your call to get_sharepoint_site.

A draft vignette describing the process and providing a simple Shiny app skeleton is here: https://github.com/Azure/Microsoft365R/blob/master/vignettes/shiny.Rmd


text:
Q: searching multiple columns with one or more keywords using sql I have one search box that I would like to have search 6 columns in my schools database when an input is made. So far the search box searches the name field only and returns a match for exact or partial inputs.
I would like to search for a specific city and have all results show up from the name AND city columns (instead of just the name column) and so on.
Say I wanted to search with a zip code, I would like the listings to be all schools in that zip code. And finally if I input 2 words (e.g. penn Philadelphia) I would like all penn schools to show that are in the name column AND city column only. (not just all the penns in the name or every school in Philadelphia) and so on. These may be an elementary questions on the matter but I've been searching for days with no success. Maybe better use of wildcards and the "AND" "OR" clauses would benefit me.
Can someone help me structure a sql query to accomplish this?
this is what I have so far:
SELECT * FROM schools
WHERE (name='%name%' OR address='%name%' OR city='%name%'OR zip='%name%')

A: There are few ways to do that-
The very basic strategy is to match input with our table columns by the query like as you mentioned -
1. SELECT * FROM table WHERE (name='%name%' or zip='%name%' or city='%name%');

2. SELECT * FROM table WHERE LOCATE(name, GROUP_CONCAT(name,city,zip)) > 0;

3.
SELECT * FROM table WHERE name like '%name%'
          UNION
SELECT * FROM table WHERE name like '%name%'
          UNION
SELECT * FROM table WHERE name like '%name%';

but suppose the case where input box have the string- "varun bharti" but actual name in database is "varun bal bharti" So when you search you will missed the record. for that case you should break the string by space in to array elements and use these queries for elements or either you can replace the space in name column and match.
set @var=REPLACE ('varun bharti', ' ', '%');
SELECT * FROM table WHERE name like concat('%',@var,'%') or
         zip like concat('%',@var,'%') or
         city like concat('%',@var,'%');

You can also use regualar expressions for that.
For example input string the day boss get
Hitesh> select * from test;
+--------------------+
| name               |
+--------------------+
| i am the boss      |
| You will get soon  |
| Happy birthday bro |
| the beautiful girl |
| oyee its sunday    |
+--------------------+
5 rows in set (0.00 sec)

Hitesh> set @var=CONCAT('.*',REPLACE('the day boss get',' ','.*|.*'),'.*');
Query OK, 0 rows affected (0.00 sec)

Hitesh> select @var;
+----------------------------------+
| @var                             |
+----------------------------------+
| .*the.*|.*day.*|.*boss.*|.*get.* |
+----------------------------------+
1 row in set (0.00 sec)

Hitesh> select * from test where name  REGEXP @var;
+--------------------+
| name               |
+--------------------+
| i am the boss      |
| You will get soon  |
| Happy birthday bro |
| the beautiful girl |
| oyee its sunday    |
+--------------------+
5 rows in set (0.00 sec)


text:
Q: Autowiring in implementation classes of an interface in Spring I'm having a Spring boot application in which based on a variable, I need to call corresponding implementation classes of an interface. This is what I have right now:
public interface Parent{
    public void call();
}

public class ABC implements Parent{
    public void call(){
        System.out.println("Called ABC");
    }
}

public class XYZ implements Parent{
    public void call(){
        System.out.println("Called XYZ");
    }
}

@Service("caller")
public class Caller{
    @Autowired
    protected OrderInfoRepository orderInfoRepository;

    AnnotationConfigApplicationContext context;

    public Caller(){
        context = new AnnotationConfigApplicationContext(Config.class);
    }

    public void callMethod(String param){
        Parent p = (Parent) context.getBean(param+"_Caller");
        p.call();
    }
}

@Configuration
public class Config{
    @Bean(name="ABC_Caller")
    public Parent getABC(){
        return new ABC();
    }

    @Bean(name="XYZ_Caller")
    public Parent getXYZ(){
        return new XYZ();
    }
}

@Repository
public interface MyRepo extends Repository<MyDAO, Long> {
    // ....
}

Basically what I want to do is, based on the param passed to Caller.callMethod(), I want to add "_Caller" to the param, and call the corresponding implementation class. So, I'm defining a @Configuration class, where I define which implementation class to return. And then using the AnnotationConfigApplicationContext, I get the corresponding bean. This works fine.
The problem I'm having is, when I try to Autowire anything in the implementation classes, I get a NoSuchBeanDefinitionException. For instance, when I autowire in the implementation class ABC
public class ABC implements Parent{
    @Autowired
    MyRepo myRepo;

    public void call(){
        System.out.println("Called ABC");
    }
}

I get Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.persistence.repositories.MyRepo] when I try to start the application. However, when I do the Autowiring in the Caller class instead, it works fine. I had asked a similar question a while back, but was not able to resolve it. Any ideas?


text:
Q: Comparing intersection between two nodes using broadcast variable and using RDD.filter in Spark GraphX i work on graphs in GraphX. by using the below code i have made a variable to store neighbors of nodes in RDD:
val all_neighbors: VertexRDD[Array[VertexId]] = graph.collectNeighborIds(EdgeDirection.Either)

i used broadcast variable to broadcast neighbors to all slaves by using below code:
val broadcastVar = all_neighbors.collect().toMap
val nvalues = sc.broadcast(broadcastVar)

i want to compute intersection between two nodes neighbors. for example intersection between node 1 and node 2 neighbors.
At first i use this code for computing intersection that uses the broadcast variable nvalues:
val common_neighbors=nvalues.value(1).intersect(nvalues.value(2))

and once i used the below code for computing intersection of two nodes:
val common_neighbors2=(all_neighbors.filter(x=>x._1==1)).intersection(all_neighbors.filter(x=>x._1==2))

my question is this: which one of the above methods is efficient and more distributed and parallel? using the broadcast variable nvalue for computing intersection or using filtering RDD method?

A: I think it depends on the situation.
In the case where your nvalues size is less and can fit into each executor and driver node, the approach with broadcasting will be optimal as data is cached in executors and this data is not recomputed over and over again. Also, it will save spark a huge communication and compute burden. In such cases, the other approach is not optimal as it might happen that all_neighbours rdd is calculated every time and this will decrease the performance as there will be a lot of recomputations and will increase computation cost.
In the case where your nvalues cannot fit into each executor and driver node,
broadcasting will not work as it will throw an error. Hence, there is no option left but to use the second approach though it might still cause performance issues at least code will work!!
Let me know if it helps!!


text:
Q: Qt: Not registered qRegisterMetaType() Im new in Qt and im trying to execute a program in a python subprocess:
class MiThread(threading.Thread):
      def __init__(self):
          threading.Thread.__init__(self)

      def run(self):
        try:
            from Queue import Queue, Empty
        except ImportError:
    #from queue import Queue, Empty  # python 3.x
            print "error"
        ON_POSIX = 'posix' in sys.builtin_module_names

        def enqueue_output(out, queue):
            for line in iter(out.readline, b''):
                queue.put(line)
            out.close()
        p= Popen(["java -Xmx256m -jar bin/HelloWorld.jar"],cwd=r'/home/karen/sphinx4-1.0beta5-src/sphinx4-1.0beta5/',stdout=PIPE, shell=True, bufsize= 4024)
        q = Queue()
        t = Thread(target=enqueue_output, args=(p.stdout, q))
        print "estoy en el hilo"
        t.daemon = True # thread dies with the program
        t.start()

But when i execute  it fails with the following error:
QObject::connect: Cannot queue arguments of type 'QTextCursor'
(Make sure 'QTextCursor' is registered using qRegisterMetaType().)

How can i fix it?


text:
Q: Laravel: How to configure api.php routes for shared hosting? I have the following .htaccess fille:
<IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews -Indexes
    </IfModule>

    RewriteEngine On

    # Handle Authorization Header
    RewriteCond %{HTTP:Authorization} .
    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

    # Redirect Trailing Slashes If Not A Folder...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} (.+)/$
    RewriteRule ^ %1 [L,R=301]

    # Send Requests To Front Controller...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]
</IfModule>

#disable directory browsing
Options -Indexes

#PROTECT ENV FILE
<Files .env>
order allow,deny
Deny from all
</Files>

#PROTECT ENV FILE
<Files .htaccess>
order allow,deny
Deny from all
</Files>

But the problem is I get a 404 status code in my production environment when trying to load "getservicedata" from a vue.js component. I think the problem is in the URL because it works when I type in the correct url, but the problem is the app loads the API from wrong URL.
I followed this guide to setup laravel shared hosting: https://laravelarticle.com/deploy-laravel-on-shared-hosting


text:
Q: qt future isRunning() vs isStarted() what is the difference between them? from docs, it says "currently running" vs "has been started"?
For example, two thread, one is main, the other is called A.
If currently, main is running, and A started once(). Will A.isRunning() return false? will A.isStarted() return ture?
what if A never starts?

A: The docs could be clearer. From reading the source code I can see that it enters Started state once, when the function is first run, and that flag doesn't get cleared (even if task is cancelled). So A.isStarted() should return true.  isRunning() however is the actual current state, which depends on current progress (eg. !isFinished()), or is false for example if it was paused or cancelled (or caught an exception).


text:
Q: Modify facet labels using ggpubr package in R I am using the ggscatter function in the ggpubr package in R. See following code using the ToothGrowth dataset as an example:
library("ggpubr")
ggscatter(ToothGrowth, x = "dose", y = "len",
  color = "supp", facet.by = "supp")

I would like to add the sample sizes (n) to the facet labels, so that they read: "OJ (n=30)" and "VC (n=30)". I assume that I need to use "panel.labs". Instructions say:
panel.labs = list(sex = c("Male", "Female"), rx = c("Obs", "Lev", "Lev2")

But I am not able to modify this to get where I hope to get. It also was not clear what "rx" means. Any suggestions would be terrific. Thank you.
Edit
Thanks for your answers below. I would like to clarify that I would like to include the "n=30" in the code, so that the '30' is automatically added from the data, not just as a text label saying 'n=30'. I need to do this at a larger scale, on which it is not possible to add each individually as text. Apologies for not being clearer in my initial question. Thank you.

A: This worked for me (as an argument to ggscatter). It needs to have the variable name that hold the factor variable name and then it need to have the items in the proper order, in this case the OJ label first:
panel.labs = list( supp=c( "OJ (n=30)" , "VC (n=30)") ) )


text:
Q: Background color of UIActivityIndicator on UITableViewCell is overridden Using iOS 6, Xcode 4.5.
I have a UIActivityIndicator that is on a UITableViewCell (using dynamic prototype cells).  When I call startAnimating, the background color of the activity indicator is changing to transparent.  This occurs whether I create the activity indicator in the storyboard file or if I create the activity indicator programatically.  However, if I place an activity indicator on a "normal" view, the background color is not changed when I call startAnimating.
Does anyone know what causes the change to a transparent background when animating on a TableViewCell?
I can work around it if I set the background color back to what I want, but only after the indicator has actually started animating (i.e. after the screen is redrawn at least once).  However, I'd like to understand the cause if possible, or report it as a bug if there doesn't seem to be a logical explanation of why it occurs.


text:
Q: Unknown class FirstViewController in Interface Builder file When I run my application i got this
I see in my console this message "Unknown class FirstViewController in Interface Builder file."
I am running TabBar application.
How can I fix this?

A: Right click on Storyboard --> Open As --> Source Code
Find your unknown class name in the storyboard source file. It may be because you have accidentally assigned a custom class name for one of your UIView subclass'.

A: It is kinda hard to understand your comments, but I think you may have deleted the FirstViewController but forgot to change all the references to it. you may need to go to MainWindow.xib and look for all FirstViewController UI components and delete them

A: It looks like you deleted FirstViewController.h & .m from project, but forgot to change view controller's class in nib file.

A: Go to project , targets , build phases , compile Sources and add the unknown class  ..done.

A: Sometimes it happens when you change target name for some reason, you have then to open storyboard as source file, then search for old target name, replace it with the new name, should work if it is the case, hope it helps.

A: This can also happen if you use the same package name for multiple projects (if you're being lazy with your provisioning). Go into your user directory, then go to Library/Application Support/iPhone Simulator/[your sdk version]/Applications and delete what's in there. You may also have to delete the app from the device. That will remove any accidental references to files from other projects, which can cause this error.

A: When you add multi project to Workspace. If you use the same Product Name in your's projects. It can conflict.
Rename Product Name in the projects have a same name.
... Hope this help ....

A: This happened to me just after Git merge and resolving few conflicts.
It had screwed up my XCode project.
I tried all over the StackOverflow. At first I thought my Custom class .m file hasn't been added to the Compile Sources class list. But it's one case, however even after adding it, it gave me same issue back.
How I resolved:

*

*I kept a backup of my .xib file and its backing custom class .m and .h files.

*Then clean the project and try to run the app via XCode (which might not work)

*Then re-add the files back to the XCode project and it will work.

Cheers!

A: This can sometimes happen if you made changes to a VC i.e. deleted prototype cell(s) within a tableview.
If all else fails I find cleaning project and restarting Xcode gets things back on track.


text:
Q: How to generate an exectutable file with netbeans 8.2 in linux I installed NetBeans 8.2 (but the same is for any version of NetBeans C/C++)  in a linux OS (Linux Mint Ulyssa, which based to what i know is ubuntu core. I can run successfully with the expected result a project (simple "hello world") but can't in the build folder of the project i can't find a file that i can execute in Linux.
What am i missing, what would the extention of the file be in Linux. Doing the same process in windows i can find the *.exe in the build folder but in linux can't find a way to create a single runnable file that i can run on any other Linux OS (of course, on the compatible ones).

A: So I don't run netbeans 8.2, but I got a hold of 12.2. And they seem pretty similar.
What I had to do to get the project running was to create the compile (build) command:
g++ main.cpp -o main

And in run I did:
./main

This allowed me to run a hello world code example through netbeans. In case you're not familiar with g++ the -o argument allows you to set a output-filename.
The code I ran was a simple "hello world":
#include <stdio.h>

int main() {
    printf("Hello World\n");
    return 0;
}

From what I understood in your comments you named the file and output test, so you should change that from my example.
I'm not sure if this solved your problem as the initial description was a bit hard to understand. But this is what I gathered from the information you gave.
To make a desktop runable application from your c-program, you can do the following.
If you want it to be executable from the users account make a <program>.desktop file and place it in ~/.local/share/applications/<program>.desktop this will allow the user to execute it witout using a terminal. If you want it to be global then place it inside of /usr/share/applications
This is the desktop-file
[Desktop Entry]
Version=1.0
Type=Application
Exec=xfce4-terminal -e "/PATH/BINARY"
Name=SCRIPTNAME

And this is the updated version of hello world, if you don't add the scanf then the program just executes without you noticing it.
#include <stdio.h>

int main(int argc, char * argv[]) {
    printf("Hello World\n");

    //Keep the program running until input
    char ch;
    scanf("%c", &ch);
    return 0;
}

Hope this helps you out.


text:
Q: Throw an error / catch from within a promise then method I've been searching for a while to find a way to trigger an error / catch from within a promise 'then' method.
Consider the following:
myPromiseToFetchAColor().then( (color) => {
  if(color == "red"){
    //THROW THE CATCH....with an error message
  } else {
    return aNewPromise();
  }
}).catch( (error => {
  console.log(error)
})

I know I can use another promise (a custom promise to do the validation on the color and then return the promise etc... but this seems over-kill. I'd love to just do my validation and then decide to continue, or through and error and trigger the catch.

A: Below is a reproducible example based on the code you've shown, so you can see the console output to help debug and understand the control flow. Because the code uses pseudorandom number generation to create different outcomes, you can repeatedly run it (press the "Run code snippet" button) to see differing results.
Promise.prototype.catch() will catch all exceptions which occur in the original promise or prior .then() callback functions in the chain.

/** @returns an element at a random index from the input array */
function getRandomElement (array) {
  return array[Math.floor(Math.random() * array.length)];
}

/** @returns a promise that will resolve to "blue" or "red" */
function myPromiseToFetchAColor () {
  return Promise.resolve(getRandomElement(['blue', 'red']));
}

/** @returns a promise that will resolve to "hello" */
function aNewPromise () {
  return Promise.resolve('hello');
}

myPromiseToFetchAColor()
  .then(color => {
    console.log('The color was:', color);
    if (color === 'red') {
      throw new Error(`Uh oh... I didn't expect RED!`);
    } else {
      return aNewPromise();
    }
  })
  .then(result => console.log(result)) // Logs "hello" if the color was "blue"
  .catch(error => console.error(error)); // Logs the error if the color was "red"

A: You can use: throw new Error('Color is red!'); in your if statement
For more details, you can read more at: https://www.w3schools.com/js/js_errors.asp
in "throw" session


text:
Q: Local DNS hostname resolving for an Apache server Sorry if this is a newby question, but I'm not a network administrator by any means.
I'm trying to set up an Apache server that can only be accessed through the local network.  It needs to have a hostname so a user could type something like foo or foo.com into their browser to get there instead of using the IP address.
The server is currently running on Fedora 11 with Apache 2.2.13, but I'll probably migrate it to CentOS eventually.  I also need to do this on Windows and possibly OS X.  The server needs to be deployed to client organizations, so each client would have their own intranet.  I don't believe we can rely on the clients having competent network administrators (underfunded schools and such), so we'd like to distribute a package that puts everything together on it's own.

A: The solution is to add a DNS A or CNAME record to the clients DNS servers.  You are not going to be able to do this via some kind of package.
However, if you enable DNS registration on the server, and the hostname you assign to that machine is the "name" of the intranet site, then when the machine is switched on and it connects to the network it will register its hostname in DNS.
So, you could name the server "intranet", and it'll register in the clients DNS as "intranet".
Clients on the same network should then be able to access it by typing http://intranet

A: You could take a look at the wikipedia page for Zeroconf, notably the sections on service discovery and name resolution. The Bonjour service would work--you could set the server to advertise its name, and bonjour-aware clients would start to recognize the name. Macs include bonjour client support, but Windows doesn't, so you'd have to install an mDNS client on each windows computer for it to recognize the bonjour packets. The zeroconf page lists some other technologies that might fit your needs better.


text:
Q: Opening a Python file from another application without saving the file first (Opening a Pandas table from Excel) I am working with pandas, and I've just modified a table
Now, I would like to see my table in excel, but it's just a quick look, and I will have to modify the table again later on, so I don't want to save my table anywhere.
In other words, the solution
my_df = pd.DataFrame()
item_path = "my/path"
my_df.to_csv("my/path")
os.startfile(os.normpath(item_path))

Is not what I want. I would like to obtain the same behavior without saving the Dataframe as CSV first.
#Something like:
my_df = pd.DataFrame()
start_excel(table_to_load = my_df) #Opens excel with a COPY of my_df

Note
To quickly explore a DataFrame, df.head() is the way, but I want to open my DataFrame from a Tkinter application. I need to use an external program to open this temporary table

A: you can have a quick look using
<dataframe_name>.head()
it will display top 5 rows by default
or
you can simply write how many rows you want
<dataframe_name>.head(<rows_you_want>)


text:
Q: WRONG LINE LENGHT shapeLayer.strokeEnd = 0.5 draws more than half of the circle I want the line to end at the top with shapeLayer.strokeEnd = 1.0 and get a circle. the line must end here
but she goes on, it just can't be seen
full circle
when i specify a value of 0.5 i want to get half of the circle but i get much more
half circle
My code:
View
    public func createCircleLine(progress: CGFloat, color: UIColor, width: CGFloat) {
    let radius = (min(bounds.width, bounds.height) - circleLineWidth) / 2
    let center = min(bounds.width, bounds.height) / 2

    let bezierPath = UIBezierPath(arcCenter: CGPoint(x: center, y: center),
                                  radius: radius,
                                  startAngle: -CGFloat.pi / 2,
                                  endAngle: 2 * CGFloat.pi,
                                  clockwise: true)

    let shapeLayer = CAShapeLayer()
    shapeLayer.path = bezierPath.cgPath
    shapeLayer.fillColor = nil
    shapeLayer.strokeColor = circleProgressLineColor.cgColor
    shapeLayer.lineWidth = circleLineWidth
    shapeLayer.lineCap = .round
    shapeLayer.strokeEnd = progress
    layer.addSublayer(shapeLayer)
}

ViewController
class ViewController: UIViewController {

@IBOutlet weak var progressView: CircleProgressView!
override func viewDidLoad() {
    super.viewDidLoad()

}
override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(false)
    progressView.createCircleLine(progress: 1.0, color: .green, width: 10)
} }

I don't understand why I can't get the correct line length, the coordinates are correct
can i get the correct line length without CABasicAnimation ()?

A: You need to change the endAngle of your circle to 3 * CGFloat.pi / 2, so it is a complete cycle with no overlapping. The current circle you have has π/2 (90 degrees) overlap
let bezierPath = UIBezierPath(arcCenter: CGPoint(x: center, y: center),
                                      radius: radius,
                                      startAngle: -CGFloat.pi / 2,
                                      endAngle: 3 * CGFloat.pi / 2,
                                      clockwise: true)


text:
Q: How can I query for multiple results while matching on multiple sets of parameters? First off, I'm using Entity Framework Core 5 with SQL Server provider and a repository pattern to do any work related to the infrastructure.
My problem is that I'm trying to query for a list of CardSale entities while matching on a list of parameters.
The CardSale entity has no key currently, it uses a composite clustered index for uniqueness and organization. we went for this kind of index for several reasons including GroupBy query optimization.
So if I want to query for a single record I can just use something simple like this:
            return await _appDbContext.CardSales
                .Where(c =>
                c.PurchaseCurrency == currency &&
                c.Date == date &&
                c.SubcategoryId == subcategoryId &&
                c.CardId == cardId &&
                c.RegionId == regionId &&
                c.AccountId == accountId)
                .Include(c => c.Card)
                .Include(c => c.Region)
                .Include(c => c.Account)
                .FirstOrDefaultAsync();

Now the problem lies in the next step, a portion of the code requires the ability to pass in a list of Notification objects to a query and receive a list of matching CardSale object on the properties mentioned above.
Before the current change in the code base we had a really big string Key property which was just the properties mentioned above interpolated into a single string (I know, it was really bad) so that meant I could pass in a List<string> ids and use something like
return await _appDbContext.CardSales
    .Where(c => ids.Contains(c.id)

and it works just fine.
But now my problem is that this big string id doesn't exist anymore, I only have the individual properties and the composite clustered index.
How can I query for multiple CardSale entities while using parameters from multiple Notification objects?
Extra notes:
All ids are Guid. Date is a date component of a DateTime object.
The query for a specific CardSale has to contain ALL the mentioned properties in the first query which all also exist in the Notification object.


text:
Q: How to mock new Date() which is called inside a function? Below is my Js code
export const getCurrentTimestamp = () => {
const d = new Date();
const date = d.toISOString().split('T')[0];
const time = d.toTimeString().split(' ')[0];
return `${date} ${time}`;
};

So I need to mock new Date(). Below is the test code
test('verifying current timestamp', () => {
  const now = new Date('2021-08-04T11:01:58.135Z');
  jest.spyOn(global, 'Date').mockImplementation(() => now);
  expect(getCurrentTimestamp()).toBe('2021-08-04 11:01:58');
});

But the test is failing. May i know the reason

A: Found the issue. Actually "d.toTimeString()" was converting the mocked timestamp to local timezone. SO i did the below change
const getCurrentTimestamp = () => {
const d = new Date();
console.log(d)
const date = d.toISOString().split('T')[0];
const time = d.toISOString().split('T')[1].split('.')[0]; // here is the change
return `${date} ${time}`;
};


text:
Q: I want a div to refresh automaticallywithout refreshing whole page I have developed a comment system with ajax and its working fine. I want to add a ajax/js code to refresh my time ago div after every 5 seconds so that the time changes while one is on same post.
Please note:
Sir, i just want code to request server to refresh div after a specific time period. I do not want to load page or div but i want contents within that div should be refreshed after a specific period of time.
I'm new in js/ajax and Ii tried this but not working yet
$(document).ready(function () {
    setInterval(function () {
        $("#showtimeago!").load();
    }, 1000);
});

Result I want is:

 <?php time_stamp($timePost);?>

Can anyone help me to solve that issue?

A: I don't know what UI you are using, here is for the php(since Jquery is same) you can tune this up for your requirement.
function loadlink(){
$('#showtimeago').load('test.php',function () {
     $(this).unwrap();
});
}

 loadlink(); // This will run on page load
 setInterval(function(){
  loadlink() // this will run after every 5 seconds
  }, 5000);

Try this:

setInterval(function(){
  $('#showtimeago').load('test.php');
 },5000);

test.php is the page the refresher stand.


text:
Q: Can't use latest versions of RProvider: Initialization of R.NET failed Encountered quite a strange behaviour from RProvider:
The latest version of RDotNet by itself works just fine.
Older versions of RProvider (up to 1.1.15) also don't produce any problems.
But any recent version (from 1.1.17 to to the newest 1.1.22) throws the following error: "Initialization of R.NET failed" (even without importing the RProvider module). Moreover, the first line of the code is highlighted in red with the following warning: ("Referenced assembly RProvider.dll has assembly level attribute TypeProviderAssemblyAttribute but no public type provider classes were found").
Digging into the problem I found that the RProvider log complains about missing R.dll (which is present, of course).
[07.04.2019 0:49:22] [Pid:10260, Tid:19, Apid:1] initAndGenerate: starting
[07.04.2019 0:49:22] [Pid:10260, Tid:19, Apid:1] Starting server 'C:\Users\Vat\source\repos\RTest\packages\RProvider.1.1.22\lib\net40\RProvider.Server.exe' with arguments 'RInteropServer_10260_14366875_1958578678 "C:\Users\Vat\AppData\Local\Temp\tmp38A0.tmp"' (exists=true)
[07.04.2019 0:49:22] [Pid:9292, Tid:1, Apid:1] Starting 'RProvider.Server' with arguments '[|"RInteropServer_10260_14366875_1958578678";
"C:\Users\Vat\AppData\Local\Temp\tmp38A0.tmp"|]'
[07.04.2019 0:49:22] [Pid:9292, Tid:1, Apid:1] Registering RInteropServer at channel 'RInteropServer_10260_14366875_1958578678'
[07.04.2019 0:49:22] [Pid:9292, Tid:1, Apid:1] Ready for connections..
[07.04.2019 0:49:22] [Pid:10260, Tid:19, Apid:1] Attempting to connect via IPC
[07.04.2019 0:49:22] [Pid:10260, Tid:19, Apid:1] Got some server
[07.04.2019 0:49:22] [Pid:9292, Tid:5, Apid:1] Attempting resolution for 'RDotNet, Version=1.7.0.0, Culture=neutral, PublicKeyToken=null'
[07.04.2019 0:49:22] [Pid:9292, Tid:1, Apid:1] Waiting for parent process pid=10260 (System.Diagnostics.Process (devenv))
[07.04.2019 0:49:22] [Pid:9292, Tid:1, Apid:1] Server started, running event loop
[07.04.2019 0:49:22] [Pid:9292, Tid:1, Apid:1] server event loop: starting
[07.04.2019 0:49:22] [Pid:9292, Tid:5, Apid:1] Probing locations: C:\Users\Vat\source\repos\RTest\packages\RProvider.1.1.22\lib\net40\..\..\..\..\packages\R.NET.1.7.0\lib\net40;C:\Users\Vat\source\repos\RTest\packages\RProvider.1.1.22\lib\net40\..\..\..\..\packages\R.NET.FSharp.1.7.0\lib\net40;C:\Users\Vat\source\repos\RTest\packages\RProvider.1.1.22\lib\net40\..\..\..\..\packages\RProvider.1.1.22\lib\net40;C:\Users\Vat\source\repos\RTest\packages\RProvider.1.1.22\lib\net40\..\..\..\..\packages\DynamicInterop.0.8.1\lib\netstandard1.2;C:\Users\Vat\source\repos\RTest\packages\RProvider.1.1.22\lib\net40\..\..\..\..\packages\FSharp.Core.4.6.2\lib\net45
[07.04.2019 0:49:22] [Pid:9292, Tid:5, Apid:1] Found assembly, checking version! (C:\Users\Vat\source\repos\RTest\packages\RProvider.1.1.22\lib\net40\..\..\..\..\packages\R.NET.1.7.0\lib\net40\RDotNet.dll)
[07.04.2019 0:49:22] [Pid:9292, Tid:5, Apid:1] ...version matches, returning!
[07.04.2019 0:49:22] [Pid:9292, Tid:5, Apid:1] Attempting resolution for 'DynamicInterop, Version=0.8.1.0, Culture=neutral, PublicKeyToken=null'
[07.04.2019 0:49:22] [Pid:9292, Tid:5, Apid:1] Probing locations: C:\Users\Vat\source\repos\RTest\packages\RProvider.1.1.22\lib\net40\..\..\..\..\packages\R.NET.1.7.0\lib\net40;C:\Users\Vat\source\repos\RTest\packages\RProvider.1.1.22\lib\net40\..\..\..\..\packages\R.NET.FSharp.1.7.0\lib\net40;C:\Users\Vat\source\repos\RTest\packages\RProvider.1.1.22\lib\net40\..\..\..\..\packages\RProvider.1.1.22\lib\net40;C:\Users\Vat\source\repos\RTest\packages\RProvider.1.1.22\lib\net40\..\..\..\..\packages\DynamicInterop.0.8.1\lib\netstandard1.2;C:\Users\Vat\source\repos\RTest\packages\RProvider.1.1.22\lib\net40\..\..\..\..\packages\FSharp.Core.4.6.2\lib\net45
[07.04.2019 0:49:22] [Pid:9292, Tid:5, Apid:1] Found assembly, checking version! (C:\Users\Vat\source\repos\RTest\packages\RProvider.1.1.22\lib\net40\..\..\..\..\packages\DynamicInterop.0.8.1\lib\netstandard1.2\DynamicInterop.dll)
[07.04.2019 0:49:22] [Pid:9292, Tid:5, Apid:1] ...version matches, returning!
[07.04.2019 0:49:22] [Pid:9292, Tid:1, Apid:1] findRHomePath
[07.04.2019 0:49:22] [Pid:9292, Tid:1, Apid:1] getRLocation
[07.04.2019 0:49:22] [Pid:9292, Tid:1, Apid:1] findRHomePath: file='C:\Dev\R\R-3.4.1\bin\x64\R.dll'
[07.04.2019 0:49:22] [Pid:10260, Tid:19, Apid:1] generateTypes: getting packages
[07.04.2019 0:49:22] [Pid:9292, Tid:5, Apid:1] Adding work item to queue
[07.04.2019 0:49:22] [Pid:9292, Tid:1, Apid:1] server event loop: got work item
[07.04.2019 0:49:22] [Pid:9292, Tid:1, Apid:1] eval(.packages(all.available=T))
[07.04.2019 0:49:22] [Pid:9292, Tid:1, Apid:1] engine: Creating and initializing instance (sizeof<IntPtr>=8)
[07.04.2019 0:49:22] [Pid:9292, Tid:1, Apid:1] engine: Creating instance failed:
System.Exception: This 64-bit process failed to load the library C:\Dev\R\R-3.4.1\bin\x64\R.dll. Native error message is 'The system cannot find the file specified'
 at DynamicInterop.UnmanagedDll.ThrowFailedLibraryLoad(String dllFullName, String nativeError)
 at DynamicInterop.UnmanagedDll..ctor(String dllName)
 at RDotNet.REngine..ctor(String id, String dll)
 at RDotNet.REngine.CreateInstance(String id, String dll)
 at RDotNet.REngine.GetInstance(String dll, Boolean initialize, StartupParameter parameter, ICharacterDevice device)
 at RProvider.Internal.RInit.engine@119.Invoke() in C:\FSharp\RProvider\src\RProvider\RInit.fs:line 126
[07.04.2019 0:49:22] [Pid:9292, Tid:1, Apid:1] Output:
[07.04.2019 0:49:22] [Pid:9292, Tid:1, Apid:1] Operation failed:
System.Exception: Initialization of R.NET failed ---> System.Exception: This 64-bit process failed to load the library C:\Dev\R\R-3.4.1\bin\x64\R.dll. Native error message is 'The system cannot find the file specified'
 at DynamicInterop.UnmanagedDll.ThrowFailedLibraryLoad(String dllFullName, String nativeError)
 at DynamicInterop.UnmanagedDll..ctor(String dllName)
 at RDotNet.REngine..ctor(String id, String dll)
 at RDotNet.REngine.CreateInstance(String id, String dll)
 at RDotNet.REngine.GetInstance(String dll, Boolean initialize, StartupParameter parameter, ICharacterDevice device)
 at RProvider.Internal.RInit.engine@119.Invoke() in C:\FSharp\RProvider\src\RProvider\RInit.fs:line 126
 --- End of inner exception stack trace ---
 at RProvider.Internal.RInit.engine@119.Invoke() in C:\FSharp\RProvider\src\RProvider\RInit.fs:line 137
 at System.Lazy`1.CreateValue()
 at System.Lazy`1.LazyInitValue()
 at RProvider.RInteropInternal.eval@292.Invoke(Unit unitVar0) in C:\FSharp\RProvider\src\RProvider\RInterop.fs:line 293
 at RProvider.Internal.Logging.logWithOutput[a](CharacterDeviceInterceptor characterDevice, FSharpFunc`2 f) in C:\FSharp\RProvider\src\RProvider\Logging.fs:line 57
[07.04.2019 0:49:22] [Pid:10260, Tid:19, Apid:1] RProvider constructor failed: System.Exception: Initialization of R.NET failed ---> System.Exception: This 64-bit process failed to load the library C:\Dev\R\R-3.4.1\bin\x64\R.dll. Native error message is 'The system cannot find the file specified'
 at DynamicInterop.UnmanagedDll.ThrowFailedLibraryLoad(String dllFullName, String nativeError)
 at DynamicInterop.UnmanagedDll..ctor(String dllName)
 at RDotNet.REngine..ctor(String id, String dll)
 at RDotNet.REngine.CreateInstance(String id, String dll)
 at RDotNet.REngine.GetInstance(String dll, Boolean initialize, StartupParameter parameter, ICharacterDevice device)
 at RProvider.Internal.RInit.engine@119.Invoke() in C:\FSharp\RProvider\src\RProvider\RInit.fs:line 126
 --- End of inner exception stack trace ---

Server stack trace:
 at RProvider.Server.EventLoop.runServerCommandSafe[a](FSharpFunc`2 f) in C:\FSharp\RProvider\src\RProvider\RInteropServer.fs:line 63
 at System.Runtime.Remoting.Messaging.StackBuilderSink._PrivateProcessMessage(IntPtr md, Object[] args, Object server, Object[]& outArgs)
 at System.Runtime.Remoting.Messaging.StackBuilderSink.SyncProcessMessage(IMessage msg)

Exception rethrown at [0]:
 at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
 at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
 at RProvider.Internal.IRInteropServer.GetPackages()
 at RProvider.RTypeBuilder.generateTypes@26-2.GenerateNext(IEnumerable`1& next) in C:\FSharp\RProvider\src\RProvider.DesignTime\RTypeBuilder.fs:line 27
 at Microsoft.FSharp.Core.CompilerServices.GeneratedSequenceBase`1.MoveNextImpl()
 at Microsoft.FSharp.Core.CompilerServices.GeneratedSequenceBase`1.System-Collections-IEnumerator-MoveNext()
 at Microsoft.FSharp.Collections.SeqModule.ToList[T](IEnumerable`1 source)
 at RProvider.RTypeBuilder.generateTypes@24-1.GenerateNext(IEnumerable`1& next) in C:\FSharp\RProvider\src\RProvider.DesignTime\RTypeBuilder.fs:line 25
 at Microsoft.FSharp.Core.CompilerServices.GeneratedSequenceBase`1.MoveNextImpl()
 at Microsoft.FSharp.Core.CompilerServices.GeneratedSequenceBase`1.System-Collections-IEnumerator-MoveNext()
 at Microsoft.FSharp.Collections.SeqModule.ToList[T](IEnumerable`1 source)
 at RProvider.RInteropClient.withServer[a](FSharpFunc`2 f) in C:\FSharp\RProvider\src\RProvider.DesignTime\RInteropClient.fs:line 121
 at RProvider.RTypeBuilder.initAndGenerate@104.GenerateNext(IEnumerable`1& next) in C:\FSharp\RProvider\src\RProvider.DesignTime\RTypeBuilder.fs:line 109
 at Microsoft.FSharp.Core.CompilerServices.GeneratedSequenceBase`1.MoveNextImpl()
 at Microsoft.FSharp.Core.CompilerServices.GeneratedSequenceBase`1.System-Collections-IEnumerator-MoveNext()
 at Microsoft.FSharp.Collections.SeqModule.ToList[T](IEnumerable`1 source)
 at RProvider.RProvider.buildTypes() in C:\FSharp\RProvider\src\RProvider.DesignTime\RProvider.fs:line 33

Any suggestion? Because I would really hate to use dated libraries in critical code.
So when I tried using exactly the same version of RDotNet (1.7.0) which is a dependency of RProvider 1.1.22 there weren't any problems if I tried initializing it like this:
engine = REngine.GetInstance()
But if I specified the path directly the program crashed out with the following exception "This 32-bit process failed to load the library C:\Dev\R\R-3.4.1\bin\x86\R.dll. Native error message is 'The system cannot find the file specified". Still works fine if I use the 32-bit version of R.dll (bin\i386\R.dll).
let engine = REngine.GetInstance(@"C:\Dev\R\R-3.4.1\bin\x86\R.dll")
At the same time RProvider 1.1.22 stubbornly attempts to link to the x64 version of R.dll no matter what architecture I choose.


text:
Q: Postgresql 9.5 won't start and doesn't give any indication to why not I have postgresql 9.5 running for a DaVinci Resolve shared server. (Postgresql is installed via the DaVinci installer)
Today the power went out and killed the Mac Mini that the server is running on.
After rebooting postgres stopped working and I can't figure out why.
I try to launch the server:
LFTapeRobot:data postgres$/Library/PostgreSQL/9.5/bin/pg_ctl -D /Library/PostgreSQL/9.5/data/ -l /Library/PostgreSQL/9.5/data/server.log start

server starting

And get the message that the server is starting.
But when I run a status nothing has happened:
LFTapeRobot:data postgres$ /Library/PostgreSQL/9.5/bin/pg_ctl -D /Library/PostgreSQL/9.5/data/ -l /Library/PostgreSQL/9.5/data/server.log status
pg_ctl: no server running

This is the output to the log
2019-06-12 13:48:40 CEST LOG:  redirecting log output to logging collector process

2019-06-12 13:48:40 CEST HINT:  Future log output will appear in directory "pg_log".

I have no backups of the database so I don't want to just reinstall.
And I can't run pg_dump because I can't get the server to run.
I tried moving the data folder to another computer with 9.5 installed but the same issue happens there.
There is no postmaster.pid file to delete.
Is there maybe a way to dump the database without launching the server?


text:
Q: How do you set the tab size in a JEditorPane? A JTextArea's tab size can easily be set using setTabSize(int).
Is there a similar way to do it with a JEditorPane?
Right now, text with tabs in my pane looks like:
if (stuff){
            more stuff;
}

And, I'd prefer a much smaller tab stop:
if (stuff){
    more stuff;
}

A: In case anyone's using a StyledDocument (The link on the other answer died)
You create a TabSet which is an array of TabStops. In my case I only cared about the 1st tab, and I wanted it 20px from the left, so this code worked for me:
StyleContext sc = StyleContext.getDefaultStyleContext();
TabSet tabs = new TabSet(new TabStop[] { new TabStop(20) });
AttributeSet paraSet = sc.addAttribute(SimpleAttributeSet.EMPTY, StyleConstants.TabSet, tabs);
pane.setParagraphAttributes(paraSet, false);

A: As JEditorPane is designed to support different kinds of content types, it does not provide a way to specify a "tab size" directly, because the meaning of that should be defined by the content model.
However when you use a model that's a PlainDocument or one of its descendants, there is a "tabSizeAttribute"  that provides what you are looking for.
Example:
JEditorPane pane = new JEditorPane(...);
...
Document doc = pane.getDocument();
if (doc instanceof PlainDocument) {
    doc.putProperty(PlainDocument.tabSizeAttribute, 8);
}
...

From the Javadoc:
/**
 * Name of the attribute that specifies the tab
 * size for tabs contained in the content.  The
 * type for the value is Integer.
 */
public static final String tabSizeAttribute = "tabSize";

A: Took me a while to figure this out.
And decided to use TabStop's in a TabSet that have calculated width based on the font size.
This has to be reset when ever the font size changes (in the paint() method of the JEditPane).
Complicated stuff! :(


text:
Q: automatically capture payment from paypal in magento I am using magento 1.7.0.
I have integrated paypal on my magento store.and I have choose payment_action authorization in paypal express checkout method.Now I want capture payment automatically after two day.Is Any solution how to capture payment automatically?

A: I am not sure if there is a setting to capture a payment automatically after 2 says within Magento, but you could create your own interface for doing this if you wanted to using PayPal's DoCapture API.  If you wanted to automate the process, you could create a script for doing this and set up a cron job to check the date of the transaction and perform the capture.

A: Take a look @ http://www.sumoheavy.com/capturing-payment-on-shipment-creation-magento/ and http://inchoo.net/ecommerce/magento/magento-orders/automatically-invoice-ship-complete-order-in-magento/
Create a magento cron job (see). In your cron job search for all orders that is older than 2 days and less than 'X' days, payment method is paypal and order status is pending
//$orders = get order filter see http://stackoverflow.com/questions/11042343/magento-get-all-orders-numbers-shipped-as-overnight-between-two-dates

foreach($orders as $order){
    if(check payment type and status){

        if (!$order->canInvoice()) {
                return $this;
        }

        $invoice = Mage::getModel('sales/service_order', $order)->prepareInvoice();
        if (!$invoice->getTotalQty()) {
                return $this;
        }

        $invoice->setRequestedCaptureCase('online');
        $invoice->register();
        $invoice->getOrder()->setIsInProcess(true);
        $transactionSave = Mage::getModel('core/resource_transaction')
        ->addObject($invoice)
        ->addObject($invoice->getOrder());

        $transactionSave->save();
    }
}


text:
Q: Finding index out of bounds exception All was well with this program until I made some changes in my addMainMenu method. Now it seems as though there is an array index out of bounds somewhere. Eclipse is not leading me too it. Does anyone know why this code has an array index out of bounds exception.
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
    at java.util.LinkedList.checkElementIndex(Unknown Source)
    at java.util.LinkedList.get(Unknown Source)
    at Menu.main(Menu.java:58)

import java.util.LinkedList;
import java.util.List;

public class Menu {
    LinkedList <LinkedList> mainMenuItems = new LinkedList <LinkedList> ();

    public void  Menu(){}

    public boolean addMainMenuItem(String newItem, String existingItem, int position){
        LinkedList <String> subMenuItems = new LinkedList <String> ();
        for (int i = 0; i<= mainMenuItems.size(); i++){
            if (mainMenuItems.get(i).contains(existingItem)){
                subMenuItems.addLast(newItem);
                int existingIndex = mainMenuItems.indexOf(existingItem);
                if (position == 1){
                    mainMenuItems.add(existingIndex + 1, subMenuItems);
                    break;
                }
                if (position == -1){
                    mainMenuItems.add(existingIndex, subMenuItems);
                    break;
                }
                if (i == mainMenuItems.size()){
                    subMenuItems.addLast(newItem);
                    mainMenuItems.add(subMenuItems);
                    break;
                }
            }
        }
    }
    return true;
}

public boolean deleteMainMenuItem(String item){
    if (mainMenuItems.contains(mainMenuItems.indexOf(item))){
        mainMenuItems.remove(mainMenuItems.indexOf(item));
        return true;
    }
    else{
        return false;
    }
}

public static void main(String[] args){
    Menu b = new Menu();
    b.addMainMenuItem("h", "b", 1);
    b.addMainMenuItem("hi", "h", 1);
    b.addMainMenuItem("i", "h", 1);
    System.out.println(b.mainMenuItems.get(0));
    b.deleteMainMenuItem("hi");
    System.out.println(b.mainMenuItems.get(0));
    System.out.println(b.deleteMainMenuItem("hi"));
}

A: There are two possible issues
1. In this line
for (int i = 0; i<= mainMenuItems.size(); i++)

you should have use i < mainMenuItems.size()
2. when you have not assigned any value to your LinkedList, you try to access an index of your LinkedList

A: Change the <= to < in: i<= mainMenuItems.size()
EDIT:
If mainMenuItems is still empty, the line mainMenuItems.get(i).contains(existingItem) will generate java.lang.IndexOutOfBoundsException because mainMenuItems.get(i) doesn't exist.

A: First - Change the for loop as shown below
for (int i = 0; i < mainMenuItems.size(); i++)

Also, you need to restructure addMainMenuItem method as shown below -
for (int i = 0; i < mainMenuItems.size(); i++){
    if (mainMenuItems.size() == 0) {
        //you should put list initialization code here
        //means, logic when there is nothing in the mainMenuItems list
    } else {
        //when the list is not empty
    }
}

You are getting IndexOutOfBoundsException because you are doing get(index) on mainMenuItems - which is empty in your for loop.
For example -
List<String> list = new LinkedList<String>();
list.get(0);    //will throw the same exception


text:
Q: Parsing Complex Soap Response with diffgram I am not able to parse below soap response  from a .net webservice,i am getting two type of response one is of anytype format which i have parsed it,but now i need to parse the below xml
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
   <soap:Body>
      <GetReminderResponse xmlns="http://tempuri.org/">
         <GetReminderResult>
            <xs:schema id="NewDataSet" xmlns="" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
               <xs:element name="NewDataSet" msdata:IsDataSet="true" msdata:UseCurrentLocale="true">
                  <xs:complexType>
                     <xs:choice minOccurs="0" maxOccurs="unbounded">
                        <xs:element name="Table">
                           <xs:complexType>
                              <xs:sequence>
                                 <xs:element name="RemMessage" type="xs:string" minOccurs="0"/>
                                 <xs:element name="InvM_Id" type="xs:int" minOccurs="0"/>
                                 <xs:element name="DocType" type="xs:int" minOccurs="0"/>
                                 <xs:element name="PrmR_TypeId" type="xs:int" minOccurs="0"/>
                                 <xs:element name="PrmR_Id" type="xs:int" minOccurs="0"/>
                              </xs:sequence>
                           </xs:complexType>
                        </xs:element>
                     </xs:choice>
                  </xs:complexType>
               </xs:element>
            </xs:schema>
            <diffgr:diffgram xmlns:msdata="urn:schemas-microsoft-com:xml-msdata" xmlns:diffgr="urn:schemas-microsoft-com:xml-diffgram-v1">
               <NewDataSet xmlns="">
                  <Table diffgr:id="Table1" msdata:rowOrder="0">
                     <RemMessage>Exeed Discount Limit on Invoice dated on 04/05/2015 for  ANDREA NORONHA , from 3 - Lokhandwala Showroom</RemMessage>
                     <InvM_Id>78455</InvM_Id>
                     <DocType>3</DocType>
                     <PrmR_TypeId>3</PrmR_TypeId>
                     <PrmR_Id>2213</PrmR_Id>
                  </Table>
                  <Table diffgr:id="Table2" msdata:rowOrder="1">
                     <RemMessage>Exeed Discount Limit on Invoice dated on 04/05/2015 for ADITI SHAH , from 3 - Lokhandwala Showroom</RemMessage>
                     <InvM_Id>78456</InvM_Id>
                     <DocType>3</DocType>
                     <PrmR_TypeId>3</PrmR_TypeId>
                     <PrmR_Id>2214</PrmR_Id>
                  </Table>
               </NewDataSet>
            </diffgr:diffgram>
         </GetReminderResult>
      </GetReminderResponse>
   </soap:Body>
</soap:Envelope>

A: there is schema of data types in Your Soap-response wchich is completly weird for me. But i've built code that ignores xs:schema part and creates array of GetReminder objects (type taken from Your previous post: How to parse diffgram anytype response from .net webservice). I think, that better idea would be creating KVMSerializables for the structure but the way below it works great too ;)
   ArrayList<GetReminder> lst = new ArrayList<GetReminder>();
   if(envelope.bodyIn instanceof SoapObject && envelope.bodyIn!=null){
       SoapObject so=(SoapObject)envelope.bodyIn;
        if(so.hasProperty("GetReminderResult")){
            SoapObject so1 = (SoapObject) so.getProperty("GetReminderResult");
            if(so1.hasProperty("diffgram")){
                SoapObject soDiffg = (SoapObject) so1.getProperty("diffgram");
                if(soDiffg.hasProperty("NewDataSet")){
                    SoapObject soNDSet = (SoapObject) soDiffg.getProperty("NewDataSet");

                    for (int i = 0; i < soNDSet.getPropertyCount(); i++) {
                        SoapObject soRem = (SoapObject) soNDSet.getProperty(i);
                        GetReminder reminder = new GetReminder();

                        if (soRem.hasProperty("RemMessage")) {
                            reminder.setRemMessage(soRem.getPropertyAsString("RemMessage"));
                        }
                        if (soRem.hasProperty("InvM_Id")) {
                            reminder.setInvM_Id(Integer.valueOf(soRem.getPropertyAsString("InvM_Id")));
                        }
                        if (soRem.hasProperty("DocType")) {
                            reminder.setDocType(Integer.valueOf(soRem.getPropertyAsString("DocType")));
                        }
                        if (soRem.hasProperty("PrmR_TypeId")) {
                            reminder.setPrmR_TypeId(Integer.valueOf(soRem.getPropertyAsString("PrmR_TypeId")));
                        }
                        if (soRem.hasProperty("PrmR_Id")) {
                            reminder.setPrmR_Id(Integer.valueOf(soRem.getPropertyAsString("PrmR_Id")));
                        }

                        lst.add(reminder);
                    }
                }
            }
       }
    }

   System.out.println(lst.size());

Regards, Marcin


text:
Q: make ggplot panel-background like in gtable I'm trying to make a graphic like this :

Optimal/efficient plotting of survival/regression analysis results
hier is my example code :
library(gtable)
library(grid)
library(gridExtra)
library(ggplot2)

tg <- tableGrob(iris[1:5,1:3], rows = NULL, cols=NULL)
tg$heights <- unit(rep(1,nrow(tg)), "null")

p <- qplot(1:5,1:5) + ggtitle("Title", subtitle = "another line") +
theme_grey(12) +
scale_y_continuous(expand=c(0,0.5))
g <- ggplotGrob(p)
g <- gtable::gtable_add_cols(g, widths = sum(tg$widths), pos = 0)
g <- gtable::gtable_add_cols(g, widths = sum(tg$widths), pos = -1)
g <- gtable::gtable_add_grob(g, list(tg, tg), t = 6, l=c(1,ncol(g)), r=c(1,ncol(g)))
grid.newpage()
grid.draw(g)

Is that possible with ggplot and gtable to change the background color of the ggplot Panel and set the Zebra-style to it like the other two gtables to be similar to the first example ?.
thanks,

A: As @MrFlick said you have to add some kind of geom layers in the background. This is my approach:
Create two data frames, one for points and one for segments and adjust segment size to match table rows.
tg <- tableGrob(iris[1:5,1:3], rows = NULL, cols=NULL)
tg$heights <- unit(rep(1,nrow(tg)), "null")
dSegment <- data.frame(X = 0, XE = 6, Y = 1:5, YE = 1:5)
dPoint <- data.frame(X = 1:5, Y = 1:5)

p <- ggplot() +
    geom_segment(data = dSegment,
                 aes(x = X, xend = XE, y = Y, yend = YE, color = factor(Y %% 2)),
                 size = 40) +
    geom_point(data = dPoint, aes(X, Y)) +
    ggtitle("Title", subtitle = "another line") +
    scale_y_continuous(expand = c(0, 0.5)) +
    scale_x_continuous(breaks = c(1:5)) +
    scale_color_manual(values = c("#dbdbdb", "#e9e9e9")) +
    theme_grey(12) +
    theme(panel.grid.major = element_blank(),
          panel.grid.minor = element_blank(),
          panel.background = element_blank(),
          legend.position = "none")
g <- ggplotGrob(p)
g <- gtable::gtable_add_cols(g, widths = sum(tg$widths), pos = 0)
g <- gtable::gtable_add_cols(g, widths = sum(tg$widths), pos = -1)
g <- gtable::gtable_add_grob(g, list(tg, tg), t = 6, l=c(1,ncol(g)), r=c(1,ncol(g)))
grid.newpage()
grid.draw(g)


text:
Q: Cannot choose related Lead in email alert salesforce I have a custom object called 'Interview' which has a Lookup relationship with Lead. When an interview is arranged, I want the process builder to send an auto email to the lead. Unfortunately, there is no option available to choose the related Lead in the email alert. I can choose Lead owner and related contact but there is no option for the lead email address.

A: The basic workaround would be to add a workflow rule that sets a new background field called "Related Lead Email".  The email field can then be selected for use by the email alert.


text:
Q: OpenGL transparency not working I am trying to draw my font texture atlas to the screen using LWJGL, but OpenGL instead draws a solid white square.
A working example using my drawing code:
import java.awt.image.*;
import java.io.*;
import java.nio.*;
import javax.imageio.*;
import org.lwjgl.*;
import org.lwjgl.opengl.*;

public class OpenGLImageTest
{
    private static int textureID;

    public static void main(String[] args) throws Exception
    {
        Display.setTitle("OpenGL Image Test");
        Display.setDisplayMode(new DisplayMode(640, 480));
        Display.create();

        GL11.glMatrixMode(GL11.GL_PROJECTION);
        GL11.glLoadIdentity();
        GL11.glOrtho(0, 640, 0, 480, 1, -1);
        GL11.glMatrixMode(GL11.GL_MODELVIEW);

        textureID = bindTextureFile("textures/font.png");

        while(!Display.isCloseRequested())
        {
            Display.sync(60);

            GL11.glClear(GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT);
            GL11.glClearColor(0, 0, 0, 1);

            GL11.glColor4f(1, 0, 0, 1);
            drawFontAtlas(0, 0);

            Display.update();
        }

        Display.destroy();
    }

    private static void drawFontAtlas(int x, int y)
    {
        GL11.glPushMatrix();
            GL11.glTranslatef(x, y, 0);
            GL11.glDisable(GL11.GL_DEPTH_TEST);
            GL11.glEnable(GL11.GL_TEXTURE_2D);
            GL11.glEnable(GL11.GL_BLEND);
                GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
                GL11.glBindTexture(GL11.GL_TEXTURE_2D, textureID);
                GL11.glBegin(GL11.GL_QUADS);
                    GL11.glVertex2i(0, 0);
                    GL11.glVertex2i(0, 256);
                    GL11.glVertex2i(256, 256);
                    GL11.glVertex2i(256, 0);
                GL11.glEnd();
            GL11.glDisable(GL11.GL_BLEND);
            GL11.glDisable(GL11.GL_TEXTURE_2D);
            GL11.glEnable(GL11.GL_DEPTH_TEST);
        GL11.glPopMatrix();
    }

    private static int bindTextureFile(String file)
    {
        try
        {
            BufferedImage image = ImageIO.read(new FileInputStream(file));

            int[] pixels = new int[image.getWidth() * image.getHeight()];

            image.getRGB(0, 0, image.getWidth(), image.getHeight(), pixels, 0, image.getWidth());

            ByteBuffer buffer = BufferUtils.createByteBuffer(image.getWidth() * image.getHeight() * 4);

            for(int y = 0; y < image.getWidth(); y++)
            {
                for(int x = 0; x < image.getHeight(); x++)
                {
                    int pixel = pixels[y * image.getWidth() + x];

                    buffer.put((byte)((pixel >> 16) & 0xFF));
                    buffer.put((byte)((pixel >> 8) & 0xFF));
                    buffer.put((byte)(pixel & 0xFF));
                    buffer.put((byte)((pixel >> 24) & 0xFF));
                }
            }

            buffer.flip();

            int textureID = GL11.glGenTextures();

            GL11.glBindTexture(GL11.GL_TEXTURE_2D, textureID);

            GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_S, GL12.GL_CLAMP_TO_EDGE);
            GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_T, GL12.GL_CLAMP_TO_EDGE);

            GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_NEAREST);
            GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_NEAREST);

            GL11.glTexImage2D(GL11.GL_TEXTURE_2D, 0, GL11.GL_RGB8, image.getWidth(), image.getHeight(), 0, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, buffer);

            return textureID;
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }

        return -1;
    }
}

Can anyone tell me what I am doing wrong and how to fix it?
Edit: font.png is white on transparent white. It's the default Minecraft font for testing purposes.

A: Your problem can be fixed by adding texture coordinates:
    {
        GL11.glTexCoord2f(0, 1); // added texture coordinate
        GL11.glVertex2i(0, 0);
        GL11.glTexCoord2f(0, 0); // added texture coordinate
        GL11.glVertex2i(0, 256);
        GL11.glTexCoord2f(1, 0); // added texture coordinate
        GL11.glVertex2i(256, 256);
        GL11.glTexCoord2f(1, 1); // added texture coordinate
        GL11.glVertex2i(256, 0);
    }

I actually used slick-util.jar to load your texture, but it will work with your code just the same... you can find a working example of my code bellow... slick-util.jar can be found here
In order to get actual transparency, you also need to change this line in your code: GL11.glTexImage2D(GL11.GL_TEXTURE_2D, 0, GL11.GL_RGB8, image.getWidth(), image.getHeight(), 0, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, buffer); and what needs to be changed is GL11.GL_RGB8 into GL11.GL_RGBA
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.DisplayMode;
import org.lwjgl.opengl.GL11;
import org.newdawn.slick.opengl.Texture;
import org.newdawn.slick.opengl.TextureLoader;

public class OpenGLImageTest {

    private static Texture tex; //private static int textureID;

    public static void main(String[] args) throws Exception {
        Display.setTitle("OpenGL Image Test");
        Display.setDisplayMode(new DisplayMode(640, 480));
        Display.create();

        GL11.glMatrixMode(GL11.GL_PROJECTION);
        GL11.glLoadIdentity();
        GL11.glOrtho(0, 640, 0, 480, 1, -1);
        GL11.glMatrixMode(GL11.GL_MODELVIEW);

        tex = loadTexture("textures/font.png"); //textureID = bindTextureFile("textures/font.png");

        while (!Display.isCloseRequested()) {
            Display.sync(60);

            GL11.glClear(GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT);
            GL11.glClearColor(0, 0, 0, 1);

            GL11.glColor4f(1, 1, 1, 1);
            drawFontAtlas(0, 0);

            Display.update();
        }

        Display.destroy();
    }

    private static void drawFontAtlas(int x, int y) {
        GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
        GL11.glPushMatrix();
        GL11.glTranslatef(x, y, 0);
        GL11.glDisable(GL11.GL_DEPTH_TEST);
        GL11.glEnable(GL11.GL_TEXTURE_2D);
        GL11.glEnable(GL11.GL_BLEND);

        tex.bind(); //GL11.glBindTexture(GL11.GL_TEXTURE_2D, textureID);
        GL11.glBegin(GL11.GL_QUADS);
        {
            GL11.glTexCoord2f(0, 1); // added texture coordinate
            GL11.glVertex2i(0, 0);
            GL11.glTexCoord2f(0, 0); // added texture coordinate
            GL11.glVertex2i(0, 256);
            GL11.glTexCoord2f(1, 0); // added texture coordinate
            GL11.glVertex2i(256, 256);
            GL11.glTexCoord2f(1, 1); // added texture coordinate
            GL11.glVertex2i(256, 0);
        }
        GL11.glEnd();
        GL11.glDisable(GL11.GL_BLEND);
        GL11.glDisable(GL11.GL_TEXTURE_2D);
        GL11.glEnable(GL11.GL_DEPTH_TEST);
        GL11.glPopMatrix();
    }

    public static Texture loadTexture(String texturePath) {
        try {
            return TextureLoader.getTexture("png", new FileInputStream(new File(texturePath)));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}


text:
Q: How to disable word-wrap in VS Code on long files I am making snippets that include full JavaScript libraries, that are minified.
But my problem is, that VScode automatically enables word-wrap for very long lines.
I searched the web, and found people saying that I should just add:
"editor.wordWrap": "off",
"editor.stopRenderingLineAfter": -1,

To my config. HOWEVER, it only works until I close the tab. If I open the file that has this long line (in this case javascripts.json snippets file), VScode automatically switches that tab to word-wrap: "on" state.
Here is a GIF of what I mean:
https://i.imgur.com/pPkrqMN.gifv
P.S. Can someone embed it for me? <3
I also tried setting these:
"editor.maxTokenizationLineLength": 9999999,
"editor.wordWrapColumn": 9999999,
"editor.stopRenderingLineAfter": 9999999,

But no luck. I don't care about performance penalties, that many people quote for this issue, I just want full line visible, just like any other IDE.
Is this a bug I have to report to VScode or am I missing some config?

A: Here is my test environment:
Version: 1.37.1 (user setup)
Commit: f06011ac164ae4dc8e753a3fe7f9549844d15e35
Date: 2019-08-15T16:17:55.855Z
Electron: 4.2.7
Chrome: 69.0.3497.128
Node.js: 10.11.0
V8: 6.9.427.31-electron.0
OS: Windows_NT x64 10.0.17763

I didn't find the direct solution. But I found there is an icon on the top right corner, it is a word-wrap icon. Just a click, and you can toggle word-wrap mode.
Another thing, I have tested this setting:
"editor.wordWrap": "wordWrapColumn",
"editor.wordWrapColumn": 10000000

and no luck.

A: In my case I noticed it was the Prettier extension that was controlling the word wrap.
I simply changed the Print Width from the default(80) to 200 and it fixed my problem.
Hope this helps!


text:
Q: elementwise comparison failed; returning scalar, but in the future will perform elementwise comparison n1data = pcatrain_data[train_labels[0, :] == i, :]
n2data = pcatrain_data[train_labels[0, :] == j, :]

the shape of pcatrain_data is (14395,40)
and the shape of train_labels is (1,14395)
it is my understanding that "train_labels[0, :] == i" will return a list of boolean of size 14395 with values true where it is equal to i.
and since pcatrain_data is of size 14395 it shouldn't cause any errors.
this is the code that is causing the issue.
I am trying to get all the columns from specific rows of pcatrain_data.
I want the rows where train_labels[0, :] == i.
I do not know why this error is coming, as I have done this before and it worked. both in python3
error is "FutureWarning: elementwise comparison failed; returning scalar, but in the future will perform elementwise comparison"

A: you need to write
import warnings
import numpy as np
warnings.simplefilter(action='ignore', category=FutureWarning)

Then the warning can disapear


text:
Q: Electric Potential Field of Parallel Electrodes within Grounded Shell Any help would be greatly appreciated
I think I need to solve this using boundary potential conditions and Laplace equations.
Here is the system I'm attempting to model:

The red rods are metal electrodes at the same potential ($V_r$) and on the same $x$ plane (offset equally from the $z$ axis). The orange cylinder is at $V=0$. I need the potential field map in 3D Cartesian coordinates, with variables of electrode voltage, electrode radius, electrode offset from the center axis, shell radius, overall system length.
Update 1:
I have simulated the system using FEMM, but in order to incorporate the answer with an applied magnetic field and particle motion, I need the solution in equation form.

Update 2:
I have this reference for a single coaxial electrode (http://www.ittc.ku.edu/~jstiles/220/handouts/Example%20The%20Electorostatic%20Fields%20of%20a%20Coaxial%20Line.pdf) in polar coordinates.

A: Brief Summary
Numerically, the mean value property of harmonic functions allows you to get an approximate solution to boundary value problems relatively quickly. Often you can improve convergence to a solution with a good initial guess, however, so analytical approaches can still be useful.
Consider the limit of an infinitely long cylinder. There is a simple closed form expression for the potential in the limit where the electrode radius vanishes, and for non-vanishing radius it is possible to use an iterative approach to find a sequence of analytic approximations.
Detailed Summary
Firstly, as mentioned in the comments, for any harmonic function $\phi(x,y)$ there is a holomorphic function $f(x+iy)$ such that $\phi(x,y)$ is the real-part of $f$. Another crucial property of solutions to Laplace's equation is invariance under conformal mappings. If $\nabla^2\phi(x,y)=0$ and $f$ is a conformal map (loosely), then $\nabla^2\phi(f(x+iy))=0$ as well. This property can be used to simplify the problem somewhat.
Let $R$ be the radius of the large cylinder, and let $\sigma(z)=Ai\frac{i-z/R}{i+z/R}$ (where $A$ is a real constant). You can check that this map sends the interior of the large cylinder (viewed as a disk in the complex plane $\mathbb C$) to the upper half plane $\mathbb H$. You can also check that it maps circles to other circles, so the electrode cylinders are mapped into two rescaled circles in the upper half plane. Moreover, the centers of the electrodes are mapped to a line parallel to the real axis, and both circles in $\mathbb H$ have equal radius. As promised, the picture:

In the new coordinates, the potential $\phi$ must vanish on the real line $z=\bar z$, and have some constant value $V$ on two circles in the upper half plane. To solve this, we can invoke another standard trick of boundary value problems: the method of image charges. If we extend $\phi$ by simultaneously reflecting it across the real-line while reversing its sign, we get a larger (but more symmetric) boundary value problem.
Now I use the fact that a harmonic function is the real part of a holomorphic function. Let $\psi(x,y)$ be the potential produced by charges on the upper right cylinder (centered at point $z_0$ with respect to the origin, which is set at the 'center of gravity' of the augmented problem), and let $f(z-z_0)$ be the holomorphic function that $\psi$ is the real part of ($f$ is viewed as a function defined near the origin but displaced by $z_0$). Then "by symmetry", the fields generated by the other cylinders are (proceeding counter-clockwise) $\overline{f(-\bar z-z_0)}=\bar f(-z-\bar z_0)$, $-f(-z-z_0)$, and $-\overline{f(\bar z-z_0)}=-\bar f(z-\bar z_0)$. The holomorphic field (call it $F(z)$) corresponding to the full potential $\phi$ is then just the sum of these individual 'reflected' holomorphic copies of $f(z-z_0)$. To satisfy the boundary conditions specified, we need to ensure that the sum of all $f$ and its reflections is purely imaginary plus a constant real part on any of the circular boundaries of electrodes. Because of the extra symmetry brought using the conformal mapping, we can focus on just one of these boundary circles.
For simplicity, let's choose the factor $A$ so that the boundary circles all have radius 1. Assuming the (locally) holomorphic function $f(z)$ has a singular expansion about $z=0$ (i.e. $f(z-z_0)$ is [potentially] singular near $z=z_0$), we can write $f(z)=\alpha \ln z + \sum_{n\in \mathbb Z} c_n z^n$. I'll also assume that $c_n=0$ for $n> 0$.
Calling $g(z-z_0)$ the sum of the three reflections of $f(z-z_0)$, we assume $g(z)$ is analytic at $z=0$, so we can write $g(z)=\sum_{n\geq 0}b_n z^n$. In order for the real part of $f(z)+g(z)$ to be constant on the unit circle, we need each nonzero frequency sector in the "Fourier expansion" to be purely imaginary. Since $f(z)$ has a singular expansion while $g(z)$ has an analytic expansion, this means imposing conditions on $b_n$ and $c_{-n}$. In order for $b_nz^n+c_{-n}z^{-n}\big|_{\partial \mathbb D}=b_ne^{in\theta}+c_{-n}e^{-in\theta}$ to be imaginary, we need $c_{-n}=-\bar b_n=-\frac{1}{n!}\overline{g^{(n)}(0)}$, where $g^{(n)}$ is the $n$-th complex derivative of $g$.
From this, we can write
\begin{align*}
f(z)=\alpha\ln z-\sum_{n\geq 0}\frac{1}{n!}\overline{g^{(n)}(0)}z^{-n},
\end{align*}
and since $\overline{g(z)}=\sum_{n=0}^\infty \frac{1}{n!}\overline{g^{(n)}(0)}\overline{z^n}$, we have $f(z)=\alpha\ln z-\overline{g(\bar z^{-1})}=\alpha\ln z - \bar g(z^{-1})$. Using the original definition of $g(z-z_0)=-\bar f(z-\bar z_0)-f(-z-z_0)+\bar f(-z-\bar z_0)$, we have a closed (functional) equation for $f(z)$:
\begin{align*}
f(z)=\alpha\ln z + f(\bar z_0-z_0+z^{-1})+\bar f(-2\bar z_0-z^{-1})-f(-\bar z_0-z_0-z^{-1})
\end{align*}
In cases where the radii of the electrodes is very small, it is reasonable to keep only the first term $\alpha \ln z$, so that $\psi(x,y)=\alpha\ln|z|$. Then  $\phi(x,y)$ is given by $\alpha (\ln |z-z_0|+\ln|z+\bar z_0|-\ln|z+z_0|-\ln|z-\bar z_0|)$, and the potential in the original coordinates ($s$ say) is given by $\phi(\sigma(s))$, where $\sigma$ was the Moebius transformation defined earlier. This approximation for $\phi$ (in the original domain) might also be a good starting point for numerical relaxation methods.
For finite radius electrodes, it is possible to use the above relation for $f$ iteratively to improve the accuracy of the approximation. The expansion can be represented diagrammatically as a sum over nodes of a sort of truncated tree, where each leaf is associated with a logarithm of a finite continued fraction.