text:
Q: p:commandLink ajax events inside of a p:dataTable Let's say we have a simple table defined as:
<p:dataTable value="#{testBean.dummyStringData}" var="data">
    <p:column>
        <p:commandLink action="#{testBean.printData(data)}">
            <h:outputLabel value="#{data}" />
        </p:commandLink>
    </p:column>
</p:dataTable>

And a simple backing bean:
 public class TestBean {

    private List<String> dummyStringData = new ArrayList<String>();

    //getters and setters omitted

    @PostConstruct
    public void postConstruct() {
        dummyStringData.add(new String("DummyData1"));
        dummyStringData.add(new String("DummyData2"));
        dummyStringData.add(new String("DummyData3"));
    }

    public void printData (String data) {
        System.out.println(data);
    }

Predictably, clicking on a link within the table will print the content of the clicked row to stdout.
Now, I would like for the printData method to be also called when a user hovers the mouse cursor over the p:commandLink within the table. To accomplish that I've tried nesting a p:ajax element inside the p:commandLink element:
<p:commandLink action="#{testBean.printData(data)}">
    <p:ajax event="mouseover" listener="#{testBean.printData(data)}" />
    <h:outputLabel value="#{data}" />
</p:commandLink>

This approach doesn't seem to work for p:commandLink and p:commandButton component. Hovering the mouse over the link seems to do nothing. If I were to use a component other than those two (i.e. a p:inputText and nest a p:ajax like the above) I get the expected behaviour.
Now, using a p:commandLink's onmouseover and p:remoteCommand I do manage to trigger the appropriate ajax event:
<p:commandLink action="#{testBean.printData(data)}" onmouseover="rc()">
    <h:outputLabel value="#{data}" />
</p:commandLink>
<p:remoteCommand name="rc" action="#{testBean.printData(data)}" />

However, the data variable passed as a parameter to the printData method isn't specific to the row from which the event was triggered. Instead, the last element from the collection is always used (in this case, that would be "DummyData3").
I'm using Primefaces 3.0.M3 on MyFaces 2.1.3 with Tomcat 7.
Cheers!

A: There's a solution on the PrimeFaces forum.
Alternatively...
I suspect that because the name of the generated JavaScript function will be the same for each iteration, the last one is the winner. You could do something like this to give each one a unique name:
<p:dataTable value="#{testBean.dummyStringData}" var="data" rowIndexVar="rowIndex">
    <p:column>
        <p:commandLink action="#{testBean.printData(data)}" onmouseover="rc_#{rowIndex}()">
            <h:outputLabel value="#{data}" />
        </p:commandLink>
        <p:remoteCommand name="rc_#{rowIndex}" action="#{testBean.printData(data)}" />
    </p:column>
</p:dataTable>


text:
Q: Why do I not need to include main.cpp? In the small example needsExtern.cpp needs the definition of global::bar. needsExtern.cpp would normally include the file with the definition (in this case main.cpp). However, since the file is main.cpp it is not needed.
Why does needsExtern.cpp not need to include main.cpp?
needsExtern.h
struct NeedsExtern
{
    NeedsExtern();
};

needsExtern.cpp
#include "needsExtern.h"
#include <iostream>

namespace global
{
    extern const int bar;
}

NeedsExtern::NeedsExtern()
{
    std::cout << global::bar << "\n";
}

main.cpp
#include "needsExtern.h"

namespace global
{
    extern const int bar{26};
}

void main()
{
    NeedsExtern ne;
}

A: This is precisely where extern is invented for: the compiler just assumes the variable is defined elsewhere in the project. You can read more about this principle here.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I find out where brew links end up? brew link puts symlinks all over the place. How do I find out where, for a particular package?
For example, I have cairo installed via brew. brew list cairo shows me a list of installed files. When I link cairo, brew creates symlinks.
$ brew link cairo
Linking /usr/local/Cellar/cairo/1.14.0... 28 symlinks created

How do I find out where those symlinks are?

A: In the case the package is already linked you can list existing links:
brew unlink <formulae> --dry-run

To get more info about the links:
brew unlink <formulae> --dry-run | xargs ls -l

A: symlinks are typically in /usr/local/ and is defined as by brew --prefix. To see where the app symlinks to (using wget as an example),
$ brew link wget --dry-run
Warning: Already linked: /usr/local/Cellar/wget/1.16.1
To relink: brew unlink wget && brew link wget

According to the brew man page:
If  --dry-run or -n is passed, Homebrew will list all files which would be linked or which would be deleted by brew link --overwrite, but will not actually link or delete any files.

To see where all of the files are located, use the list [formula] --verbose option like so
$ brew list wget --verbose
/usr/local/Cellar/wget/1.16.1/AUTHORS
/usr/local/Cellar/wget/1.16.1/bin/wget
/usr/local/Cellar/wget/1.16.1/ChangeLog
/usr/local/Cellar/wget/1.16.1/COPYING
/usr/local/Cellar/wget/1.16.1/INSTALL_RECEIPT.json
/usr/local/Cellar/wget/1.16.1/NEWS
/usr/local/Cellar/wget/1.16.1/README
/usr/local/Cellar/wget/1.16.1/share/info/wget.info
/usr/local/Cellar/wget/1.16.1/share/man/man1/wget.1


text:
Q: Different sized lists to dataframe I have the user input a list of minutes and then a specific size. I then have a function that calculates the average price difference for every time that size shows up and this value is added to a list. Thus, I will have as many lists as the length of minutes. For example, if the user inputs 5,10; then I have 2 lists. I then try to add the list into a data frame, but am unable to as the lists are different in size and get an error that : ValueError: Length of values does not match length of index
This is the code I have for trying to insert the list into the dataframe (i is which element in the minutes list; i.e for 5,10 I have i=0 for 5 and i=1 for 10 done in a loop) list1 is a list, list2 is a dataframe:
 list2.insert(i,i, list1)
 export_csv = list2.to_csv(file2 ,index = None, header=False)
 list1=[]

The error comes for this line of code: list2.insert(i,i, list1)
Here is an example:
List 1=[0.5,3.5,7.5]
then I want to insert it into the data frame: list2.insert(i,i, list1)
Then I want to empty the list.
Once it goes through the function the next list will be List1 is now= [7, 0.5, 8, 51.5, 2]
and I want to insert that into column 2, why I wrote list2.insert(i,i, list1)
Here is my full code if necessary:
#df is a data frame
#b is also a dataframe
#list2 is a dataframe
#list1 is a list

for i in range (0, len(df)):
            size=df.iloc[i,0]
            for i in range(0,len(numbers)-1):
                for number in numbers:
                #for i in range (0, len(numbers)-1):
                    print(number)
                    for filename in filenames:
                        b['diff']=abs(b['price']-b['orig_price'])
                        list1.extend((b['diff']))
                        print('size', size, list1)
                    list2[i+size+number]=list1
                    export_csv = list2.to_csv(file2 ,index = None, header=True)
                    list1=[]

A: IIUC, you want to set some list as a new dataframe column.
The ValueError: Length of values does not match length of index is most likely coming up because you're trying to insert a list of different length to a dataframe. In other words, make sure the length of your list equals the the number of rows in your dataframe. Otherwise, you will keep receiving this error. If you want to see a slightly more efficient way of creating new columns, keep reading.
Let's start with a sample list:
print(l)
[1, 2, 3]

And a sample dataframe:
print(df)
  c1  c2  c3
0  a   8   6
1  b   8   6
2  c   8   6

Then you can simply assign the list to a new column by:
df['new_lst_variable'] = l

print(df)
  c1  c2  c3  new_lst_variable
0  a   8   6                 1
1  b   8   6                 2
2  c   8   6                 3

Update
If you have a list that doesn't quite match up with the number of rows in your dataframe:
l2 = [1, 2, 3, 4]

You could use pandas.concat
df = pd.concat([df,pd.Series(l2)], ignore_index=True, axis=1)

print(df)
     0    1    2  3
0    a  8.0  6.0  1
1    b  8.0  6.0  2
2    c  8.0  6.0  3
3  NaN  NaN  NaN  4

You could also use DataFrame.fillna to fill these nans with whatever you'd like:
df = df.fillna(0)

print(df)
   0    1    2  3
0  a  8.0  6.0  1
1  b  8.0  6.0  2
2  c  8.0  6.0  3
3  0  0.0  0.0  4


text:
Q: Monitor folder on remote PC for changed files I have a measuring device on a PC in our network.  The PC is not joined to the domain, however has a shared folder for which I have a username and password.
I am attempting to build a Powershell script to monitor this folder from a remote server, for new CSV files, the script will then copy the file to a specified folder location.  I am struggling to pass through the parameters to the FileSystemWatcher cmdlet.
Any ideas?
$folder = '\\remoteip\folder\subfolder'# <--'<full path to the folder to watch>'
$filter = '*.csv'
$destination = '\\mynetworkstorage\folder\' # <--' Where is the file going?

$fsw = New-Object IO.FileSystemWatcher $folder, $filter -Property @{
    IncludeSubdirectories = $true              # <-- set this according to your requirements
    NotifyFilter = [IO.NotifyFilters]'FileName, LastWrite'
}
$onCreated = Register-ObjectEvent $fsw Created -SourceIdentifier FileCreated -Action {
    $path = $Event.SourceEventArgs.FullPath
    $name = $Event.SourceEventArgs.Name
    $changeType = $Event.SourceEventArgs.ChangeType
    $timeStamp = $Event.TimeGenerated
    Write-Host "The file '$name' was $changeType at $timeStamp"
    Copy-Item $path -Destination $destination -Force -Verbose
}

EDIT -
The script will be run from a server joined to our domain, so there is a need to pass through credentials to the folder in order that I can access it.  I have these credentials.

A: I refactored the code a little (mainly so I could more easily understand it):
$folder = '\\localhost\c$\tmp'
$filter = '*.*'
$destination = '\\localhost\c$\tmp_destination\'

$fsw = New-Object IO.FileSystemWatcher
$fsw.Path = $folder
$fsw.Filter = $filter
$fsw.IncludeSubdirectories = $true
$fsw.EnableRaisingEvents = $true
$fsw.NotifyFilter = [IO.NotifyFilters]'FileName, LastWrite'

$action = {
    $path = $Event.SourceEventArgs.FullPath
    $name = $Event.SourceEventArgs.Name
    $changeType = $Event.SourceEventArgs.ChangeType
    $timeStamp = $Event.TimeGenerated
    Write-Host "The file '$name' was $changeType at $timeStamp"
    Copy-Item $path -Destination $destination -Force -Verbose
}

$created = Register-ObjectEvent $fsw Created -Action $action

while ($true) {sleep 1}

I ran this code locally and managed to get files created in $folder automatically copied to $destination.
FileSystemWatcher run in the context of the current user. In the case of accessing remote systems that require login, impersonation is required.
If the remote system only got local users, no domain user that the source system can log on as, then impersonation does not seem to be possible.
See this and this link for more details on impersonation.


text:
Q: SubString of a string I Have a string like filename\34\filename
I just need  the numerical value to separate.
what can I do?
I used the following code:
string versionId = filename.Substring(filename.IndexOf("\\"), filename.LastIndexOf("\\"));

I may have the filename with directory name also. If that is the case How can I get the numeric value from that string?

A: try following code
string filename=@"filename\34\filename";
string[] lst=filename.Split('\\');
int version=-1;
foreach(var i in lst)
{
    try
    {
        version= int.Parse(i);
    }
    catch{}
}
Console.WriteLine(version);

A: Using regex, but take care when the input format doesn't match:
string filename = @"filename\34\filename";
Console.WriteLine(new System.Text.RegularExpressions.Regex(@"^.*\\(\d*)\\.*$").Match(filename).Groups[1].Value);

A: If you are sure that your fileptah will have a static format then sligh modification in your code will give you exact numeric value.
Please note that This solution will work only If you have following file location format:

RootDrive\NumeriCvalue\Filename.Extention

Test data:
string filePath = @"C:\34\test.txt";
string filePath = @"D:\32344\word.docx";

Code
 string versionId = filePath.Substring(filePath.IndexOf("\\")+1, filePath.LastIndexOf("\\")-3);


text:
Q: Why should I prefer Azure App Service over .NET REST Web API? Why should I use Azure App Service and not just implement a common .NET RESTful Web API backend?
What's the explicit benefit of this service compared to a common .NET RESTful Web API backend hosted on Azure?

A: An Azure App Service is a place to host your web application or API. Normally when you have a .NET web API you host it behind IIS or something on a virtual machine.
Azure helps you with these common scenarios wit Platform as a Service (PaaS). An App Service completely abstracts the operating system and the way you host your web application.
App Service can host web apps both on Windows and Linux. You can use all kinds of frameworks such as PHP, .NET or Java. You can even host containers without worrying about the host.
A good sample to start with hosting your .NET Web App on Azure App Services can be found here: Quickstart: Create an ASP.NET Core web app in Azure

A: Yes, there is a huge difference between Azure App Service and .Net REST WebAPI backend on Azure.
Hosting on Azure can be done using two ways

*

*Create your own VM, then install IIS and do all the required stuff

*Use AppService Plan

AppService Plan allows you to leverage the powerful functionality of Azure. Here a separate VM is not assigned to you. Azure App service can scale automatically depending upon the Scaling rule which is not present in restful API hosted on Azure VM.

A: My question blatantly was a stupid Newbie question, and as such, I'm afraid it is non-sense, which I now know by the answers you've given.
I'm currently reading the book "Azure and Xamarin Forms" to learn Xamarin and Azure. Apparently it's outdated. It suggests to "create a Mobile App on Azure". From the book that Mobile App is just a plain App Service running a RESTful Web API with EF, but utilizing completely different namespaces to do so.
My question targeted towards these other namespaces. I didn't see a reason for them.
Apparently, Microsoft noticed the same. There is no "Mobile App" available in the Azure Marketplace anymore.

A: Azure App Service is a PaaS solution from Microsoft hosted on Azure. You can think of Azure App Service as some sort of "Micrsoft Heroku", because they work on a similar fashion. For many REST Projects, it can save you hours, if not DAYS of development. It has automatic TLS like heroku, but it is hosted on Azure instead of AWS and it can integrate very well with your existing Azure resources. One common pattern is to host the REST API on App Service and use a database service from Azure such as Azure SQL or Cosmos DB (which is a NoSQL service that, from the point of view of your app, it operates as MongoDB, but can be configured to behave as other DBMS).


text:
Q: Select system call not scanning more than 2 descriptors I am writing a Server program serving to Multiple client(max 5). As any client connects to server, server stores the descriptor into an array and checks for any activity in those descriptors via Select system call. But, it is only reading from any 2 clients only and rest client requests are not being served at all. Here is a code for Server
#define NUM_CLIENT 5

void main(int argc,char** argv)
{
 int master_sock, newSocket, err;
 struct sockaddr_in Server_addr, Client_addr;
 char buf[100];
 int i=0;
 int activity;

 //socket descriptors for select
 fd_set readfd;
 int client_fd[NUM_CLIENT]={-1,-1,-1,-1,-1};

 //Socket creation
 master_sock= socket(AF_INET,SOCK_STREAM,0);
 if(master_sock<0){
    perror("socket");
    return;
 }

 //structure filling for listening to the port
 Server_addr.sin_family = AF_INET;
 Server_addr.sin_port = htons(atoi(argv[1]));
 Server_addr.sin_addr.s_addr = INADDR_ANY;

 //Binding to the Address and port filled in structure
 err = bind(master_sock,(struct sockaddr*)&Server_addr,sizeof(Server_addr));
 if(err<0){
    perror("socket");
    return;
 }

 printf("\nlistening to port");
 err = listen(master_sock,NUM_CLIENT);  //to inform, the willlingness to accept connections.
 if(err<0){
    perror("Listen");
    return;
 }
 printf("\nAccepting connection");

 while(1)
 {
    //Select modifies the objects in structure for any activity,
    // So we need to load them again.
    FD_ZERO(&readfd);   //clearing the readfd list
    FD_SET(master_sock,&readfd);    //adding the descriptor for select to listen

    for(i=0;i<NUM_CLIENT;i++){
        if(client_fd[i] != -1){
            FD_SET(client_fd[i],&readfd);   //Add socket to the list

        }
    }
    //Descriptors loaded..

    //start Select operation....

    activity = select(NUM_CLIENT+1,&readfd,NULL,NULL,NULL); //wait here until any activiy occurs
    if(activity < 0){
        perror("Select");break;
    }
    printf("\nactivity happened in socket...");

    //If activity related to master socket i.e. New client is trying to connect.
    if( FD_ISSET(master_sock,&readfd) ) {
        printf("\nactivity in master socket...");
        int len = sizeof(Client_addr);

        //Accept the connection
        newSocket = accept(master_sock, (struct sockaddr*)&Client_addr ,&len);  //blocking call
        if(newSocket<0){
            perror("accept");return;
        }
        printf("\nNew connection accepted");

 //     puts("Receiving data");
        if( recv(newSocket,buf,100,0) > 0 )     //blocking call
            printf("\n%s",buf);
        else
            strcpy(buf,"hey");

//      puts("Sending data");
        if( send(newSocket,buf,strlen(buf),0) < 0 )
            perror("send");

        //creating client database of descriptors
        for(i=0;i<NUM_CLIENT;i++){
            printf("\nfd[%d] = %d\n",i,client_fd[i]);
            if(client_fd[i] == -1){
                client_fd[i]= newSocket;
                //FD_SET(newSocket,&readfd);    //Add socket to the list
                //printf("\nfd[%d] = %d\n",i,client_fd[i]);
                break;
            }

        }

    }

    //If activity(read or write) in other sockets, check it out
    printf("\nChecking Activity in Other File Descriptors\n");
    for(i=0;i<NUM_CLIENT;i++){

        if(FD_ISSET(client_fd[i],&readfd)){

            printf("\nactivity in client %d ...",i);
 //     puts("Receiving data");
            if( recv(client_fd[i],buf,100,0) > 0 )  //blocking call
                puts(buf);
            else
                strcpy(buf,"hello");
 //     puts("Sending data");
            if( send(client_fd[i],buf,strlen(buf)+1,0) == -1 )
                perror("send");
                //printf("\n%s",buf);
        }

    }

  }

 }

And every client sends and receive data after sleeping for given time(provided via command line). Example: client1 5sec ,client2 4sec and so on...
The code for client is :
void main(int argc, char** argv)
{
 int fd, err;
 char buf[100],buf2[100];
 struct sockaddr_in server;

 fd = socket(AF_INET,SOCK_STREAM,0);
 if(fd<0){
    perror("socket");return;
 }

I2A(buf,getpid());  //Integer to array conversion, returns array
strcat(buf,"Hello");

printf("%s\n",buf);
server.sin_family = AF_INET;
server.sin_port = htons(atoi(argv[1])); //Host to network
server.sin_addr.s_addr = inet_addr("127.0.0.1");
printf("Connecting with server\n");
if( connect(fd, (struct sockaddr*)&server,sizeof(server) ) < 0) {
    perror("connect");return;
}
printf("Connected with server\n");

while(1){

//  printf("Sending data\n");
 if( send(fd,buf,20,0) < 0)
    perror("send");

 // printf("Receiving data\n");
 if( recv(fd,buf2,sizeof(buf2),0) >0 )
    printf("%s\n",buf2);
 sleep(atoi(argv[2]));
 }

Thanks in advance.

A: This line is wrong:
activity = select(NUM_CLIENT+1,&readfd,NULL,NULL,NULL); //wait here until any activiy occurs

The first argument to select() should not be NUM_CLIENT+1, but rather the maximum file descriptor value (across all of the file descriptor values that you called FD_SET() on)), plus one.


text:
Q: Использование php на сайте Только начинаю изучение веба, а именно php, все что выдает гугл это "Создание сайта на php + mysql". Вопрос следующий - это единственный способ использования php на сайте (в перемешку с html)? просто читал что php - серверный язык.
Можно ли его вызывать отдельным файлом? И стоит ли?
Если да - можете скинуть сайты где изучали php (если изучали)

A: PHP - серверный язык, а значит для работы с ним необходим сервер. Просто так открыть файл в браузере и увидеть результат нельзя. Если Вы используете Windows, то самый простой вариант для Вас - Openserver. Простая в использовании утилита, на старте не нужно тратить много времени на то, чтобы разобраться как им пользоваться. Если у Вас Linux, то стандартный LAMP сервер также отлично подойдет для начала.
Сам язык можно начать изучать здесь:
https://www.codecademy.com/learn/php. О взаимодействии с базами данных можно почитать и в официальной документации http://php.net/manual/ru/book.pdo.php Но сначала лучше пройти курс по языку.

A: Смотрите, давайте сперва разберемся что такое html и что такое php.
    *html - это гипертекст, разметка, визуальное представление, то что видит конечный пользователь. Это декларативный язык разметки. (почитайте о декларативных и императивных языках)
    *php - это гипертекстовый препроцессор, тоесть в каком то смысле логика поведения вашей html разметки.
С помощью php ваш сайт сможет как то взаимодействовать с пользователем на стороне сервера, например самое банальное выводить какую то информацию из БД(базы данных).
    *Теперь собственно о php + mySql. Конечно это не единственный способ использования php. С его помощью можно создавать полнофункциональные клиент-серверные приложения, но в большинстве случаев вы будете использовать БД для структурирования ваших данных неважно сайт это или приложение, по этому php +mySql самый распространенный случай использования php.
    *Можно ли его вызывать отдельным файлом? Конечно можно, конечно нужно. Отделение логики от представления это хороший тон, отделяя ваш php код от html вам потом будет легче поддерживать ваш код, дополнять его чем то. И главное вы сможете легко менять внешний вид вашего сайта не нарушая функциональность(почитайте также о MVC (шаблон проектирования)).
*Чтобы подключить php скрипт к html документу  с расширением '.html' используйте  код: <!--#include virtual='script.php' -->
*Чтобы подключить php скрипт к html документу  с расширением последнего '.php' пишите так:
<?php include("script.php"); ?>

A:
Можно ли его вызывать отдельным файлом?

Да, можно. Например, в консоли:
> php myScript.php

Если при этом внутри myScript.php написать что-то вроде <?php echo 2+2;, то в консоли ты увидишь 4.

И стоит ли?

Стоит, если тебе, например, нужно консольное приложение. Это обычная практика - делать такие скрипты и запускать их консольно. На практике на сайте такой скрипт может запускаться по расписанию и делать какие-то отложенные задачи для сайта по ночам: рассылать почту, подбивать кассу, считать статистику и т.д.
Если же задача запустить такой скрипт консольно, а потом открыть результат его работы в браузере, то это тоже возможно с помощью встроенного в php сервера: http://php.net/manual/ru/features.commandline.webserver.php
Но не используйте его для создания полноценных сайтов. Он придуман для отладки и небольших задач.

Если да - можете скинуть сайты где изучали php (если изучали)

Официальная документация на русском вполне годится для изучения и основ и более сложных вещей под капотом http://php.net/manual/ru/
Да, она не учит созданию сайтов с нуля, но это отдельная история и для этого не обязательно изучать именно php.


text:
Q: Is WebRTC sufficient for peer to peer video calling I'm building an application with peer-to-peer video calling. So far, I only know WebRTC. Is this sufficient for p2p video calling across the globe if I just have simplest Turn server(s)? By sufficient I mean it is as smooth as a normal video calling services like Google Meet or Zoom. If no, what else should I do to ensure smooth video calling?

A: For P2P calls with a few participants, WebRTC should absolutely be sufficient. WebRTC has evolved so much in the past decade that it's not unreasonable to estimate that most video applications that are not Zoom are built on it.
There are lots of tutorials about building WebRTC apps from scratch (here's one on DEV, and I appreciate everything Karl Stolley writes).
The only question is if you need to build the WebRTC logic from scratch. Jitsi is a good open-source library. There are other solutions with free tiers like Twilio, Agora, or Daily (full disclosure, where I work).
Good luck!


text:
Q: expo-firebase-analytics screen resolutions aren't send I've installed expo-firebase-analytics ( expo-install expo-firebase-analytics )
I've added and linked the google-service.json file from firebase console correctly and I can get datas on my google analytics dashboard.
However it seems that the screen resolution isn't part of the sent datas …
In tech details > Screen resolutions that's what I have :

How can I get it ?


text:
Q: Running pure Groovy code in a step inside a Jenkinsfile I have the following stages in my test.groocy pipeline:
stages {
  stage('Test') {
    steps {
       env.SOME_VAR = new File("settings.gradle")
         .readLines()
         .findAll { someLogic }
         .collect { it =~ /.*'(.*)'/ }
       echo "got: ${SOME_VAR}"
    }
  }
}

But I'm getting:
java.io.FileNotFoundException: settings.gradle (No such file or directory)

If I change the code to:
stages {
  stage('Test') {
    steps {
       sh(returnStdout: true,
       script: '''#!/bin/bash
                  cat settings.gradle''')
    }
  }
}

I can see the file's content.

*

*Why isn't it recognizing the file in the first snippet, but does recognize it in the second one?

*Is there a way to make the upper snippet works as expected in Jenkins?

A: sh, as other Jenkins steps, started in current workspace directory.
So, you could replace native java/groovy new File with Jenkins readFile and the rest of your code should work.
readFile("settings.gradle").readLines()...

Or specify the full path for new File
new File("${WORKSPACE}/settings.gradle").readLines()...


text:
Q: change UIBarButtonItem back button I'm trying to change the navigation controller backBarButton,
with out create new function of back.
here is my code:
UIImage *backButtonImage = [[UIImage imageNamed:@"backt.clicked@2x~iphone.png"] resizableImageWithCapInsets:UIEdgeInsetsMake(0, 27, 0, 27)];

(width =27,hight=27);
 [[UIBarButtonItem appearance] setBackButtonBackgroundImage:backButtonImage forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];

and here what i get:

how can i change the size and remove the title?

A: - (UIBarButtonItem *)createBackMenuButton {
    UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [backButton addTarget:self action:@selector(popViewControllerAnimated:) forControlEvents:UIControlEventTouchUpInside];
    [backButton setFrame:BACK_BUTTON_FRAME];
    [backButton setExclusiveTouch:YES];
    [backButton setImage:[UIImage imageNamed:BACK_BUTTON_DEFAULT_ICON] forState:UIControlStateNormal];

    UIBarButtonItem *backButtonHolder = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    return backButtonHolder;
}

- (void)viewWillAppear:(BOOL)animated {

    self.navigationItem.leftBarButtonItem = [self createBackMenuButton];
}

A: Try this
UIImage *backButtonImage = [[UIImage imageNamed:@"backt.clicked@2x~iphone.png"] resizableImageWithCapInsets:UIEdgeInsetsMake(0, 27, 0, 27)];
CGRect frame = CGRectMake(0, 0, backButtonImage.size.width, backButtonImage.size.height);

UIButton *button = [[UIButton alloc] initWithFrame:frame];
[button setImage:backButtonImage forState:UIControlStateNormal];
[button addTarget:self action:@selector(backButtonPressed:) forControlEvents:UIControlEventTouchUpInside];

self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:button];

EDIT
UIImage *backButtonImage = [[UIImage imageNamed:@"backt.clicked@2x~iphone.png"] resizableImageWithCapInsets:UIEdgeInsetsMake(0, 27, 0, 27)];
[[UIBarButtonItem appearance] setBackButtonBackgroundImage:backButtonImage forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
self.navigationController.navigationBar.topItem.title = @"";


text:
Q: Is map_flex_1_20.swc library deprecated? we have developed an application using flex builder 3 and we are using map_flex_1_20.swc library to display google maps and do other stuff in our application.According to https://developers.google.com/maps/documentation/flash/ link. From September 2, 2014, google MAP API for Flash will no longer be available.will this have any effect on my library?
will my library stop working and will not display google map or any request that will send from this library?
Can someone explain this to me please.Detail will be highly appreciated


text:
Q: Adding page curl animation to view when button is tapped on Appcelerator.Titanium I'm a newbie in appcelerator.titanium. I started development from today onwards.
My problem is,
I want to display a page curl transition effect when a button is tapped on one of my view.
I used the following code for doing this. But the application is crashed. I searched a lot in SO and titanium documentation. But couldn't find a solution.
//This function returns a window

function ApplicationWindow()
{
    //load component dependencies
    var FirstView = require('ui/common/FirstView');

    //create component instance
    var self = Ti.UI.createWindow({
        backgroundColor:'#ffffff'
    });

    //construct UI
    var firstView = new FirstView();
    self.add(firstView);

    //Adding button for displaying view 2
    var button1 = Ti.UI.createButton({
        height  : '50',
        width   : '50%',
        top     : '70%',
        title : 'Add Child'
    });

    //Adding event listner for button
    button1.addEventListener('click',function(e){
        var view = createView();
        win.add(view);
    });
    self.add(button1);

    //creating second view
    function createView()
    {
        var view = Ti.UI.createView({
            backgroundColor : '#aabbcc'
        });

            //creating button for view 2
        var button2 = Ti.UI.createButton({
        height  : '50',
        width   : '50%',
        top     : '70%',
        title   : 'Show Curl'
    });

    //Adding event listner for button
    button2.addEventListener('click',function(e)
    {
            //creating animation
        var animation = Titanium.UI.createAnimation({
        transition :  Ti.UI.iPhone.AnimationStyle.CURL_UP
            });
        animation.backgroundColor = 'black';
        animation.duration = 1000;
        var animationHandler = function() {
             animation.removeEventListener('complete',animationHandler);
             animation.backgroundColor = 'orange';
             view.animate(animation);
        };
        animation.delay = 5000
        animation.addEventListener('complete',animationHandler);
        view.animate(animation);
     });

     view.add(button2);
     return view;
    }
    return self;
}

//creating window and opening
var win = ApplicationWindow();
win.open();

Thanks in advance

A: Use this module instead: http://support.appcelerator.com/kb/119/tickets
It's all done for you..


text:
Q: Cannot set CPU frequency I'm trying to set my CPU max frequency to the max value supplied by scaling_available_frequencies, but it looks like the kernel is simply ignoring me.
My kernel:
# uname -a
Linux valfenda 5.10.32-051032-generic #202104210836 SMP Wed Apr 21 13:18:19 UTC 2021 x86_64 x86_64 x86_64 GNU/Linux

But it was the same using 5.8.
My processor is AMD Ryzen 7 4700U with Radeon Graphics, 8 cores.
# cpufreq-info -c0
cpufrequtils 008: cpufreq-info (C) Dominik Brodowski 2004-2009
Report errors and bugs to cpufreq@vger.kernel.org, please.
analyzing CPU 0:
  driver: acpi-cpufreq
  CPUs which run at the same hardware frequency: 0
  CPUs which need to have their frequency coordinated by software: 0
  maximum transition latency: 4294.55 ms.
  hardware limits: 1.40 GHz - 2.00 GHz
  available frequency steps: 2.00 GHz, 1.70 GHz, 1.40 GHz
  available cpufreq governors: conservative, ondemand, userspace, powersave, performance, schedutil
  current policy: frequency should be within 1.40 GHz and 1.40 GHz.
                  The governor "performance" may decide which speed to use
                  within this range.
  current CPU frequency is 1.40 GHz (asserted by call to hardware).
  cpufreq stats: 2.00 GHz:0.05%, 1.70 GHz:0.04%, 1.40 GHz:99.91%  (199)

Pay attention at the line: frequency should be within 1.40 GHz and 1.40 GHz.
I tried:
# cat scaling_available_frequencies
2000000 1700000 1400000
# cut -d' ' -f1 scaling_available_frequencies > scaling_max_freq
# cat scaling_max_freq
1400000

And:
# cpufreq-set -u2GHz
# cpufreq-info | ag 'current policy'
  current policy: frequency should be within 1.40 GHz and 1.40 GHz.
  current policy: frequency should be within 1.40 GHz and 1.40 GHz.
  current policy: frequency should be within 1.40 GHz and 1.40 GHz.
  current policy: frequency should be within 1.40 GHz and 1.40 GHz.
  current policy: frequency should be within 1.40 GHz and 1.40 GHz.
  current policy: frequency should be within 1.40 GHz and 1.40 GHz.
  current policy: frequency should be within 1.40 GHz and 1.40 GHz.
  current policy: frequency should be within 1.40 GHz and 1.40 GHz.

No difference.
My modules:
# lsmod
Module                  Size  Used by
msr                    16384  0
btrfs                1351680  0
blake2b_generic        20480  0
xor                    24576  1 btrfs
raid6_pq              114688  1 btrfs
ufs                    81920  0
qnx4                   16384  0
hfsplus               110592  0
hfs                    61440  0
minix                  45056  0
ntfs                  106496  0
msdos                  20480  0
jfs                   196608  0
xfs                  1511424  0
rfcomm                 81920  4
nf_conntrack_netlink    49152  0
xfrm_user              36864  1
xfrm_algo              16384  1 xfrm_user
xt_addrtype            16384  2
br_netfilter           28672  0
ccm                    20480  6
xt_CHECKSUM            16384  1
xt_MASQUERADE          20480  4
xt_conntrack           16384  2
cmac                   16384  5
algif_hash             16384  2
ipt_REJECT             16384  2
algif_skcipher         16384  2
nf_reject_ipv4         16384  1 ipt_REJECT
af_alg                 32768  10 algif_hash,algif_skcipher
xt_tcpudp              20480  9
ip6table_mangle        16384  1
ip6table_nat           16384  1
iptable_mangle         16384  1
iptable_nat            16384  1
nf_nat                 49152  3 ip6table_nat,iptable_nat,xt_MASQUERADE
nf_conntrack          147456  4 xt_conntrack,nf_nat,nf_conntrack_netlink,xt_MASQUERADE
nf_defrag_ipv6         24576  1 nf_conntrack
nf_defrag_ipv4         16384  1 nf_conntrack
nf_tables             208896  0
libcrc32c              16384  5 nf_conntrack,nf_nat,btrfs,nf_tables,xfs
nfnetlink              20480  3 nf_conntrack_netlink,nf_tables
ip6table_filter        16384  1
ip6_tables             32768  3 ip6table_filter,ip6table_nat,ip6table_mangle
iptable_filter         16384  1
bpfilter               16384  0
bridge                233472  1 br_netfilter
stp                    16384  1 bridge
llc                    16384  2 bridge,stp
bnep                   24576  2
overlay               131072  0
joydev                 28672  0
amdgpu               5988352  40
snd_hda_codec_realtek   139264  1
snd_hda_codec_generic    81920  1 snd_hda_codec_realtek
ledtrig_audio          16384  1 snd_hda_codec_generic
snd_hda_codec_hdmi     65536  1
snd_hda_intel          53248  5
iommu_v2               20480  1 amdgpu
iwlmvm                413696  0
snd_intel_dspcfg       28672  1 snd_hda_intel
soundwire_intel        40960  1 snd_intel_dspcfg
gpu_sched              40960  1 amdgpu
soundwire_generic_allocation    16384  1 soundwire_intel
soundwire_cadence      32768  1 soundwire_intel
ttm                   102400  1 amdgpu
snd_acp3x_pdm_dma      16384  1
snd_hda_codec         147456  4 snd_hda_codec_generic,snd_hda_codec_hdmi,snd_hda_intel,snd_hda_codec_realtek
mac80211              970752  1 iwlmvm
drm_kms_helper        233472  1 amdgpu
snd_hda_core           94208  5 snd_hda_codec_generic,snd_hda_codec_hdmi,snd_hda_intel,snd_hda_codec,snd_hda_codec_realtek
snd_hwdep              16384  1 snd_hda_codec
snd_acp3x_rn           16384  1
soundwire_bus          77824  3 soundwire_intel,soundwire_generic_allocation,soundwire_cadence
snd_soc_dmic           16384  1
libarc4                16384  1 mac80211
cec                    53248  1 drm_kms_helper
edac_mce_amd           32768  0
snd_soc_core          282624  4 soundwire_intel,snd_acp3x_rn,snd_soc_dmic,snd_acp3x_pdm_dma
rc_core                57344  1 cec
i2c_algo_bit           16384  1 amdgpu
binfmt_misc            24576  1
btusb                  57344  0
kvm_amd               102400  0
snd_seq_midi           20480  0
iwlwifi               376832  1 iwlmvm
snd_seq_midi_event     16384  1 snd_seq_midi
btrtl                  24576  1 btusb
fb_sys_fops            16384  1 drm_kms_helper
snd_compress           28672  1 snd_soc_core
ac97_bus               16384  1 snd_soc_core
kvm                   798720  1 kvm_amd
snd_pcm_dmaengine      16384  1 snd_soc_core
snd_rawmidi            36864  1 snd_seq_midi
btbcm                  16384  1 btusb
syscopyarea            16384  1 drm_kms_helper
snd_pcm               118784  9 snd_hda_codec_hdmi,snd_hda_intel,snd_hda_codec,soundwire_intel,snd_compress,snd_soc_core,snd_hda_core,snd_acp3x_pdm_dma,snd_pcm_dmaengine
btintel                28672  1 btusb
crct10dif_pclmul       16384  1
nls_iso8859_1          16384  1
snd_seq                73728  2 snd_seq_midi,snd_seq_midi_event
sysfillrect            16384  1 drm_kms_helper
ghash_clmulni_intel    16384  0
bluetooth             651264  31 btrtl,btintel,btbcm,bnep,btusb,rfcomm
aesni_intel           372736  11
snd_seq_device         16384  3 snd_seq,snd_seq_midi,snd_rawmidi
snd_timer              40960  2 snd_seq,snd_pcm
crypto_simd            16384  1 aesni_intel
cryptd                 24576  4 crypto_simd,ghash_clmulni_intel
sysimgblt              16384  1 drm_kms_helper
snd                    94208  25 snd_hda_codec_generic,snd_seq,snd_seq_device,snd_hda_codec_hdmi,snd_hwdep,snd_hda_intel,snd_hda_codec,snd_hda_codec_realtek,snd_timer,snd_compress,snd_soc_core,snd_pcm,snd_rawmidi
glue_helper            16384  1 aesni_intel
ecdh_generic           16384  2 bluetooth
cfg80211              843776  3 iwlmvm,iwlwifi,mac80211
soundcore              16384  1 snd
ecc                    32768  1 ecdh_generic
input_leds             16384  0
snd_rn_pci_acp3x       20480  0
rapl                   20480  0
ccp                   102400  1 kvm_amd
snd_pci_acp3x          20480  0
serio_raw              20480  0
hp_wmi                 20480  0
sparse_keymap          16384  1 hp_wmi
efi_pstore             16384  0
wmi_bmof               16384  0
hid_multitouch         28672  0
k10temp                16384  0
ucsi_acpi              16384  0
typec_ucsi             36864  1 ucsi_acpi
typec                  53248  1 typec_ucsi
mac_hid                16384  0
hp_accel               28672  0
lis3lv02d              24576  1 hp_accel
hp_wireless            16384  0
acpi_tad               20480  0
sch_fq_codel           20480  2
cuse                   16384  3
parport_pc             45056  0
ppdev                  24576  0
lp                     20480  0
parport                65536  3 parport_pc,lp,ppdev
drm                   548864  20 gpu_sched,drm_kms_helper,amdgpu,ttm
ip_tables              32768  3 iptable_filter,iptable_nat,iptable_mangle
x_tables               45056  12 ip6table_filter,xt_conntrack,iptable_filter,xt_tcpudp,xt_addrtype,xt_CHECKSUM,ip6_tables,ipt_REJECT,ip_tables,ip6table_mangle,xt_MASQUERADE,iptable_mangle
autofs4                45056  2
hid_generic            16384  0
rtsx_pci_sdmmc         28672  0
crc32_pclmul           16384  0
nvme                   45056  4
ahci                   40960  0
rtsx_pci               94208  1 rtsx_pci_sdmmc
i2c_piix4              28672  0
xhci_pci               20480  0
libahci                36864  1 ahci
nvme_core             122880  6 nvme
xhci_pci_renesas       20480  1 xhci_pci
wmi                    32768  2 hp_wmi,wmi_bmof
video                  49152  0
i2c_hid                32768  0
hid                   135168  3 i2c_hid,hid_multitouch,hid_generic

I've seen other similar questions, but no satisfying answer.

A: The following sets all the cpu cores to maximum frequency. you may need to install utility cpupower.
cd /sys/devices/system/cpu/
sudo cpupower frequency-set -g performance


text:
Q: pgRouting:how to use reverse_cost? I add a new column, naming it "reverse_cost", and give it the same data in the shape_leng column.

But as I run the shortest path algorithm in pgadmin, I got an error message.

here's my sql code
SELECT * FROM shortest_path('
            SELECT gid as id,
                     start_id::int4 AS source,
                     end_id::int4 AS target,
                     shape_leng::double precision as cost
                    FROM network',
            10, 17, true, true);

and here's the error
Error:  Error, reverse_cost is used, but query did't return 'reverse_cost' column

********** Error **********

Error: Error, reverse_cost is used, but query did't return 'reverse_cost' column
SQL status: XX000

As I change the code to this one, everything went well,
SELECT * FROM shortest_path('
            SELECT gid as id,
                     start_id::int4 AS source,
                     end_id::int4 AS target,
                     shape_leng::double precision as cost
                    FROM network',
            10, 17, false, false);

so I want to know how to use reverse_cost in PostGIS?

A: You haven't included the reverse cost in the query that gets the data. Add that column and it should work:
SELECT * FROM shortest_path('
    SELECT gid as id,
        start_id::int4 AS source,
        end_id::int4 AS target,
        shape_leng::double precision as cost,
        shape_leng::double precision as reverse_cost
        FROM network',
    10, 17, true, true);

Also, you're not even using the cost (nor reverse_cost) columns from your table, but just the shape_leng with an alias. If you want to use the actual columns, change to:
SELECT * FROM shortest_path('
    SELECT gid as id,
        start_id::int4 AS source,
        end_id::int4 AS target,
        cost::double precision,
        reverse_cost::double precision
        FROM network',
    10, 17, true, true);


text:
Q: Get the name of a custom attribute from attrs.xml I have created custom attributes in attrs.xml :
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="StarWars">
  <attr name="sw_jedi" format="string" />
  <attr name="sw_rank" format="string" />
</declare-styleable>

I get the int value backed in R (for example R.styleable.StarWars_sw_jedi) but how can I get the attribute name (jedi) ?
EDIT to be more specific :
I want the "name" String of the attribute not the value from R (which is an int) :
For example, I want to retrieve "jedi" and not the int (R.styleable.StarWars_sw_jedi or R.attr.sw_jedi)
In fact i would like a getAttributeName(R.styleable.StarWars_sw_jedi)
Thx in advance !

A: I have Worked on your same Style and is working perfectly check once for reference.
step 1:
Create custom style by creating a file attrs.xml in res/values folder
here is attrs.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="StarWars">
  <attr name="sw_jedi" format="string" />
  <attr name="sw_rank" format="string" />
</declare-styleable>
</resources>

Declare the format you have specified in res/values/strings.xml
   <string name="sw_jedi">Hi</string>
        <string name="sw_rank">Bye</string>

And when I use in my java code
it works without any ambiguity.
If you want to get the value of jedi do like this
 String jedi=getResources().getResourceEntryName(StarWars_sw_jedi);

A: Well I don't know why I didn't find it but the function I was looking for is getResourceEntryName which actually does exactly what I want
In my case if I want "jedi" I will do :
String name = getResources().getResourceEntryName(R.attr.sw_jedi);


text:
Q: make a copy of a string column and cut the string based on certain value I have a DataFrame with a column with installation KKS-codes in Python.
The KKS-codes look like this:

1BLA43AA030
1BOR53AR021
1BHY28UI021

I want to make a new column where the string only has the relevant information. sometimes the code requires a number but it usually doesn't. The required number is given after the 3digit letter which specify the certain object. like this:

BLA
BOR
BHY2

I cut the full KKS-codes  with
df_1['KKS'] = df_1.Object.str[1:4]

but for certain strings i need it to be
df_1['KKS'] = df_1.Object.str[1:5]

My if-statements don't work, please help

A: I dont fully understand what you mean by

The required number is given after the 3digit letter which specify the certain object.

If you can explain this further with examples I can help more. Otherwise, this is how you can apply a function to a row in a dataframe:
import pandas as pd

def test_for_four(s: str) -> bool:
    third_digit_letter = s[4]
    if third_digit_letter != "2":
        return True
    return False

def split_kks_code(s: str) -> str:
    if test_for_four(s):
        return s[1:4]
    return s[1:5]

df = pd.DataFrame([{'KKS-Code': '1BLA43AA030'},
                   {'KKS-Code': '1BOR53AR021'},
                   {'KKS-Code': '1BHY28UI021'}])

df['KKS'] = df['KKS-Code'].apply(split_kks_code)


text:
Q: Media Queries behaving differently for each Browser I'm working on a simple institutional website and all works well, except for the media queries. I'm new to this technology so I don't really know whats going on.
My issue appears when I open the collapsed bootstrap menu on iPad like screens and smaller and it depends on the browser.
It works fine for Firefox and has some issues with Chrome and Safari, so it makes me believe that my code is working, but I am missing some important aspects of browser compatibility.
I want the navbar menu to open with a gray background when the screen is medium size (only works for Firefox) and black for mobile (Safari has a bug which opens the whole menu and them cuts it by half).
This is the website: flowersforpeaceproject.com
And here is the code:
body {
    margin: 0;
    padding: 0;
    font-family: 'Merriweather Sans', sans-serif;
}

/*NAVBAR*/

.navbar{
    border: 0;
    position: absolute;
    top: 0;
    z-index: 10;
    width: 100%;
}

.navbar .nav > li > a{
    color: #1E73BE;
}

.navbar-default{
    background-color: transparent;
}

nav .navbar-brand img{
    height: 220px;
    margin-right: 20px;
}

/*MEDIA QUERIES*/
@media screen and (max-width: 1000px) {
  .navbar-header {
      float: none;
  }
  .navbar-toggle {
      display: block;
  }
  .navbar-collapse {
      border-top: 1px solid transparent;
      box-shadow: inset 0 1px 0 rgba(255,255,255,0.1);
  }
  .navbar-fixed-top {
      top: 0;
      border-width: 0 0 1px;
  }
  .navbar-collapse.collapse {
      display: none!important;
  }
  .navbar-nav>li {
      float: none;
  }
  .navbar-nav>li>a {
      padding-top: 10px;
      padding-bottom: 10px;
  }
  .collapse.in{
      display:block !important;
  }

  /*MY CODE*/
  #bs-example-navbar-collapse-1 .navbar-right{
      background-color: rgb(50,50,50, 0.9);
      border-radius: 10px;
      max-width: 180px;
  }
}

@media screen and (max-width: 480px){
    nav .navbar-brand img{
        height: 120px;
        margin-right: 20px;
    }

    #bs-example-navbar-collapse-1 .navbar-right{
        border: 0;
        position: absolute;
        top: 10;
        left: 0;
        z-index: 10;
        width: 700px;
        margin-left: 20px;
        background-color: black;
        border-radius: 10px;

    }

}
/*END MEDIA*/

