text:
Q: Test data in JUnit I'm new in testing. So, I have a learning task.
This program calculate quadratic equation.
How can I check, for example, that c != 0 and D > 0 using JUnit?
I want to do it in the right way.
I tried to call input() from JUnit but the test became endless.
public class Main {
public static Scanner input;
public static double a, b, c;
public static double d;
public static double x1, x2;

public static void main(String args []) {
    input();
}

public static void input() {
    System.out.println("ax^2 + bx + c = 0");
    input = new Scanner(System.in);
    try {
        System.out.print("a -> ");
        a = input.nextFloat();
        System.out.print("b -> ");
        b = input.nextFloat();
        System.out.print("c -> ");
        c = input.nextFloat();
    } catch (InputMismatchException e) {
        System.out.println("Input number!\n");
        input();
    }

    if(a == 0 || b == 0 || c == 0) {
        System.out.println("Not right\n");
        input();
        return;
    }

    calculate();
}

public static void calculate() {
    d = (b * b) - (4 * a * c);
    System.out.println("D = " + d);

    if(d < 0) {
        System.out.print("No answer");
    } else if(d == 0) {
        x1 = (-b) / (2 * a);
        System.out.println ("x = " + x1);
    } else {
        x1 = (-b + Math.sqrt(d)) / (2 * a);
        x2 = (-b - Math.sqrt(d)) / (2 * a);
        System.out.println("x1 =  " + x1);
        System.out.println("x2 = " + x2);
    }
}

}

A: Your program is not testable in its current form. This is an alternative:
public class Parabola {
  // These are required in the constructor. Omitted for brevity
  private final double a;
  private final double b;
  private final double c;
  // Public API. Test this
  public double x1() { /*...*/ }
  public double x2() { /*...*/ }
}

Now writing tests is trivial:
@Test public void test1() {
  Parabola target = new Parabola(1, 2, 3);
  assertEquals(target.x1(), 44.23);
  assertEquals(target.x2(), 17.23);
}

@Test public void test2() {
  Parabola target = new Parabola(1, 0, 0);
  assertEquals(target.x1(), -1);
  assertEquals(target.x2(), 13.43);
}

And finally this is how a main() looks like:
public void main(String... args) throws Exception {
  Scanner console = ...;
  System.out.println("Type a:");
  Double a = Double.parseDouble(console.nextLine());
  // Same for b and c
  Parabola p = new Parabola(a, b, c);
  System.out.println("X axis intersected in "  + p.x1() + " and " + p.x2());
}

Bonus: When comparing doubles in unit tests, you may want to use this version of assertEquals() that accepts a threshold parameter because of how floating point arithmetic works and/or the decimal representation of binary numbers works


text:
Q: Does Selenium- Jenkins Integration needs TestNG or JUnit Framework Should we need TestNG or Junit framework to integrate Selenium with Jenkins. I have project which is build without TestNG or JUnit can i integrate it with Jenkins.

A: You can use both JUnit and TestNG frameworks as Jenkins supports both.
Steps in details for TestNG integration with Jenkins.
Step 1: Create Free Style project in Jenkins and fill the details and Save the project.
Step 2: click on Configure
Step 3: In the Build section of Configure:
java -cp J:\taf\testng\*;J:\taf\workspace\TestNGExamples\bin;J:\automation\* org.testng.TestNG J:\taf\workspace\TestNGExamples\testng1.xml

