text:
Q: Dynamics of circular motion of the bob in a conical pendulum The question has asked us to find the velocity and tension in the string whose lenght is L. Let 'r' be the radius of the circular path of the bob. I think the free body diagram looks like this

I want to calculate tension first
In the diagram ,
T = mg.costheta and
mg = T.costheta
From the driagram of the entire system
costheta = √(L^2 - r^2) / L
So my answer depends on which equation i use. The second one is the correct one. How to know which equation we have to use? the answer for velocity is is also different for the two equations.
Is there something like i should only resolve one of these two? Because since tension's component is what i need to find centripetal force, i dont really need to resolve mg?

A: Hope this helps

So you have:
ΣFy = T cosθ = mg (since the mass is stationary in the y-direction)
ΣFx = T sinθ = ma = $\frac{mv^2}{r}$ (since the sine component is responsible for the centripetal force of the circular motion)
From pythagoras you know that sinθ = $\frac{r}{L}$ so
T sinθ = T$\frac{r}{L}$ = $\frac{mv^2}{r}$
By dividing T$\frac{r}{L}$ = $\frac{mv^2}{r}$ by T cosθ = mg you get
$\frac{r}{cos θ L}$ = $\frac{v^2}{g r}$
By rearranging the above equation:
v = r ⋅ sqrt($\frac{g}{cosθ L}$), which is the tangetial speed of the mass.
The angular speed ω = $\frac{v}{r}$ so
ω = sqrt($\frac{g}{cosθ L}$)
The tension in the string can either be written as
T = $\frac{m v^2 L}{r^2}$
or
T = $\frac{m g}{cosθ}$
Hope it helped


text:
Q: About actual applymiddleware implementation in the redux

export default function applyMiddleware(...middlewares) {
  return (createStore) => (...args) => {
    const store = createStore(...args)
    let dispatch = () => {
      throw new Error(
        'Dispatching while constructing your middleware is not allowed. ' +
          'Other middleware would not be applied to this dispatch.'
      )
    }

    const middlewareAPI = {
      getState: store.getState,
      dispatch: (...args) => dispatch(...args),
    }
    const chain = middlewares.map((middleware) => middleware(middlewareAPI))
    dispatch = compose(...chain)(store.dispatch)

    return {
      ...store,
      dispatch,
    }
  }
}

This code is the actual implementation of applymiddleware form https://github.com/reduxjs/redux/blob/4.x/src/applyMiddleware.js . In this code mapping a middlewares passing middlewareAPI as argument to each middelware
let's take example thunk function
In that thunk function I am getting a dispatch and getState as arguments to handle async actions
please observe my question i am try to understand my doubt clearly
In that applyMiddleware function each middleware is passing a middlewareAPI as argument but inside middlewareAPI object dispatch is a some anonymous function returning a other function named as disptach. In the place of store we are passing a middlewareAPI object But how thunk function is getting a composed disptach as argument
My Doubts:
1.dispatch: (...args) => dispatch(...args) what is the meaning to this line and how it's going help in that code
2.we are passing middlewareAPI in the place of store object before store.dispatch function is updating and my thunk function is getting arguments as diapatch and getState. From redux-thunk my thunk function will be calling with diapatch and getState arguments. How dispatch function is getting updated dispatch function as argument to my thunk function

redpajama_set_name: RedPajamaStackExchange


text:
Q: Reading only Doubles don't work I have a problem reading double values from txt file. My program only converts ints to doubles, but i want to ignore them.
Example file:
1 2 3 4.5
5 6 7 8.1
9 10 11 12.7

Here is my code:
File file = new File("file.txt");

    try{
        Scanner scanner = new Scanner(file);
        scanner.useLocale(Locale.US);
        while (scanner.hasNextLine()){
            if (scanner.hasNext() && scanner.hasNextDouble()){
                double value = scanner.nextDouble();
                System.out.println(value);
            }
        }
    }catch(FileNotFoundException e){}

My output is:
1.0
2.0
3.0
4.5
5.0
6.0
7.0
8.1
9.0
10.0
11.0
12.7

A: Well, Integers can be represented as Doubles, so Scanner will pick them up when you ask it to find Doubles. You'll have to either check for Integer values manually after you scan them in, or else use Scanner.nextInt to skip over integer inputs and only use nextDouble when you (temporarily) run out of Integers. So your conditional inside your loop would look something like this:
if (scanner.hasNext()) {
    if (scanner.hasNextInt()) {
        scanner.nextInt(); // Ignore this value since it's an Integer
    } else if (scanner.hasNextDouble()){
        double value = scanner.nextDouble();
        System.out.println(value);
    }
}

Although to be perfectly honest, I'm a little confused why you're using hasNextLine() as the condition for your while loop, since this requires you to check separately for hasNext(), as you're doing now. Why not just do this?
while (scanner.hasNext()) { // Loop over all tokens in the Scanner.
    if (scanner.hasNextInt()) {
        scanner.nextInt(); // Ignore this value since it's an Integer
    } else if (scanner.hasNextDouble()){
        double value = scanner.nextDouble();
        System.out.println(value);
    }
}

A: Well then check if it has an integer as the next token, with .hasNextInt().

A: Try this...
if (scanner.hasNext()) {
        double value = scanner.nextDouble(); // Ignore this value since it's an Integer
        if (!value.toString().endsWith(".0"))
             System.out.println(value);
    }
}

It will break if you're not using standard numerals, but I'm not aware of any places that aren't. The reason for your error is that java converts int to double implicitly.


text:
Q: Force main.css to upload after sass compiler has run when using vscode Force main.css to upload after sass compiler has run when using vscode.
I'm using a extension called simple-ftp, but willing to try another extension for fix.


text:
Q: iOS app link usage in app for sharing detail about an app, which is still pending Apple's review, will Apple allow this? when I completed itunes connect app process (status is waiting for review) , itunes connect shows the app link in "links" section.
I am going to upload app first version (not yet any earlier version to Appstore) to Apple app store ,but i want to show the same app itunes link in my app (which is I am uploading) itself for share app link via email(body text) functionality but app is not yet ready for sale.
(Once app will approve,same link can work for download) ?
Is apple allow this and will approve app if I am doing like this ?

A: This is an absolutely normal thing. I have implemented that for asking the user to rate my own games and apps. When the app was submitted, the links didn't work, of course. They were accepted and when each app went live it would allow rating by the user.
I also have experience with "gift this app" links: no problem.


text:
Q: spring mvc one init binder for all controllers I have 5 controllers and i would like to register an InitBinder to all of them.
I know i can add this code to each of them.
@InitBinder
public void initBinder(WebDataBinder binder)
{
    binder.registerCustomEditor(StringWrapper.class, new StringWrapperEditor());
}

But i would like to define it only once (even create a bean of StringWrapperEditor and use it instead of creating new every time.)
I searched SO and some other places but didn't find any answear.
Is it even possible?
Im using spring 3.1.1 with java 1.6.

A: Though the initial question was about Spring 3.1, the following might be useful for those who use newer Spring versions.
One possible option is to move your @InitBinder to @ControllerAdvice, for example
@ControllerAdvice
class InitBinderControllerAdvice {
    @InitBinder
    fun initBinder(dataBinder: WebDataBinder) {
        dataBinder.registerCustomEditor(
            MLQueryOutputFormat::class.java,
            StringToMLQueryOutputFormat()
        )
        dataBinder.registerCustomEditor(
            IDatabaseOps.SortDirection::class.java,
            StringToSortDirection()
        )
    }
}

Regarding ConfigurableWebBindingInitializer, even though it's quite a powerful thing, it requires additional configuration in terms of validation and etc. So pay attention to detail once implementing it. For instance, the following code does the job as per InitBinder, but lacks setting a Validator. As a result, the validation of the rest controller param annotated with @Validated didn't work:
@Configuration
class WebMvcConfig {
    @Bean
    fun configurableWebBindingInitializer(): ConfigurableWebBindingInitializer {
        val initializer = ConfigurableWebBindingInitializer()
        initializer.propertyEditorRegistrars = arrayOf(
            PropertyEditorRegistrar {
                it.registerCustomEditor(
                    MLQueryOutputFormat::class.java,
                    StringToMLQueryOutputFormat()
                )
            }, PropertyEditorRegistrar {
                it.registerCustomEditor(
                    IDatabaseOps.SortDirection::class.java,
                    StringToSortDirection()
                )
            }
        )
        return initializer
    }
}

To add validation, one could do the following:
@Bean
fun configurableWebBindingInitializer(
    @Qualifier("defaultValidator") validator: Validator
): ConfigurableWebBindingInitializer {
    val initializer = ConfigurableWebBindingInitializer()
    initializer.validator = validator
    ...

A: Implement a PropertyEditorRegistrar which registers all your custom PropertyEditors. Then in your configuration add a ConfigurableWebBindingInitializer which you hookup with the created PropertyEditorRegistrar and hook it to your HandlerAdapter.
public class MyPropertyEditorRegistrar implements PropertyEditorRegistrar {

    public void registerCustomEditors(PropertyEditorRegistry registry) {
         registry.registerCustomEditor(StringWrapper.class, new StringWrapperEditor());
    }
}

If you have a <mvc:annotation-driven /> tag in your configuration, the problem is that with this tag you cannot add the WebBindingInitializer to the adapter next to that there is already a ConfigurableWebBindingInitializer added to the pre-configured HandlerAdapter. You can use a BeanPostProcessor to proces and configure the bean.
public class MyPostProcessor implements BeanPostProcessor {

    public Object postProcessBeforeInitialization(Object bean, String name) throws BeansException {
        if (bean instanceof RequestMappingHandlerAdapter) {
            WebBindingInitializer wbi = ((RequestMappingHandlerAdapter) bean).getWebBindingInitializer();
            if (wbi == null) {
                wbi = new ConfigurableWebBindingInitializer();
                ((RequestMappingHandlerAdapter) bean).setWebBindingInitializer(wbi);
            }

            if (wbi instanceof ConfigurableWebBindingInitializer) {
                ((ConfigurableWebBindingInitializer) wbi).setPropertyEditorRegistrar(new MyPropertyEditorRegistrar());
            }

        }
    }

}

Requires a bit of work but it is doable. You could also implement your own WebBindingInitializer.
If you don't have the tag you can simply manually configure a RequestMappingHandlerAdapter and wire everything together.
Links

*

*PropertyEditorRegistrar javadoc

*ConfigurableWebBindingInitializer javadoc

*Reference Guide link


text:
Q: event machine gem bundle install is not working I am following a tutorial and had to do a bundle install following the forking & cloning of a repository. Subsequently we are instructed to run bundle install. However, it is not working and I am getting the following error message:
make
generating rubyeventmachine-i386-mingw32.def
compiling binder.cpp
In file included from binder.cpp:20:0:
project.h:85:0: warning: "FD_SETSIZE" redefined
<command-line>:0:0: note: this is the location of the previous definition
compiling cmain.cpp
In file included from cmain.cpp:20:0:
project.h:85:0: warning: "FD_SETSIZE" redefined
<command-line>:0:0: note: this is the location of the previous definition
cmain.cpp: In function 'int evma_send_file_data_to_connection(long unsigned int,
 const char*)':
cmain.cpp:752:6: error: 'fstati64' was not declared in this scope
make: *** [cmain.o] Error 1