...

A: There's an good Resource available for learning and playing with media querys. here

*

*Since this is an Browser based media query bug you can easily solved by specifying different CSS to each screen resolutions.
Here is an good tool to generate media Query. Open Site.
in your code you can generate css, for example for different Screen Resolutions.
@media screen and (max-width: 400px) {
    border: 0;
            position: absolute;
            top: 10;
            left: 0;
            z-index: 10;
            width: 700px;
            margin-left: 20px;
            background-color: black;
            border-radius: 10px;
}

@media screen and (min-width: 401px) and (max-width: 720px) {
    border: 0;
            position: absolute;
            top: 10;
            left: 0;
            z-index: 10;
            width: 700px;
            margin-left: 20px;
            background-color: black;
            border-radius: 10px;
}

@media screen and (min-width: 721px) and (max-width: 1280px) {
    border: 0;
            position: absolute;
            top: 10;
            left: 0;
            z-index: 10;
            width: 700px;
            margin-left: 20px;
            background-color: black;
            border-radius: 10px;
}

@media screen and (min-width: 1281px) and (max-width: 1440px) {
    border: 0;
            position: absolute;
            top: 10;
            left: 0;
            z-index: 10;
            width: 700px;
            margin-left: 20px;
            background-color: black;
            border-radius: 10px;
}