Note: you have to change the paths as per your system.
In -cp argument, we must provide testng.jar, project location and ``selenium jarslocations/paths.
org.testng.TestNG- TestNG Main Class.
andlocation to the XML of testng configuration`

Download and install the testng-plugin for jenkins from here and restart Jenkins in order to take effect.
Step 4: In the Post-build Actions section,

*

*Select Publish TestNG Results from Add post-build action dropdown.

*provide the path where to look for TestNG results (.xml file containing results).

*Click Apply and Save buttons.

Screenshot for reference:

A: TestNG and JUnit on simple terms can be visualised as "java code execution" mechanisms with support to do validations.
So instead of you having only one main() method that would be the single point of entry for execution of your selenium code, TestNG/JUnit takes up that role and lets you run multiple java classes via themselves.
Jenkins is an orchestrator tool that lets you build, test, deploy as per your wish.
The test phase can be skipped by not using TestNG and JUnit, and you resorting to executing your selenium based tests via a main() method which takes care of doing all validations as well (assertions in the JUnit/TestNG world)

redpajama_set_name: RedPajamaStackExchange


text:
Q: I can't generate the gRPC stubs classes I managed to generate the classes through the .proto file but they are in the build.
I would like the classes to be generated within the main because when I am going to extend the stub, it is not being possible to implement the methods.
Look:
File .proto:
syntax = "proto3";

package demogrpcserver.tcp;

option java_multiple_files = true;
option java_package = "com.example.demogrpcserver";
option java_outer_classname = "tcp";

service TCPService {
  rpc execute(TCPMonitorRequest) returns (TCPMonitorResponse);
}

message TCPMonitorRequest {
  string socketOpen = 1;
  string messageType = 2;
}

message TCPMonitorResponse {
  bool success = 1;
  string txId = 2;
}

The .proto file is inside the main folder.
Does anyone know how to solve?

A: You can use a plugin in the pom file to auto-generate proto files in the src path.
<plugin>
            <groupId>com.github.os72</groupId>
            <artifactId>protoc-jar-maven-plugin</artifactId>
            <version>3.6.0.1</version>
            <executions>
                <execution>
                    <phase>generate-sources</phase>
                    <goals>
                        <goal>run</goal>
                    </goals>
                    <configuration>
                        <includeMavenTypes>direct</includeMavenTypes>

                        <inputDirectories>
                            <include>src/main/resources</include>
                        </inputDirectories>

                        <outputTargets>
                            <outputTarget>
                                <type>java</type>   <outputDirectory>src/proto/</outputDirectory>
                            </outputTarget>
                            <outputTarget>
                                <type>grpc-java</type>
                                <pluginArtifact>io.grpc:protoc-gen-grpc-java:1.15.0</pluginArtifact>
                            <outputDirectory>src/proto/</outputDirectory>
                            </outputTarget>
                        </outputTargets>
                    </configuration>
                </execution>
            </executions>
        </plugin>

Else with your current setup you can import your proto files and extend it.

A: See the Generated Code section of the gRPC Java readme. For non-Android Gradle builds, you'd use:
plugins {
    id 'com.google.protobuf' version '0.8.15'
}

protobuf {
  protoc {
    artifact = "com.google.protobuf:protoc:3.12.0"
  }
  plugins {
    grpc {
      artifact = 'io.grpc:protoc-gen-grpc-java:1.36.0'
    }
  }
  generateProtoTasks {
    all()*.plugins {
      grpc {}
    }
  }
}

You can also take a look at the grpc-java examples.

A: You can generate your Java classes anywhere you want with the protoc tool
protoc \
  -I PATH_TO_YOUR_PROTOS \
  --java_out=PATH_TO_JAVA_LOCALTION \
  PROTO_FILE_NAME_THAT_WILL_BE_IN_$PATH_TO_YOUR_PROTOS

protoc \
  -I $PATH_TO_YOUR_PROTOS \
  --java_out=$PATH_TO_JAVA_LOCALTION \
  --plugin=protoc-gen-grpc-java=/usr/local/bin/protoc-gen-grpc-java \
  PROTO_FILE_NAME_THAT_WILL_BE_IN_$PATH_TO_YOUR_PROTOS

Installing the protoc and protoc-grpc-java plugin
PROTOC_VERSION="3.12.0"
JAVA_GEN_VERSION="3.7.1"
JAVA_GRPC_GEN_VERSION="1.24.0"

## Protobuf compiler
RUN apt-get update && \
        apt-get install -y unzip && \
        wget https://github.com/protocolbuffers/protobuf/releases/download/v$PROTOC_VERSION/protoc-$PROTOC_VERSION-linux-x86_64.zip && \
        unzip protoc-$PROTOC_VERSION-linux-x86_64.zip -d /usr/local/ && \
        rm -rf protoc-$PROTOC_VERSION-linux-x86_64.zip

# Protobuf Java
RUN curl https://repo1.maven.org/maven2/io/grpc/protoc-gen-grpc-java/1.27.2/protoc-gen-grpc-java-1.27.2-linux-x86_64.exe -o  /usr/local/bin/protoc-gen-grpc-java && \
    chmod +x /usr/local/bin/protoc-gen-grpc-java

You can find more information here


text:
Q: Составить регулярное выражение для HTML текста с определенными тегами Нужно регулярные выражением выделить текст между тегами color: #21201e"> и <' + '/div> помогите пожалуйста, мне нужно конкретно выделить этот текст конкретно между двумя этими тегами
Текст примерно такой:
var scripts = document.getElementsByTagName('script');
var script = scripts[scripts.length - 1];
var borq='';
borq += '<' + 'article style="margin: 15px auto; max-width: 560px;"><' + 'div style="background:#fff; border: 1px solid #e6e5e0; border-radius: 3px"><' + 'header style="display: -webkit-box; display: -ms-flexbox; display: flex; -webkit-box-align: flex-startnpm; -ms-flex-align: flex-startnpm; align-items: flex-startnpm; -webkit-box-pack: justify; -ms-flex-pack: justify; justify-content: space-between; font-size: 9px; font-weight: bold; line-height: 12px; color: #827e7c"><' + 'a style="margin: 0; padding: 15px 15px 12px; color: #859900; text-decoration: none" href="/quote/451014">#451014<' + '/a><' + 'span style="padding: 15px 15px 12px">28.06.2018<' + '/span><' + '/header><' + 'div style="margin: 0 1px; padding: 0 15px 18px; font-size: 14px; line-height: 21px; color: #21201e">Вот есть люди (много людей), кто от армии упорно "косит". А был у меня знакомый, который яро желал вступить в ряды оборонительных сил любимой страны. Настало время призыва, так он руку сломал, в футбол играя. Ладно, говорит, не беда - на следующий призыв пойду, буду уже здоровый, как бык, к тому времени. Окей, приходит время призыва, всё отлично, его берут в ВДВ. Рад страшно. Уже пора и очаливать в армию, так, ессесн, решили проводить. Проводить не на поезд (или куда там ещё), а именно устроить прощальное пати. Напились, время около полдесятого вечера. Несомненно, закупленного заранее алкоголя не хватило и этот товаристч решил сходить в магазин за добавкой. Двадцать минут нет, полчаса... Телефон не взял с собой. Пошли искать. Поиски были рекордно короткими - шёл по лестнице в подъезде, упал. Там лежать и остался ВДВ-шник наш. Ногу поломал, мениск повреждён. В общем, теперь навечно непригоден. Сходил в армию, ять. А ведь, так хотел. Судьба?<' + '/div><' + 'footer style="margin: 0; padding: 0 0 20px; height: 40px; line-height: 40px; font-size: 13px; text-align: center"><' + 'a href="http://bash.im/" target="_blank" title="bash.im откроется в новом окне" style="display: inline-block; padding: 10px 50px; font-size: 14px; line-height: 18px; text-align: center; color: #fff; background-color: #859900; border: none; border-radius: 3px; text-decoration: none; cursor: pointer;">Больше на bash.im!<' + '/a><' + '/footer><' + '/div><' + '/article>';
setTimeout(function() {
  script.outerHTML += borq;
}, 500);

Код примерно такой:
Random rnd = new Random();
System.Net.WebClient wc = new System.Net.WebClient();
byte[] raw = wc.DownloadData("https://bash.im/forweb/?u");
string webData = System.Text.Encoding.UTF8.GetString(raw);
Regex regex = new Regex("<;.*>", RegexOptions.IgnoreCase);
string[] str = regex.Split(webData);
string[] items = {""};
for (int i = 0; i < str.Length; i++)
{
    if (str[i] == "") str = (from x in str where !items.Contains(x) select x).ToArray();

}
Console.Write(str[rnd.Next(1,str.Length-1)]);
Console.ReadKey();

A: По идее как-то так:
Regex.Match(@"color: #21201e"">(.*?)<' \+ '\/div>").Groups[1].Value

A: Используйте
var text = Regex.Match(s, @"(?s)color:\s*#21201e"">(.*?)<'\s+\+\s+'/div>")?.Groups[1].Value;

Пример работы регулярного выражения.
Подробности

*

*(?s) - модификатор, позволяющий точке находить переводы строки

*color: - строка color:

*\s* - 0 и более пробельных символов

*#21201e""> - строка #21201e">

*(.*?) - Захватывающая подмаска №1: любые 0 и более символов, как можно меньше

*<' - строка <'

*\s+ - 1 и более пробельных символов

*\+ - знак +

*\s+ - 1 и более пробельных символов

*'/div> - строка '/div>.


text:
Q: How to run Jruby 1.6.6 on Aptana Studio 3.0.8 *ON WINDOWS* I have read the launching Jruby from Aptana Studio 3 on Windows XP thread (to be fair, I am on windows 7) and created the wrapper script ruby.bat (@C:\jruby-1.6.6\bin\jruby %* - MY particular path)
Tried naming it "just" ruby, ruby.sh whatever, but Aptana wont find it. From any windows shell (cmd) it works without a hitch.
Also tried copying the JRuby.exe to Ruby.exe. That still won't work. Linking ruby.exe to jruby.exe with the mklink command still wont work.
Looked around the internet, but all I found are dead ends.
Any fix to this? Can't be THAT rare a setup, THAT difficult, or can it?

A: I did that by a simple trick...
I created a c++ file ruby.cpp:
#include <cstdlib>
#include <iostream>

using namespace std ;

int main( int argc, char *argv[] ) {
    string cmd = "jruby.exe" ;
    for (int i = 1 ; i < argc ; ++i)
        cmd.append( " " ).append( argv[i] ) ;
    return system( cmd.c_str() ) ;
}

Compiled as ruby.exe and moved to C:\jruby-1.6.6\bin.
It works...


text:
Q: How to delete columns? I have generated the following text file below:
fe120b99164f151b28bf86afa6389b22 -rw-r--r-- 1 joey joey 186 2010-03-14 19:26 Descript.txt
41705ea936cfc653f273b5454c1cdde6 -rw-r--r-- 1 joey joey  30 2010-03-14 20:29 listof.txt
0e25cca3222d32fff43563465af03340 -rw-r--r-- 1 joey joey  28 2010-03-14 23:35 sedexample.txt
d41d8cd98f00b204e9800998ecf8427e -rw-r--r-- 1 joey joey   0 2010-02-16 15:11 test1.txt
d41d8cd98f00b204e9800998ecf8427e -rw-r--r-- 1 joey joey   0 2010-02-16 15:11 test2.txt
d41d8cd98f00b204e9800998ecf8427e -rw-r--r-- 1 joey joey   0 2010-02-16 15:11 test3.txt
d41d8cd98f00b204e9800998ecf8427e -rw-r--r-- 1 joey joey   0 2010-02-16 15:11 test4.txt
d41d8cd98f00b204e9800998ecf8427e -rw-r--r-- 1 joey joey   0 2010-02-16 15:11 test5.txt
d41d8cd98f00b204e9800998ecf8427e -rw-r--r-- 1 joey joey   0 2010-02-16 15:11 test6.txt
f5c7f1856249d0526be10df5bd5b895a -rw-r--r-- 1 joey joey  26 2010-03-13 14:13 testingfile.txt
d41d8cd98f00b204e9800998ecf8427e -rw-r--r-- 1 joey joey   0 2010-03-15 00:28 uniquelist.txt

Basically I would like to get rid of the access, amount column, user and group columns.  In other words, I want rid of columns 3,4,5.  I have tried using cut to keep the columns that I do want and having " " as my delimiter however because of the file size figures, it messes up using "space" as a delimiter.  Any advice would be much appreciated!  Oh just to add, I would like to save the output as another text file.  Many thanks!

A: Easily done as a shell pipe.
cut --delimiter=' ' --fields=3-5 --complement

If you really need to do this in C, you could run that command in a subprocess via popen.
If you had mixed space and tab delimiters, you would need to convert one to the other as cut does not like multiple delimiters. Do this with tr or col -x.

A: how does your cut command look like?
$ cut -d" " -f1,6- file
fe120b99164f151b28bf86afa6389b22 186 2010-03-14 19:26 Descript.txt
41705ea936cfc653f273b5454c1cdde6  30 2010-03-14 20:29 listof.txt
0e25cca3222d32fff43563465af03340  28 2010-03-14 23:35 sedexample.txt
d41d8cd98f00b204e9800998ecf8427e   0 2010-02-16 15:11 test1.txt
d41d8cd98f00b204e9800998ecf8427e   0 2010-02-16 15:11 test2.txt
d41d8cd98f00b204e9800998ecf8427e   0 2010-02-16 15:11 test3.txt
d41d8cd98f00b204e9800998ecf8427e   0 2010-02-16 15:11 test4.txt
d41d8cd98f00b204e9800998ecf8427e   0 2010-02-16 15:11 test5.txt
d41d8cd98f00b204e9800998ecf8427e   0 2010-02-16 15:11 test6.txt
f5c7f1856249d0526be10df5bd5b895a  26 2010-03-13 14:13 testingfile.txt
d41d8cd98f00b204e9800998ecf8427e   0 2010-03-15 00:28 uniquelist.txt

redirect to new file as needed.
Or awk
$ awk '{$2=$3=$4=$5="";gsub(/ +/," ")}1' file
fe120b99164f151b28bf86afa6389b22 186 2010-03-14 19:26 Descript.txt
41705ea936cfc653f273b5454c1cdde6 30 2010-03-14 20:29 listof.txt
0e25cca3222d32fff43563465af03340 28 2010-03-14 23:35 sedexample.txt
d41d8cd98f00b204e9800998ecf8427e 0 2010-02-16 15:11 test1.txt
d41d8cd98f00b204e9800998ecf8427e 0 2010-02-16 15:11 test2.txt
d41d8cd98f00b204e9800998ecf8427e 0 2010-02-16 15:11 test3.txt
d41d8cd98f00b204e9800998ecf8427e 0 2010-02-16 15:11 test4.txt
d41d8cd98f00b204e9800998ecf8427e 0 2010-02-16 15:11 test5.txt
d41d8cd98f00b204e9800998ecf8427e 0 2010-02-16 15:11 test6.txt
f5c7f1856249d0526be10df5bd5b895a 26 2010-03-13 14:13 testingfile.txt
d41d8cd98f00b204e9800998ecf8427e 0 2010-03-15 00:28 uniquelist.txt

A: Do you have to do this in C? This would be easier to do in a scripting language like perl, or even awk.
awk '{print $1 $6 $7 $8 $9}' file.txt

A: Pipe it through awk '{print $1 $6 $7 $8 $9;}'?

A: I smell homework, but I'll give you the benefit of the doubt.
Cut will work, but you need to merge one or more spaces into just one first:
sed "s/ \+/ /g" input_file | cut -d' ' -f-2,6-

To save the output of any command to a file, it's command > file.

A: I tried using awk '{print $1 $6 $7 $8 $9}' file.txt however it gives me the following output:
fe120b99164f151b28bf86afa6389b221862010-03-1419:26Descriptions.txt
41705ea936cfc653f273b5454c1cdde6302010-03-1420:29listofnumbers.txt
0e25cca3222d32fff43563465af03340282010-03-1423:35sedexample.txt
d41d8cd98f00b204e9800998ecf8427e02010-02-1615:11test1.txt
d41d8cd98f00b204e9800998ecf8427e02010-02-1615:11test2.txt
d41d8cd98f00b204e9800998ecf8427e02010-02-1615:11test3.txt
d41d8cd98f00b204e9800998ecf8427e02010-02-1615:11test4.txt
d41d8cd98f00b204e9800998ecf8427e02010-02-1615:11test5.txt
d41d8cd98f00b204e9800998ecf8427e02010-02-1615:11test6.txt
f5c7f1856249d0526be10df5bd5b895a262010-03-1314:13testingfile.txt
d41d8cd98f00b204e9800998ecf8427e02010-03-1500:28uniquelist.txt
All the columns have become joined into one which is not ideal for me as I will be using uniq one this at some point.  Thanks for your help!

A: $ perl -lane'$, = " "; print @F[0,5..$#F]' input.txt

NOTE: As well as the cut version it replaces two or more spaces in the input by a single space e.g., it can broke filenames in the input.

A: Try to open  them in excel with space as delimiter, delete it there. See if it works.


text:
Q: How to rotate a model in ARkit using Raycast and touch in unity? I am trying to drag or move and rotate a model by touching the device. I am placing it by single touch and rotating it by by double touch. I have added a tag named "Region" to the model. Below is the code. I am attaching this script to the instantiated model.
public float rotspeed = 8f;
private RaycastHit vision;

// Use this for initialization
void Start ()
{

}

// Update is called once per frame
void Update()
{
    if (Input.touchCount == 2 && Input.GetTouch(0).phase == TouchPhase.Moved)
    {
        Debug.Log("Double Touch");
        // Get movement of the finger since last frame
        Vector2 touchDeltaPosition = Input.GetTouch(0).deltaPosition;

        if(Physics.Raycast(Input.GetTouch(0).position,
           this.transform.position,
           out vision))
        {
            Debug.Log("Entered Region");
            if(vision.transform.tag=="Region")
            {
                Debug.Log("Hit Region");
                transform.Rotate(Vector3.up,
                                 -touchDeltaPosition.x * rotspeed * Time.deltaTime,
                                 Space.World);
                transform.Rotate(Vector3.right,
                                 touchDeltaPosition.y * rotspeed * Time.deltaTime,
                                 Space.World);
            }
        }
    }
}


text:
Q: Mudar HTML da paginação no Laravel 5.1 Existe uma maneira de alterar o HTML retornado pelo método render(), na paginação embutida no Laravel 5.1?
Nota: eu resolvi isto criando um helper que usa str_replace(), mas acredito que não seja o meio mais correto.
Grato.

A: Abre a página que contém a paginação.
Abre o Inspect Element do Chrome ou outro navegador que você usa e inspeciona os elementos que montam a paginação.
Altere via CSS.

A: Encontrei esta biblioteca - Landish/Pagination - que já traz alguns paginadores e permite facilmente criar seus próprios.


text:
Q: how to use Lucene highlighter with phraseQuery? How to use Lucene's Highlighter with phraseQuery ?
I did a google search, and I am getting confused with spanScorer, QueryScorer, and few things like that..
The Lucene version I am using is 3.0.3
My requirements are
- Doing a multi field query
- Doing a wildcard search
- Doing a phrase query
All the above needs to be highlighted.
How do I achieve this ?

A: So I found the answer to my own question...
After a LOT of hair pulling and google searching, I found this :
http://www.gossamer-threads.com/lists/lucene/java-...g=highlight%20wildcard;#116172
Specifically setting up the QueryScorer with this :
qs.setExpandMultiTermQuery(true);
did the job of highlighting wildcard searches.
As for the multi field stuff, I did ask it to highlight looping through my array of fields. So that was ugly, but works.
Phrase query words with QueryScorer easily.


text:
Q: simplexml_load_file() и кириллический дмоен Есть код для обновления информации о товарах из другого магазина через файл Яндекс.Маркета. В начале я подгружаю файл с помощью simplexml_load_file(). Сайт одного из новых клиентов размещается на кириллическом домене (итоговая ссылка на файл по типу 'мойсайт.рф/pricelist.xml'), в итоге ничего не работает. Пытался элементарно перевести домен в punycode — не работает.
Мастера, подскажите, как мне быть? Всякие дополнительные библиотеки ставить не могу, т.к. хостинг виртуальный. Заранее всем спасибо!

A: Простейшая проверка говорит что всё должно работать:
<?php
$xml = simplexml_load_file('https://xn----7sbb5aamccpiegbel3bh1td.xn--p1ai/sitemap.xml');

foreach ($xml->url as $line) {
    echo "{$line->loc}\n";
}

Проверьте, нет ли ошибки DNS:
var_dump(gethostbyname('xn----7sbb5aamccpiegbel3bh1td.xn--p1ai'));

Если ошибки DNS нет (команда выше возвращает IP адрес), и вы можете загрузить файл локально из браузера, то обращайтесь в поддержку хостинга.
В вашем конкретном случае похоже на сервере блокируются запросы без заголовка User-Agent. Это легко исправить так:
<?php
$file = file_get_contents('http://xn--80aaanvlco2b3a.xn--p1ai/pricelist.xml', false, stream_context_create([
  'http' => [
    'header' => 'User-Agent: PHP'
  ]
]));

$xml = simplexml_load_string($file);

var_dump($xml->shop->name);


text:
Q: SVN: E000104: Error running context: Connection reset by peer I'm trying to follow this tutorial to get started with LLVM.
But checking out the project via SVN results in the E000104 error every time. And each time it is at a different point of the process. (seemingly random)
I just installed SVN, went into a new folder, and my command is:
svn co http://llvm.org/svn/llvm-project/llvm/trunk llvm

Is there a svn error log file where I get more information about this? Or a known solution maybe?


text:
Q: pygame image transparency not showing I used a graphic routine to draw and image on grabbed it as an image as shown below.
    for event in pygame.event.get():

    if event.type == UPDATE:

        y += 1

        get_image = screen.subsurface(60, 62, 82, 70)
        get_image.set_colorkey( (0,0, 0), RLEACCEL )
        if imageno <= 9:
            st = "0" + str(imageno)
        else:
            st = str(imageno)

        pygame.image.save(get_image, "graphicstest\\" + "mojo" + st + ".png")

        imageno += 1

But when I load an image with
img=pygame.image.load(path).convert.alpha()

and blit to screen the black area of the image shows. It is NOT transparent.
Any suggestions?

A: Change your convert_alpha() to just convert(), then the colorkey should work. If it doesn't, take away the RLEACCEL.
I just came across this same issue last night. I was using convert_alpha() on my images along with colorkey, and my images still had their undesired background. Changing to just convert() solved it.

A: i solved the problem.
I removed the line get_image.set_colorkey( (0,0, 0), RLEACCEL )
from the code block where I grab the image.
Then I loaded it with img=pygame.image.load(path.
Did img.set_colorkey((0, 0, 0))
        pygame.Surface.convert_alpha(img)

This worked perfectly.


text:
Q: XML Elements to Linq I'm trying to show all the info I need from an XML to a datagridview1. The XML has a <Product> tag that contains it's own attributes and several Elements with it's own Attributes.
It looks like this:
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<Import>
    <Products>
        <Product Id="1" Name="prodcut1">
            <Prices price=10,10/>
            <Barcodes barcode="123123123123"/>
        </Product>

        <Product Id="2" Name="Product2">
            <Prices price=9,9/>
            <Barcodes Barcode="123123123123"/>
        </Product>

    </Products>

</Import>

Since a datagridview as far as I know, cant show more than one table (ie. dataGrid1.DataSource = dataSet.Tables[1];), I was trying with Linq and anonymous types to select whatever I want and show it in one line per <Product> tag.
On the datagrid it should look like something like this:
id | Name         | Barcode | Price
1   product1        123...      10,10
2   product2        123....     9,9

So far I wrote this to show <Product> and its attributes, 'id' and 'name':
XElement ProdXML = XElement.Load(@"C:\Export\ppp.xml");
var query = from st in ProdXML.Descendants("Product")
            select new
            {
                Id = st.Attribute("Id").Value,
                name = st.Attribute("Name").Value,

             };
dataGridView1.DataSource = query.ToList();

Is there any way to retrieve Prices => Price and Barcodes => barcode inside the Select?

A: Yes, you only need to access the element:
XElement ProdXML = XElement.Load(@"C:\Export\ppp.xml");
            var query = from st in ProdXML.Descendants("Product")

select new
{
    Id = st.Attribute("Id").Value,
    name = st.Attribute("Name").Value,
    price = st.Element("Prices").Attribute("Price").Value,
    barcode = st.Element("Barcodes").Attribute("Barcode").Value
};
dataGridView1.DataSource = query.ToList();

A: Try with xml deserializer, it will be easier to use. You can then convert into list objects and play with it.
something like:
string xml = "";//Get xml here
var serializer = new XmlSerializer(typeof(Import));
var import = (Import)serializer.Deserialize(xml);

Use System.Xml.Serialization Namespace
The classes that you can use can be like:
[XmlRoot(ElementName = "Prices")]
public class Prices
{
    [XmlAttribute(AttributeName = "price")]
    public string Price { get; set; }
}

[XmlRoot(ElementName = "Barcodes")]
public class Barcodes
{
    [XmlElement(ElementName = "barcode")]
    public List<string> Barcode { get; set; }
}

[XmlRoot(ElementName = "Product")]
public class Product
{
    [XmlElement(ElementName = "Prices")]
    public Prices Prices { get; set; }
    [XmlElement(ElementName = "Barcodes")]
    public Barcodes Barcodes { get; set; }
    [XmlAttribute(AttributeName = "Id")]
    public string Id { get; set; }
    [XmlAttribute(AttributeName = "Name")]
    public string Name { get; set; }
}

[XmlRoot(ElementName = "Products")]
public class Products
{
    [XmlElement(ElementName = "Product")]
    public List<Product> Product { get; set; }
}

[XmlRoot(ElementName = "Import")]
public class Import
{
    [XmlElement(ElementName = "Products")]
    public Products Products { get; set; }
}


text:
Q: Error creating database in SQLite I am getting an error when trying to save data in SQLite database. My application has two EditText fields, when user taps 'save' the data entered have to be saved in database.
I am using android studio 3.0.1. Bellow is the error I am getting:
16:13:01.270 12710-12710/com.vysh.gridlayoutmanagerrecyclerview
E/SQLiteLog: (1) no such table: myTable
02-03 16:13:01.277 12710-12710/com.vysh.gridlayoutmanagerrecyclerview
E/SQLiteDatabase: Error inserting Password=123 Name=luane

android.database.sqlite.SQLiteException: no such table: myTable (code
1): , while compiling: INSERT INTO myTable(Password,Name) VALUES (?,?)

at
android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native
Method)

When user taps 'save' button, the method insertData() is called. Bellow is the class which contains this method:
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.widget.Toast;

class MyDbAdapter {
    MyDbHelper helper;

    public MyDbAdapter(Context context)
    {
        helper = new MyDbHelper(context);
    }

public long insertData(String name, String password)
{
    SQLiteDatabase db = helper.getWritableDatabase();
    ContentValues contentValues = new ContentValues();
    contentValues.put(MyDbHelper.NAME, name);
    contentValues.put(MyDbHelper.PASSWORD, password);
    long id = db.insert(MyDbHelper.TABLE_NAME, null , contentValues);
    //Toast.makeText(context, message, Toast.LENGTH_LONG).show();
    return id;
}

static class MyDbHelper extends SQLiteOpenHelper {
    private static final String DATABASE_NAME = "myDatabase";
    private static final String TABLE_NAME = "myTable";
    private static final int DATABASE_Version = 1;
    private static final String UID="_id";
    private static final String NAME = "Name";
    private static final String PASSWORD= "Password";
    private static final String CREATE_TABLE = "CREATE TABLE "+TABLE_NAME +
            "( "+UID+" INTEGER PRIMARY KEY AUTOINCREMENT ," +NAME+ "VARCHAR(225)" + PASSWORD+"VARCHAR(225));";
    // private static final String DROP_TABLE ="DROP TABLE IF EXISTS "+TABLE_NAME;
    private Context context;

    public MyDbHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_Version);
        this.context=context;
        Message.message(context,"Started...");
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        try {

            db.execSQL(CREATE_TABLE);
            Message.message(context,"TABLE CREATED");
        } catch (Exception e) {
            Message.message(context,""+e);
        }
      }
    }// end of MyDbHelper
}

Any help is welcome

A: You have omitted spaces between column names and the column types. This will result in the table not being created due to the syntax error (a column name cannot contain ()).
The reason why this is not detected until you click the save button is that the database will not be created/opened until either getReabableDatabase or getWriteableDatabase is called.
You should change :-
private static final String CREATE_TABLE = "CREATE TABLE "+TABLE_NAME +
            "( "+UID+" INTEGER PRIMARY KEY AUTOINCREMENT ," +NAME+ "VARCHAR(225)" + PASSWORD+"VARCHAR(225));";

To be something like :-
private static final String CREATE_TABLE = "CREATE TABLE "+TABLE_NAME +
            "( "+UID+" INTEGER PRIMARY KEY AUTOINCREMENT ," +NAME+ " VARCHAR(225)" + PASSWORD+" VARCHAR(225));";

Note that you will need to delete the App's data or uninstall the App after making the changes, so that the database is deleted and thus allowing the onCreate method to be run.


text:
Q: How to plot multiple columns into a barplot in R This is my dataframe.
    Month NY_Month_Freq Chi_Month_Freq LA_Month_Freq Aus_Month_Freq
1      1           593            204           188             67
2      2           331            174           166             58
3      3           371            211           170             65
4      4           320            219           190             80
5      5           442            222           195             92
6      6           414            236           182             64
7      7           434            245           176             82
8      8           364            250           186             77
9      9           379            216           175             61
10    10           378            205           195             80
11    11           339            203           183             66
12    12           355            185           175             86

I want to plot the different frequencies by month, given the 4 cities.

A: Try reshaping your data:
library(tidyverse)
#Code
df %>% pivot_longer(-Month) %>%
  ggplot(aes(x=factor(Month),y=value,fill=name))+
  geom_bar(stat = 'identity',position = position_dodge(0.9))+
  labs(fill='city')+
  theme(legend.position = 'top')+xlab('Month')

Output:

Some data used:
#Data
df <- structure(list(Month = 1:12, NY_Month_Freq = c(593L, 331L, 371L,
320L, 442L, 414L, 434L, 364L, 379L, 378L, 339L, 355L), Chi_Month_Freq = c(204L,
174L, 211L, 219L, 222L, 236L, 245L, 250L, 216L, 205L, 203L, 185L
), LA_Month_Freq = c(188L, 166L, 170L, 190L, 195L, 182L, 176L,
186L, 175L, 195L, 183L, 175L), Aus_Month_Freq = c(67L, 58L, 65L,
80L, 92L, 64L, 82L, 77L, 61L, 80L, 66L, 86L)), class = "data.frame", row.names = c("1",
"2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"))

A: Same as the answer from @Duck mostly. I didn't see it until after I typed it up.
library(tidyverse)

df <- tibble::tribble(
        ~Month, ~NY_Month_Freq, ~Chi_Month_Freq, ~LA_Month_Freq, ~Aus_Month_Freq,
            1L,           593L,            204L,           188L,             67L,
            2L,           331L,            174L,           166L,             58L,
            3L,           371L,            211L,           170L,             65L,
            4L,           320L,            219L,           190L,             80L,
            5L,           442L,            222L,           195L,             92L,
            6L,           414L,            236L,           182L,             64L,
            7L,           434L,            245L,           176L,             82L,
            8L,           364L,            250L,           186L,             77L,
            9L,           379L,            216L,           175L,             61L,
           10L,           378L,            205L,           195L,             80L,
           11L,           339L,            203L,           183L,             66L,
           12L,           355L,            185L,           175L,             86L
        )

df2 <- df %>%
  pivot_longer(-Month, names_to = "location", values_to = "count") %>%
  mutate(location = str_remove(location, "_Month_Freq")) %>%
  rename(month = Month)

ggplot(df2, aes(month, count, fill = location)) +
  geom_col(position = "dodge")


text:
Q: SQL Server pick random (or first) value with aggregation How can I get SQL Server to return the first value (any one, I don't care, it just needs to be fast) it comes across when aggregating?
For example, let's say I have:
ID      Group
1       A
2       A
3       A
4       B
5       B

and I need to get any one of the ID's for each group. I can do this as follows:
Select
max(id)
,group
from Table
group by group

which returns
ID      Group
3       A
5       B

That does the job, but it seems stupid to me to ask SQL Server to calculate the highest ID when all it really needs to do is to pick the first ID it comes across.
Thanks
PS - the fields are indexed, so maybe it doesn't really make a difference?

A: There is an undocumented aggregate called ANY which is not valid syntax but is possible to get to appear in your execution plans. This does not provide any performance advantage however.
Assuming the following table and index structure
CREATE TABLE T
(
id int identity primary key,
[group] char(1)
)

CREATE NONCLUSTERED INDEX ix ON T([group])

INSERT INTO T
SELECT TOP 1000000 CHAR( 65 + ROW_NUMBER() OVER (ORDER BY @@SPID) % 3)
FROM sys.all_objects o1, sys.all_objects o2, sys.all_objects o3

I have also populated with sample data such that there are many rows per group.
Your original query
SELECT MAX(id),
       [group]
FROM   T
GROUP  BY [group]

Gives Table 'T'. Scan count 1, logical reads 1367 and the plan
  |--Stream Aggregate(GROUP BY:([[T].[group]) DEFINE:([Expr1003]=MAX([[T].[id])))
       |--Index Scan(OBJECT:([[T].[ix]), ORDERED FORWARD)

Rewritten to get the ANY aggregate...
;WITH cte AS
(
SELECT *,
        ROW_NUMBER() OVER (PARTITION BY [group] ORDER BY [group] ) AS RN
FROM T)
SELECT id,
       [group]
FROM    cte
WHERE RN=1

Gives Table 'T'. Scan count 1, logical reads 1367 and the plan
  |--Stream Aggregate(GROUP BY:([[T].[group]) DEFINE:([[T].[id]=ANY([[T].[id])))
       |--Index Scan(OBJECT:([[T].[ix]), ORDERED FORWARD)

Even though potentially SQL Server could stop processing the group as soon as the first value is found and skip to the next one it doesn't. It still processes all rows and the logical reads are the same.
For this particular example with many rows in the group a more efficient version would be a recursive CTE.
WITH    RecursiveCTE
AS      (
        SELECT TOP 1 id, [group]
        FROM T
        ORDER BY [group]
        UNION   ALL
        SELECT  R.id, R.[group]
        FROM    (
                SELECT  T.*,
                        rn = ROW_NUMBER() OVER (ORDER BY (SELECT 0))
                FROM    T
                JOIN    RecursiveCTE R
                        ON  R.[group] < T.[group]
                ) R
        WHERE   R.rn = 1
        )
SELECT  *
FROM    RecursiveCTE
OPTION  (MAXRECURSION 0);

Which gives
Table 'Worktable'. Scan count 2, logical reads 19
Table 'T'. Scan count 4, logical reads 12

The logical reads are much less as it retrieves the first row per group then seeks into the next group rather than reading a load of records that don't contribute to the final result.


text:
Q: how to make mysql works in a R function I wrote a code using RMySQL package, it works as a code, but when I wrote it as a function it always returned

Error in .local(dbObj, ...) :
    internal error in RS_DBI_getConnection: corrupt connection handle.

How can I fix the problem?
I took out function{}, and it works, but every time I put it back, it crashed. I also tried pinning down when the problem occurred, but cannot find the location.
move_data_summary <- function(path,DSfile,hostname,outpath){
  library(RMySQL)
  library(readxl)
  library(readr)
  library(stringi)
  library(tidyr)

  path <- path
  DSfile <- sprintf("%s/%s",path,DSfile)
  DS <- read_excel(DSfile,"RunSpec")

  pollutantID <- c(31,87,110)
  pollutant   <- c("NOx","VOC","PM2.5")
  ERRORfile <- sprintf("%s/data_summary_error.txt",path)
  if (file.exists(ERRORfile)) file.remove(ERRORfile)
  write(paste("total lines",length(DS$countyID)),ERRORfile,append = TRUE)

  for (c in 1:length(DS$countyID)){
    if(DS$countyID[c] %in% NA){
      write(paste("error data in line",c),ERRORfile,append = TRUE)
    }else{
      write(paste("finished data in line",c),ERRORfile,append = TRUE)
      database <- DS$`CDM Output Name`[c]
      mydb = dbConnect(MySQL(), user='moves', password='moves',
                       dbname=database, host= hostname)
      on.exit(dbDisconnect(mydb))
      rs1 = dbSendQuery(mydb, "SELECT countyID, yearID, pollutantID, sourcetypeID, sum(emissionQuant) FROM movesoutput
                    group by countyID, sourceTypeID, pollutantID")
      data_tmp1 = fetch(rs1, n=-1)
      all_cons <- dbListConnections(MySQL())
      for (con in all_cons)
        dbDisconnect(con)
      tmpoutfile <- sprintf("%s/%s.csv",outpath,database)
      write.csv(data_tmp1,tmpoutfile)
      if (c == 1){
        data <- data_tmp1[which(data_tmp1$pollutantID == 31 |
                                  data_tmp1$pollutantID == 87 |
                                  data_tmp1$pollutantID == 110),]
      }else{
        data_tmp <- data_tmp1[which(data_tmp1$pollutantID == 31 |
                                      data_tmp1$pollutantID == 87 |
                                      data_tmp1$pollutantID == 110),]
        data <- rbind(data,data_tmp)
      }
    }
  }
  write("finished all data",ERRORfile,append = TRUE)
  return(data)
}

if I took out the function{}, it worked. Otherwise, show me the error,

Error in .local(dbObj, ...) :
    internal error in RS_DBI_getConnection: corrupt connection handle
  In addition: There were 50 or more warnings (use warnings() to see the first 50).

I've used
all_cons <- dbListConnections(MySQL())
for (con in all_cons)
    dbDisconnect(con)

to disconnet the SQL server.


text:
Q: Why c# treats 0 as int and not as short/decimal etc? In c# when i say :
var s = 0;

what should be type of s ? it makes it int32. then seems like var is not usable for types like short and others(?).

A: Look at this post here at StackOverflow.
You can specify a postfix for all numbers.
var i = 0;
var d = 0d;
var f = 0f;
var l = 0L;
var m = 0m;

A: As per the C# language standard, specifically §2.4.4.2 on integer literals:

The type of an integer literal is determined as follows:

*

*If the literal has no suffix, it has the first of these types in which its value can be represented: int, uint, long, ulong.

*If the literal is suffixed by U or u, it has the first of these types in which its value can be represented: uint, ulong.

*If the literal is suffixed by L or l, it has the first of these types in which its value can be represented: long, ulong.

*If the literal is suffixed by UL, Ul, uL, ul, LU, Lu, lU, or lu, it is of type ulong.

The first rule is all that needs to be applied here. The literal 0 has no suffix and can be represented as type int (or, in BCL terms, Int32), so that's the type it has.
As you can infer from the above, to change the type of a literal, you can append a suffix to it. For example, the literal 0u will be of type uint. Alternatively, you could explicitly cast the literal to a different type; for example: (short)0 would cause the compiler to treat the literal as a short.

A: From the specification (§ 2.4.4.2):

If the literal has no suffix, it has the first of these types in which its value can be represented: int, uint, long, ulong.

So smaller types are not automatically inferred. You can add a cast to force such a smaller type:
var s = (short)0;

A: The C# compiler infers the type to be Int32. And you cannot implicitly cast it to a short or byte because they are smaller in size and you could lose data.
If you'd like the compiler to infer decimal you can:
var s = 0M;


text:
Q: How to prevent CSS left/right properties from pushing window I am using the right and left properties to place tiny images on the edges of my page.
.class img {position:absolute;left:60%}

The above example places the image at the end of the screen on the right and only half of the image is visible but it also triggers a horizontal overflow making the page draggable towards the full width of the image.
I tried setting overflow to hidden but it didn't help.
Any ideas on how I can achieve this?

A: Any time you want to allow for items off screen, but prevent scrolling, you're going to have to restrict the user's viewport. This can usually be done by setting the overflow-x or overflow-y to hidden on the body.

/* The problem */
.off-screen {
  position: absolute;
  right: -50px;

  width: 100px;
  height: 100px;

  background-color: red;
}

/* The solution */
body {
  overflow-x: hidden;
}

Note: Depending on your specific situation, this may need to be tweaked, but the concept is the same. I can update this to be more specific if you include more code in your initial post.

A: It sounds like you want your images to appear at the right edge of the screen. This should work:
.class img {
    position: absolute;
    right: 0;
}


text:
Q: How to make the buttons responsive? How to move my buttons to right and make it responsive. Please can anyone help me with this?
Here is my code:
I am using background image in CSS here

        <button style="top:170px; width:25%;" id="logintl" type="button" class="btn btn-info btn-lg sharp pull-right btn-group-vertical" title="Login with MiiSky" data-toggle="modal" data-target="#myModal"> | Login with SATMP</button>

 | Register with SATMP

My buttons are at the right but it is not responsive.
Current Output:
      Buttons are moving out of the image as shown in the image below...
      I want to fit the image so that it should not be altered even if the browser size is reduced.
      Any idea would be helpful
      [1]: http://i.stack.imgur.com/F5Dty.jpg
      [2]: http://i.stack.imgur.com/9uL7G.png
      [3]: http://i.stack.imgur.com/ibhCa.png

A: I got what you want. Basically, here's what I did.

*

*Removed the inline CSS style from button and anchor tag.

*Removed the width property.

*Added class bt1 and bt2 to the buttons.

*bt1 and bt2 were style with top:100px and top:120px respectively. You can change the pixel to whatever height you want.

Below is my working code.
<!DOCTYPE HTML>

    <title>
        About TechGenium
    </title>

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css"></link>

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" integrity="sha512-dTfge/zgoMYpP7QbHy4gWMEGsbsdZeCXz7irItjcC3sPUFtf0kuFbDz/ixG7ArTxmDjLXDmezHubeNikyKGVyQ==" crossorigin="anonymous">

                <button id="logintl" type="button" class="bt1 btn btn-info btn-lg sharp pull-right btn-group-vertical" title="Login with MiiSky" data-toggle="modal" data-target="#myModal"> | Login with SATMP</button>

 | Register with SATMP

Replace the background image to whatever image you have and the code will work.

A: html
Here is my final code with modification:

                <button id="logintl" type="button" class="bt1 btn btn-info sharp pull-right btn-group-vertical" data-toggle="modal" data-target="#myModal"> | Login with SATMP</button>

 | Register with SATMP

css
Here i changed the width of my buttons so it worked perfectly for me!!

Final Output:
image1
image2
image3


text:
Q: add fixed parameter to await callback I am attempting to load some files asynchronously using d3's queue, defer and await. The problem is trying to do so in a loop, and for each item in the loop, store the fetched data in the dictionary:
var myDictionary = {};

// e.g. hierarchy = ["State", "County"]
hierarchy.forEach(function(geo) {
    queue()
      .defer(d3.json, 'assets/data/geo/' + geo + '/' + geo + '.json')
      .defer(d3.csv,  'assets/data/geo/' + geo + '/' + geo + '_info.csv')
      .await(myFunc);
});

function myFunc(error, jsonData, csvData) {
    // need access to geo
    console.log(geo);

    myDictionary[geo].jsonData = jsonData;
    myDictionary[geo].csvData  = csvData;
}

in myFunc, I would like access to geo to fill in the appropriate keys in the dictionary, however passing them inside .await.myFunc(geo) would print undefined inside myFunc.
I don't know whether this problem pertains to Javascript's callback functions, or D3's await(), or both.
Any recommendations?
Thanks

A: You can use this:
function myFunc(geo) {

    return function(error, jsonData, csvData) {
        // geo available here
        console.log(geo);

        myDictionary[geo].jsonData = jsonData;
        myDictionary[geo].csvData  = csvData;
    };
};

Then:
var myDictionary = {};

// e.g. hierarchy = ["State", "County"]
hierarchy.forEach(function(geo) {
    queue()
      .defer(d3.json, 'assets/data/geo/' + geo + '/' + geo + '.json')
      .defer(d3.csv,  'assets/data/geo/' + geo + '/' + geo + '_info.csv')
      .await(myFunc(geo));
});

A: You could add it as a task so it gets passed into your myFunc.
queue()
  .defer(d3.json, 'assets/data/geo/' + geo + '/' + geo + '.json')
  .defer(d3.csv,  'assets/data/geo/' + geo + '/' + geo + '_info.csv')
  .defer(callback=>callback(geo))
  .await(myFunc);
...
function myFunc(error, jsonData, csvData, geo) {
    console.log(geo);
}


text:
Q: how to run one java aplication JFrame on Ubuntu Server with Xinit I`m trying to run one java jframe aplication on Ubuntu Server with xinit, it is possible? I tried to run the java aplication with:
startx java -jar myapp.jar