Gem files will remain installed in c:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0
.0/gems/eventmachine-0.12.10 for inspection.
Results logged to c:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/eventmach
ine-0.12.10/ext/gem_make.out
An error occurred while installing eventmachine (0.12.10), and Bundler cannot
continue.
Make sure that `gem install eventmachine -v '0.12.10'` succeeds before bundling.

I'm rather stuck on what to do at this point. I am on a Windows machine, any advice on how to troubleshoot this?

A: Try gem install eventmachine -v '0.12.10' Or sudo gem install eventmachine -v '0.12.10' and then retry bundle install.
Some gem needs sudo privileges to install.
For windows gem install eventmachine --pre. Its a known issue for window with ruby 1.9. https://github.com/eventmachine/eventmachine/issues/319

A: I was able to fix this by installing the latest version of the Eventmachine gem: https://rubygems.org/gems/eventmachine
And then subsequently instaling the latest version of the SQLite gem:
http://rubygems.org/gems/sqlite3-ruby
You might be prompted to update your Gemlockfile make sure to do that then everything else should work.


text:
Q: How do I grant privileges to a user/role in Windows 7? How do I grant specific privileges (not permissions) to a specific user?  I'm confused because it seems there are "permissions" and "privileges" and I need to be able to grant the SE_SYSTEMTIME_NAME privilege so that a piece of software I wrote can modify the system clock in Windows 7.  Apparently I need this privilege granted so I can make the the call to SetSystemTime defined by:
 Declare Function SetSystemTime Lib "Kernel32.dll" (ByRef lpSystemTime As SYSTEMTIME) As UInt32

However, I am unclear as to how to grant this privilege.  I do have Administrator permissions so I should be able to enable this privilege.  I've been going crazy trying to figure this out.  Any help on how to st privileges within Windows 7 would be greatly appreciated.
In short I want to know how to use the Windows 7 user interface or system utility to grant the SE_SYSTEMTIME_NAME privilege to my account.  How do I get this privilege granted so I can set the system time?


text:
Q: What & where is net.sf.josql? Look at this pom (as well as various other poms) in maven central:
http://repo1.maven.org/maven2/org/apache/activemq/activemq-optional/5.6.0/activemq-optional-5.6.0.pom.
In these poms are dependencies on net.sf.josql
<dependency>
  <groupId>net.sf.josql</groupId>
  <artifactId>josql</artifactId>
</dependency>
<dependency>
  <groupId>net.sf.josql</groupId>
  <artifactId>gentlyweb-utils</artifactId>
</dependency>

When you try http://mvnrepository.com/artifact/net.sf.josql/josql, it would return a 404.
So ... why would maven central have a pom which includes a dependency that is not found in maven central?
In fact, I can't find net.sf.josql in either jboss or maven central repositories.
What is it and where can I find it?

A: From Guide to uploading artifacts to the Central Repository:

I have other repositories or pluginRepositories listed in my POM, is that a problem?
At present, this won't preclude your project from being included, but we do strongly encourage making sure all your dependencies are included in Central. If you rely on sketchy repositories that have junk in them or disappear, it just creates havok for downstream users. Try to keep your dependencies among reliable repos like Central, Jboss, etc.

So clearly Apache wished people would do this, but they don't thoroughly enforce it.
Googling for your artifact, it seems it is hosted here: http://repo.fusesource.com/maven2/. You will need to add this as an additional repository in your POM or settings file (see http://maven.apache.org/guides/mini/guide-multiple-repositories.html for the runes).

A: <repository>
  <id>repo.fusesource.com</id>
  <name>repo.fusesource.com</name>
  <url>http://repo.fusesource.com/maven2-legacy/</url>
  <layout>default</layout>
</repository>

Please add this on you pom.xml

A: I had same isse with Apollo 1.7.1.
I found all dependencies in apache-apollo-1.7.1-windows-distro.zip (apache-apollo-1.7.1\lib folder).
So I just run folowing in apache-apollo-1.7.1\lib
mvn install:install-file -Dfile=proton-0.3.0-fuse-2.jar -DgroupId=org.apache.qpid -DartifactId=proton-hawtdispatch -Dversion=0.3.0-fuse-2 -Dpackaging=jar
mvn install:install-file -Dfile=josql-1.5.jar -DgroupId=net.sf.josql -DartifactId=josql -Dversion=1.5 -Dpackaging=jar
mvn install:install-file -Dfile=gentlyweb-utils-1.5.jar -DgroupId=net.sf.josql -DartifactId=gentlyweb-utils -Dversion=1.5 -Dpackaging=jar


text:
Q: Is there a way to make matlab gridlines bold? I know that I can set the color of gridlines using:
pax = gca;
pax.GridColor = 'black';

But the gridlines are still a faint grey. I would like to make them darker. Is there a way to make the gridlines bold?
Note I do not want to make the gridlines thicker, I just want to make them darker that the faint grey that seems to be the automatic when using black
I am using polar plots and when I print them, the grids are almost too faint to see.

A: You need to modify the GridAlpha property as well so that the grid lines are actually opaque. The default value is 0.15 so even though they are black they appear gray since they are transparent. You'll want to use a GridAlpha value of 1 .
pax.GridAlpha = 1


text:
Q: if I were to use the getchar() function and enter two characters, where does the second character get stored? For example:
#include<stdio.h>

int main()
{
   char c;
   c = getchar(); // Let's say you enter AA
   printf("%c\n", c);
}

Does the second character get stuck in some reserve spot in memory like the stack? Because I know if I were to added another c = getchar(), the second character would be assigned to the variable c.

A:
Does the second character get stuck in some reserve spot in memory like the stack?

It is most likely in a buffer associated with stdin.

A: If you enter AA for a single character the remaining input will still be in the stdin buffer, as this program demonstrates. Instead of printing the characters, it prints their ASCII value for clarity. I entered AA<Enter> just once.
#include<stdio.h>

int main()
{
    char c;
    c = getchar(); // Let's say you enter AA<Enter>
    printf("%d\n", c);

    c = getchar(); // still another A to come
    printf("%d\n", c);

    c = getchar(); // still a newline to come
    printf("%d\n", c);

    return 0;
}

Program session
AA
65
65
10

A: as you know getchar only take one variable.so the 2nd 'A' will not store any where.it will be on ROM for sometime but the moment you hit enter it will vanish.


text:
Q: I'm moving jar file to other PC then the program not showing image I finished my project and done the compilation. Running the Jar file, program is working.
If I'm moving jar file to other PC then the program is not showing image and not showing information from txt files.
I thinking this is from wrong paths. Can you help me?
This some code:
FileInputStream fr2 = new FileInputStream("C:\\Users\\Nickolskiy\\IdeaProjects\\DeutcheCard\\src\\com\\2.txt");
BufferedReader br2 = new BufferedReader (new InputStreamReader(fr2, "Cp1251"));

A: The first line you gave is referring to an absolute file path. If the target machine does not have a file at that exact file location, it will not be able to open the file.
Because the file is located in the src directory, it will be packaged into the JAR. You can then use a different API to get a resource inside a JAR file, which looks like this:
/*
 * /com/ because the file is located in the com package
 */
InputStream is = getClass().getResourceAsStream("/com/2.txt");

That way, your code will stay portable.
Also, because you are not saying you got a stack trace, I suspect you have code like this:
try
{
    // Perform I/O actions
} catch (IOException ioe)
{
}

The empty catch block will cause all errors to be discarded. At least put a ioe.printStackTrace() in there to get the stack trace!
Another reason might be that you are not running the JAR file from a terminal. If you run the jar file with java -jar thejarfile.jar, you will be able to see when something gets printed out.

A: You are using an absolute path. You will get an FileNotFound-Exception, unless the other PC is using the same path. (C:\Users\Nickolskiy ...). Try to use a relative path.


text:
Q: Django - Html tags in email template I' m using Django signals to send emails when a new record is added:
@receiver(post_save, sender=MeetingMember)
def send_invited_emails(sender, instance,  **kwargs):
    host = instance.meeting.host
    subject = "Mizban invition"
    # htmly = get_template('sendingemail.html')
    domain = Site.objects.get_current().domain
    context={'host':host,'meeting': instance,'domain':domain}
    html_content = render_to_string('sendingemail.html',context)
    send_mail(subject, html_content, settings.EMAIL_HOST_USER,[instance.email])

This code works but it sends html tags in email as well how can I solve the issue?

A: The second parameter message is the message you want to display as raw text. You can pass the content of a HTML message through the html_message=… parameter of the send_mail(…) function [Django-doc]:
# …
html_content = render_to_string('sendingemail.html',context)
send_mail(
    subject,
    html_content,
    settings.EMAIL_HOST_USER,[instance.email],
    html_message=html_content
)
Usually for the message, one also creates a text variant of the message: one without HTML that can be used by simple email clients to display the email on a console terminal for example.


text:
Q: find average salaries from file in c++ I need to find average salary from employees of file
   John Harris $50000.00
   Lisa Smith $75000.00
   Adam Johnson $68500.00
   Sheila Smith $150000.00
   Tristen Major $75800.00
   Yannic Lennart $58000.00
   Lorena Emil $43000.00
   Tereza Santeri $48000.00

How can I access the salaries of the employees so that i can find the average? I have managed to get each line of a file into a string but I dont know how to access the salaries of each employee
my code is:
#include<iostream>
#include<fstream>
#include<cstring>

#include<cstdlib>
using namespace std;

int main()
{
    ifstream in;
    in.open("HW6Prob2.txt");

    if(in.fail())
    {
        cout<<"ERROR: File could not open."<<endl;
        exit(1);
    }

    string word[8];

    int i=0;
    for(i=0;i<8;i++)
    {
        getline(in,word[i]);    //get line string
        out<<word[i]<<endl;
    }
    string a=word[0];
    string b=word[1];
    string d=word[3];
    string e=word[4];
    string f=word[5];
    string g=word[6];
    string h=word[7];
    cout<<a[13]<<endl;
    string sum=
    cout<<sum<<endl;

    return 0;
}

A: This looks like a school assignment, so I'll give you some tips on how to approach the challenge with pseudo-code:
sum = 0
numberOfPersons = 0
for each line in "HW6Prob2.txt"
  pos = find position of $
  salary = cut the string from pos and parse as double

  sum = sum + salary
  numberOfPersons = numberOfPersons + 1
loop

average = sum / numberOfPersons

I hope you'll find this helpful!