@media screen and (min-width: 1441px) and (max-width: 1920px) {
    border: 0;
            position: absolute;
            top: 10;
            left: 0;
            z-index: 10;
            width: 700px;
            margin-left: 20px;
            background-color: black;
            border-radius: 10px;
}

@media screen and (min-width: 1921px) {
    border: 0;
            position: absolute;
            top: 10;
            left: 0;
            z-index: 10;
            width: 700px;
            margin-left: 20px;
            background-color: black;
            border-radius: 10px;
}


text:
Q: Access data from Microsoft SQL Server into Unity3d We have spent more than a couple of days on this have gone though almost all available threads online but nothing has worked so far.
We are using Unity Version 2019.2.1 and Visual Studio 2019 Community Edition.
We have already tried the following:

*

*We have tried using Entity Framework model using both ObjectContext and DataContext and in both ways the app.config file and .edmx file are lost when we reload the solution

*We have also tried using legacy SqlConnection using System.Data and System.Data.SqlClient namespaces by copying the dlls into the Plugins folder
We have checked and double checked all SQL Server configurations, ports, authentication, etc. and use SQL Server on day-to-day basis for our other projects.
Can someone please point to any working sample / example / video / article on how to access data from Microsoft SQL Server in Unity3d?
Thanks in advance!
Regards,
Swapneel Shah