but I receive the next messages

And these are the warning messages in the log
[   601.694] (WW) The directory "/usr/share/fonts/X11/cyrillic" does not exist.
[   601.694]    Entry deleted from font path.
[   601.694] (WW) The directory "/usr/share/fonts/X11/100dpi/" does not exist.
[   601.694]    Entry deleted from font path.
[   601.694] (WW) The directory "/usr/share/fonts/X11/75dpi/" does not exist.
[   601.694]    Entry deleted from font path.
[   601.694] (WW) The directory "/usr/share/fonts/X11/100dpi" does not exist.
[   601.694]    Entry deleted from font path.
[   601.694] (WW) The directory "/usr/share/fonts/X11/75dpi" does not exist.
[   601.715] (WW) Falling back to old probe method for modesetting
[   601.715] (WW) Falling back to old probe method for fbdev
[   601.715] (WW) Falling back to old probe method for vesa
[   601.719] (WW) vmware(0): Failed to initialize Gallium3D Xa. No render acceleration available.
[   601.719] (WW) vmware(0): Skipped initialization of direct rendering due to lack of render acceleration.
[   601.720] (WW) vmware(0): Disabling Xv because no adaptors could be initialized.


text:
Q: Contacts and Phone on iPhone think I'm in a different country Yesterday I got a call from my wife and the iPhone said "Maybe Mrs. SSteve". The phone number was the international version of a U.S. phone number and her custom ringtone didn't play:

Voicemail is also showing international versions of U.S. phone numbers and also shows "Maybe" (normally it just shows the name and no phone number at all):

Contacts isn't formatting phone numbers at all:

Contacts on my iPad still formats numbers the way I expect:

I'm running iOS 12.3.1 on an iPhone 6. I remember seeing recently that there was a carrier update. I must have installed it because Settings -> General -> About doesn't show an available carrier update.
I tried iPhone Contact List Default Country Wrong but dialing *228 says the number isn't allowed.
I tried setting my Region in Settings -> General -> Language & Region away from United States and back but that didn't work. Where else does iOS get the region for phone numbers?

A: When I was writing this question and was in Language & Region, I tried setting the iPhone Language even though I didn't expect it to do anything. It was already set to English but I went ahead and selected "English (US)". It went to a black screen that said "Setting Language" (or something similar) for a while and when it was done all the phone numbers are displaying correctly. So I guess it's possible the language wasn't set to "English (US)" but I can't imagine why. Anyway, since I already went through the effort of editing the screenshots and writing the question I figured I'd leave this here in case it's helpful to someone.

A: iOS apparently gets the region from a buggy codebase, unfortunately. I'm glad you were able to solve this!
Like Christopher and JDH, an overseas adventure with an eSIM & Physical SIM messed me up - and it even persisted across a backup.
Given no combination of changing region (and restarting via power off), language (incl. a full restart), and Dial Assist (of course incl. restart via power off as well) will get the iPhone dialer to show the standard (###) ###-#### phone number format format, I have one last idea. I believe I still have a foreign SIM in the phone (although the line is disabled in favor of using my eSIM as my only, Primary line). I'll remove it. Even if that fixes the formatting, I'll still reset my phone as I upgraded from 13 to 14 without setting the phone up as new and it's showing its age (iPhone 11 Pro).
Thank you for the thread!


text:
Q: What purpose do CPU limits have in Kubernetes resp. Docker? I dig into Kubernetes resource restrictions and have a hard time to understand what CPU limits are for. I know Kubernetes passes requests and limits down to the (in my case) Docker runtime.
Example: I have 1 Node with 1 CPU and 2 Pods with CPU requests: 500m and limits: 800m. In Docker, this results in (500m -> 0.5 * 1024 = 512) --cpu-shares=512 and (800m -> 800 * 100) --cpu-quota=80000. The pods get allocated by Kube scheduler because the requests sum does not exceed 100% of the node's capacity; in terms of limits the node is overcommited.
The above allows each container to get 80ms CPU time per 100ms period (the default). As soon as the CPU usage is 100%, the CPU time is shared between the containers based on their weight, expressed in CPU shares. Which would be 50% for each container according to the base value of 1024 and a 512 share fo each. At this point - in my understanding - the limits have no more relevance because none of the containers can get its 80ms anymore. They both would get 50ms. So no matter how much limits I define, when usage reaches critical 100%, it's partitioned by requests anyway.
This makes me wonder: Why should I define CPU limits in the first place, and does overcommitment make any difference at all? requests on the other hand in terms of "how much share do I get when everything is in use" is completely understandable.

A: One reason to set CPU limits is that, if you set CPU request == limit and memory request == limit, your pod is assigned a Quality of Service class = Guaranteed, which makes it less likely to be OOMKilled if the node runs out of memory. Here I quote from the Kubernetes doc Configure Quality of Service for Pods:

For a Pod to be given a QoS class of Guaranteed:

*

*Every Container in the Pod must have a memory limit and a memory request, and they must be the same.

*Every Container in the Pod must have a CPU limit and a CPU request, and they must be the same.

Another benefit of using the Guaranteed QoS class is that it allows you to lock exclusive CPUs for the pod, which is critical for certain kinds of low-latency programs. Quote from Control CPU Management Policies:

The static CPU management policy allows containers in Guaranteed pods with integer CPU requests access to exclusive CPUs on the node. ... Only containers that are both part of a Guaranteed pod and have integer CPU requests are assigned exclusive CPUs.

A: According to the Motivation for CPU Requests and Limits section of the Assign CPU Resources to Containers and Pods Kubernetes walkthrough:

By having a CPU limit that is greater than the CPU request, you
  accomplish two things:

*

*The Pod can have bursts of activity where it makes use of CPU resources that happen to be available.

*The amount of CPU resources a Pod can use during a burst is limited to some reasonable amount.

I guess that might leave us wondering why we care about limiting the burst to "some reasonable amount" since the very fact that it can burst seems to seems to suggest there are no other processes contending for CPU at that time. But I find myself dissatisfied with that line of reasoning...
So first off I checked out the command line help for the docker flags you mentioned:
    --cpu-quota int                  Limit CPU CFS (Completely Fair Scheduler) quota
-c, --cpu-shares int                 CPU shares (relative weight)

Reference to the Linux Completely Fair Scheduler means that in order to understand the value of CPU limit/quota we need to undestand how the underlying process scheduling algorithm works. Makes sense, right? My intuition is that it's not as simple as time-slicing CPU execution according to the CPU shares/requests and allocating whatever is leftover at the end of some fixed timeslice on a first-come, first-serve basis.
I found this old Linux Journal article snippet which seems to be a legit description of how CFS works:

The CFS tries to keep track of the fair share of the CPU that would
  have been available to each process in the system. So, CFS runs a fair
  clock at a fraction of real CPU clock speed. The fair clock's rate of
  increase is calculated by dividing the wall time (in nanoseconds) by
  the total number of processes waiting. The resulting value is the
  amount of CPU time to which each process is entitled.
As a process waits for the CPU, the scheduler tracks the amount of
  time it would have used on the ideal processor. This wait time,
  represented by the per-task wait_runtime variable, is used to rank
  processes for scheduling and to determine the amount of time the
  process is allowed to execute before being preempted. The process with
  the longest wait time (that is, with the gravest need of CPU) is
  picked by the scheduler and assigned to the CPU. When this process is
  running, its wait time decreases, while the time of other waiting
  tasks increases (as they were waiting). This essentially means that
  after some time, there will be another task with the largest wait time
  (in gravest need of the CPU), and the currently running task will be
  preempted. Using this principle, CFS tries to be fair to all tasks and
  always tries to have a system with zero wait time for each
  process—each process has an equal share of the CPU (something an
  "ideal, precise, multitasking CPU" would have done).

While I haven't gone as far as to dive into the Linux kernel source to see how this algorithm actually works, I do have some guesses I would like to put forth as to how shares/requests and quotas/limits play into this CFS algorithm.
First off, my intuition leads me to believe that different processes/tasks accumulate wait_runtime at different relative rates based on their assigned CPU shares/requests since Wikipedia claims that CFS is an implementation of weighted fair queuing and this seems like a reasonable way to achieve a shares/request based weighting in the context of an algorithm that attempts to minimize the wait_runtime for all processes/tasks. I know this doesn't directly speak to the question that was asked, but I want to be sure that my explanation as a whole has a place for both concepts of shares/requests and quotas/limits.
Second, with regard to quotas/limits I intuit that these would be applicable in situations where a process/task has accumulated a disproportionately large wait_runtime while waiting on I/O. Remember that the quoted description above CFP prioritizes the process/tasks with the largest wait_runtime? If there were no quota/limit on a given process/task then it seems to me like a burst of CPU usage on that process/task would have the effect of, for as long as it takes for its wait_runtime to reduce enough that another task is allowed to preempt it, blocking all other processes/tasks from execution.
So in other words, CPU quotas/limits in Docker/Kubernetes land is a mechanism that allows the given container/pod/process to burst in CPU activity to play catch up to other processes after waiting on I/O (rather than CPU) without in the course of doing so unfairly blocking other processes from also doing work.

A: There is no upper bound with just cpu shares. If there are free cycles, you are free to use them. limit is imposed so that one rogue process is not holding up the resource forever.
There should be some fair scheduling. CFS imposes that using cpu quota and cpu period via the limit attribute configured here.
To conclude, this kind of property ensures that when I schedule your task you get a minimum of 50 milliseconds to finish it. If you need more time, then if no one is waiting in the queue I would let you run for few more but not more than 80 milliseconds.

A: I think it's correct that, during periods where the Node's CPU is being fully utilized, it's the requests (CPU shares) that will determine how much CPU time each container gets, rather than the limits (which are effectively moot at that point). In that sense, a rogue process can't do unlimited damage (by depriving another of its requests).
However, there are still two broad uses for limits:

*

*If you don't want a container to be able to use more than a fixed amount of CPU even if extra CPU is available on the Node. It might seem weird that you wouldn't want excess CPU to be utilized, but there are use cases for this. Some that I've heard:

*

*You're charging customers for the right to use up to x amount of compute resources (a limit), so you don't want to give them more sometimes for free (which might dissuade them from paying for a higher tier on your service).

*You're trying to figure out how a service will perform under load, but this gets complicated/unpredictable, because the performance during your load testing depends on how much spare CPU is lying around that the service is able to utilize (which might be a lot more than the spare CPU that'll actually be on the Node during a real-world high-load situation). This is mentioned here as a big risk.