A: I would suggest that you keep adding the average while you read the lines, so you just iterate once through the salaries list.
int i = 0;
float avg_salary = 0;
string line;
// get the sum while you read the lines
while(getline(in, line)) {
    // find the first salary digit position (just after the $ sign)
    int salaryStartPos = line.find('$') + 1;
    // Convert the salary string to a float with the atof method
    avg_salary += atof(line.substr(salaryStartPos, line.size()-1)
    ++i;
}
// Finally calculate the average
avg_salary = avg_salary / i;

A: You can use the stof function to get the float value from the string. All you need is to figure out the starting point of the float. In your case, you can use position of $ + 1 as the starting point. Use find function for that.

A: First you should iterate through the file lines (until end) to read all the data:
std::string line;
while(std::getline(file, line))
{
  // tokenize to get the last item and store it
}

If you have your file structure strictly defined as presented: [first_name] [last_name] $[salary] you can read each salary entry like:
const string salaryText = line.substr(line.find_last_of('$') + 1);

The extracted salary text should be converted to a number and either stored in a vector<float> or aggregated for each line. This depends on whether you also need to access particular salaries at some point. If you'd go with the vector option you could write smth like:
salaryList.push_back(std::stof(salaryText));

Afterwards you can calculate mean salary with:
const double salarySum = std::accumulate(salaryList.begin(), salaryList.end(), 0.0);
const double salaryMean = salarySum / salaryList.size();

The advantage of having the salary list is that you can further calculate other statistics, not only the mean value.


text:
Q: Deixar apenas uma coluna do JTable editável Tenho meu modelo de dados que fiz pra testes como mostra o código abaixo:
public class ModeloDados {

    private String nome;
    private String sobreNome;
    private String telefone;

    public ModeloDados(String nome, String sN, String fn){
        this.nome=nome;
        this.sobreNome=sN;
        this.telefone=fn;
    }

    /**
     * @return the nome
     */
    public String getNome() {
        return nome;
    }

    /**
     * @param nome the nome to set
     */
    public void setNome(String nome) {
        this.nome = nome;
    }

    /**
     * @return the sobreNome
     */
    public String getSobreNome() {
        return sobreNome;
    }

    /**
     * @param sobreNome the sobreNome to set
     */
    public void setSobreNome(String sobreNome) {
        this.sobreNome = sobreNome;
    }

    /**
     * @return the telefone
     */
    public String getTelefone() {
        return telefone;
    }

    /**
     * @param telefone the telefone to set
     */
    public void setTelefone(String telefone) {
        this.telefone = telefone;
    }

}

E montei tambem uma classe com o AbstractTableModel, que seria o modelo de tabela:
public class tabelaPrincipal extends AbstractTableModel {

    private ArrayList linhas = null;
    private String[] colunas = null;

    public tabelaPrincipal(ArrayList lin, String[] col) {
        setLinhas(lin);
        setColunas(col);

    }

    public ArrayList getLinhas() {
        return linhas;
    }

    public void setLinhas(ArrayList dados) {
        linhas = dados;
    }

    public String[] getColunas() {
        return colunas;
    }

    public void setColunas(String[] nomes) {
        colunas = nomes;
    }

    @Override
    public int getColumnCount() {
        //retorna a quantidade de colunas(conta a quantidade e retorna)
        return colunas.length;
    }

    @Override
    public int getRowCount() {
        //retorna o tamanho do array(quantos letras tem)
        return linhas.size();
    }

    @Override
    public String getColumnName(int numCol) {
        return colunas[numCol];
    }

    @Override
    public Object getValueAt(int numLin, int numCol) {
        Object[] linha = (Object[]) getLinhas().get(numLin);
        return linha[numCol];
    }

    public boolean isCellEditabel(int rowIndex, int columnIndex){
        return true;
    }
}

E dentro de um Form criei um evento que a clicar que preenche a JTable, com valores de teste.

O evento que criei ficou assim
ModeloDados d1 = new ModeloDados("Valdecir", "Padovani", "AAAA");
    ModeloDados d2 = new ModeloDados("João", "Silva", "BBBB");
    ModeloDados d3 = new ModeloDados("Jose","Martins","CCCC");

    ArrayList array = new ArrayList<>();

    array.add(new Object[]{d1.getNome(),d1.getSobreNome(),d1.getTelefone()});
    array.add(new Object[]{d2.getNome(),d2.getSobreNome(),d2.getTelefone()});
    array.add(new Object[]{d3.getNome(),d3.getSobreNome(),d3.getTelefone()});

    String[] colunas = {"NOME","SOBRE NOME","NUMERO"};

    tabelaPrincipal modeloTabela = new tabelaPrincipal(array, colunas);
    jTable1.setModel(modeloTabela);

Gostaria deixar uma coluna editável, como por exemplo a ultima que seria para o usuário editar o telefone.
Porém não estou conseguindo deixar a coluna editável será que alguém poderia me ajudar nisso?

A: Tomando seu código como ponto de partida, onde a tabela aparenta ter apenas 3 colunas, altere seu método desta forma:
public boolean isCellEditabel(int rowIndex, int columnIndex){
    return columnIndex == 2;
}

Lembrando que você precisará também implementar o método setValueAt() herdado da classe AbstractTableModel.
Caso tenha dúvidas quanto a implementação, nesta pergunta há instruções completas da implementação de um tablemodel próprio.

O setValueAt() poderia ser algo desta forma:
@Override
public void setValueAt(Object aValue, int rowIndex, int columnIndex) {

   Object[] linha = (Object[]) getLinhas().get(rowIndex);
   linha[columnIndex] = aValue;
   //este método é quem notifica a mudança do model na tabela
   fireTableDataChanged();
}


text:
Q: Looping through a RefCell wrapped Vec with Rust I have a struct that contains a RefCell for storing mutable values within a vector, and I'd like to loop over its values.
Adding an element causes no problems, but when attempting to convert the borrowed vector into an iterator it throws:

error: cannot move out of borrowed content [E0507]

Why does the borrow even matter, if it's immutable? I don't understand why the compiler would mark this as a potential issue when the content of the variable doesn't even change.
I can get around the ownership issue by cloning it, but why do I need to do that in the first place? Cloning the structure I'm trying to loop over is probably going to have a high CPU cost and I'd prefer not to have to do it if possible.
Example of what I'm trying to achieve:
fn main() {
    use std::cell::RefCell;
    let c = RefCell::new(vec![1, 2, 3]);

    let arr = c.borrow();

    for i in arr.into_iter() {
        println!("{}", i);
    }
}

Is there something I'm missing here or is Rust being overly cautious about this?
Would appreciate it if someone could fill any gaps in my understanding of how this works.

A: It appears the issue was in there being a difference between Vec.into_iter and Vec.iter. To solve, change:
for i in arr.into_iter() {
    println!("{}", i);
}

to:
for i in arr.iter() {
    println!("{}", i);
}

As described in Effectively Using Iterators In Rust.


text:
Q: I need to have dependent drop down lists in my google sheet I have gone through many formulas, scripts, and functions but still not solved. If anybody can provide me the script or suggest me a best add on for this then it will really pleasure for me.Note. I want to insert dependent drop down lists in Columns D & E, D= Battery Name & E= Battery Type and when we select battery name then it shows the relevant categories types of selected battery name.Thanks, Stay blessed.
https://docs.google.com/spreadsheets/d/1b_a4jA1UD-QgzxD7Y-I-6swGqXPjm-R-O8dMTEYV-rk/edit?usp=sharing


text:
Q: Is there any Alternative to "IN" statement in T-SQL? Consider this code snippet:
SELECT
    vbs.SKUID, SKUName, SUM(vbs.Quantity) AS Qty
FROM
    BatchStocks AS vbs
WHERE
    vbs.SKUID IN (Here i have almost 12000 SKU)
    AND vbs.StoreID IN (%q)
    AND vbs.StockType = %n
GROUP BY
    vbs.SKUID, vbs.SKUName

In the where condition, i have almost 12000 SKUID which take much time to execute statement. Can you please suggest how I can improve this query?

A: you can use EXISTS()
put the SKU in a temp table
and
WHERE  vbs.SKUID IN (Here i have almost 12000 SKU)

change to
WHERE  EXISTS
       (
           SELECT *
           FROM   #TEMP x
           WHERE  x.SKUID  = vbs.SKUID
       )

A: You can also use Inner Join, EXISTS instead of IN.
Please refer EXISTS query :
SELECT
    vbs.SKUID, SKUName, SUM(vbs.Quantity) AS Qty
FROM
    BatchStocks AS vbs
WHERE
    EXISTS ( select 1 from #TEMPTABLE t on t.SKUID = vbs.SKUID)
    AND vbs.StoreID IN (%q)
    AND vbs.StockType = %n
GROUP BY
    vbs.SKUID, vbs.SKUName

Please refer below query for INNER JOIN:
SELECT
    vbs.SKUID, SKUName, SUM(vbs.Quantity) AS Qty
FROM
    BatchStocks AS vbs
    INNER JOIN #TEMPTABLE t on t.SKUID = vbs.SKUID
WHERE  vbs.StoreID IN (%q)
    AND vbs.StockType = %n
GROUP BY
    vbs.SKUID, vbs.SKUName


text:
Q: How to get location of a pdf file opened in preview I have opened a pdf file in preview, without knowing where this file is located. How can I find out?

A: Simply ⌘+Click on it's name in the title bar or secondary click (right click) on it .
(I have a polish OS X on the screenshot)

A: Mojave - just click on the name, it will reveal the popup window with location. Alternatively, you can hover the cursor over the name - it will invoke a little downward arrow - click on it and you'll see the same popup with location.

A: *

*Command+O  this opens a dialogue with the current file.

*Select the file, and press Command+R, this reveals the file in Finder.

*In Finder, select the file, and press Option+Command+C, this copies the full path to the Clipboard.


text:
Q: Cross-compile any aptitude package? I have an ARM Chromebook. There is a project called Crouton that is able to install Ubuntu to the internal harddrive pretty easily (I've done it).
But most packages in the repositories are of course only for X86 and X64.

*

*Is it even possible technically to take an arbitrary apt package and cross-compile it to run on my ARM Chromebook?

*If it is possible, how can I do so relatively painlessly? I have access to a very fast 24-core system for the compilation if I can figure out a way to automate the process of making ARM packages.

A: You can get the source for any package in the apt repository. You can even download it and compile it all in one command.
There is, of course, no guarantee that something not ported to your flavor of ARM will work. Many things have x86 assembly deep in them.
sudo apt-get build-dep <package>
sudo apt-get source --compile <package>

See this answer.


text:
Q: What options are there to connect to SharePoint lists if direct connection from Python isn't allowed I have to consolidate multiple SharePoint lists into one data source for a report. This has to be done on a daily basis. At the moment, I'm handling this with:

*

*Connect to SharePoint lists from Excel

*Use Python to refresh the Excel-SharePoint connections

*Read refreshed data and consolidate into one source with pandas

It's taking really long for the refreshing step to be done (ie. 20 mins on my machine which has 32GB RAM and 50 mins on my co-worker machine which only has 12GB).
I looked at connecting to SharePoint directly with the sharepoint package but I keep getting this error:
SSLError: HTTPSConnectionPool(host='sharepoint.xxx.com', port=443): Max retries exceeded with url: / (Caused by SSLError(SSLError("bad handshake: Error([('SSL routines', 'tls_process_server_certificate', 'certificate verify failed')])")))

What other options do I have to improve the time it takes to get data from SharePoint lists?

A: You may try HttpNtlmAuth:
import requests
from requests_ntlm import HttpNtlmAuth
import getpass

username= 'YourDomain\\your_user'
response = requests.get(url_site, auth=HttpNtlmAuth(username, getpass.getpass()))

From then on, you can manipulate your response object.
Note: The getpass asks for a password on runtime, you may use a saved password string, but it may not be advisable for security reasons.


text:
Q: Offset a subfigure vertical axis I have a figure made of three subfigures, one on top and two below it.
Currently the two lower figures are aligned based on the height of their caption. I need the left subfigure to be closer to the top one, as shown on the scheme below. This subfigure doesn't need a caption.

I tried things with vspace but no success (I'm still a beginner). Here is a MWE of my code :
\documentclass[french]{report}
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage{lmodern}
\usepackage[a4paper]{geometry}
\usepackage{pgfplots}
\usepackage{graphicx}
\usepackage{mwe}
\usepackage{subcaption}
\usepackage{tikz}
\usepackage{tikzscale}
\usepackage{babel}

\begin{document}

    \begin{figure}
        \centering
        \begin{subfigure}{1\linewidth}
            \includegraphics[width=0.97\linewidth]{example-image-a}
            \caption{Top subfigure caption}
            \vspace{0.5cm}
        \end{subfigure}
        \begin{subfigure}[t]{0.4\linewidth}
            \includegraphics[width=0.9\linewidth]{example-image-b}
        \end{subfigure}
        \begin{subfigure}[t]{0.5\linewidth}
            \begin{tikzpicture}% table
                \begin{axis}
                    \addplot table[x=x,y=y] {data.dat};
                \end{axis}
            \end{tikzpicture}
            \caption{Table caption}
        \end{subfigure}
    \end{figure}

\end{document}

data.dat contains
x y
1 1
2 4
3 9
4 16
5 25

A: The optional parameter t is aligning the subfigures regarding the top baseline of its contents (and the baseline of an image is its lower border). But this is not what you want, you want to align them regarding the upper border. For this the parameter T has to be used:
\documentclass[french]{report}
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage{lmodern}
\usepackage[a4paper]{geometry}
\usepackage{pgfplots}
\usepackage{graphicx}
\usepackage{mwe}
\usepackage{subcaption}
\usepackage{tikz}
\usepackage{tikzscale}
\usepackage{babel}

\begin{document}

    \begin{figure}
        \centering
        \begin{subfigure}{1\linewidth}
            \includegraphics[width=0.97\linewidth]{example-image-a}
            \caption{Top subfigure caption}
            \vspace{0.5cm}
        \end{subfigure}
        \begin{subfigure}[T]{0.4\linewidth}
            \includegraphics[width=0.9\linewidth]{example-image-b}
        \end{subfigure}
        \begin{subfigure}[T]{0.5\linewidth}
            \begin{tikzpicture}% table
                \begin{axis}
                    \addplot table[x=x,y=y] {data.dat};
                \end{axis}
            \end{tikzpicture}
            \caption{Table caption}
        \end{subfigure}
    \end{figure}

\end{document}


text:
Q: Elegant way to fetch custom tag in string Is here some elegant way to get and replace custom tags in string?
For example
"some long text [o:prop] and [u:date]"

Result array :

*

*"[o:prop]"

*"[u:date]"

Thanks

A: @"\[[a-z]:[a-z]{4}\]"

assumes 1 lowercase character followed by a colon, followed by four lowercase characters, all bounded by square brackets.

A: It's always risky, but you could go for some regex like:
"\\[(.*?)]"

with the global modifier.
Safer: \\[(o:prop|u:date)]

A: Yes. use a regular expression.
http://www.regular-expressions.info/
Read. Learn. Apply.

A: Try
var replacements = new Dictionary<string,string> {
    {"[o:prop]","FISH"},
      {"[u:date]","2013-04-12"}
};

var testString = "some long text [o:prop] and [u:date]";

var result= new Regex(@"\[[^[]*?]").Replace(
      testString,
      match => replacements.ContainsKey(match.Value) ? replacements[match.Value] : match.Value);


text:
Q: How to center the text for the toggle switch I have a pricing plan page that I am trying to add a toggle switch to. I can't seem to figure out the proper way to vertically align the text of it: here is my fiddle
I've tried to set the margin and the padding but the Monthly and Annual are always at the top.

      Monthly

        <input type="checkbox" id="checbox" onclick="check()" />

      Annual

Personal

Custom domains

Sleeps after 30 mins of inactivity

        Free
        Sign up

Small team

Never sleeps

Multiple workers for more powerful apps

        $150
        Free trial

Enterprise

Dedicated

Simple horizontal scalability

        $400
        Free trial

A: you just had to add position: relative to the spans containing the text and than update the bottom value to bottom: -5px
here's the updated fiddle: https://jsfiddle.net/a2nwet54/

A: Remove the margin-bottom from that switch element and add display:flex;justify-content:center;align-items:center; to .toggle-btn
Here's the edited fiddle: https://jsfiddle.net/bjd3wps1/


text:
Q: Admin Access in Amazon AppStream image instances for registry edits? I am trying to write a script in Amazon AppStream that will edit the registry's, and ultimately register a user to Tableau and activate a license for them. The script on my desktop runs perfectly, and does exactly what it needs to do, which is edit the registry, register it with Tableau, and activate the license.
Below is the line of code intended to edit the registry:
"C:\Scripts\User_Tab.reg"

I have successfully created an image of the script in AppStream, the first thing it does is try and edit the registry, but get's blocked because "editing has been disabled by your administrator." Is there anyway to enable this so that my script can run?
"editing has been disabled by your administrator " - error
As a side note, my script is also not behaving as expected in other ways. Even though it will run Tableau, it seems unable to perform any Tableau specific commands, such as activating the license. Which is weird, because they all have the same file path, and it works on my desktop...
Any help appreciated.
EDIT
A similar issue happens when I try to run a PowerShell script to edit the registries, based on information I obtained from this question.
Running a PowerShell script also requires a degree of administrator access that I don't know how to give an image instance.
PowerShell Script requires admin password
This question appears to be more about giving admin access to a image instance in AppStream than it does about registries. The title has been changed from "Editing Registry's in Amazon AppStream image instances?" to "Admin Access in Amazon AppStream image instances for registry edits?" to reflect this.

A: A solution to this has been given here by awsMuraliR
Where in order to get around this error you need to instead write a PowerShell script to edit the registry, essentially avoiding the admin access requested for editing the registry using a .bat file.
Then, the get around admin access required for running a PowerShell script, you need a .bat file to run the PowerShell script for you.
Create an image of the .bat file that runs the PowerShell script.


text:
Q: Spark SQL performance: version 1.6 vs version 1.5 I have tried to compare the performance of Spark SQL version 1.6 and version 1.5. In a simple case, Spark 1.6 is quite faster than Spark 1.5. However, in a more complex query - in my case an aggregation query with grouping sets, Spark SQL version 1.6 is very much slower than Spark SQL version 1.5. Does anybody notice the same issue? and even better have a solution for this kind of query?
Here is my code
case class Toto(
                 a: String = f"${(math.random*1e6).toLong}%06.0f",
                 b: String = f"${(math.random*1e6).toLong}%06.0f",
                 c: String = f"${(math.random*1e6).toLong}%06.0f",
                 n: Int = (math.random*1e3).toInt,
                 m: Double = (math.random*1e3))

val data = sc.parallelize(1 to 1e6.toInt).map(i => Toto())
val df: org.apache.spark.sql.DataFrame = sqlContext.createDataFrame( data )

df.registerTempTable( "toto" )
val sqlSelect = "SELECT a, b, COUNT(1) AS k1, COUNT(DISTINCT n) AS k2, SUM(m) AS k3"
val sqlGroupBy = "FROM toto GROUP BY a, b GROUPING SETS ((a,b),(a),(b))"
val sqlText = s"$sqlSelect $sqlGroupBy"

val rs1 = sqlContext.sql( sqlText )
rs1.saveAsParquetFile( "rs1" )

Here are 2 screenshots Spark 1.5.2 and Spark 1.6.0 with --driver-memory=1G. The DAG on Spark 1.6.0 can be viewed at DAG.

A: Thanks Herman van Hövell for his reply on spark dev community. In order to share with other members, I share his response here.

1.6 plans single distinct aggregates like multiple distinct aggregates; this inherently causes some overhead but is more stable in case of high cardinalities. You can revert to the old behavior by setting the spark.sql.specializeSingleDistinctAggPlanning option to false. See also: https://github.com/apache/spark/blob/branch-1.6/sql/core/src/main/scala/org/apache/spark/sql/SQLConf.scala#L452-L462

Actually in order to revert the setting value should be "true".


text:
Q: Replacing a part of a string with null I need to automate the import of an Excel-file into PostgreSQL using Python. I'm relatively new to Python but managed to automate the creation of the tables. Now I got stuck on importing the data into the  tables.
The problem I'm having is that in PostgreSQL I have defined certain columns as Date columns. However, for many of the "Date" columns there isn't any data yet. Therefore it is marked as nan. But, psycopg2 doesnt like nan as a value for a Date column and instead expects a null.
When converting the list to a string, which should be passed into the INSERT INTO {sheet} VALUES ({formatted_data_string}), I believe the individual entries for the Table should be in a string looking something like this: 'data', 'data', 'data', null, 'data' The code below gets the data from the Excel-File and then creates the formatted_data_string which should be inserted into the SQL-Statement.
 def import_data(path):
    xl = pd.ExcelFile(path)
    sheets = xl.sheet_names
    conn = psycopg2.connect(host=host, port=port, database=database, user=user, password=password)
    cur = conn.cursor()
    sheet_column_names = []
    for sheet in sheets:
        if sheet == 'ReadMe':
            continue

        df = pd.read_excel(xl, sheet)
        list_of_rows = df.to_numpy().tolist()
        for entry in list_of_rows:
            if entry == list_of_rows[0]:
                continue

            formatted_data = []
            for element in entry:
                if element == 'nan':
                    formatted_data.append('null')
                else:
                    formatted_data.append(f"'{element}'")
            formatted_data_str = ','.join(str(element) for element in formatted_data)
            print(formatted_data_str)

Almost all of the data is formatted correctly except for the 'nan' values which still appear as 'nan' and not the null I'm expecting. I checked the code severall times but can't figure out why it's not replacing nan with null.
This is a sample of the formatted_data_str that I currently get from this code:
'25...1','Something','XX','XX','[relToChild, relToParent]','Some Other Data','2018-10-09 06:04:28.015000','nan','1','DISABLED','nan',...
Is there something wrong with this code. Or am I missing something obvious to get nan replaced with a null without quotation marks?

A: So I found a solution to my problem that works just fine.
Creating a second DataFrame with the following command replaces all nan with None.
df = pd.read_excel(xl, sheet)
df1 = df.where(pd.notnull(df), None)

This then allows me to target the None with a For-Loop, replacing all None's with null. While adding a second single quotation arround the Data objects.
for element in entry:
   if element != None:
      formatted_data.append(f"'{element}'")
      continue
   else:
      formatted_data.append('null')

After converting the new list (formatted_data) to a string using
formatted_data_str = ','.join(str(element) for element in formatted_data)

The resulting string is in the  required format that I explained above. The SQL Statement is accepted by the Server and the data appears to be correct in the PostgreSQL DB. I know that this might not be the nicest solution but it works for me and thats all I need right now.


text:
Q: How to get second value of second column in output I have an output like this:
NAME              CLUSTER_IP     EXTERNAL_IP   PORT(S)    SELECTOR                  AGE
docker-registry   172.30.131.5   <none>        5000/TCP   docker-registry=default   33m

Now I want to get the IP. Nothing else.
I used awk but always got CLUSTER_IP with it too
result=$(oc get svc/docker-registry | awk '{print $2}')

A: Just select the 2nd line:
result=$(oc get svc/docker-registry | awk 'NR==2{print $2}')

A: You need to skip the header line. Like this:
result=$(oc get svc/docker-registry | awk 'NR!=1{print $2}')


text:
Q: Does someone still have all the documentaton on Quickly? The project seams to be dead, but I am using it to create an app, but I need more documentation.
I cant run the quickly tutorial, maybe because I'm using elementary Freya, but I am missing a lot of thing because I need that documentation.
Does anyone know where to find this? Youtube videos and the wiki on ubuntu site are not enough, thanks in advance...
Also it s sad to see this project dead...


text:
Q: How to check SQL connection in C#.Net? I want check my SQL server connection before to connect with DB, and I need to update the status of SQL Server connection in my GUI.
Here is the code I am checking SQL connection, but I couldn't able to get status frequently
Scenario :

*

*Stop the sql server service from services window

*Running the project and will show status "Connection Not Available"

*Start Sql server service and displaying "Connection Live"

*And Again Stop SQL server service and i am not getting the status as ""Connection Not
Available". It's returning status as "Connection Live"

*It's not getting to the catch block
Code:
  private void timer1_Tick(object sender, EventArgs e)
    {
        bool Flag = false;
        try
        {
            using (SqlConnection con = new SqlConnection(strcon))
            {
                con.Open();
            }
        }
        catch (SqlException s)
        {
            Flag = true;
            label1.Text = "Connection Not available";
        }
        finally
        {
            if (Flag == false)
            {
                label1.Text = "Connection Live";
            }
        }
    }

A: Wrap your connection attempt in a try..catch (it should be using a using statement at the very least). [The precise location of a try..catch in your code depends somewhat on the structure of your code.]
It is unusual for an application to maintain whether a SQL Server is available. After all, it might be unavailable milliseconds after you test and display that it is available.

A: If there server is unavailable, your application will hang while it tries to connect.  This should be run in a background worker and the status updated with a callback.


text:
Q: in Spring is there an application.properties by deafult? I was trying to decompile the jar files inside Spring trying to find the default application.properties, am I wrong or it exists something like a mother file that we override.
Thanks in advance!

A: When using Spring Boot, the usual way to create an executable JAR file is to simply use the provided spring-boot-maven-plugin (or the Gradle equivalent, spring-boot-gradle-plugin).
By default, the structure of the JAR when created this way is as follows:
$ ls
my-app-0.0.1-SNAPSHOT.jar

$ unzip my-app-0.0.1-SNAPSHOT.jar
$ ls my-app-0.0.1-SNAPSHOT
./BOOT-INF
./META-INF
./org

The application configuration is, by default, located under ./BOOT-INF/classes. Any application.properties (as well as other resources under src/main/resources) will be located there by default.
If you do not provide an application.properties, then sensible defaults will be used for many (but not all) components that you may be using (by e.g. including them in your pom.xml or build.gradle project file). In this case, no application.properties file will be present inside the JAR file. For example, if no server.port property was defined, a default of 8080 will be used to run your application.
There are many ways to configure a Spring Boot application. For the full list, including precedence of each way, see the reference documentation.

A: There is no default application.properties (or application.yaml file) in Spring Boot. Instead, the defaults are defined in code, typically in classes annotated with @ConfigurationProperties. The properties that Spring Boot itself supports and their default values are listed in the reference documentation.

A: Spring Boot provides various properties that can be configured in the application.properties file. The properties have default values. We can set a property(s) for the Spring Boot application. Spring Boot also allows us to define our own property if required.


text:
Q: How does HWSURFACE differ from a texture? When making a surface in SDL, there's an option to use the HWSURFACE tag, which I imagine means the surface is handled by the GPU instead of the CPU. But now SDL2 has textures, and I'm wondering, what's the difference? Will there be and performance difference using hardware surfaces instead of textures? Do they behave the same?
I've tried googling all over, but I can only find info on regular software surfaces.

A: There are no textures support in SDL1, and there is no HWSURFACE (or any other surface flag) in SDL2. flags in SDL_CreateRGBSurface in SDL2 commented as "The flags are obsolete and should be set to 0". There is no sane way to mix them.

A: Specifying SDL_HWSURFACE would cause the surface to be created using video memory.  PCs without GPUs still have video memory and it is faster to put data in that memory area onto the screen than to copy it from system RAM.
Textures are uploaded to the GPU's own dedicated RAM and data must be passed through that memory in order to be put on the screen at all.  SDL2 no longer has the SDL_HWSURFACE flag because the rendering subsystem uses the GPU via OpenGL or Direct3D and cannot use the old way to get graphics on the screen.


text:
Q: How to redirect to current url in java? I'm using
<%=request.getRequestURL()%>

to redirect to current page but it has problem with addresses with some parameters like this:
http://xxx.com/yyy/x/search?mesg=welcome&initial=true&app=

and redirects to address without parameter which causes problems.
is there any solution to get whole of address?

A: As the documentation for HttpServletRequest.getRequestURL() states, it does not include the query string. I can't see any methods on HttpServletRequest that does include this "directly", so you might have to construct this yourself, which shouldn't be too difficult. You can use the getParameterMap() method to get a map of all query parameters.
Edit
HttpServletRequest.getQueryString() was the method I was looking for. Thanks @AlpeshGediya. So by combining it with getRequestURL, you have what you want.

A: You can redirect url using below two methods.
Using core jsp taglib.( I prefers this one)
<c:redirect url="your url">
     <c:param name="mesg" value ="${mesg}" />
     <c:param name="initial" value ="${initial}" />
     <c:param name="app" value="${app}" />
<c:redirect>

Using scriptlet
<%
  String queryString =  request.getQueryString();
  if(queryString != null) {
    response.sendRedirect("http://xxx.com/yyy/x/search?" + queryString);
  }
  else {
    response.sendRedirect("http://xxx.com/yyy/x/search");
  }
%>

getQueryString(), returns query string of the request ,but if no request parameters are supplied/availible then it returns null so you need to handle that null.

A: I just modified the previous answers and wrote this:
<c:set var="parameter" value="<%=request.getQueryString()%>"/>
<c:if test="${not empty parameter}">
    <c:set var="parameter" value="?${parameter}"/>
</c:if>

thanks everbody


text:
Q: segmentation fault when using shared memory created by open_shm on Xeon Phi I have written my code for single Xeon Phi node( with 61 cores on it). I have two files. I have called MPI_Init(2) before calling any other mpi calls. I have found ntasks, rank also using mpi calls. I have also included all the required libraries. Still i get an error. Can you please help me out with this?
In file 1:
 int    buffsize;
 int    *sendbuff,**recvbuff,buffsum;
 int *shareRegion;
 shareRegion = (int*)gInit(MPI_COMM_WORLD, buffsize, ntasks);   /* gInit is in file 2 */
 buffsize=atoi(argv[1]);
 sendbuff=(int *)malloc(sizeof(int)*buffsize);
 if( taskid == 0 ){
   recvbuff=(int **)malloc(sizeof(int *)*ntasks);
   recvbuff[0]=(int *)malloc(sizeof(int)*ntasks*buffsize);
   for(i=1;i<ntasks;i++)recvbuff[i]=recvbuff[i-1]+buffsize;
 }
 else{
   recvbuff=(int **)malloc(sizeof(int *)*1);
   recvbuff[0]=(int *)malloc(sizeof(int)*1);
 }

 for(i=0;i<buffsize;i++){
     sendbuff[i]=1;

 MPI_Barrier(MPI_COMM_WORLD);

 call(sendbuff, buffsize, shareRegion, recvbuff[0],buffsize,taskid,ntasks);

In file 2:
 void* gInit( MPI_Comm comm, int size, int num_proc)
 {
    int share_mem = shm_open("share_region", O_CREAT|O_RDWR,0666 );

    if( share_mem == -1)
     return NULL;
    int rank;
    MPI_Comm_rank(comm,&rank);

    if( ftruncate( share_mem, sizeof(int)*size*num_proc) == -1 )
       return NULL;

    int* shared =  mmap(NULL, sizeof(int)*size*num_proc, PROT_WRITE | PROT_READ,    MAP_SHARED, share_mem, 0);

    if(shared == (void*)-1)
       printf("error in mem allocation (mmap)\n");

    *(shared+(rank)) = 0

    MPI_Barrier(MPI_COMM_WORLD);

    return shared;
 }

 void call(int *sendbuff, int sendcount, volatile int *sharedRegion, int **recvbuff, int recvcount, int rank, int size)
 {
    int i=0;
    int k,j;
    j=rank*sendcount;
    for(i=0;i<sendcount;i++)
    {
      sharedRegion[j] = sendbuff[i];
      j++;
    }

    if( rank == 0)
      for(k=0;k<size;k++)
        for(i=0;i<sendcount;i++)
        {

           j=0;
           recvbuff[k][i] = sharedRegion[j];
           j++;

        }
 }

Then i am doing some computation in file 1 on this recvbuff.
I get this segmentation fault while using sharedRegion variable.

A: MPI represents the Message Passing paradigm. That means, processes (ranks) are isolated and are generally running on a distributed machine. They communicate via explicit communication messages, recent versions allow also one-sideded, but still explicit, data transfer. You can not assume that shared memory is available for the processes. Have a look at any MPI tutorial to see how MPI is used.
Since you did not specify on what kind of machine you are running, any further suggestion is purely speculative. If you actually are on a shared memory machine, you may want to use a real shared memory paradigm instead, e.g. OpenMP.

A: While it's possible to restrict MPI to only use one machine and have shared memory (see the RMA chapter, especially in MPI-3), if you're only ever going to use one machine, it's easier to use some other paradigm.
However, if you're going to use multiple nodes and have multiple ranks on one node (multi-core processes for example), then it might be worth taking a look at MPI-3 RMA to see how it can help you with both locally shared memory and remote memory access. There are multiple papers out on the subject, but because they're so new, there's not a lot of good tutorials yet. You'll have to dig around a bit to find something useful to you.

A: The ordering of these two lines:
shareRegion = (int*)gInit(MPI_COMM_WORLD, buffsize, ntasks);   /* gInit is in file 2 */
buffsize=atoi(argv[1]);

suggest that buffsize could possibly have different values before and after the call to gInit. If buffsize as passed in the first argument to the program is larger than its initial value while gInit is called, then out-of-bounds memory access would occur later and lead to a segmentation fault.
Hint: run your code as an MPI singleton (e.g. without mpirun) from inside a debugger (e.g. gdb) or change the limits so that cores would get dumped on error (e.g. with ulimit -c unlimited) and then examine the core file(s) with the debugger. Compiling with debug information (e.g. adding -g to the compiler options) helps a lot in such cases.


text:
Q: Graph Results via Non GUI mode in JMeter Is there any possibilities to get my below mentioned Graph Results in JMeter test, which is executed in non GUI mode. I can extract its values using csv, but we need to run the test in non GUI mode to get dashboard results also. Any possibilities for this ?

A: Given you run your JMeter test in command-line non-GUI mode like:
jmeter -n -t test.jmx -l results.jtl

Once test is finished you should be able to open JMeter GUI, add Graph Results listener, locate results.jtl file using "Browse" button and you will see the chart.
Also there is an option to generate some charts in unattended manner using Command-Line Graph Plotting Tool available via JMeter Plugins project, see Automatically generating nice graphs at end of your Load Test with Apache JMeter and JMeter-Plugins guide for details.

A: I am trying to write web app based on Django to work with test results, do an online monitoring, etc. (kinda dashboard) for load tests which runned in Jmeter console mode (incl. distributive testing).
Maybe you will want to participate in development or so :):
https://github.com/v0devil/JMeter-Control-Center


text:
Q: Error with Request when using no Proxy I've got a problem with my VB.Net-application. When i'm trying to send a request to http://ask.fm without proxy, i got the following response in fiddler: HTTP/1.1 502 Fiddler - DNS Lookup Failed
What does this mean? And why is there no error when using a proxy server for the request?
I send the request with the following code:
  Public Function GetRequest(ByVal url As String, ByVal referer As String, ByVal cookie As CookieContainer, Optional proxy As String = "") As String

    Dim request As HttpWebRequest
    Dim response As HttpWebResponse

    Try
        Dim cookies As String = ""
        request = CType(HttpWebRequest.Create(url), HttpWebRequest)
        request.CookieContainer = cookie
        request.ServicePoint.Expect100Continue = False
        request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; rv:8.0) Gecko/20100101 Firefox/8.0"
        If referer <> "" Then
            request.Referer = referer
        End If
        request.Timeout = 10000
        If proxy <> "" Then
            request.Proxy = New WebProxy(proxy)
        End If
        response = CType(request.GetResponse(), HttpWebResponse)

        cookies = response.GetResponseHeader("Set-Cookie")

        If url.Contains("ask.fm/") Then
            If New Regex("l=.*?; domain=ask.fm; path=/;").Match(cookies).Value = "" Then
                Return "ERROR"
            End If
        End If

        Dim source As String = New StreamReader(response.GetResponseStream()).ReadToEnd()
        If source.Contains("No robots allowed!") Then
            source = "ERROR"
        End If
        If source = "" Then
            source = "ERROR"
        End If
        Return source
    Catch ex As Exception
        Return "ERROR"
    End Try

End Function

A: Are you using Fiddler to inspect the traffic? If so, make sure Fiddler can redirect your traffic correctly.
Go to Help > About Fiddler and make sure your Gateway is correct (either set to the proxy you use for accessing internet or equal to No Gateway if you can access directly).


text:
Q: How to repeat train and test 10 times in R I'm using Keras and I'd like to make 10 different train and test samples to repeat the fit function with those samples.
for (i in 1:10) {
## 75% of the sample size
smp_size <- floor(0.8 * nrow(cifarSmall$x))

## set the seed to make your partition reproducible
set.seed(123)
train_ind <- sample(seq_len(nrow(cifarSmall$x)), size = smp_size)

train_x <- cifarSmall$x[train_ind,,,]

train_y <- cifarSmall$y[train_ind]

test_x <- cifarSmall$x[-train_ind,,,]
test_y <- cifarSmall$y[-train_ind]

conjuntos_train_x[i] <- c(train_x)

}

A: Perhaps do 10 times cross validation:
n <- 5
repeat <- 2
for(j in 1:repeat){
  indexes <- split(sample(1:nrow(iris)),1:n)
  for (i in 1:n) {
  test_x <- iris[indexes[[i]],]
  train_x <- iris[-indexes[[i]],]

  ## train, evaluate keras model
  ## do some hyper tuning
  }
}

Good thing about cross validation is that you assume Independence between train and test sets, while maintaining large proportion of data for training. Now the test errors and metrics are independent, so you can compare and tune your models, assuming i.i.d. in the input data.


text:
Q: Switch to correct iframe? In Visual Studio, using Selenium, I'm trying to click on a element that's inside a iframe.
The code:

The problem is i get an error if I use ECMMyChangeActions like this:
driver.SwitchTo().Frame("ECMMyChangeActions");

Error:
Message: OpenQA.Selenium.NoSuchFrameException : No frame element found with name or id ECMMyChangeActions
Using Selenium IDE I have recorded this testcase and confirmed that a change of iframe is needed before clicking on any element inside this iframe.

Using driver.SwitchTo().Frame(0); works in Visual Studio but I can still not find any element inside it. So I'm suspecting that iframe index=0 is incorrect.
I have tried figuring out which iframe to use by counting all iframes on the page in this for-loop:
[Test]
        public void CountIframes()
        {
            int size = driver.FindElements(By.TagName("iframe")).Count();

            for (int i = 0; i <= size; i++)
            {
                driver.SwitchTo().Frame(i);
                int total = driver.FindElements(By.XPath("//td[contains(@title,'Find...')]")).Count();
                Console.Write(total);
                driver.SwitchTo().DefaultContent();
            }
        }

The output I get using this for-loop is: 000. As I understand this for-loop code, it will only generate a "1" if the element I specified is found inside any of the iframes. So 000 would mean that no such element is found in any of the iframes.
This is a picture of the HTML for that iframe:

Please help me find the correct iframe.

A: You can use a wait frame like this:
wait.waitFrame("idFrame");
driver.SwitchTo().Frame(driver.FindElement(By.Id("idFrame")));

public void waitFrame(string idElement)
{
   WebDriverWait wa = new WebDriverWait(driver, TimeSpan.FromSeconds(30));
   wa.Until(c => c.FindElement(By.Id(idElement)));
}

Also, check all the frames that the page has:
driver.FindElements(By.TagName("frame"))[n];

Where n is the numerator for all the frames.

A: The iframe (ECMMyChangeActions) I was trying to reach was nestled inside three other iframes. This became evident when reading the html more thoroughly.
<HTML>
 <body>
  ...
  <iframe>name="firstiframe"
   ...
   <iframe>name="seconidframe"
    ...
    <iframe>name="thirdiframe"
     ...
     <iframe>name="ECMMyChangeActions"

To reach ECMMyChangeActions I first had to reset selenium to look at the root of the HTML document:
driver.SwitchTo().DefaultFrame();
And then I swtiched to each iframe in the following order to nestle my way to ECMMyChangeActions:
driver.SwitchTo().Frame("firstiframe");
driver.SwitchTo().Frame("secondiframe");
driver.SwitchTo().Frame("thirdiframe");
driver.SwitchTo().Frame("ECMMyChangeActions");


text:
Q: Dialogue box does not show up I am creating a dialogue box that should appear to the user in case of the GPS service is disabled. But what is happening is, although I disabled the service manually to force the dialogue appear, the App starts and nothing is happening.
The code below shows how I tried to create the dialogue box and when. Please let me know if there is any mistake.
JavaCode:
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_gpstest00);

    locMgr = (LocationManager) getSystemService(LOCATION_SERVICE);
    gpsEnable = locMgr.isProviderEnabled(LocationManager.GPS_PROVIDER);
    if (!gpsEnable) {
        showGPSDialogueBox();
    }
    locMgr.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1, 1, this.locationListener);
}