A: Check this for Connect to MS SQL database:
https://forum.unity.com/threads/connect-to-ms-sql-database.484855/


text:
Q: Quickblox status 404 while getUsersByTags Hello every one I'm trying to make a video call app for android using  Quickblox.
However when I execute the project I got error '404 Not found' while trying to get the list of users.
 private void initOpponentListAdapter() {
        final ListView opponentsList = (ListView) view.findViewById(R.id.opponentsList);
        List<QBUser> users = ((CallActivity) getActivity()).getOpponentsList();

        QBPagedRequestBuilder requestBuilder = new QBPagedRequestBuilder();
        requestBuilder.setPerPage(100);

        if (users == null) {
            List<String> tags = new LinkedList<String>();
            tags.add("webrtcusers");

            QBUsers.getUsersByTags(
                tags, requestBuilder,
                new QBEntityCallback<ArrayList<QBUser>>() {

                    @Override
                    public void onSuccess(ArrayList<QBUser> qbUsers, Bundle bundle) {
                        Log.d("Track", "download users from QickBlox");
                        ArrayList<QBUser> orderedUsers = reorderUsersByName(qbUsers);

                        if(isAdded()) {
                            ((CallActivity) getActivity()).setOpponentsList(orderedUsers);
                            prepareUserList(opponentsList, orderedUsers);
                            progresDialog.dismiss();
                        } else {
                            Log.e("getActivity() error", "get Activity is null, because adapter wasn't added");
                        }
                    }

                    @Override
                    public void onSuccess() {
                    }

                    @Override
                    public void onError(List<String> strings) {
                        Log.d("Track", "onError()");
                    }
                }
            );
        } else {

            ArrayList<QBUser> userList = ((CallActivity) getActivity()).getOpponentsList();
            prepareUserList(opponentsList, userList);
            progresDialog.dismiss();

        }
    }