*If the requests on all the containers aren't set especially accurately (as is often the case; devs might set the values upfront and forget to update them as the service evolves, or not even set them very carefully initially). In these cases, things sometimes still function well enough if there's enough slack on the Node; limits can then be useful to prevent a buggy workload from eating all the slack and forcing the other pods back to their incorrectly-set(!) requested amounts.


text:
Q: UDP Flooding locally? Could somebody tell me what the IP 27.27.27.27 is and why this works with UDP flooding?
Flooding 27.27.27.27 lags my entire network, but flooding my local IP 192.168.1.10 or 127.0.0.1 does nothing.
Are there any ways to isolate the the lag effects when flooding 27.27.27.27 to my local machine only?


text:
Q: How can I limit Jenkins LDAP access to users in a specific groupOfNames? I can configure Jenkins so it limits access to users on my ldap server by setting the Server and Root DN without a problem.
Now I want to tie down access a little more and only allow access to members of the groupOfNames cn=MyProject,ou=Group,dc=bogus,dc=biz, but I don't see how to do that in Jenkins.
Can someone explain how they configured Jenkins or Hudson to handle something like this ?
Thanks !

A: NOTE: I'm not sure if this would work for LDAP (we use active directory)

*

*In the project configuration page, check Matrix-based security.

*Remove all access for anonymous

*Add your 'groupOfNames' to the "user/group to add" and give them the rights you want to.

Any user in that group should get the rights you assign. This is how we did it.

A: Old thread, I know. I got it working by installing the memberof and refint overlays on the OpenLDAP server (2.4.31) and setting the User Search Base on Jenkins to filter the result, i.e.
(&(uid={0})(memberOf=cn=MyGroupName,ou=group,dc=mydomain,dc=com))


text:
Q: How to mosaic multiple MODIS images of Multiple months using MRT tool? I have monthly MODIS images for 2001-2014.
For few images mosaicing with reprojection can be done using MRT tool. However, for large number of images it's a cumbersome process.
There are multiple folder in a pattern, where each image is saved in a particular folder (representing MONTH) and all the months of a particular year are stored in a specific folder named after corresponding YEAR. Below is the example for reference
MODIS\Y2000\M01
Image#1
Image#2
...

MODIS\Y2000\M02
Image#1
Image#2
...
...
...
...
...

MODIS\Y2014\M12
Image#1
Image#2
...

Is there any way out to automate this process using MRT tool?