/*if (savedInstanceState == null) {
    getSupportFragmentManager().beginTransaction().add(R.id.container, new PlaceholderFragment()).commit();
}*/

private void showGPSDialogueBox() {
    AlertDialog.Builder alertDialogue = new AlertDialog.Builder(this);
    alertDialogue.setTitle("GPS Settings");
    alertDialogue.setMessage("GPS is deactivated. Do you want to switch " + to settings menu to activate it?");

    alertDialogue.setPositiveButton("Settings",new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which) {
            // TODO Auto-generated method stub
            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            startActivity(intent);
        }
    });

    alertDialogue.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which) {
            // TODO Auto-generated method stub
            dialog.cancel();

        }
    });
}// Enf of showDialogueBox function.

A: You need to call show function for the dialog box to show
alertDialogue.show();

A: You need to create AlertDialog from AlertDialog.Builder object then show the AlertDialog using show() method as follows...
AlertDialog dialog = alertDialogue.create();
dialog.show();

Update your showGPSDialogueBox() as below...
private void showGPSDialogueBox() {
    AlertDialog.Builder alertDialogue = new AlertDialog.Builder(this);
    alertDialogue.setTitle("GPS Settings");
    alertDialogue.setMessage("GPS is deactivated. Do you want to switch " +
            "                 to settings menu to activate it?");

    alertDialogue.setPositiveButton("Settings",new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which) {
            // TODO Auto-generated method stub
            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            startActivity(intent);
        }
    });

    alertDialogue.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which) {
            // TODO Auto-generated method stub
            dialog.cancel();

        }
    });

    AlertDialog dialog = alertDialogue.create();
    dialog.show();
}