This is the result in logcat.
06-06 03:44:11.154: W/EGL_genymotion(3050): eglSurfaceAttrib not implemented
06-06 03:44:11.238: W/EGL_genymotion(3050): eglSurfaceAttrib not implemented
06-06 03:44:11.490: D/dalvikvm(3050): GC_FOR_ALLOC freed 306K, 9% free 4158K/4568K, paused 6ms, total 6ms
06-06 03:44:11.890: D/QBASDK(3050): *********************************************************
06-06 03:44:11.890: D/QBASDK(3050): *** RESPONSE *** ac58f201-a366-40c0-a6e7-22ea22b2dd41 ***
06-06 03:44:11.890: D/QBASDK(3050): STATUS : 404
06-06 03:44:11.890: D/QBASDK(3050): HEADERS
06-06 03:44:11.890: D/QBASDK(3050):     Access-Control-Allow-Origin=*
06-06 03:44:11.890: D/QBASDK(3050):     Cache-Control=no-cache
06-06 03:44:11.890: D/QBASDK(3050):     Connection=keep-alive
06-06 03:44:11.890: D/QBASDK(3050):     Content-Type=application/json; charset=utf-8
06-06 03:44:11.890: D/QBASDK(3050):     Date=Sat, 06 Jun 2015 07:44:11 GMT
06-06 03:44:11.890: D/QBASDK(3050):     QB-Token-ExpirationDate=2015-06-06 09:44:09 UTC
06-06 03:44:11.890: D/QBASDK(3050):     QuickBlox-REST-API-Version=0.1.1
06-06 03:44:11.890: D/QBASDK(3050):     Server=nginx/1.0.15
06-06 03:44:11.890: D/QBASDK(3050):     Status=404 Not Found
06-06 03:44:11.890: D/QBASDK(3050):     Transfer-Encoding=chunked
06-06 03:44:11.890: D/QBASDK(3050):     X-Rack-Cache=miss
06-06 03:44:11.890: D/QBASDK(3050):     X-Request-Id=4dde392fc0e70b3032595495dc3e4ebc
06-06 03:44:11.890: D/QBASDK(3050):     X-Runtime=0.023759
06-06 03:44:11.890: D/QBASDK(3050):     X-UA-Compatible=IE=Edge,chrome=1
06-06 03:44:11.890: D/QBASDK(3050): BODY
06-06 03:44:11.890: D/QBASDK(3050):     ' '
06-06 03:44:11.890: D/Track(3050): onError()

Please any suggestion and thank you.

A: I solved the problem i just forgot to add tags to my users


text:
Q: Observer\DOMDocument' not found when use new DOMDocument() in Obeserver I am calling api in the Obeserver file. After this load xml data of response i am using
$doc = new DOMDocument();
$doc->loadXML($response);

But i am getting Fatal Error: Class 'PackageName\ModuleName\Observer\DOMDocument' not found in
Please provide me some solution.

A: I have found solution
We can use as following:
use Magento\Framework\DomDocument\DomDocumentFactory;

public function __construct(
 DomDocumentFactory $domFactory
) {

    $this->domFactory = $domFactory;

}
public function execute(\Magento\Framework\Event\Observer $observer) {
    $doc = $this->domFactory->create();
    $doc->loadXML($response);
}

A: We can also use it including it like this:
namespace Vendor\Namespace\Controller\Checkout;

use \DOMDocument;
use Magento\Framework\Filesystem\DirectoryList;

class MyClass ...

````


text:
Q: OSGi unit testing without step that packages bundles I have checked a few testing solution for OSGI including PAX and had a quick look at the abstract TestCase within Spring DM but they both appear to require one to jar up and bundle associated bundles. I was hoping to find something that works without this intermediate step.
Imagine the ability to package up packages on your classpath so that packages x and y made up bundle XY and packages x and z made up bundle XZ. Bundle XZ would not "see" package "y" but could import a service from XY living in package x. Any comments if this is possible or if a equivalent test case / library exists ?

A: I think that using Tiny Bundles from OPS4J with Pax Exam is what you are looking for.
http://wiki.ops4j.org/display/paxexam/ExamAndTinybundles

A: If you really want to enforce runtime visibility rules than you probably have to run your tests inside OSGi environment and pay some performance overhead.
However it might be sufficient for you to enforce compile time visibility by separating your classes into distinct compilation units (e.g. separate Maven modules X,Y,Z) with proper dependencies and then running a standard testing framework (e.g. JUnit) without OSGi.


text:
Q: Android Studio Layout Preview stuck loading I'm having this problem with a new mac I got. The issue is that whenever I try to use the preview for layout or the design of the layout, I get the loading spinner that doesn't stop. It just keeps going. I've waited several minutes and nothing happens. It just keeps on spinning.
I've tried to invalidate my cache and restart android studio, but it freezes. Forcing me to force quit the application and restart it.
I've tried upgrading my Android Studio version to the latest (3.5 preview), but to no avail
I've tried changing all of the options like API, device, App Theme in the design
I'm currently using a Mac on 10.13.6

A: This below command helped me to fix the stucking issue:
rm -Rf ~/Library/Preferences/AndroidStudio*
rm -Rf ~/Library/Preferences/com.google.android.*
rm -Rf ~/Library/Preferences/com.android.*
rm -Rf ~/Library/Application\ Support/AndroidStudio*
rm -Rf ~/Library/Logs/AndroidStudio*
rm -Rf ~/Library/Caches/AndroidStudio*

A: I had this issue but non of the above answers worked for me, this was how I solved it:

*

*close the existing project

*take android studio to the welcome screen

*at the bottom of the welcome screen click on Configure
see image for more details

*from the list of items select Restore Default Settings
see image for more details

*finally select Restore and Restart
see image for more details
Your android studio will restart. If you are asked to import settings, select Do not import. I believe this issue is caused by a corrupt android studio settings so re-importing existing settings will lead to the same error.
For windows computers, the solution might just be to delete the android studio folder in your home directory that carries the version of android studio you're using.
Installing another version of android studio could also solve this issue only if you do not re-import your existing android studio settings.

A: After opening your project on Android Studio, from your Mac's Menubar, navigate to
Files -> Sync Project with Gradle Files
Wait for the project to sync completely.
Hope this helped.