A: I use cygwin Linux shell under Windows OS. You should install Cygwin  firstly. Then create MRT .prm file of single stage (this you have done for fewer images) by using MRT tool.

Put this .prm file with all modis tiles under same folder such as test. Open .prm with txt and you could modify some parameters.
#INPUT_FILENAMES = ( D:\2000\049\MOD09A1.A2000049.h23v04.005.2006268204857.hdf D:\2000\049\MOD09A1.A2000049.h23v05.005.2006268204906.hdf D:\2000\049\MOD09A1.A2000049.h24v04.005.2006268205301.hdf D:\2000\049\MOD09A1.A2000049.h25v05.005.2006268195439.hdf D:\2000\049\MOD09A1.A2000049.h25v06.005.2006268195239.hdf D:\2000\049\MOD09A1.A2000049.h26v05.005.2006268195515.hdf D:\2000\049\MOD09A1.A2000049.h26v06.005.2006268195738.hdf D:\2000\049\MOD09A1.A2000049.h27v06.005.2006268195209.hdf D:\2000\049\MOD09A1.A2000049.h28v05.005.2006268195532.hdf D:\2000\049\MOD09A1.A2000049.h28v06.005.2006268195152.hdf D:\2000\049\MOD09A1.A2000049.h28v07.005.2006268195415.hdf D:\2000\049\MOD09A1.A2000049.h29v06.005.2006268195305.hdf )

INPUT_FILENAME = D:\TmpMosaic.hdf

SPECTRAL_SUBSET = ( 1 1 )
#ORIG_SPECTRAL_SUBSET = ( 1 1 0 0 0 0 0 0 0 0 0 0 0 )

SPATIAL_SUBSET_TYPE = INPUT_LAT_LONG

SPATIAL_SUBSET_UL_CORNER = ( 49.999999996 77.786191329 )
SPATIAL_SUBSET_LR_CORNER = ( 9.999999999 121.851193415 )

OUTPUT_FILENAME = D:\m2000049.tif

RESAMPLING_TYPE = NEAREST_NEIGHBOR

OUTPUT_PROJECTION_TYPE = GEO

OUTPUT_PROJECTION_PARAMETERS = (
0.0 0.0 0.0
0.0 0.0 0.0
0.0 0.0 0.0
0.0 0.0 0.0
0.0 0.0 0.0 )

DATUM = NoDatum

OUTPUT_PIXEL_SIZE = 0.009

last, open cygwin shell and cd to the modis tiles folder.
cd  E:/modis/change/MOD09Q1/test

use codes as follow:
day=2000049      #start time
while [ $day -le 2000081 ]   #end time serial
do
for trl in MOD09Q1.A$day.*.hdf      # modis image file names
do
if [ -f $trl ]
then
HDFFILES=$(ls MOD09Q1.A$day.*.hdf)
echo $HDFFILES > MOSAICINPUT.TXT
MRTMOSAIC -i MOSAICINPUT.TXT -s "1 0 0" -o MOSAIC_TMP_$day.hdf
RESAMPLE -p MOD09Q1.PRM -i MOSAIC_TMP_$day.hdf -o MOD09Q1_$day.tif

#MOD09Q1.PRM  the .prm file have saved before

let "day=day+8"    # the modis image time interval such as 8day,16day...

break
else
let "day=day+8"
break
fi

done
done


text:
Q: What is the purpose of the string "- 4/24" from a record that holds a date? I have an already generated script that uses the following code: ORDER BY TO_CHAR((A.VERIFIED_DTTM - 4/24),'YYYY-MM-DD'). The output of A.VERIFIED_DTTM is a simple date eg: 09-SEP-19.
I was my understanding that 4/24 is the same as saying 4 hours. I have tried removing this string from my query and received radically different results (not just sorting or ordering).
In another area of the script, I have a code that makes excellent sense (A.VERIFIED_DTTM >= sysdate - 30). This I understand.
Can anyone explain what is actually happening with this query line?
Thank you!

A: It is subtracting 4 hours and converting the date value to a string in the format of YYYY-MM-DD.  This is probably a timezone adjustment.
To be honest, I'm not sure why it doesn't just use:
ORDER BY A.VERIFIED_DTTM

Removing it should not radically change the results.


text:
Q: SQL query to select a column with expression of non-aggregate value and aggregate function Tables used:

1) v(date d, name c(25), desc c(50), debit n(7), credit n(7))
name in 'v' refers name in vn table
2) vn(date d, name c(25), type c(25), obal n(7))
name in 'vn' is a primary key and different names are grouped by type
ex: names abc, def, ghi belongs to type 'bank', names xyz, pqr belongs to type 'ledger', ...

I've a query like this:
SELECT vn.type, SUM(vn.obal + IIF(v.date < sd, v.credit-v.debit, 0)) OpBal, ;
    SUM(IIF(BETWEEN(v.date, sd, ed), v.credit-v.debit, 0)) CurBal ;
    FROM v, vn WHERE v.name = vn.name GROUP BY vn.type ;
    ORDER BY vn.type HAVING OpBal + CurBal != 0

It works fine but the only problem is, obal is a value which is entered only once per name in table 'vn' but with this query for every calculation of credit-debit in table 'v', obal is added multiple times and displayed under OpBal. When the query is modified like below:
SELECT vn.type, vn.obal + SUM(IIF(v.date < sd, v.credit-v.debit, 0)) OpBal, ;
    SUM(IIF(BETWEEN(v.date, sd, ed), v.credit-v.debit, 0)) CurBal ;
    FROM v, vn WHERE v.name = vn.name GROUP BY vn.type ;
    ORDER BY vn.type HAVING OpBal + CurBal != 0

it shows an error message like 'Group by clause is missing or invalid'!
RDBMS used MS Visual Foxpro 9. sd and ed are date type variables used for the purpose of query where sd < ed.
Please help me out getting the expected result. Thanks a lot.

A: I saw the SQL Syntax for SQL with VFP for the first time a few minutes ago, so this could well be full of errors, but as a 'guessful hunch':
SELECT vn.type,
       SUM(vn.obal + (SELECT SUM(IIF(v.date < sd, v.credit-v.debit, 0))
                      FROM v
                      WHERE v.name = vn.name)) OpBal,
       SUM(SELECT SUM(IIF(BETWEEN(v.date, sd, ed), v.credit-v.debit, 0))
           FROM v
           WHERE v.name = vn.name) CurBal
FROM vn
GROUP BY vn.type
ORDER BY vn.type
HAVING OpBal + CurBal != 0

Basically, I've just turned selection from v into subselects to avoid vn.obal to be repeated. It shouldn't matter for v that it first gets the sum for the individual person before summing them all together.

A: just a few things.  VFP 9 has a setting to NOT require grouping for all non-aggregate for backward compatibility and similar results like MySQL where not all columns must be aggregates.  Such as querying extra columns from a customer's record that never change no matter how many records you are joining against on its PK column (name, address, phone, whatever).
SET ENGINEBEHAVIOR 80

default for VFP 9
SET ENGINEBEHAVIOR 90

requires all non group-by columns to be aggregates to comply.
Next... it looks like you have very bad columns in the tables you are dealing with... 3 reserved words in VFP... "date", "Name" and "type", however you are ok by qualifying them in the query with alias.column reference.
The following sample code will create temporary tables (cursors) of the structures you've described in your question.  I've also inserted some sample data and simulated your "sd" (start date) and "ed" (end date) variables
CREATE CURSOR vn;
   ( date d, ;
     name c(25), ;
     type c(25), ;
     obal n(7) )

INSERT INTO vn VALUES ( CTOD( "5/20/2012" ), "person 1", "person type 1", 125 )
INSERT INTO vn VALUES ( CTOD( "5/20/2012" ), "person 2", "another type ", 2155 )

CREATE CURSOR v;
   ( date d, ;
     name c(25), ;
     desc c(50), ;
     debit n(7), ;
     credit n(7))

INSERT INTO V VALUES ( CTOD( "6/1/2012" ), "person 1", "description 1", 10, 32 )
INSERT INTO V VALUES ( CTOD( "6/2/2012" ), "person 1", "desc 2", 235, 123 )
INSERT INTO V VALUES ( CTOD( "6/3/2012" ), "person 1", "desc 3", 22, 4 )
INSERT INTO V VALUES ( CTOD( "6/4/2012" ), "person 1", "desc 4", 53, 36 )
INSERT INTO V VALUES ( CTOD( "6/5/2012" ), "person 1", "desc 5", 31, 3 )
INSERT INTO V VALUES ( CTOD( "6/1/2012" ), "person 2", "another 1", 43, 664 )
INSERT INTO V VALUES ( CTOD( "6/4/2012" ), "person 2", "more desc", 78, 332 )
INSERT INTO V VALUES ( CTOD( "6/6/2012" ), "person 2", "anything", 366, 854 )

sd = CTOD( "6/3/2012" )      && start date of transactions
ed = DATE()  && current date as the end date...

Now, the querying...  You are trying to get groups by type but the per person (name) needs to be pre-aggregated on a per person basis FIRST.  Now, it appears you are trying to get a total opening balance of transactions prior to the start date (sd) as the basis at a given point in time, then looking at activity WITHIN the start/end date in question.  Do this first, but don't deal with adding in the "obal" column from the "vn" table.  Since it needs aggregates of non-group by columns, I would just use "MAX()" of the column.  Since it is by a PK (name) basis, you'll end up with whatever it was, but with the rolled-up totals of transactions, yet have all your data pre-summarized into a single row via...
select;
      vn.name,;
      vn.type,;
      MAX( vn.obal ) as BalByNameOnly,;
      SUM( IIF( v.date < sd, v.credit-v.debit, 000000.00 )) OpBal, ;
      SUM( IIF( BETWEEN(v.date, sd, ed), v.credit - v.debit, 000000.00 )) CurBal ;
   FROM ;
      v,;
      vn ;
   WHERE ;
      v.name = vn.name;
   GROUP BY ;
      vn.Name,;
      vn.Type;
   INTO ;
      CURSOR C_JustByName READWRITE

With this results (from my sample data) would look like...
Name      Type            BalByNameOnly   OpBal   CurBal
person 1  person type 1       125         -90     -63
person 2  another type       2155         621     742

Your final aggregate to get by type, you can just query the above result "cursor" (C_JustByName) and use IT to get your grouping by type, having, etc... something like
SELECT ;
      JBN.type, ;
      JBN.BalByNameOnly - JBN.OpBal as OpBal,;
      JBN.CurBal ;
    FROM ;
       C_JustByName JBN ;
    GROUP BY ;
       vn.type ;
    ORDER BY ;
       vn.type ;
    HAVING ;
       OpBal + CurBal != 0;
    INTO ;
       CURSOR C_Final

Now, I am just simplifying the above because I don't know what you are really looking for as the date within your "VN" (appears to be like a customer table) with a date that is unclear of its purpose and its oBal column with respect to the transactions table.
The nice thing about VFP is that you can query into a temporary cursor without creating a permanent table and use IT as the basis for any querying after that... It helps in the readability of not having to nest query inside query inside query.  It also allows you to see the results of each layer and know you are getting the answers you are EXPECTING before continuing to the next query phase...
Hopefully this will help you in the direction of what you are trying to solve.

A: Once again, this question was bumped to front :( Before I made a comment like:

It is unfortunate that this question from 6 years back has been bumped
  to front page :( The reason is that the question is starving for some
  explanations and the design is screaming of flaws. Without knowing
  those details no answer would be good. 1) Never ever rely on the old
  enginebehavior to workaround this error. It was a BUG and corrected.
  Relying on a bug is not the way to go. 2) To create a date value,
  never ever do that by converting from a string. That is settings
  dependent. Better either use solid date(), datetime() functions or
  strict date\datetime literals.

That comment stands and there are more, anyway.
Let's add more about the flaws and a reply based on what I understand from the question.
In the question OP says:"
SELECT vn.type, SUM(vn.obal + IIF(v.date < sd, v.credit-v.debit, 0)) OpBal, ;
    SUM(IIF(BETWEEN(v.date, sd, ed), v.credit-v.debit, 0)) CurBal ;
    FROM v, vn WHERE v.name = vn.name GROUP BY vn.type ;
    ORDER BY vn.type HAVING OpBal + CurBal != 0