text:
Q: Three.js - Drag and drop (XZ) I'm new to three.js and I used the example of http://threejs.org/examples/webgl_interactive_draggablecubes.html to drag and drop my objects. The problem is that I want them to move only on the XZ plane (not on the Y axis) and I don't know how to achieve it in order to move them on a plane. The user should only be able to "slide" them on the ground. I'm using the OrbitControls instead of the TrackballControls.
https://jsfiddle.net/d58bbLey/
    function onDocumentMouseMove( event ) {
    event.preventDefault();

    mouse.x = ( event.clientX / window.innerWidth ) * 2 - 1;
    mouse.y = - ( event.clientY / window.innerHeight ) * 2 + 1;

    raycaster.setFromCamera( mouse, camera );

    if ( SELECTED ) {
        var intersects = raycaster.intersectObject( plane );

        if ( intersects.length > 0 ) {
            SELECTED.position.copy( intersects[ 0 ].point.sub( offset ) );
        }
        return;
    }

    var intersects = raycaster.intersectObjects( objects );

    if ( intersects.length > 0 ) {

        if ( INTERSECTED != intersects[ 0 ].object ) {

            if ( INTERSECTED ) INTERSECTED.material.color.setHex( INTERSECTED.currentHex );
            INTERSECTED = intersects[ 0 ].object;
            INTERSECTED.currentHex = INTERSECTED.material.color.getHex();
            plane.position.copy( INTERSECTED.position );
            plane.lookAt( camera.position );
        }
        container.style.cursor = 'pointer';
    } else {
        if ( INTERSECTED ) INTERSECTED.material.color.setHex( INTERSECTED.currentHex );
        INTERSECTED = null;
        container.style.cursor = 'auto';
    }
}