A: It downloads the essential file for using layout as u can see it on the background tasks on the bottom right nearer to the corner.
So loading signifies as it downloads some modules on background
so just dont close the program

A: Remove the project and Reimport the project again. It works for me :)


text:
Q: Clustered composite key high fragmentation and fill factor I've recently made a table to hold the language preferences of my users as follow:
CREATE TABLE [dbo].[systemUserLangPreference](
  [systemUserID] [int] NOT NULL,
  [langID] [int] NOT NULL,
  [preferredOrder] [int] NOT NULL,
  [createdBy] [int] NOT NULL,
  [createdOn] [datetime] NOT NULL,
  [lastActionBy] [int] NOT NULL,
  [lastActionOn] [datetime] NOT NULL,
CONSTRAINT [PK_systemUserLangPreference] PRIMARY KEY CLUSTERED
([systemUserID] ASC, [langID] ASC)
WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF,
 ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 80) ON [PRIMARY]
) ON [PRIMARY]

There's less than 1,000 rows in there now so performance isn't much of an issue at this time however when I run an index fragmentation report this index and more of my compound keys always comes up as high fragmentation no matter what I do.
Using
SELECT ps.database_id, ps.OBJECT_ID,
ps.index_id, b.name,
ps.avg_fragmentation_in_percent
FROM sys.dm_db_index_physical_stats (DB_ID(), NULL, NULL, NULL, NULL) AS ps
INNER JOIN sys.indexes AS b ON ps.OBJECT_ID = b.OBJECT_ID
AND ps.index_id = b.index_id
WHERE ps.database_id = DB_ID()

This one index will return 80% avg fragmentation even moment after I rebuild it.  I've tried playing with the fill factor with the following results:
Fill 100%; Fragmentation 75%
Fill 80%; Fragmentation 80%
Fill 50%; Fragmentation 62.5%
Fill 10%; Fragmentation 19.44%
Fill 1%; Fragmentation 1.90%

So it seems the lower I go the better? I'm not sure I'm interpreting this right. Since the table is mostly reads (insert on new user and I guess when they learn a language) wouldn't a higher fill factor be better? Why does it lead to immediate fragmentation and is it a bad thing?

A: For very small tables, fragmentation is not only irrelevant, but nearly impossible to control.  The first eight pages are allocated out of mixed extents, which are almost always going to be non-sequential.  Only after an index has more than eight pages will it be allocated additional pages from uniform extents.
At fewer than 1,000 rows, your clustered index would be well under 64K and entirely allocated out of mixed extents (unless you start forcing the issue by adjusting the fill factor, as you have seen).

You can get an idea of how this clustered index's pages are allocated by issuing this command:
DBCC EXTENTINFO( DB_NAME, systemUserLangPreference, PK_systemUserLangPreference)

Once the index is large enough that it is allocated more than eight pages, you can ensure that they are all allocated out of uniform extents by dropping the index and then creating it again.  Again, though, for such a small table, fragmentation is not going to have a performance impact, and you probably shouldn't try to solve it by fiddling with fill factor.
Lowering the fill factor might actually have detrimental results, as fewer records fit on each page, so more pages needed to be loaded into memory.  Here's more on why to be careful with the fill factor.
For more details on pages and extents, see this article.


text:
Q: Insert component into html dynamically I'm trying to insert a angular-material component inside a piece of html dynamically. The way i think, i won't be able to use ViewContainerRef.
Here's how it needs to work:
I'll retrieve a string from the database (it can be any material component, such as inputs, buttons, etc... Something like this:
let stringFromDB = "<md-spinner></md-spinner>"

I would need to pass this string to my html's div (which is my "container"). So i tryied:
@Component({
    selector: 'report',
    template: `<div [innerHtml]="stringFromDB"></div>`
})
export class ReportComponent{
    stringFromDB : string = null;

    constructor(){
        this.stringFromDB =this.someService.getTemplateStringFromDatabase();
    }
}

I can pass a simple

.
But not a component like md-spinner. Any thoughts on how to accomplish this?

A: In angular 4 you can use ngComponentOutlet.
Template:
<ng-container *ngComponentOutlet="dynamicComponent; ngModuleFactory: dynamicModule;"></ng-container>

Build dynamic module and component with your template string:
import { Compiler } from '@angular/core';

build() {
    this.dynamicComponent = this.createDynamicComponent(this.stringFromDB);
    this.dynamicModule = this._compiler.compileModuleSync(this.createDynamicModule(this.dynamicComponent));
}

createDynamicModule(componentType: any) {
    @NgModule({
        imports: [ ],
        declarations: [
            componentType
        ],
        entryComponents: [componentType]
    })
    class RuntimeModule { }
    return RuntimeModule;
}

createDynamicComponent(template: string) {
    @Component({
        selector: 'dynamic-component',
        template: template ? template : '

'
    })
    class DynamicComponent {
        constructor() {
        }
    }
    return DynamicComponent;
}


text:
Q: Conditional typedefs If I have a little peice o' code as such...
template <typename _T>
class Foo
{
public:
    typedef const T& ParamType;
    void DoStuff(ParamType thingy);
};

This can be non-optimal if sizeof(_T) <= sizeof(_T*).
Therefore, I want to have a conditional typedef. If the size of _T is less than or equal to that of a pointer, just pass it in by value. Otherwise, pass it by const reference. Is this possible? I hear all this stuff about templates being turing complete but this is hurting my head.

A: Quite easy to achieve using partial template specialization.
template< typename _T, bool _ByVal >
struct FooBase {
  typedef const _T& ParamType;
};

template< typename _T >
struct FooBase< _T, true > {
  typedef const _T ParamType;
};

template< typename _T, bool _ByVal = sizeof(_T) <= sizeof(void*) >
class Foo : public FooBase< _T, _ByVal > {
  typedef typename FooBase< _T, _ByVal >::ParamType ParamType;
  void DoStuff(ParamType thingy);
};

EDIT As per Jeff's sol'n one should indeed compare sizeof(_T) and sizeof(_T&) but I kept the original <= void* requirement.

A: You can do that, but it's a little tricky.
My main concern here if your motive. I understand that you don't want to pass large objects by value, but whether or not the object is large is irrelevant -- what you really want to know is how long the copy constructor takes to create the parameter.
As a concrete example, the size of an std::vector is actually very tiny as it allocates all the memory on the heap and only needs a pointer. However, copying a vector takes much more time. Something like that is not something you can really include in a condition.
You're best bet here is to just pass by const & so that you cover the worst case. Also, I can't guarantee this, but the I believe that a compiler would be smart enough to pass by value if it thought that was more efficient.

A: template <class T, bool Smaller>
class BestArgumentPassingType {};

template <class T>
class BestArgumentPassingType<T, true> {
  public:
    typedef T Type;
};

template <class T>
class BestArgumentPassingType<T, false> {
  public:
    typedef const T& Type;
};

template <class T>
class ArgumentType : public BestArgumentPassingType<T, sizeof(T) < sizeof(T*)> {
};

struct B { double d; double d2; };
struct S { double d; };

class A {
  public:
    static void foo(ArgumentType<B>::Type big);
    static void bar(ArgumentType<S>::Type small);
};

int main()
{
  B b;
  S s;
  A::foo(b);
  A::bar(s);
  return 0;
}

Like so.

A: You can use Boost call traits.
template <typename _T>
class Foo
{
public:
    void DoStuff(boost::call_traits<_T>::param_type thingy);
};

From the documentation:

If T is a small built in type or a pointer, then param_type  is defined as T const, instead of T const&.

A: I know it's not directly what you asked for, but it's your goal. I would use a different way to achieve this: Pass classes (this includes structs and unions) by reference, and pass everything else by value.
template<typename>
struct tovoid { typedef void type; };

template<typename T, typename = void>
struct parm_type {
  typedef T type;
};

template<typename T>
struct parm_type<T, typename tovoid<int T::*>::type> {
  typedef T const& type;
};

template <typename T>
class Foo
{
public:
    typedef typename parm_type<T>::type ParamType;
    void DoStuff(ParamType thingy);
};

This implements the (in my opinion) very good point that @Poita_ made.


text:
Q: How to display only taxonomies of custom post type in a page? I have created recipe as a custom post and types as a taxonomy.
In that taxonomy I have created vegetables and fruits as fields and I have 5 posts in each fields, but I need to display only vegetables and fruits in the page?
The below Query is what I currently use. It displays all posts.
<?php
    $mypost = array( 'post_type' => 'recipe', );
    $loop = new WP_Query( array( 'post_type' => 'recipe', 'posts_per_page' => 9 ) );
?>

Can anyone help me?

A: You can use a taxonomy query, like this:
$args = array(
        'post_type' => 'recipe',
        'tax_query' => array(
            array(
                'taxonomy' => 'types',
                'field' => 'slug',
                'terms' => array( 'vegetables', 'fruit' )
                 )
        )
);
$query = new WP_Query( $args );


text:
Q: Attribute Error: Generator object has no attribute 'X' I am trying to implement a method (python 3.4) in which two objects are passed. But I am receiving the following error.
"AttributeError: Generator object has no attribute 'X'"
The code is as shown below:
    def method_name(node1, node2):
        parsed = []
        nextList = asyncio.Queue()
        iterations = 0
        while not ((newNode.X == node2.X) and (newNode.Y == node2.Y)):
            #code

I am unable to figure out why I am getting this error. I tried printing the value of the attributes before using them in the while loop. I am able to succesfully print it. But I face issues when I try to use it in the while loop.
Thanks in advance for your help.


text:
Q: Trouble starting up with kinect toolbox recorder I am starting up with the kinect for the first time along with the kinect.toolbox. I was trying to use the kinect.toolbox recorder along with the color basics wpf c# provided with the microsoft developer toolkit for the kinect sdk v1.8. However, when I click on the start recording button, it doesn't create a .recorded file as explained in this answer. Can you please help me and tell me what I am doing wrong?
Below is my code:
using Kinect.Toolbox.Record;

namespace Microsoft.Samples.Kinect.ColorBasics
{
    using System;
    using System.Globalization;
    using System.IO;
    using System.Windows;
    using System.Windows.Media;
    using System.Windows.Media.Imaging;
    using Microsoft.Kinect;

    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        /// <summary>
        /// Active Kinect sensor
        /// </summary>
        private KinectSensor sensor;
        Stream recordStream;
        KinectRecorder recorder;

        /// <summary>
        /// Bitmap that will hold color information
        /// </summary>
        private WriteableBitmap colorBitmap;

        /// <summary>
        /// Intermediate storage for the color data received from the camera
        /// </summary>
        private byte[] colorPixels;

        /// <summary>
        /// Initializes a new instance of the MainWindow class.
        /// </summary>
        public MainWindow()
        {
            InitializeComponent();
        }