works fine."
But of course, any seasoned developer using SQL, would immediately see that it would not work fine, the results could only be fine coincidentally. Let's make it clear why it wouldn't really work. First let's create some cursors describing the OP's data:
CREATE CURSOR vn ( date d, name c(25), type c(25), obal n(7) )

INSERT INTO vn (date, name, type, obal) VALUES ( DATE(2012,5,20), "abc", "bank", 100 )
INSERT INTO vn (date, name, type, obal) VALUES ( DATE(2012,5,20), "def", "bank", 200 )
INSERT INTO vn (date, name, type, obal) VALUES ( DATE(2012,5,20), "ghi", "bank", 300 )
INSERT INTO vn (date, name, type, obal) VALUES ( DATE(2012,5,20), "xyz", "ledger", 400 )
INSERT INTO vn (date, name, type, obal) VALUES ( DATE(2012,5,20), "pqr", "ledger", 500 )

CREATE CURSOR v ( date d, name c(25), desc c(50), debit n(7), credit n(7))

INSERT INTO V (date,name,desc,debit,credit) VALUES ( DATE(2012,6,1), "abc", "description 1", 50, 0 )
INSERT INTO V (date,name,desc,debit,credit) VALUES ( DATE(2012,6,2), "abc", "description 1", 60, 0 )
INSERT INTO V (date,name,desc,debit,credit) VALUES ( DATE(2012,6,3), "abc", "description 1", 70, 0 )
INSERT INTO V (date,name,desc,debit,credit) VALUES ( DATE(2012,6,1), "def", "description 1", 50, 0 )
INSERT INTO V (date,name,desc,debit,credit) VALUES ( DATE(2012,6,2), "def", "description 1", 60, 0 )
INSERT INTO V (date,name,desc,debit,credit) VALUES ( DATE(2012,6,3), "def", "description 1", 70, 0 )
INSERT INTO V (date,name,desc,debit,credit) VALUES ( DATE(2012,6,1), "ghi", "description 1", 50, 0 )
INSERT INTO V (date,name,desc,debit,credit) VALUES ( DATE(2012,6,2), "ghi", "description 1", 60, 0 )
INSERT INTO V (date,name,desc,debit,credit) VALUES ( DATE(2012,6,4), "xyz", "description 1", 50, 0 )
INSERT INTO V (date,name,desc,debit,credit) VALUES ( DATE(2012,6,5), "xyz", "description 1", 60, 0 )
INSERT INTO V (date,name,desc,debit,credit) VALUES ( DATE(2012,6,6), "pqr", "description 1", 50, 0 )
INSERT INTO V (date,name,desc,debit,credit) VALUES ( DATE(2012,6,7), "pqr", "description 1", 60, 0 )
INSERT INTO V (date,name,desc,debit,credit) VALUES ( DATE(2012,6,8), "pqr", "description 1", 70, 0 )

Let's run OP's query on this data:
LOCAL sd,ed
sd = date(2012,6,1)  && start date of transactions
ed = DATE()          && current date as the end date...
SELECT vn.type, SUM(vn.obal + IIF(v.date < sd, v.credit-v.debit, 0)) OpBal, ;
    SUM(IIF(BETWEEN(v.date, sd, ed), v.credit-v.debit, 0)) CurBal ;
    FROM v, vn WHERE v.name = vn.name GROUP BY vn.type ;
    ORDER BY vn.type HAVING OpBal + CurBal != 0

We get a result like:
TYPE    OPBAL   CURBAL
------- -----   ------
bank     1500     -470
ledger   2300     -290

which is obviously incorrect. With a query like this, the more you get credit or debit, the more you have an opening balance. Let's see why is that happening, removing the group by and aggregation, check what we are really summing up:
SELECT vn.type, vn.name, v.date, vn.obal, v.credit, v.debit ;
    FROM v, vn ;
    WHERE v.name = vn.name

Output:
  TYPE     NAME DATE         OBAL CREDIT DEBIT
  bank     abc  06/01/2012    100      0    50
  bank     abc  06/02/2012    100      0    60
  bank     abc  06/03/2012    100      0    70
  bank     def  06/01/2012    200      0    50
  bank     def  06/02/2012    200      0    60
  bank     def  06/03/2012    200      0    70
  bank     ghi  06/01/2012    300      0    50
  bank     ghi  06/02/2012    300      0    60
  ledger   xyz  06/04/2012    400      0    50
  ledger   xyz  06/05/2012    400      0    60
  ledger   pqr  06/06/2012    500      0    50
  ledger   pqr  06/07/2012    500      0    60
  ledger   pqr  06/08/2012    500      0    70

You can see that, say for 'abc' OBal 100 is repeated 3 times, because of the 3 entries in v. Summing would make it 300 when it is just 100.
When you are using an aggregate like SUM() or AVG(), you should do the aggregation first without a join, then do your join. You can still do the aggregation, with a join, PROVIDED, the join results in a 1-to-many relation. If the above resultset were:
  TYPE   NAME OBAL CREDIT DEBIT
  bank    abc  100      0   180
  bank    def  200      0   180
  bank    ghi  300      0   110
  ledger  xyz  400      0   110
  ledger  pqr  500      0   180

it would be OK to SUM() BY type (1 side of 1-to-Many).
Having said that and adding VFP supports subqueries let's write a solution:
Local sd,ed
sd = Date(2012,6,1)  && start date of transactions
ed = Date()          && current date as the end date...

Select vn.Type, Sum(vn.OBal - tmp.TotCd) As Opbal, Sum(tmp.Curbal) As Curbal ;
    FROM vn ;
    LEFT Join ;
       (Select v.Name, Sum(Iif(v.Date < sd, v.credit-v.debit, 0)) TotCd, ;
               SUM(Iif(Between(v.Date, sd, ed), v.credit-v.debit, 0)) Curbal ;
        FROM v ;
        GROUP By v.Name ) tmp On tmp.Name = vn.Name ;
    GROUP By vn.Type ;
    ORDER By vn.Type ;
    HAVING Sum(vn.OBal - tmp.TotCd + tmp.Curbal) != 0

we get what we want:
TYPE    OPBAL   CURBAL
------- -----   ------
bank      600     -470
ledger    900     -290


text:
Q: Laravel Relationship tables passing extra "s" with id name I am getting "'lessons.subjects_id" while there is "subject_id" in lesson table. dont know where is problem in my relationship. My relationship models are as under:
    class Lessons extends Model
{
    public function subject()
    {
    return $this->belongsTo('Lea\Subjects');
    }

    public function category()
    {
    return $this->belongsTo('Lea\Category');
    }

}

Subject Model is:
    class Subjects extends Model
    {

       public function category()
       {
         return $this->belongsTo('Lea\Category');
       }
       public function Lessons()
       {
         return $this->hasMany('Lea\Lessons');
       }
    }

A: If you didn't respect the Laravel convention you have to teach him about yours ;) by adding you foreign key name.
In the documentation you have :

Eloquent determines the foreign key of the relationship based on the
  model name. In this case, the Phone model is automatically assumed to
  have a user_id foreign key. If you wish to override this convention,
  you may pass a second argument to the hasOne method:

class Lessons extends Model
{
    public function subject()
    {
           //                                  your foreign key
         return $this->belongsTo('Lea\Subjects', 'subject_id');
    }

    public function category()
    {
    return $this->belongsTo('Lea\Category');
    }

}

And
class Subjects extends Model
{

   public function category()
   {
     return $this->belongsTo('Lea\Category');
   }
   public function Lessons()
   {
     //                                  your foreign key
     return $this->hasMany('Lea\Lessons', 'subject_id');
   }
}


text:
Q: Changing Database in run time and making the changes reflect in Django in run time I am developing a Cloud based data analysis tool, and I am using Django(1.10) for that.
I have to add columns to the existing tables, create new tables, change data-type of columns(part of data-cleaning activity) at the run time and can't figure out a way to update/reflect those changes, in run time, in the Django model, because those changes will be required in further analysis process.
I have looked into 'inspectdb' and 'syncdb', but all of these options would require taking the portal offline and then making those changes, which I don't want.
Please can you suggest a solution or a work-around of how to achieve this.
Also, is there a way in which I can select what database I want to work from the list of databases on my MySQL server, after running Django.

A: Django's ORM might not be the right tool for you if you need to change your schema (or db) online - the schema is defined in python modules and loaded once when Django's web server starts.
You can still use Django's templates, forms and other libraries and write your own custom DB access layer that manipulates a DB dynamically using python.


text:
Q: AngularJS - ui - carousel Пытаюсь реализовать карусель на ангулахJS. Но что-то идет не так. Юзаю пример по это ссылке. https://www.npmjs.com/package/angular-ui-carousel
Устанавливаю дериктивы таким образом

 <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/angular-ui-carousel@0.1.10/dist/ui-carousel.min.css" integrity="sha256-EBvZV6QlRzFD0ZxEjZ7f0bV7eyyM+JNuYP3Fq1f00+o=" crossorigin="anonymous">

Ссылки беру вот
тут
Как я понимаю так тоже можно, не обязательно ж нпм или галп
В итоге я собираю как в инструкции
(function (angular) {
angular.module('app', ['ui.router', 'ngCookies', 'ui.bootstrap', 'ngAnimate', 'ui.carousel']);
})(window.angular);