I appreciate your help! :D

A: Finally I found the problem:
each object has a plane which lookAt the camera. So, I deleted the plane.lookAt(camera.position) and added this line:
plane.applyMatrix(new THREE.Matrix4().makeRotationX( -Math.PI / 2));

Now my objects stays on the plane (XZ axis).

A: I have to do the same stuff, so far I used the DragControls
const geometry = new THREE.SphereGeometry(5, 32, 32);
const materialSphere = new THREE.MeshBasicMaterial({ color: 0xff0000, side: THREE.DoubleSide, wireframe: true });
const sphereMesh = new THREE.Mesh(geometry, materialSphere);
this.scene.add(sphereMesh);

this.dragControls = new DragControls([sphereMesh], camera, renderer.domElement);

this.dragControls.addEventListener('drag', (event) => {
  event.object.position.z = 0;
  event.object.position.x = 0;
});


text:
Q: Need javascript code I need a javascript code because I want to remove the class w3-spin in this id="imgg" when i pause an audio element...

 <audio id="audio" controls loop autoplay style="width:100%;" onclick="pause()">
    <source src="<?php echo $row['Song']?>" type="audio/mpeg">
</audio>

my javascript..

A: The event you should be listening to when an audio element is paused is pause.
As with play, it's (you guessed it) play.
Check media events list on MDN for a list of possible event you can listen to for audio element.
Here's an example.
Added red background color to .w3-spin to help illustrate the class name.

var audioPlayer = document.getElementById("audio");
var imgg = document.getElementById("imgg");
audioPlayer.onpause = function() {
  imgg.className = imgg.className.replace(/\bw3-spin\b/g, "");
};
audioPlayer.onplay = function() {
  if (imgg.className.indexOf("w3-spin") === -1) {
    imgg.className = imgg.className + " w3-spin";
  }
};
.w3-spin {
  background-color: red;
}

 <audio id="audio" controls loop autoplay style="width:100%;">
    <source src="https://upload.wikimedia.org/wikipedia/en/2/26/Europe_-_The_Final_Countdown.ogg" type="audio/ogg">
</audio>