        /// <summary>
        /// Execute startup tasks
        /// </summary>
        /// <param name="sender">object sending the event</param>
        /// <param name="e">event arguments</param>
        private void WindowLoaded(object sender, RoutedEventArgs e)
        {
            // Look through all sensors and start the first connected one.
            // This requires that a Kinect is connected at the time of app startup.
            // To make your app robust against plug/unplug,
            // it is recommended to use KinectSensorChooser provided in Microsoft.Kinect.Toolkit (See components in Toolkit Browser).
            foreach (var potentialSensor in KinectSensor.KinectSensors)
            {
                if (potentialSensor.Status == KinectStatus.Connected)
                {
                    this.sensor = potentialSensor;
                    break;
                }
            }

            if (null != this.sensor)
            {
                // Turn on the color stream to receive color frames
                this.sensor.ColorStream.Enable(ColorImageFormat.RgbResolution640x480Fps30);

                // Allocate space to put the pixels we'll receive
                this.colorPixels = new byte[this.sensor.ColorStream.FramePixelDataLength];

                // This is the bitmap we'll display on-screen
                this.colorBitmap = new WriteableBitmap(this.sensor.ColorStream.FrameWidth, this.sensor.ColorStream.FrameHeight, 96.0, 96.0, PixelFormats.Bgr32, null);

                // Set the image we display to point to the bitmap where we'll put the image data
                this.Image.Source = this.colorBitmap;

                // Add an event handler to be called whenever there is new color frame data
                this.sensor.ColorFrameReady += this.SensorColorFrameReady;

                // Start the sensor!
                try
                {
                    this.sensor.Start();
                }
                catch (IOException)
                {
                    this.sensor = null;
                }
            }

            if (null == this.sensor)
            {
                this.statusBarText.Text = Properties.Resources.NoKinectReady;
            }
        }

        /// <summary>
        /// Execute shutdown tasks
        /// </summary>
        /// <param name="sender">object sending the event</param>
        /// <param name="e">event arguments</param>
        private void WindowClosing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            if (null != this.sensor)
            {
                this.sensor.Stop();
            }
        }

        /// <summary>
        /// Event handler for Kinect sensor's ColorFrameReady event
        /// </summary>
        /// <param name="sender">object sending the event</param>
        /// <param name="e">event arguments</param>
        private void SensorColorFrameReady(object sender, ColorImageFrameReadyEventArgs e)
        {
            using (ColorImageFrame colorFrame = e.OpenColorImageFrame())
            {
                if (colorFrame != null)
                {
                    // Copy the pixel data from the image to a temporary array
                    colorFrame.CopyPixelDataTo(this.colorPixels);

                    // Write the pixel data into our bitmap
                    this.colorBitmap.WritePixels(
                        new Int32Rect(0, 0, this.colorBitmap.PixelWidth, this.colorBitmap.PixelHeight),
                        this.colorPixels,
                        this.colorBitmap.PixelWidth * sizeof(int),
                        0);
                }
            }
        }

        /// <summary>
        /// Handles the user clicking on the screenshot button
        /// </summary>
        /// <param name="sender">object sending the event</param>
        /// <param name="e">event arguments</param>
        private void ButtonScreenshotClick(object sender, RoutedEventArgs e)
        {
            if (null == this.sensor)
            {
                this.statusBarText.Text = Properties.Resources.ConnectDeviceFirst;
                return;
            }

            // create a png bitmap encoder which knows how to save a .png file
            BitmapEncoder encoder = new PngBitmapEncoder();

            // create frame from the writable bitmap and add to encoder
            encoder.Frames.Add(BitmapFrame.Create(this.colorBitmap));

            string time = System.DateTime.Now.ToString("hh'-'mm'-'ss", CultureInfo.CurrentUICulture.DateTimeFormat);

            string myPhotos = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures);

            string path = Path.Combine(myPhotos, "KinectSnapshot-" + time + ".png");

            // write the new file to disk
            try
            {
                using (FileStream fs = new FileStream(path, FileMode.Create))
                {
                    encoder.Save(fs);
                }

                this.statusBarText.Text = string.Format(CultureInfo.InvariantCulture, "{0} {1}", Properties.Resources.ScreenshotWriteSuccess, path);
            }
            catch (IOException)
            {
                this.statusBarText.Text = string.Format(CultureInfo.InvariantCulture, "{0} {1}", Properties.Resources.ScreenshotWriteFailed, path);
            }
        }

        private void button_Start_Recording(object sender, RoutedEventArgs e)
        {
            string generatedName = Guid.NewGuid().ToString();
            string recordStreamPathAndName = @"C:\" + generatedName + ".recorded";
            this.recordStream = File.Create(recordStreamPathAndName);
            this.recorder = new KinectRecorder(KinectRecordOptions.Color | KinectRecordOptions.Skeletons, recordStream);
            button1.IsEnabled = false;

        }

        private void button_Stop_Recording(object sender, RoutedEventArgs e)
        {
            if (recorder != null)
            {
                recorder.Stop();
                recorder = null;
                button1.IsEnabled = true;
            }
        }
    }
}

A: I cant see the call to this.recorder.Record(colorFrame) in your private void SensorColorFrameReady(object sender, ColorImageFrameReadyEventArgs e) method.
Try to add this.


text:
Q: Installing Eclipse RCP Plugins I have an Eclipse RCP application that I would like to install a plugin into. I know the plugin works with the application, and with older versions of the application I could just drop the plugin JAR into plugins/ folder and it would be available next time I loaded the application.
However, with the current version, the JAR doesn't seem to get picked up when I put it in the plugins/ folder. I've tried running the application with the --clean flag, but that doesn't help.
How do I tell the application that I want to install the plugin?
Update: Got it working by adding the plugin to the config.ini - I've not needed to do that before, previously it would just be picked up when I placed it in the plugins/ folder. Is there a configuration option that disables the detection of new plugins from the plugins/ folder?

A: @Fredrik basically says it: You need to put the plugin in the "dropins" folder, the sister directory to the plugins directory.  Then restart.  I usually run eclipse -clean just to be safe.  If there's a problem with the plugin, you will need to using the p2 debugger as mentioned in https://stackoverflow.com/a/12480978/2295812

A: Got it working by adding the plugin to the config.ini - I've not needed to do that before, previously it would just be picked up when I placed it in the plugins/ folder. Is there a configuration option that disables the detection of new plugins from the plugins/ folder?


text:
Q: How to include json content inside a js variable I have this js variable which is parsing a json content inline:
var places = {
    "type": "FeatureCollection",
    "features": [{
        "type": "Feature",
        "properties": {
            "icon": "theatre"
        },
        "geometry": {
            "type": "Point",
            "coordinates": [-77.038659, 38.931567]
        }
    }]
};

I need this content to be inside an external json file since it is a long list to load dynamically.
Can you tell me how to call the json file (the code must be as it is and not parsed)? I tried dozens of solution here but without results :(
Thanks in advance for your help


text:
Q: How to get default collation in rails? In database.yml i have this configuration:
  development:
      adapter: mysql2
      encoding: utf8
      ...

But ActiveRecord::Base.connection.collation returns latin1_swedish_ci this is not what i expected, because default collation is utf8_unicode_ci. How can i get default collation in rails?

A: As per my knowledge you can check it on two places, remember you have also to check your mysql database. For ruby on rails you can check configuration and add as per following at end of your database.yml file
encoding: utf8mb4
collation: utf8mb4_unicode_ci

Restart server and now it should be following this configuration. Than check with following command
ActiveRecord::Base.connection.collation

Now let us check on mysql
mysql> show variables like 'collation%';

Right now I can't check these things as mysql is not setup, so will edit later to confirm you all.


text:
Q: Select * from a table using data from specific entry in table I have an author table
| au_id | au_fname | au_lname | city | state |
what i am trying to do is get a query of first and last names based on who lives in the same state as Sarah
Heres what I have so far:
SELECT AU_FNAME, AU_LNAME FROM authors WHERE "STATE" like 'CA'

I don't want to use a static state in my code, I want it to be based on the selected person  - Sarah in this case.
Thanks

A: Use a Sub-Query to find the state of Sarah and filter that state
Try this
SELECT AU_FNAME, AU_LNAME
FROM authors
WHERE STATE in (select state from authors where au_fname = 'Sarah')

A: SELECT AU_FNAME, AU_LNAME FROM authors WHERE STATE in (select state from authors where au_fname = 'sarah')

or
select a1.AU_FNAME, a1.AU_LNAME FROM authors a1
inner join authors a2 on a1.state = a2.state
where a2.au_fname = 'sarah'

A: If there is only one "Sarah", then it is best to use = rather than in:
select a.AU_FNAME, a.AU_LNAME
from authors a
where a.state = (select a2.state from authors a2 where a2.au_fname = 'Sarah');

Of course, if there could be more than one Sarah, then in is needed.  But = often has better performance, because the database engine knows to search for a single value.

A: The question is defined a bit vaguely, so based on a qualified guess, it seems asking for the solution to retrieve data rows (containing either ALL data fields, i.e. SELECT * as per the title, or just first/last names as per description, i.e. SELECT AU_FNAME, AU_LNAME) for the states related to some au_fname (e.g. Sarah) passed as a parameter to a SQL query. In the most general case, there can be multiple different authors with the same first name related to multiple different states. Based on this assumption, the query/sub-query may look like
SELECT * FROM authors
WHERE STATE IN (SELECT [state] from authors WHERE au_fname = @afname)

The exact syntax may depend on the specifics of the Database used in the solution.

A: An inner join would be my first choice over a subquery... some db engines have poor performance with subqueries (older MySQL versions come to mind), but just about any engine ought to be optimized for an inner join:
SELECT a1.AU_FNAME, a1.AU_LNAME
FROM Authors AS a1
INNER JOIN Authors AS a2 ON a1.state = a2.state
WHERE a2.au_fname = 'sarah'
GROUP BY a1.AU_FNAME, a1.AU_LNAME;


text:
Q: How to add peers dynamically to an existing hyperledger fabric network using node sdk? In all of the tutorials , I see that we can add an organization or peer manually to  an existing fabric network. But how do i dynamically assign an incoming node as a peer or an orderer depending on some criteria?

A: I am not sure about adding peer to fabric network using node sdk, but you can definitely add peer by using CLI.
For that you need to generate crypto material for new Peer and joining the existing channel
Please follow below link for more detail
Extending Hyperledger Fabric Network: Adding a New Peer


text:
Q: How does Mocha know to be async? Mocha can determine whether to expect a callback (done), or whether it should run a test in sync, solely based off of you passing the callback as a parameter.
// Sync
it("should be amazing", function (){
    expect(amazing).equals(true);
});

// Async
it("should be amazing, eventually", function (done) {
  setTimeout(function () {
    expect(amazing).equals(true);
    done();
  }, 1000);
});

I don't know how it does this. The only way I can think is that it literally parses the function as a string, breaks it down and determines if a parameter is passed.
Is this what happens?

A: You wouldn't expect it, but functions have a length property! It is equal to the number of arguments the function takes.
I'll edit the answer to add a snippet out of mocha when I find it, but that's a valid way that it can detect whether or not it accepts an argument. Check the length for if it's one, that decides whether or not the test is async or not.
Edit: I found it. For context, it inherits from Runnable.
function Runnable(title, fn) {
    // Other properties...
    this.async = fn && fn.length;
    // Other properties...
}

A: It uses either a string parser on the callback or an argument length check.
Something like this
function it(name, callback) {

   if (callback.length > 0) {
      callback(function done(e) {
          if (e) throw "test finished with error"
          //test finished
      })

   } else {
       callback()
       //test finished
   }
}


text:
Q: Subversion + Vimdiff: how to abandon the diff process? I have configured svn to open differences using the text (i.e. not graphical) version of vim. Whenever I'm satisfied viewing the changes of the current file I quit vim -- with :qa -- and the next file is opened up. How can I abort this process without the need to view all of the files? (I don't know if this is something that must be done within vim or svn.)

A: I don't know how exactly the invocation of Vim from svn works (and you didn't list your configuration so that I could quickly try this), but you could try quitting Vim with :cquit, which sends an error code back to the invoking process. Maybe that causes svn to abort the loop.


text:
Q: Getting error for user fields in LWC component when using schema? I am trying to retrive field information for user fields using following code.
But except for the Name field of User, it is throwing error for every other field.
Any idea why its not letting me access user fields using schema.
I went ahead and tried Apex route also but same result.
import { LightningElement, wire, track } from 'lwc';
import USER_ID from '@salesforce/user/Id';
import NAME_FIELD from '@salesforce/schema/User.Name';
import PHONE_FIELD from '@salesforce/schema/User.Phone';
import ROLE_FIELD from '@salesforce/schema/User.UserRole.Name';