app.run
(function (angular) {
angular.module('app').run(runFn);

runFn.$inject = ['$rootScope', 'Carousel', '$transitions', '$location', 'authService'];

function runFn($rootScope, Carousel, $transitions, $location, authSevice) {
    Carousel.setOptions({
        arrows: true,
        autoplay: false,
        autoplaySpeed: 3000,
        cssEase: 'ease',
        dots: false,

        easing: 'linear',
        fade: false,
        infinite: true,
        initialSlide: 0,

        slidesToShow: 1,
        slidesToScroll: 1,
        speed: 500,
      });

Ну и HTML
 <ui-carousel slides="ctrl.fade.slides" slides-to-show="3" slides-to-scroll="1">
    <carousel-item>

    </carousel-item>
</ui-carousel>

И по факту на HTML просто пусто!..директива никак не реагирует. Как заставить ее работать? Может у кого то есть адекватный короткий вариант?


text:
Q: Why is output of adb devices inconsistent? I'm running android emulator on Mac, the output of adb devices is different every time I run it,
[PWD: ~/Library/Android]
%> adb devices
List of devices attached
emulator-5564   offline
emulator-5562   offline
emulator-5560   offline
emulator-5554   offline
emulator-5556   device

[PWD: ~/Library/Android]
%> adb devices
List of devices attached
emulator-5560   offline
emulator-5556   device

What could the problem be?
I already killed the server and restarted it.

A: Totally sad story!
I have programs listening on local ports 5551, 5553, 5554, 5555, 5561 etc.
And adb is connecting to these ports which receives unexpected response, resulting in inconsistent output.


text:
Q: Problems running scripts in ArcGIS 10.3 after upgrade from Python 2.6 to 2.7 as part of upgrading from ArcGIS 10.0 I'm new to python scripting, but have been trying to oversee a script that a former coworker created to help us automate mapmaking in my office.  We recently switched from ArcGIS 10.0 to 10.3, and from Python 2.6 to Python 2.7.  Now some of the scripts no longer work.  Does anyone have any tips to help get me started on likely reasons for this problem?  Thank you in advance!
UPDATE: The script that doesn't work does not produce an error.  It just gets to 100%, but is never completed.  It seems that 100% isn't actually 100% because it stops at the point of "Identifying optimal scale for tracts..." I've pasted in (below) the script starting at this point where the script just stops working.
##select by attributes, zoom to layer and copy scale
arcpy.AddMessage("Identifying optimal scale for tracts...")
mxd.activeView = "PAGE_LAYOUT"
arcpy.MakeFeatureLayer_management(consCopy, "ZoomLayer")
addLyr = arcpy.mapping.Layer("ZoomLayer")
arcpy.mapping.AddLayer(df, addLyr)
arcpy.RefreshActiveView()
arcpy.RefreshTOC()
urows = arcpy.UpdateCursor(consCopy)
for row in urows:
    id = row.getValue("TRACT_UID")
    strID = str(id)
    expression = '"TRACT_UID" =' + "'" + strID + "'"
    selection = arcpy.SelectLayerByAttribute_management("ZoomLayer", "NEW_SELECTION", expression)
    df.zoomToSelectedFeatures()
    arcpy.RefreshActiveView()
    rScale = df.scale
    if rScale >= 48000:
        scale = 96000
    elif rScale >= 24000:
        scale = 48000
    elif rScale >= 22800:
        scale = 24000
    elif rScale >= 21600:
        scale = 22800
    elif rScale >= 20400:
        scale = 21600
    elif rScale >= 19200:
        scale = 20400
    elif rScale >= 18000:
        scale = 19200
    elif rScale >= 16800:
        scale = 18000
    elif rScale >= 15600:
        scale = 16800
    elif rScale >= 14400:
        scale = 15600
    elif rScale >= 13200:
        scale = 14400
    elif rScale >= 12000:
        scale = 13200
    elif rScale >= 10800:
        scale = 12000
    elif rScale >= 9600:
        scale = 10800
    elif rScale >= 8400:
        scale = 9600
    elif rScale >= 7200:
        scale = 8400
    elif rScale >= 6000:
        scale = 7200
    elif rScale >= 4800:
        scale = 6000
    elif rScale >= 3600:
        scale = 4800
    elif rScale >= 2400:
        scale = 3600
    elif rScale >= 1500:
        scale = 2400
    elif rScale >= 1200:
        scale = 1500
    elif rScale >= 600:
        scale = 1200
    else:
        scale = 600

    row.setValue("Scale", scale)
    urows.updateRow(row)
    row.setValue("rawScale", rScale)
    urows.updateRow(row)

del urows
del row

# add a scale for the topographic context maps
urows = arcpy.UpdateCursor(consCopy)
for row in urows:
    case_id = row.getValue("Scale")
    value = case_id*2
    row.setValue("TopoScale", value)
    urows.updateRow(row)

#set new consplan as data driven pages index
arcpy.AddMessage("Setting new results as data driven pages index...")
for keepers in arcpy.mapping.ListLayers(mxd):
    if keepers.name == "Tract":
        keepers.replaceDataSource(workSpace, "FILEGDB_WORKSPACE", consCopy)
    elif keepers.name == "Other tracts used by producer":
        keepers.replaceDataSource(workSpace, "FILEGDB_WORKSPACE", consCopy)
    elif keepers.name == "TractIndex":
        keepers.replaceDataSource(workSpace, "FILEGDB_WORKSPACE", consCopy)
del keepers

# Turn off toolKit Layers
arcpy.AddMessage("Turning off ToolKit layers...")
offList = arcpy.mapping.ListLayers(mxd)
for off in offList:
    if off.name == "ZoomLayer":
        arcpy.mapping.RemoveLayer(df, off)
    elif off.name == "Practices (points)":
        off.visible = False
    elif off.name == consplanTitle:
        off.visible = False
    elif off.name == "Land Unit Topology":
        off.visible = False
    elif off.name == "Active PLUs":
        off.visible = False
    elif off.name == "AOI":
        off.visible = False
    elif off.name == "Base Layer":
        off.visible = False
    elif off.name == "Practices (lines)":
        off.visible = False
    elif off.name == "Practices (polygons)":
        off.visible = False
    elif off.name == "Legacy PLUs":
        off.visible = False
    elif off.name == "Case PLUs":
        off.visible = False
    elif off.name == "History PLUs":
        off.visible = False

#clean up and clock out
arcpy.RefreshActiveView()
arcpy.RefreshTOC()
mxd.dataDrivenPages.refresh()

del offList
del off
del mxd
del urows
del df
del id
del strID
del scale
del selection
del expression

A: Thank you for your input everyone.  CWebster and I figured out that the df.zoomToSelectedFeatures() command was not selecting a feature to zoom upon (line 15 in the script above).  Because no feature was selected the script would not continue to run.
To fix this we replaced the df.zoomToSelectedFeatures() command line with df.extent = lyr.getSelectedExtent() and the script now runs to completion again.
We are not sure if the issue was with the ArcGIS 10.3 update or with the Python 2.7 update, but if other people run into similar issues maybe this information can help.


text:
Q: Why cant I use dots in arrays? I wanted to try something out with an API from a company. I wanted to put their data into my database. But I've run into a problem. The API has one JSON object called "venue.country". But I can't use dots in my array for some reason?
Here is the code:
    foreach ($data[1]['hits']['hits'] as $row) {
        $statement->execute(array(
            "name" => $row['fields']['name'][0],
            "date" => $row['fields']['start'][0],
            "lang_long" => "test",
It is this one! -> "country" => $row['fields']['venue.country'][0],
            "genres" => $row['fields']['genres'][0],
            "desc" => $row['fields']['description'][0],
            "logo" => $row['fields']['logo'][0],
            "header_pic" => $row['fields']['header'][0]
        ));
    }

\everything else works in the PHP
And here is a piece of the JSON:
venue.country: [
"Nederland"
],

How can I get this to work? Can I use the "explode" method?
This is the full JSON:
https://hugo.events/genre/pop/next/200/120
Thanks.
EDIT:
Even with the answer @Prototype Chain gave it is giving me this error: Notice: Undefined index: venue in /home/ubuntu/workspace/pop.php on line 18

A: This code works just fine given your example JSON data:
$string = <<<EOT
  {INSERT YOUR JSON STRING HERE}
EOT;

$json = json_decode( $string, true );
echo $json[1]['hits']['hits'][0]['fields']['venue.location'][0] . "\n";
echo $json[1]['hits']['hits'][0]['fields']['venue.location'][1] . "\n";

A: It's a little hard to debug without seeing the entire contents of the JSON data, however, in the past when I've hard trouble parsing JSON or XML data from a source that formatted it strangely, I found it useful to perform a pre-process str_replace() on the data before I parsed it.
So something like this might work for you:
$input = some_function_to_get_string_data_from_api();
$input = str_replace( "venue.country", "venuecountry", $input );
$json  = json_encode( $input );

It's not an elegant solution, and it falls apart quickly if you're dealing with lots and lots of fields that need modifying, but if you're only dealing with a single field or two that are giving you trouble, it can be a quick and dirty patch.

A: The code works fine. After debugging I found that, there is no key/index venue.country for the array elements $data[1]['hits']['hits'][50] and $data[1]['hits']['hits'][51]. Since there is no index, its throwing notice.
You can add @before the variable to suppress the notice or check the condition if the index exixts.
"country" => @$row['fields']['venue.country'][0],

"country" => isset($row['fields']['venue.country']) ? $row['fields']['venue.country'][0] : '',

// run this code for testing.
error_reporting(E_ALL);
ini_set('display_errors', 1);
$jsondata = file_get_contents('https://hugo.events/genre/pop/next/200/100');
$data     = json_decode($jsondata, true);
foreach ($data[1]['hits']['hits'] as $row) {
   // echo $row['fields']['name'][0].'=>'.@$row['fields']['venue.country'][0].'<br/>';
   $array[]= array(
        "name" => $row['fields']['name'][0],
        "country" => isset($row['fields']['venue.country']) ? $row['fields']['venue.country'][0] : ''
        );
}
echo "<pre>";
print_r($array);

A: Hope this will do the trick..
$row['fields']['venue']['country'][0]


text:
Q: Default Values for PhysicsBody If I do NOT set any values for the following, what are the default values in Swift 3, SpriteKit?
self.physicsBody?.restitution
self.physicsBody?.friction
self.physicsBody?.linearDamping

Thanks :D

A: You can see all those values at the SKPhysicsBody API:
restitution = 0.2
friction = Defaults to 0.2
linearDamping = 0.1

A: Restitution from the official Apple docs

This property is used to determine how much energy the physics body
  loses when it bounces off another object. The property must be a value
  between 0.0 and 1.0. The default value is 0.2.

Friction from the official Apple docs

This property is used to apply a frictional force to physics bodies in
  contact with this physics body. The property must be a value between
  0.0 and 1.0. The default value is 0.2.

Linear Dampening from the official Apple docs

This property is used to simulate fluid or air friction forces on the
  body. The property must be a value between 0.0 and 1.0. The default
  value is 0.1. If the value is 0.0, no linear damping is applied to the
  object.


text:
Q: Alterar Dinamicamente Bar Percentage Eu tenho esta bar percentage e queria alterar dinamicamente o valor dela só que não estou a conseguir.

Código da Bar

Código que usei para tentar alterar Dinamicamente

A: Eu reformulei a sua função para dar um load na progressBar, dê uma olhada:
Criei a função changePercentage(), nela você informa a barra de progresso que deseja que aconteça o load. Caso informe somente a progressBar, ele irá capturar o novo valor da barra pelo atributo data-percentage, caso queira um novo valor que não seja o desse atributo basta coloca no segundo argumento da função.
Exemplo:

$(document).ready(function() {
  function changePercentage(progress) {
    var percentage = arguments.length > 1 ? arguments[1] : progress.attr('data-percentage')
    percentage = Math.floor(percentage);
    var bar = progress.siblings().children();
    bar.stop().animate({
      width: percentage * progress.width() / 100
    }, {
      duration: 2000,
      easing: 'linear',
      step: function() {
        var cdt = Math.round(100 * bar.width() / progress.width());
        progress.text(cdt + "%");
      }
    });
  }

  changePercentage($('.bar-percentage')); // Captura o novo valor do data-percentage

  $('button').click(function() {
    changePercentage($('.bar-percentage'), 10); // Captura o valor do segundo argumento (10)
  });
})
.bar-container {
  width: 100%;
  background: #c7c7c7;
  height: 30px;
}

.bar-container .bar {
  background: #333;
  height: 30px;
  width: 0
}

<button>Mudar porcentagem para 10%</button>


text:
Q: Derivative of chi-squared function w.r.t. parameter vector I'm trying to derive the derivative of the chi-squared function w.r.t. the parameter vector $p$.
With $\chi^2$ being:
$\chi^2(p) = \sum \left[ \frac{y(t_i) - \hat{y}(ti_i; p)}{\sigma_{y_i}} \right]^2$
with $y$ being a 1xn vector, $\hat{y}$ being 1xn and $\sigma$ being a nxn symmetric matrix. In vector notation:
$$
(y - \hat{y}(p))^TW(y-\hat{y}(p)) \\
= y^TWy - 2y^TW\hat{y} + \hat{y}^TW\hat{y}
$$
with $W = 1/\sigma^2_{yi}$.
I dropped the dependence of $\hat{y}$ on $p$ on the second line for simplicity.
What i get is this:
$$
\frac{\partial}{\partial{p}}\chi^2 = \frac{\partial}{\partial{p}} \left( y^TWy - 2y^TW\hat{y} + \hat{y}^TW\hat{y} \right) \\
= -2y^TW + \hat{y}^T(W + W^T) \\
= -2(y-\hat{y})^TW
$$
However according to this the solution should be:
$$
\frac{\partial}{\partial{p}}\chi^2 = 2(y-\hat{y})^TW \frac{\partial}{\partial{p}} (y-\hat{y}) \\
= -2(y-\hat{y})^TW \left[ \frac{\partial{\hat{y}}}{\partial{p}}\right] \\
= -2(y-\hat{y})^TWJ
$$
where $J$ is the Jacobian. So somehow i seem to be missing the jacobian $J$ in my derivation. Can someone explain why?


text:
Q: PHP Preg_replace for all instance of specific text? I have the following text and want to replace all instace which begin and end with ##, how can i prepare regular expression for preg_replace php.
Example

We are encountering a problem ##anytext## and will update you soon
  regarding this problem ##textsomethingelse##

My question how can i replace all instance of ##anytext## with specific text?

A: You probably need to use preg_replace_callback for this task.
And an example:
<?php
$replacements = array(
    'anytext' => 'ANYTEXT',
    'else' => 'ELSE',
);
echo preg_replace_callback(
    '/##(.*?)##/',
    create_function(
        '$matches',
        'global $replacements; return $replacements[ $matches[1] ];'
    ),
    'We are encountering a problem ##anytext## and will update you soon regarding this problem ##else##'
);

Note: This example uses create_function, but if you're on PHP >= 5.3 you're better of using a closure.

A: Wondering why a global flag wont work with simple preg_replace. Like this:
<?php
$string = 'We are encountering a problem ##anytext## and will update you soon regarding this problem ##textsomethingelse##';

$pattern = '/##anytext##/g';
$replacement = 'with the service';
echo preg_replace($pattern, $replacement, $string);
?>

This will output:
We are encountering a problem with the service and will update you soon regarding this problem ##textsomethingelse##