text:
Q: saving data in multiple tables in one transaction using entity framework How can I save data into multiple tables in one transaction using entity framework?
I have multiple void methods where I populate the context, but I want to save it in one transaction rather than saving it multiple times. What is the best way of doing this?
namespace DataAccess.Services
{
    public class Submissions
    {
        DataContext Context;

        public Submissions()
        {
            Context = new DataContext();
        }

        public void InsertAllData()
        {
             //Save all data at once for all below contexts
             //DataContext.SaveChanges();
        }

        void InsertObject1(int Object1Id )
        {
               var obj1 = new DataAccess.Entity.Object1();

                obj1.Field1 = ....
                obj1.Field2 = ....
                .....

                DataContext.Objects.Add(obj1);
        }

        void InsertObject2(int Object2Id )
        {
               var obj2 = new DataAccess.Entity.Object2();

                obj2.Field1 = ....
                obj2.Field2 = ....
                .....

                DataContext.Objects.Add(obj2);
        }

        void InsertObject3(int Object3Id )
        {
               var obj3 = new DataAccess.Entity.Object3();

                obj3.Field1 = ....
                obj3.Field2 = ....
                .....

                DataContext.Objects.Add(obj3);
        }

    }
}

A: Your example code looks fine.
Entity framework is a change tracker and keeps track of all your changes. Every change you make to an object in your context will be stored by that context locally and all changes will be commited at once when you call DataContext.SaveChanges();.
So in this case, if you subsequentially call your InsertObject1, then InsertObject2 and InsertObject3, and then DataContext.SaveChanges();, everything will be stored in one go.
If you meant how you can do all this in inside an SQL database transaction, you can read about how to use those here: http://msdn.microsoft.com/en-us/data/dn456843


text:
Q: Before buying it, how can I tell if a storage array makes certain performance counters available over SNMP? I've noticed that documentation for SNMP reporting that is built-in to devices (i.e. doesn't need an agent running in an OS) usually doesn't include a list of performance counters that are available for monitoring.  It seems like the MIB for the device would reveal what counters are available, but I'm not sure and I haven't been able to find authoritative sources of MIB anyway.  A possibly representative MIB I did find was rather cryptic.
So, I'm left with these questions:

*

*How do you tell what performance counters (or any data over SNMP for that matter) are available for a device?

*Suppose I did have an MIB for a device, how do I interpret what each of the MIB objects means?

Background:
Right now I'm looking at the Dell MD3200.  I'm shooting for some sequential read and write targets, and would like to instrument the storage array in case I'm not meeting those targets.  This is the first time I've attempted performance monitoring with SNMP.

A: Contact the vendor and request the details that you want.


text:
Q: Is it possible to create custom metric(filter pattern) to calculate the average time taken by an API in AWS Cloudwatch I have an apiExecution duration in the log event.
I want to get the average time taken by the API for a specified time.
Ex -
getEmployee API is called 6 times in last 5 mins with the execution duration 100,450,800,300,150,600 (Duration in milliseconds)
The total duration =2400
the output will be 2400/6=400 MS
Is this possible in the Cloudwatch custom metrics using filter pattern?
Note - Consider the logs are posted to Cloudwatch from on-prem servers.


text:
Q: Snowflake Update Syntax This is my first post on Stackoverflow, I hope I'm in-bounds with the rules. I'm currently going through the Snowflake DB and I'm trying to update a table using "UPDATE", but I receive this error SQL compilation error: syntax error line 6 at position 0 unexpected 'UPDATE'. syntax error line 7 at position 38 unexpected ') I've already checked the syntax format and special characters. Could someone assist? (I'm a novice)
Select Replace (Fdgrp_cd,'~','') as Fdgrp_cd

from "USDA_NUTRIENT_STDREF_01"."PUBLIC"."FD_GROUP_INGEST"

UPDATE "USDA_NUTRIENT_STDREF_01"."PUBLIC"."FD_GROUP_INGEST"

SET Fdgrp_cd = REPLACE(fdgrp_cd,'~','')

A: UPDATE "USDA_NUTRIENT_STDREF_01"."PUBLIC"."FD_GROUP_INGEST"
SET fdgrp_cd = REPLACE(fdgrp_cd,'~','')

This statement should work all by itself.  The issue you are having is because you are trying to execute both statements at the same time in the UI, which only allows 1 query at a time.  Separate your queries with ; to delineate the queries so Snowflake UI understands that these are 2 separate queries.

A: Just run the update by itself (although a semicolon between the expressions might also work).
Often, it is more efficient in an update to only update the rows that need to be updated.  For this, you would use a where clause:
UPDATE "USDA_NUTRIENT_STDREF_01"."PUBLIC"."FD_GROUP_INGEST"
    SET Fdgrp_cd = REPLACE(fdgrp_cd, '~', '')
    WHERE fdgrp_cd LIKE '%~%';


text:
Q: Graphing a scatter plot or line graph with Mac Excel I have the following data:
Subject      Avg Calorie Intake     Avg Min in MVPA
  41              908.79                 25
  21             1050.43                 23.33
  15             2956.33                 64.16

How do I get three lines for each subject with the averages as the x and y axis?
It keeps giving me the x axis as the subjects and that's not what I want.

A: You can specifically tell excel which axis you want the series to be located like this:
With xlApp.ActiveChart
  .SeriesCollection(1).XValues = "='sheet name'!R21C4:R46C4"
  .SeriesCollection(1).Values = "='sheet name'!R21C5:R46C5"
  .SeriesCollection(1).Name = "='series name'"
  .SeriesCollection(1).axisgroup = Excel.XlAxisGroup.xlPrimary
End With

Post some of your code and I'll give you better direction.

A: Generally, when Excel is giving you trouble with how your data is being presented in a chart, you can use the following steps to better customize your data.

*

*Insert Chart (e.g. Scatter), while a blank cell is highlighted.  This will create a completely blank chart, with no Excel assumptions about how you want your data displayed.

*Select your chart, right click and Select Data.

*Add Legend Entries (Series).

*For a Scatter Chart, you can then select your Series Name, X Values and Y Values.  Using your sample data you could choose Subject for Series Name, Avg Calorie Intake for X Values and Avg Min for Y Values.


text:
Q: Hallar la Fecha Mínima en una lista de eventos estoy corriendo este query:
SELECT   distinct Plataforma, SubPlataforma,  Job,  Schedule, Error,
Observaciones,  IdPersonaRegistra, strClic,
                         1 AS ContadorFallas,
FORMAT(min(dtmFechaHoraFalla), 'yyyy-MM-dd HH:mm:ss') AS fecha
FROM          tblProcesosFallidos
WHERE        (Plataforma = 1) AND strClic IS NOT NULL
group by Plataforma, SubPlataforma,  Job,  Schedule,  Error,
Observaciones,  IdPersonaRegistra, strClic
order by strClic DESC

Obtengo el resultado de la tabla:

Sin embargo, salen repetidos los StrClic's, lo que se requiere es que el # de clic solo se muestre una vez( ningun strClic repetido) y que se muestre la primera fecha donde ocurre. Alguna pista de como puedo arreglarlo?

A: La cláusula group by funciona haciendo grupos en base a la lista de campos que le das. Es decir, va a sacar una fila de resultados por cada combinación que haya de los campos que se le dan, aplicando las funciones de agregación, como count(), sum(), min(), max() a todos los registros que forman parte de ese grupo.
En resumen, si quieres que strClic salga una sola vez, agrupa solamente por ese campo, así que la consulta básica sería algo como:
SELECT strClic, min(dtmFechaHoraFalla) FechaPrimeraFalla
  FROM tblProcesosFallidos
 WHERE (Plataforma = 1)
   AND strClic IS NOT NULL
 group by strClic
 order by strClic DESC

Si necesitas incluir información de otros campos, entonces la única manera de que no se repita strClic es forzando al motor a elegir solamente uno de ellos, ya que de manera general, existe el riesgo que haya dos o más valores distintos en el campo y eso haría que aparezcan dos o más filas con el mismo strClic en el resultado, entonces, puedes mostrar el más pequeño que aparezca
SELECT   strClic
       , min(dtmFechaHoraFalla) FechaPrimeraFalla
       , min(Plataforma) PrimeraPlataforma
       , min(SubPlataforma) PrimeraSubPlataforma
       , etcétera
  FROM tblProcesosFallidos
 WHERE (Plataforma = 1)
   AND strClic IS NOT NULL
 group by strClic
 order by strClic DESC

En resumen: Al momento que incluyas un segundo campo en la cláusula group by no podrás garantizar que haya una sola fila para cada strClic.
Generalizando la idea, supongamos estos datos:
Puesto     | Departamento  |  Salario | Empleado
-------------------------------------------------
Jefe       | Ventas        | 100      | Juan Pérez
Secretaria | Ventas        | 100      | María Godinez
Jefe       | Compras       | 200      | José Rodríguez
Secretaria | Compras       | 150      | Inés Hernández
Secretaria | Compras       | 100      | Miriam Pérez

Si agrupas solo por Puesto, digamos:
select Puesto, sum(Salario) from Empleado group by Puesto

Vas a obtener solo dos registros:
Puesto      | Suma
----------------------
Jefe        | 300
Secretaria  | 350

De manera similar si agrupas por Departamento, pero en el momento que agrupas por puesto y departamento, vas a obtener 4 registros, pues cada combinación de puesto y departamento son un grupo
select Puesto, sum(Salario) from Empleado group by Puesto

Va a devolver:
Puesto      | Departamento | Suma
----------------------------------
Jefe        | Ventas       | 100
Jefe        | Compras      | 100
Secretaria  | Ventas       | 200
Secretaria  | Compras      | 250


text:
Q: Snow Leopard install Ruby on Rails (with MySQL) I've done a clean re-install of OS X Snow Leopard, so there's nothing on my system at all.
I've installed Xcode and I'm ready to install Rails.
However, my system is a MacBook (MacBook2,1) and apparently it doesn't support 64-bit by default. Apple is going to add this at a later date.
How would I go about installing Rails? Do I go about it the normal way?
How about MySQL, do I need the 64-bit binary?

A: Most of the time (maybe always, I'm not really sure) you can run binaries compiled for 32 bit even if your system is 64 bit. They just won't have any benefits of 64 bit (either storing bigger things or processing stuff faster).
If your macbook is a recent one it has 64 bit support (Core 2 Duo processor), if it is an older version (Core Duo) it is 32 bit. You can determine the processor type by checking 'About this Mac' in the Apple menu.

A: Your MacBook does support 64bit, but it cannot boot in 64bit mode. You should be able to install 64bit binary packages just fine.

A: You should definitely install the 64-bit binory packages such as mysql.

A: You can certainly install the 64-bit packages. They will be able to access the memory space and every advantage of running with 64bits. The only thing that won't boot in 64bit is the Kernel, but it's not something to be worrying about for the moment.
Check out the Hivelogic's guide for installing MySQL, Rails and Ruby on Snow Leopard:
MySQL
Git
Ruby, Rails


text:
Q: How to recover information from Dropbox? Well, we had an emplyee who used to store all of his business accounts in Dropbox. Now he left our company turned off the sync and uninstalled dropbox so all of his files went poof! His Dropbox account was not registered to his work email so we can't access the account. Now, we all are trying to recover those files, we tried Pandora Recovery but no success.
What are our options to get this information back? Any help will be highly appreciated.

A: Piriform makes a program called Recuva, I have recovered some deleted files I thought were gone. It might work for you.  In the future I would encourage(force) employees to use a network location with backup on it rather then letting them store information like that in a non-company cloud
Recuva

A: You have two options:
1) if you get access to the Dropbox account, you might recover the files through the web-interface.
2) If your ex employee would not provide the log-in info. Then you can recover the data even if they are deleted and new data is overwritten on the old ones. However, the digital forensics may not be easy if you are new on it. Then I would strongly suggest you to contact with companies that does data-recovery, I think it would be the easiest option so that they can recover all lost file as they use good tools. It is even possible to recover the data with a professional tools even your hard disk is physically crashed. If you do Google search, you should see the available companies as Google provides result (or ads) considering your location.
In any case, do not use your computer as new data might be overwriten on the lost ones which will make harder to recover the lost data. If you want to continue using your computer, then take image of your hard-disk, so that you can continue using your desktop or if you try to recover the data by yourself, you can attempt to recover data from the image file which will ensure that your PC's file system will not be damaged . You can use Winhex to take the image and it also provides data-recovery options. but it is a basic program. More professional (and commercial) tools would be EnCase, Forensic Toolkit, DMZ F.I.R.E., Maresware
But as I said it would save you from a lot trouble if you contact with a company which does data-recovery.