export default class myComponent extends LightningElement {
    @track error ;
    @track name;
    @track phone;
    @track role;
    @wire(getRecord, {
         recordId: USER_ID,
         fields: [NAME_FIELD]
    }) wireuser({
         error,
         data
     }) {
         if (error) {
            this.error = error ;
         } else if (data) {
             this.name = data.fields.Name.value;
             //this.phone = data.fields.Phone.value;
             //this.role = data.fields.UserRole.value.fields.Name.value;
         }
     }
}

Error Details:

Invalid reference User.Phone of type sobjectField in file
myComponent.js: Source

Addtional Details:
I am using following extension for editing the code.
Salesforce LWC Editor

A: For getting around similar error in LWC Editor, select 'Standard Deployment?' checkbox on the bottom right corner of the editor.

A: This is a known issue with the LWC Deployment with the tooling API of Salesforce. If the underlying tool in your case the chrome extension uses tooling API for LWC Bundle deployment causing the issue.
Currently only workaround for this is to switch to alternate tools like SFDX CLI or use Salesforce VSCode extension to deploy your LWC component as those use Metadata API than using the tooling API.


text:
Q: php - how to store expiry date in a database and run a (delete) script at date I have a simple website where users can post ads, i want to set an expiry date based in a mysql table when the user uploads an ad, say in one months time and then when that date is reached then my delete script will be automatically run to remove the ad
any help much appreciated!!

A: add script:
INSERT INTO ads (expires_on, ...)
VALUES (now() + INTERVAL 1 MONTH, ...)

delete script:
SELECT ...
WHERE expires_on <= now()

Simply have your delete script run once a day (e.g. cron job)

A: *

*Write a script which queries the database and deletes/flags any expired ads based on a timestamp set when the ad is created.

*Call this script from a cron job set to run nightly.

Better yet, if the data set is small, ignore the expired ads in your main code instead of deleting them at all.

A: add query:
INSERT INTO ads (expires_on, ...)
VALUES (now() + INTERVAL 1 MONTH, ...)

delete query:
DELETE from ads
WHERE expires_on <= now()

And run them in cron jobs, as others mentioned.


text:
Q: iOS initialise view programmatically without constraining the position Here is my problem, I have a scroll view scrollExerciseIndex that I use only as a scrolling bar, in this scroll view I place a UIView indexesView and I want it to be always at the center of the scroll view. For this I use layout constraints :

    UIView * indexesView = [[UIView alloc] initWithFrame: CGRectMake(xPosition, 0, dimension*numberIndexes, dimension)];
    [self.scrollExerciseIndex addSubview:indexesView];
    [self.scrollExerciseIndex setContentSize:CGSizeMake(dimension*numberIndexes, dimension)];
    if (xPosition != 0) {
        NSLayoutConstraint * xCenterConstraint = [NSLayoutConstraint constraintWithItem:indexesView attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:self.scrollExerciseIndex attribute:NSLayoutAttributeCenterX multiplier:1.0 constant:0];
        [self.scrollExerciseIndex addConstraint:xCenterConstraint];
    }
Here is the expected result :

Don't pay attention to all the element, just the bar at the bottom of the screen is my problem.
I have to create view programmatically because sometimes I will activate the constraints, sometimes not and I have to set the frame of the view dynamically. So for now I initialise the view indexesView like so :
UIView * indexesView = [[UIView alloc] initWithFrame: CGRectMake(xPosition, 0, dimension*numberIndexes, dimension)];
 (I know, not very original)
I would like to know if there is a way to initialize the view programmatically but to say to auto-layout that it has no constraints on the position because right now if the screen turns in landscape mode there is a conflict as the scrollview's frame changes so the distance between the center of the scroll view (on which I set a constraint) and the position of the subview's frame (xPosition) is no longer the same.

As you can see, the view is no longer at the center of the scroll view and I have some constraints broken.

Will attempt to recover by breaking constraint
  NSLayoutConstraint:0x7bed6c50 UIView:0x7bed6ad0.centerX == UIScrollView:0x7e273200.centerX

Thanks for your help.

A: Ok, I found what I was looking for by reading a book about Audio-Layout.
My problem was that audio layout would create constraints behind my back automatically. When using AutoLayout a type of constraints is created from non-autoLayout specifications (The used to describe interface when auto layout didn't exist). So constraints are created using the initial frame of the view. The only thing I had to do was :
[indexesView setTranslatesAutoresizingMaskIntoConstraints:NO];

to disable this creation of constraints from the frame, and then recreate explicitly the constraints for width and height if needed (which wasn't the case for me, but I still made the test) like so :
`NSLayoutConstraint * widthConstraint = [NSLayoutConstraint constraintWithItem:indexesView attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:0 multiplier:1.0 constant:widthValue];
 NSLayoutConstraint * heightConstraint = [NSLayoutConstraint constraintWithItem:indexesView attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:0 multiplier:1.0 constant:heightValue];

[indexesView addConstraint: heightConstraint];
[indexesView addConstraint: widthConstraint];`

When adding constraints programmatically, don't forget to call : [indexesView setNeedsUpdateConstraints]; so the constraints are recalculated only when needed.
Last info that I read and can be useful in general, when adding a lot of constraints, the apple doc specifies that it is more efficient to use the method :
    [myView addConstraints:(NSArray<NSLayoutConstraints *> *)] than to call addConstraint: for each constraint.
Hope it can be useful to someone.


text:
Q: ¿Cómo contar palabras en un vector de caracteres? El ejercicio pide un vector de caracteres Z con una frase. Mostrar la cantidad de palabras.
Entonces conté los espacios existentes en el arreglo, pero eso no contempla a la primera palabra. Para la última palabra conté el '.'. Lo hice así:
int Z[50];
int palabras;
for (int i=0;i<50;i++){
  if (z[i]==' ' || z[i] == '.')
     palabras++;
}

Hay otra forma para considerar la primera y última palabra de la frase?

A: Creo que tu idea de contar los espacios y puntos para determinar la cantidad de palabras tiene varios problemas, si comenzamos o terminamos la frase con un espacio o punto, o si hay más espacios entre palabras, en cualquier caso estaremos contando de más.
Lo que deberías hacer es considerar los espacios y los puntos como separadores (podríamos agregar cualquier otro caracter) y usarlos para ir sumando una palabra siempre que el caracter anterior no sea un "separador" es decir sea una palabra. Algo como esto:
#include  <stdio.h>

int main(void)
{

    char z[50]=" Un ejemplo, veamos cuantas palabras cuenta. ";
    int palabras=0;
    int es_palabra=0;

    for (int i=0;(i<50 && z[i]!=0);i++){
        if (z[i]!=' ' && z[i] != '.') {
          es_palabra = 1;
        } else {
          if (es_palabra == 1) {
              palabras++;
              es_palabra = 0;
          }
      }
    }
    /* Si el último caracter es de un palabra no olvidar sumarlo */
    if (es_palabra == 1)
        palabras++;

    printf("La frase \"%s\" tiene %d palabras\n", z, palabras);
    return 0;
}

Notas:

*

*En tu ejemplo has denominado de dos formas distintas el array Z, recuerda que C es sensible a mayúsculas y minúsculas.

*No olvides inicializar las variables, en C no hay valores iniciales,  al hacer esto int palabras; e intentar usar palabras sin inicalizar obtendrás cualquier valor.


text:
Q: wifi information files (/sys/devices/virtual/net/wlan0/*) missing on samsung galaxy On Samsung devices, the directory with network statistics /sys/devices/virtual/net/wlan0/ is missing... There are directories for other (e.g.loopback) interfaces.
wlan0 is the right name for the interface, it is in /sys/class/net or programmatic listing from java application.
Does anybody know why or where to find these data (e.g. nr of transmitted bytes and similar?)

A: The following is taken from Open Source Code PowerTutor
String interfaceName = SystemInfo.getInstance().getProperty("wifi.interface");
if(interfaceName == null) interfaceName = "eth0";

transPacketsFile = "/sys/devices/virtual/net/" +
                   interfaceName + "/statistics/tx_packets";

Hope this could help you.

A: In motorola X and Nexus 7 that file is located at :
/sys/class/net/wlan0/*

Network statistics on Nexus 7


text:
Q: Stop reflecting model of each other if same controller used twice in a page I have used mvc partial control in my page twice for search functionality.
It has it own controller to search, so my page has two controller with same name.

        @Html.Partial("_SearchPartial") // say it search1
        // some other code to show search results
        // ....
        // ..

        @Html.Partial("_SearchPartial") // say it search2
        // some other code to show search results
        // ....
        // ..

This is _SearchPartial:
<form name="SearchCommon">

                <input type="text" value="" placeholder="Stock" ng-model="search.Stock" />

                <input type="text" value="" placeholder="Make" ng-model="search.Make" />

                <input type="text" value="" placeholder="Year" ng-model="search.Year" />

                <input type="submit" value="SEARCH" ng-click="searchdata(search)" />

</form>

Now on init of MainController , i set the search model value in SetSearchParam() method like below:
$scope.SetSearchParam = function(){
   var s = {};
   s.Make = "Test";
   s.Year = "2012";
   s.Stock = "5"

   $scope.search = s;
};

As search model is used in SearchPartialController, and page has two search control, value of s will be set in both partial controller. Also when i change params in search1, it will reflect search2.
I want that those search params only set for search1, not for search2.
When i change search1 params , it should not reflect the search2 or vice versa.
Is there any way to achieve it?

A: I thing you should initialize your filter(search) before your function.
Controller:
$scope.search1 = { Make : "Test", Year: "2012", Stock : "5" };
$scope.searchdata = function(search){console.log(search);};

Your view:

    <form ng-submit="searchdata(search1)">
        <input type="text" placeholder="Stock" ng-model="search1.Stock" />
        <input type="text" placeholder="Make" ng-model="search1.Make" />
        <input type="text" placeholder="Year" ng-model="search1.Year" />
        <button type="submit" class="btn btn-sm btn-primary">
                    Save
        </button>
    </form >


text:
Q: Signalr connectionid in client side disconnect event How to get signalr connection id in client side disconnect event? I am using below method but $.connection.hub.id is always undefined.
$.connection.hub.disconnected(function () {
            var ConnectionID = $.connection.hub.id;
            alert(ConnectionID);
        });

A: I suppose one way you could do it is to create your own property on the hub object that stores the id when a connection to the server hub is established.
$.connection.hub.start(function() {
    $.connection.hub.__myConnection = $.connection.hub.id;

});

$.connection.hub.disconnected(function () {
    alert($.connection.hub.__myConnection );
});


text:
Q: Javascript play sound I want to know is there any play to play same wmv or mp3 from javascript, that will work for all the browsers?
I had a look at HTML5 audio tag, but seems i need to add there .ogg, .mp3,.wav files to support all the browsers, though i need to have only one audio file.
Any idea?
Many Thanks,
Hrayr

A: There probably is a way: http://jsmad.org/.
It is a pure javascript mp3 decoder.

A: If you want the best cross-browser support, you should provide more than one encoding. It's very simple to generate the other versions using a free encoding tool like Audacity. Then, provide at least an mp3 and an ogg version of the resource (I wouldn't bother with wav) as this will cover all the browsers that support html5 audio. Then, if you want to provide a fallback option, like flash, you can cover all those users of non-html5 browsers who have the flash plug-in installed. You can use something like mediaelementjs to simplify the process of providing a unified player.