A: If the data is really vital, and for some reason you are not able to get hold of your ex-employee, I suggest you go for professional data recovery service like SalvageData Recovery.
You could also try data recovery service provided by the harddrive manufacture's data recovery service. I know Seagate does this.
If you really dont want to pay for it you could try an array of free data recovery tools like:

*

*Test Disk

*Recuva

*Undelete Plus


text:
Q: How to access attributes of php object inside a array of php objects from javascript I have an array of php objects. Inside a javascript function I want to access attributes of an object in the array. If I json_encode the whole array it shows these attributes are undefined. How can I do this. I new to PHP.
PHP Code:
$_SESSION['objArray'] = $objArray;

Javascript Code:
const objArray = <?php echo json_encode(($_SESSION['objArray'])) ?>;

A: You certainly need to encode your array to JSON so it can be usable by a JavaScript client.
As you mentioned, you have instances of particular classes in your array, so simple JSON encoding won't work for sure.
Here, PHP comes with the JsonSerializable interface. You will have to implement this interface on your classes. Let's take a Foo example:
class Foo implements JsonSerializable
{
  private $thing;

  public function __construct($thing)
  {
    $this->thing = $thing;
  }

  public function jsonSerialize()
  {
    return [
      'thing' => $this->thing,
    ];
  }
}

Here is an example of the above code snippet. As you can see, now you can create an instance of Foo, embed it into an array or whatever, and JSON-encode it with your own representation:
$foo = new Foo('something');
echo json_encode(['foo' => $foo]);

// {"foo": {"thing": "something"}}

Outputting this into an inline JavaScript block would work similar to what you wrote:
<script type="application/javascript">
const obj = "<?php echo json_encode(($_SESSION['objArray'])) ?>;";
</script>

A: Store php array into javascript variable,
Example Value: (example array inside $_SESSION['objArray'])
$_SESSION['objArray'] = array(
    'name' => 'foo',
    'email' => 'foo@gmail.com',
    'age' => 30
);

Convert object to array: (optional) (if you have object value inside $_SESSION['objArray'])
$_SESSION['objArray'] = json_decode(json_encode($_SESSION['objArray']), true);

Solution: (assign in to javascript variable objArray)
<script>
    const objArray = "<?php echo json_encode($_SESSION['objArray']); ?>";
    console.log(objArray);
</script>

Console Output:
{"name":"foo","email":"foo@gmail.com","age":30}

Explanation: json_encode function will convert array in to a json string and javascript will consider it as a string and at assignment time it need to cover with quotation ether its ' or ".
Hope this help.


text:
Q: merge two file text with php I have two text files I have created this way:
<?php
$lines = file('Country.txt');
$newf = array();
foreach ($lines as $line)
  $newf[] = substr($line, 2);
file_put_contents('country2.txt', implode("\n", $newf));

$lines2 = file('countryenglish.txt');
$newf2 = array();
foreach ($lines2 as $line)
  $newf2[] = substr($line, 3);
file_put_contents('countryenglish2.txt', implode("\n", $newf2));

?>

Both display data like this:
Country2.txt:
Text1Data1
text1Data2
text1Data3
>
countryenglish2.txt
Text2Data1
text2Data2
text2Data3

I would like to display:
Text2Data1Text1Data1
text2Data2text1Data2
text2Data3text1Data3

Thanks in advance for your help!

A: Try this : You need to give third parameter FILE_APPEND or else it will overwrite the file.
file_put_contents('countryenglish2.txt', implode("\n", $newf2), FILE_APPEND);

ref: http://php.net/manual/en/function.file-put-contents.php

A: From your function, you can do this:
$newf3 = array();
$to = count($newf2);

for ($i=0; $i<$to; $i++) {
  $newf3[] = $newf2[$i] . $newf1[$i];
}

print_r($newf3);

A: You could try something like this:
$lines = file('Country.txt');
$lines2 = file('countryenglish.txt');

foreach ($lines as $key => $val) {
    $lines[$key] = $val.$lines2[$key];
}

file_put_contents('countryenglish2.txt', implode("\n", $lines));

A: The File Append answer above is the best way. Here is a source for you to reference http://w3schools.com/php/php_file.asp

A: U can checkout this: https://github.com/bircher/php-merge

When working with revisions of text one sometimes faces the problem that there are several revisions based off the same original text. Rather than choosing one and discarding the other we want to merge the two revisions.
Git does that already wonderfully. In a php application we want a simple tool that does the same. There is the xdiff PECL extension which has the xdiff_string_merge3 function. But xdiff_string_merge3 does not behave the same way as git and xdiff may not be available on your system.
PhpMerge is a small library that solves this problem. There are two classes: \PhpMerge\PhpMerge and \PhpMerge\GitMerge that implement the \PhpMerge\PhpMergeInterface which has just a merge method.
PhpMerge uses SebastianBergmann\Diff\Differ to get the differences between the different versions and calculates the merged text from it. GitMerge uses GitWrapper\GitWrapper, writes the text to a temporary file and uses the command line git to merge the text.


text:
Q: How to change color of UIActionSheet in iOS 7? I wish I could use custom colors to display Actionsheet in iOS 7.I've been searching for proper answer since couple of days.
Any help will be appreciated Thanks..
I'm using UIActionsheet to display PickerView in it

A:  UIActionSheet is not designed to be subclassed, nor should you add views to its hierarchy.
 If you need to present a sheet with more customization than provided by the
 UIActionSheet API, you can create your own.

As per apple doc Reference,
So you have to use some custom class for that,
show this cocoacontrols.

A: I want to stress that this violates Apple's rules, but this works:
- (void)willPresentActionSheet:(UIActionSheet *)actionSheet
{
    [actionSheet.subviews enumerateObjectsUsingBlock:^(UIView *subview, NSUInteger idx, BOOL *stop) {
      if ([subview isKindOfClass:[UIButton class]]) {
          UIButton *button = (UIButton *)subview;
          button.titleLabel.textColor = [UIColor greenColor];
          NSString *buttonText = button.titleLabel.text;
          if ([buttonText isEqualToString:NSLocalizedString(@"Cancel", nil)]) {
             [button setTitleColor:[UIColor greenColor] forState:UIControlStateNormal];
          }
      }
  }];
}

(conform to UIActionSheetDelegate)

A: I have created class which extedns UIActionSheet funcionality with ability to set colors, fonts, text colors and images to Action Sheet buttons. It works fine both for iOs6 and iOs7, and both for iPhone and iPad applications.
https://github.com/gloomcore/UICustomActionSheet
It doesn't use hidden API, so it's safety for Appstore. Enjoy.


text:
Q: MongoDB complex aggregation I have documents with the following structure in my database:
{
    "reading_ts": ISODate(...),
    "points": 2.3,
    "user_id": 2
}

I will have more documents like this for each user_id per day...millions of them...
I would like to implement the following aggregation:

*

*Get the data for one month

*Group the data for each user_id

*Group the data for each day (so I will have the data for each day, for each user_id)

*Get the max 'points' for each user for each day

*Count how many users has the max points under value 10, how many between 10 and 20 and how many over 20

I can do the step 1 with a $match
I can do the step 3 using this:
{
    "$group": {
        "_id": {
            "$subtract": [
                "$reading_ts",
                {
                    "$mod": [
                        {
                            "$toLong": "$reading_ts"
                        },
                        (1000 * 60 * 60 * 24)
                    ]
                }
            ]
        }
    }
}

The problem is that I don't know how to merge the steps 2 and 3 for now.

A: You can combine the steps 2,3 and 4 in a single $group stage using $dayOfMonth and $max to get the max 'points' for each user for each day.
Then, you can count the users by buckets using the $bucket operator with boudaries set to [0, 10, 20]:
db.collection.aggregate([
  {
    "$match": {
      "reading_ts": {
        "$gte": ISODate("2019-01-01"),
        "$lte": ISODate("2019-01-30")
      }
    }
  },
  {
    "$group": {
      "_id": {
        "user": "$user_id",
        "day": {
          "$dayOfMonth": "$reading_ts"
        }
      },
      "max": {
        "$max": "$points"
      }
    }
  },
  {
    "$bucket": {
      "groupBy": "$max",
      "boundaries": [
        0,
        10,
        20
      ],
      "default": 20,
      "output": {
        "users": {
          "$sum": 1
        },

      }
    }
  }
])

try it online: mongoplayground.net/p/jzZdz2V7R4-


text:
Q: How to reduce the size of spatial index data How to reduce the size of spatial index data?
is there any way to compress the location details

A: Data_compression option is not supported for spatial index in SQL Server 2008, According to Microsoft Documentation, support for data compression was added for spatial indexes in SQL Server 2012. SQL Server adds support for index compression of spatial indexes, using the same options as data and index compression in SQL Server 2012 and above.

As Microsoft Documentation specifies about DATA_COMPRESSION :-

 DATA_COMPRESSION = {NONE | ROW | PAGE}

Applies to: SQL Server 2012 (11.x) through SQL Server 2017, SQL Database.
    Determines the level of data compression used by the index.

NONE
No compression used on data by the index

ROW
Row compression used on data by the index

PAGE
Page compression used on data by the index

Using compression with spatial indexes appears to be quite effective.You may obtain between 25-40% reduction in size with ROW compression and 50-90% reduction in size with PAGE compression. Queries that use a compressed spatial index execute in about the same (in some cases, less) CPU and elapsed time as the same queries using uncompressed spatial indexes.

A: Yes, there are a few options you can tweak to reduce or increase it's size. However, knowing exactly what implications they bring might require investigating a little.

*

*Use DATA_COMPRESSION option. Default is NONE, you can use ROW or PAGE.

*Modifying the FILLFACTOR ratio.

*Use a custom tesellation grid with lower cells per object/level. This will greatly impact on how "useful" the index becomes when doing "seeks".


text:
Q: isql (sql anywhere) updating NULL value How can i change (NULL) value of a table? I have searched everywhere but didn't find the right answer.
Works, but updates 0 rows:
UPDATE Club
SET Place = 24
WHERE Place = NULL;

Not working:
UPDATE Club
SET Place = 24
WHERE Place IS NULL;

A: Something worth trying
Update Club
Set Place = 24
where CLUBID in (Select CLUBID from Club where place is NULL)

A: UPDATE Club
SET Place = 24
WHERE Place IS NULL;

This works fine. If its not working then, you don't have records where Place is null.
Check with null case as well, as sql is case sensitive.