text:
Q: Python. Mostrar el índice de los números pares Estoy tratando de separar los números pares introducidos por el usuario y separados con espacios con el método split(). Debo mostrar el índice de cada número par, no el número par en sí que es lo que yo consigo.
numeros = input('Introduce una cadena separada por espacios: ').split()
pares = []

for numero in numeros:
    if int(numero) % 2 == 0:
        pares = numero
        print(pares)

Y esta sería la otra versión que consigo, pero que me muestra los resultados en formato lista sin conseguir mostrar el índice.
¿A alguien se le ocurre como puedo solucionarlo?
numeros = input('Introduce una cadena separada por espacios: ').split()
pares = []

for numero in numeros:
    if int(numero) % 2 == 0:
        pares.append(numero)
print(pares)

Resultado
Introduce una cadena separada por espacios:
10 4 7 8 6 5
['10', '4', '8', '6']

A: Cuando te piden el índice, es señal de que tienes que iterar con un range(len(numeros)).
Dentro de la iteración ya tienes el índice, con el cual puedes recuperar el entero ingresado para ver si es par o no. Si es par, agregas el índice a la lista.
numeros = input('Introduce una cadena separada por espacios: ').split()
pares = []

for indice in range(len(numeros)):
    numero = numeros[indice]
    if int(numero) % 2 == 0:
        pares.append(indice)

print(pares)

produce:
Introduce una cadena separada por espacios: 1 2 3 4 5 6 7 8 9 10
[1, 3, 5, 7, 9]

Introduce una cadena separada por espacios: 1 3 5 7
[]

Introduce una cadena separada por espacios: 2 4 6 8 10
[0, 1, 2, 3, 4]

A: Lo que quieres hacer se consigue muy fácil con la función enumerate. Es una función que viene por defecto en Python. Tu código está bien sólo tienes que cambiar un par de cosas. Leer más aquí. Pero en síntesis esta es la estructura de la función enumerate(iterable, start) donde el iterable es la lista que quieres enumerar, y el start el índice de inicio dónde quieres empezar a enumerar. Si no proporcionas start por defecto es el índice 0. enumerate(iterable, start=0)
nums = input('Ingresa los números separados por un espacio: ')

# Se crea la lista de números
nums = nums.split(' ')

# La lista de índices
lista_de_indices = []

# Al usar enumerate tenemos que usar 2 variables, la primera será el índice y la segunda el número en esa posición.
for index, numero in enumerate(nums):
    # Comprobamos que el número sea par
    if int(numero) % 2 == 0:
        # Si es par, su índice se añade a la lista.
        lista_de_indices.append(index)

print(lista_de_indices)

Como ves en el ejemplo. Cuando usas enumerate en el for necesitas especificar 2 variables. La primera siempre será el índice y la segunda el objeto en esa posición.
Espero te sirva.

A: Tu problema es muy fácil, para eso solo hacemos uso de la función list.index(elemet) el cual nos devuelve el índice del elemento que deseamos. Según tu código.
numeros = input('Introduce una cadena separada por espacios: ').split()
#pares = []

for numero in numeros:
    if int(numero) % 2 == 0:
        #pares.append(numero)
        indice = numeros.index(numero)
        print(f"El indice del numero par es {indice}")
#print(pares)

Probamos
Introduce una cadena separada por espacios: 2 4 5 6 7 8
El indice del numero par es 0
El indice del numero par es 1
El indice del numero par es 3
El indice del numero par es 5

No sé si aun quieres guardar los números en una lista, si lo quieres hacer descomentas esas líneas y si quieres saber el índice según la lista pares lo haces de igual forma con un ciclo for.


text:
Q: Packaging Videos Within An App I am in the process of developing a fitness app.  I want the user to have the option to view a demonstration video of each exercise (of which there are ten).  I am currently accessing YouTube videos for the demonstrations.  I filmed people at my gym doing the movements today and I am curious what would be the best way to package these videos within my application.  I'm assuming I can include them in my drawables and access them from there.  Also, what type of files should I make them?  The videos will each be less than 30 seconds so I don't think they will take up too much space in the application, but I could be wrong.  Anyway, any advice would be welcome.  Thanks in advance.

A: You can put them into the raw folder (/res/raw). Create it if needed.
Supported formats are 3gp and mp4.
To play them you can use:
 VideoView view = (VideoView)findViewById(R.id.videoView);
    String path = "android.resource://" + getPackageName() + "/" + R.raw.video_file;
    view.setVideoURI(Uri.parse(path));
    view.start();

redpajama_set_name: RedPajamaStackExchange


text:
Q: Sorting Algorithm Not Passing I'm trying to take a file and run it through a sorting algorithm, insertion sort in this case. After I pass it through the algorithm and print the array, it doesn't look sorted. My thinking is because I'm trying to pass an array to the function, and view the information through a pointer, but I think I'm messing it up.
void insertionSort(int arr[]) {
    int key, j;
    for(int i = 1; i < (sizeof(arr) / sizeof(int)); i++) {
        int key = arr[i];
        int j = i-1;
        while(j >= 0 && arr[j] > key) {
            arr[j+1] = arr[j];
            j = j - 1;
        }
        arr[j+1] = key;
    }
}

I have the function set to void because I thought I'd be able to just access the array since it is a pointer. Would it be better if I returned the array? My logic is obviously wrong, so any pointers (no pun intended) would be great.
Here is the block of code from my main()
case 2:
    printf("Filling array...\n");

    fp = fopen("Random.txt", "r");
    if (fp == NULL) {
        printf("\nError opening Random.txt\n");
        exit(1);
    }

    for (int i = 0; i < (sizeof(arr) / sizeof(int)); i++) {
        fscanf(fp, "%d", &arr[i]);
    }

    insertionSort(arr);

    for (int i = 0; i < (sizeof(arr) / sizeof(int)); i++) {
        printf("%d\n", arr[i]);
    }

    fclose(fp);
    break;
}

A: void insertionSort(int arr[]) {

Arrays decay to pointers when passed to functions, so this is basically
void insertionSort(int *arr) {

which means this will not give you the number of elements in the array
for(int i = 1; i < (sizeof(arr) / sizeof(int)); i++) {

You need to explicitly pass the size of the array to the function.
void insertionSort(int arr[], int size) {
    for (int i = 1; i < size; i++) {
        int key = arr[i];
        int j = i - 1;
        while (j >= 0 && arr[j] > key) {
            arr[j + 1] = arr[j];
            j = j - 1;
        }
        arr[j + 1] = key;
    }
}

To call the function:
insertionSort(arr, sizeof(arr) / sizeof(int));

In main(), where the array is created, you can use sizeof(A) / sizeof(int), because main() knows the size of the array.


text:
Q: dnsPython - answer from dns.resolver.query I need some help with getting nameserver (NS) records from specific domains.
So far i had no problem with my script but now I realised that it has
problem getting answer from domains like this: fpv.ukf.sk
With simple domain like google.com, ukf.sk etc. I have no problem.
used code:
answers = dns.resolver.query('fpv.ukf.sk', 'NS')
I get this error:
    answers = dns.resolver.query('fpv.ukf.sk', 'NS')
  File "build\bdist.win32\egg\dns\resolver.py", line 920, in query
    raise_on_no_answer, source_port)
  File "build\bdist.win32\egg\dns\resolver.py", line 858, in query
    raise_on_no_answer)
  File "build\bdist.win32\egg\dns\resolver.py", line 133, in init
    raise NoAnswer
NoAnswer
any suggestions why I cant get answer when I send query for fpv.ukf.sk domain?

A: If you send any kind of query about the fpv.ukf.sk, you'll see that there is no answer. That is what the Python exception is showing you. So you are getting the expected behaviour.
Try to do:
nslookup fpv.ukf.sk -type=NS

By this you will be making a dns query to the nameserver which is configure in your system. If the authoritative server is a different one, you can to as follows.
nslookup fpv.ukf.sk <authoritative_nameserver> -type=NS

With this commands you can troubleshoot any dns query.


text:
Q: Migrating AWS RDS SQL Server Express to Azure SQL DB I have a task to migrate an AWS RDS SQL Server Express instance to an Azure SQL Database. I already assessed the RDS db using Data Migration Assessment Tool and there are not compatibility issues, however it is on the Azure Database Migration Service where I am getting blocked.
I keep on getting the "network-related or instance-specific error occurred while establishing a connection to SQL Server" error, as if the AWS RDS is down, but I can connect to it on my local SSMS and the Data Migration Assessment Tool.
I already added the Database Migration Service's IP address into the Amazon RDS's security group's inbound rules IP address, but it still hasn't worked. I already created an Azure Virtual Network Gateway and used its IP on the inbound rules but I'm still getting the same error.
I'm a little lost now on what to check and configure. Can anyone point me what to properly configure in this type of migration?


text:
Q: React router ignores URL after // for multiple optional parameters I want to match this url https://localhost:8050/search/Contact//* to the path given below.
    <Route path="/search/:type?/:subType?/:query?" component={TestComponent}?>

As subtype is optional parameter so I am passing blank instead.
But the "query" parameter is ignored all together.
I get match as follows in props
match {
    params: {type: "Contact", subType: undefined, query: undefined}
    path: "/search/:type?/:subType?/:query?"
    url: "/search/Contact"
}

I want * to be mapped with query  in match params

A: If you are not using :subType then remove it or use 2 different routes.
<Route exact path="/search/:type?/:query?" component={TestComponent}?>
<Route path="/search/:type?/:subType?/:query?" component={TestComponent}?>


text:
Q: How can I use 'this' jquery selector with angular 2 I try to use below code.
$('button').click(() => {
   console.log($('button').index(this)); // should show clicked element index
   //but in angular2 can't use 'this'
})

I know if I used 'let i = index' if I use ngFor...
but I have to use 'd3.js'
How can I use 'this' selector with angular 2?
or there have another way to get selected element index number?

A: You can try using event.currentTarget instead of this:
$('button').click((e) => {
   console.log($('button').index(e.currentTarget));
})

See also

*

*https://api.jquery.com/event.currentTarget/


text:
Q: When is it not possible to replace a Promise by Future? Just reading this article on promises, and the author uses the following example:
def redeemCampaignPledge(): Future[TaxCut] = {
    val p = Promise[TaxCut]()
    Future {
      println("Starting the new legislative period.")
      Thread.sleep(2000)
      //p.success(TaxCut(20))
      //println("We reduced the taxes! You must reelect us 2018!")
      p.failure(LameExcuse("global economy crisis"))
      println("We didn't fullfil our promises, so what?")
    }
    p.future
}

val taxCutF: Future[TaxCut] = redeemCampaignPledge()
  println("Now they're elected, let's see if they remember their promise.")
  taxCutF.onComplete {
    case Success(TaxCut(reduction)) =>
      println(s"Miracle! Taxes cut by $reduction percent.")
    case Failure(ex) =>
    println(s"They broke the promise again. Because of a ${ex.getMessage}")
  }

My question is, can't I just get rid of Promises and rewrite it as:
def redeem(): Future[TaxCut] = Future {
    println("Starting legislative period...!!!!")
    Thread.sleep(2000)

    println("We were successful")
    TaxCut(25)
}

What is this second version lacking? I am not fully grasping the value that promises bring.

A: Yes, you are absolutely correct. this is a very common anti pattern with JavaScript Promises (where, Futures are called Promises and Promises are called deferred).
Basically, instead of using the continuations that futures provide, it is building a new continuation around them in a callback like fashion.


text:
Q: jQuery SlideUp() and SlideDown() in IE 11 doesn't work I want to do some sliding up-down menu for my help site.
I have this code:
$(".li_about").click(function(){
    if ($(".ul_about").is(":hidden")) $(".ul_about").slideDown(400);
    else $(".ul_about").slideUp(400);
})

O programie

Czym jest Creator?

Twój pierwszy obraz

 etc [...]

#left-contener{
    position:relative;
    z-index: 5;
    width:30%;
    max-width:400px;
    height:calc(100% - 45px);
    background-color: #F8F8F8;
    float:left;
    white-space: nowrap;
    overflow-x: hidden;
    overflow-y:scroll;
    -webkit-touch-callout: none;
  -webkit-user-select: none;
  -khtml-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
}
#menu{
    margin-top:10px;
    margin-left:15px;
}
ul {
list-style:none;
padding:0;
margin:0;
}
li:not(.sep_1):not(.sep){
    height:40px;
    line-height: 40px;
    cursor:pointer;
    background-repeat: no-repeat;
    background-size: 30px 30px;
    background-position: 0px 5px;
    text-indent: 40px;
}
li:not(.sep):not(.sep_1):hover{
    text-indent:50px;
    color:#16C0FF;
}
.ul_tools,.ul_about,.ul_main{
    display: none;
}

Why SlideDown() and SlideUp() doesn't work in IE (11) ? Other browsers are fine.
PS. Some more texts coz Stackoveflow saying i need to put it more but i think i explain my problem enough...

A: Could you just use .slideToggle()?  And this may be a silly question, but is jQuery loaded properly?
$(".li_about").click(function(){
    $(".ul_about").slideToggle(400);
});

A: You've got a typo in this line:

O programie

You don't close your span. Here's the fixed line:

O programie

IE is not as forgiving of unclosed tags as other browsers, that may be the problem.


text:
Q: How can I get the events associated with an element that is inside an iframe? I am using Chrome DevTools and am looking at Event Listeners in the element tab. It works great when the element under consideration is not inside an iframe -- but when it is inside an iframe, things are a bit wonky. How can I remedy this? Thanks in advance
edit: I forgot to mention, it's not my site

A: This is a security thing with cross-origin iframes. If you own the domain that is inside of that iframe, then it should work fine. Working example for same-origin iframes
(code from that site is pasted below)
const iframe = document.getElementsByTagName('iframe')[0]; // grab a reference
iframe.contentWindow.document.getElementsByTagName('body') // here's the body!

If you were to execute the above code on an iframe that had a different domain than the page you're currently on, then you would get a CORS error that looks like the below

A workaround is if you have a script inside the frame and use something like a postMessage you can broadcast the information you want into the parent window that's embedding the iframe. This requires working with the company/website whose domain you're embedding, which obviously requires some amount of trust that you won't do anything malicious.
If you think about it, one of the reasons this might exist is so that if you are embedding a login page for another site, you can't add event listeners and steal users' logins.
Hope this helps!


text:
Q: Java jpa: find entities with many to many property that contains every element of given collection I have 2 Entities: Post & Attributes
public class DbPost {
    ....

    @ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
    @JoinTable(name = "posts_attributes",
            joinColumns = {@JoinColumn(name = "post_id")},
            inverseJoinColumns = {@JoinColumn(name = "attribute_value_id")})
    @Builder.Default
    private Set<DbAttributeValue> attributeValues = new HashSet<>();

    ....
}

public class DbAttributeValue {
    ...

    @Id
    @Column(name = "attribute_value_id")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @PropertyDefinition
    private Long id;

    ...
}

Now, how can i get all posts where every post contains every AttributeValue from list of AttributeValue ids?
i've already tried:
    List<DbPost> findAllByAttributeValuesIdIn(Collection<Long> attributeValues_Id);

and
public Specification<DbPost> createPostJpaSpecification(List<Long> attributeValueIds) {
    return (root, query, criteriaBuilder) -> {
        List<Predicate> predicates = new ArrayList<>();
        if (attributeValueIds != null && attributeValueIds.size() > 0) {
            predicates.add(
                    root.joinSet("attributeValues").get("id").in(attributeValueIds)
            );
        }
        return criteriaBuilder.and(predicates.toArray(new Predicate[0]));
    };
}

what i'm doing wrong here?

A: Try this
    public Specification<DbPost> createPostJpaSpecification(List<Long> attributeValueIds) {
        return (root, query, builder) -> {
            final List<Predicate> predicates = new ArrayList<>();
            if (attributeValueIds != null) {
                for(Long id : attributeValueIds) {
                    predicates.add(
                        createAttributeIdPredicate(id, root, query, builder)
                    );
                }
            }
            return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
        };
    }

    Predicate createAttributeIdPredicate(Long attributeId, Root<DbPost> root, CriteriaQuery<DbPost> query, CriteriaBuilder builder) {
         Subquery<Integer> subquery = query.subquery(Integer.class);
         Root<DbPost> post = subquery.from(DbPost.class);
         Join<DbAttributeValue, DbPost> attribute = post.join("attributeValues");

         Predicate mainQueryRelationPredicate = builder.equal(root.get("id"), post.get("id"));
         Predicate subqueryPredicate = builder.equal(attribute.get("id"), attributeId);

         subquery.select(builder.literal(1))
                 .where(mainQueryRelationPredicate, subqueryPredicate);

         return buider.exists(subquery);
    }


text:
Q: Colored polygon outlines displayed as just all white opaque polygons Someone shared a kml with me that was created in Google Earth Web along with a screenshot of it.
When I opened it up in Google Earth Pro, the colored polygons displayed as solid white.
For a test, I created a test polygon in Google Earth Web and exported it as KML.

*

*Projects > New project > Create KML file

*Draw line or shape > create polygon

*Set fill color red at 75%

*Set color 4px

*Select export as KML

Same thing, the polygon shows up as a white box in Google Earth Pro.
The exported KML is structured like this:
<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns=http://www.opengis.net/kml/2.2 xmlns:gx=http://www.google.com/kml/ext/2.2 xmlns:kml=http://www.opengis.net/kml/2.2 xmlns:atom=http://www.w3.org/2005/Atom>
<Document>
        <name>Untitled Project</name>
        <gx:CascadingStyle kml:id="__managed_style_147D324643211BD21CEE">
                <Style>
                        <IconStyle>
                                <Icon>
                                        <href>https://earth.google.com/earth/rpc/cc/icon?color=1976d2&id=2000&scale=4</href>
                                 </Icon>
                                 <hotSpot x="64" y="128" xunits="pixels" yunits="insetPixels"/>
                        </IconStyle>
                        <LabelStyle>
                        </LabelStyle>
                        <LineStyle>
                            <color>ffa21f7b</color>
                            <width>3.63636</width>
                        </LineStyle>
                        <PolyStyle>
                            <color>c02f2fd3</color>
                        </PolyStyle>
                        <BalloonStyle>
                            <displayMode>hide</displayMode>
                        </BalloonStyle>
                </Style>
            </gx:CascadingStyle>
            ...

        <StyleMap id="__managed_style_0C1991940B211BD21CEE">
            <Pair>
                 <key>normal</key>
                 <styleUrl>#__managed_style_147D324643211BD21CEE</styleUrl>
            </Pair>
            <Pair>
                 <key>highlight</key>
                 <styleUrl>#__managed_style_2EB2C27FFE211BD21CEE</styleUrl>
            </Pair>
        </StyleMap>

        <Placemark id="09A507D5E3211BD1D53F">
            <name>Test Polygon</name>
            <styleUrl>#__managed_style_0C1991940B211BD21CEE</styleUrl>
            <Polygon>
                <outerBoundaryIs>
                    <LinearRing>
                        <coordinates>
                                                                                0.0287244781654028,51.5286273373769,4.888032506075639 0.03124375777183053,51.52899071640604,5.649232085770059 0.03060716674301966,51.5305703663013,6.296306355936279 0.02835525808849049,51.53027540191405,5.649128389213159 0.0287244781654028,51.5286273373769,4.888032506075639
                        </coordinates>
                    </LinearRing>
                </outerBoundaryIs>
            </Polygon>
        </Placemark>
</Document>
</kml>

The <gx:CascadingStyle> does not appear in the KML reference.
https://developers.google.com/kml/documentation/kmlreference
What is going on here?
i am expecting the original colored polygon to appear in Google Earth Pro.

A: The <gx:CascadingStyle> is an undocumented element that is created in Google Earth Web that is unsupported by Google Earth Pro.
If you make a minor edit to the KML, then it will work as expected.
Make these changes:

*

*Remove <Style> and </Style> elements.

*Globally change <gx:CascadingStyle kml:id="xxx"> to <Style id="xxx">.
Replace <gx:CascadingStyle kml:id= with <Style id=

*Replace </gx:CascadingStyle> with</Style>
Example:
Old:
    <gx:CascadingStyle kml:id="__managed_style_147D324643211BD21CEE">
        <Style>
            ...
        </Style>
    </gx:CascadingStyle>

New:
    <Style id="__managed_style_147D324643211BD21CEE">
        ...
    </Style>

You can globally make the changes to the KML using a text editor; e.g. Notepad++.
The KML is now valid with respect to the OGC KML 2.2 standard and will work in Google Earth Pro.


text:
Q: Question on eigenstates of hermitian operators that fulfill canonical commutation relation
Two operators, in a suitable basis with matrix representations $A$ and $B$ have the following commutator $[A, B] = AB − BA = kI$, where $k$ is a non-zero complex number and $I$ is the $n × n$ identity matrix, where $n$ can be any integer between 1 to ∞. Determine if the matrices $A$ and $B$ are of finite or infinite dimensionality, and prove your assertion, using only the commutation relation given above.


text:
Q: Set every Integer in Arraylist to certain value I try to do it like this, but somehow it doesn't seem to work:
ArrayList<Integer> possible_values= new ArrayList<Integer>();
public void setValueToZero(){
   for (Integer temp : possible_values) {
      temp=0;
   }
}

A: You could use Collections.fill(List<T> list, T obj).
In your case that would be Collections.fill(possible_values, 0)

A: The  temp in your program is not the elements of the ArrayList,it is a new Object. In the other word, your program is not to set the integer in arraylist. You are just set the value of temp,which is a new object and you didn't change the true value of the element in the arraylist.  Well, I hope you can understand what I write. I'm not a native speaker.

A: You are assigning values to temp variable and there is no change to the possible_values list object elements, you can set the 0 values to the List elements as shown below:
public void setValueToZero(ArrayList<Integer> possible_values){
    for (int i=0; i<possible_values.size(); i++) {
       possible_values.set(i, 0);
    }
}

or else, you can use streams (one liner code) as shown below:
IntStream.range(0,possible_values.size()).forEach(i->possible_values.set(i, 0));


text:
Q: Rake aborted! Don't know how to build task 'up' I'm having trouble migrating up.  Thanks for sharing your time, and I appreciate the help!

*

*Windows 7(64 bit)

*Ruby: 1.9.2p290

*Rails: 3.2.3

*MySQL: 5.5.24

> rake db:migrate up VERSION=20120529170841 --trace
** Invoke db:migrate (first_time)
** Invoke environment (first_time)
** Execute environment
** Invoke db:load_config (first_time)
** Invoke rails_env (first_time)
** Execute rails_env
** Execute db:load_config
** Execute db:migrate
** Invoke db:_dump (first_time)
** Execute db:_dump
** Invoke db:schema:dump (first_time)
** Invoke environment
** Invoke db:load_config
** Execute db:schema:dump
rake aborted!
Don't know how to build task 'up'
C:/Ruby192/lib/ruby/gems/1.9.1/gems/rake-0.9.2.2/lib/rake/task_manager.rb:49:in
`[]'
C:/Ruby192/lib/ruby/gems/1.9.1/gems/rake-0.9.2.2/lib/rake/application.rb:115:in
`invoke_task'
C:/Ruby192/lib/ruby/gems/1.9.1/gems/rake-0.9.2.2/lib/rake/application.rb:94:in `
block (2 levels) in top_level'
C:/Ruby192/lib/ruby/gems/1.9.1/gems/rake-0.9.2.2/lib/rake/application.rb:94:in `
each'
C:/Ruby192/lib/ruby/gems/1.9.1/gems/rake-0.9.2.2/lib/rake/application.rb:94:in `
block in top_level'
C:/Ruby192/lib/ruby/gems/1.9.1/gems/rake-0.9.2.2/lib/rake/application.rb:133:in
`standard_exception_handling'
C:/Ruby192/lib/ruby/gems/1.9.1/gems/rake-0.9.2.2/lib/rake/application.rb:88:in `
top_level'
C:/Ruby192/lib/ruby/gems/1.9.1/gems/rake-0.9.2.2/lib/rake/application.rb:66:in `
block in run'
C:/Ruby192/lib/ruby/gems/1.9.1/gems/rake-0.9.2.2/lib/rake/application.rb:133:in
`standard_exception_handling'
C:/Ruby192/lib/ruby/gems/1.9.1/gems/rake-0.9.2.2/lib/rake/application.rb:63:in `
run'
C:/Ruby192/lib/ruby/gems/1.9.1/gems/rake-0.9.2.2/bin/rake:33:in `'
C:/Ruby192/bin/rake:23:in `load'
C:/Ruby192/bin/rake:23:in `'

A: The correct syntax is
rake db:migrate:up VERSION=2012052917

instead of (rake db:migrate up ...)


text:
Q: solving an exponential equation in Raku
I'm trying to solve this exponential equation like this:
my ($l,$r);

for (1 .. 100) -> $x {
    $l = $x * e ** $x;
    $r = 5 * (e ** $x - 1);
    say $x if $l == $r;
    }

But it doesn't work. How to solve it in a straightforward and comprehensive fashion?

A: Sorry for the double-answering.
But here is a totally different much simpler approach solved in Raku.
(It probably can be formulated more elegant.)
#!/usr/bin/env raku

sub solver ($equ, $acc, $lower0, $upper0) {
    my Real $lower = $lower0;
    my Real $upper = $upper0;
    my Real $middle = ($lower + $upper) / 2;

    # zero must be in between
    sign($equ($lower)) != sign($equ($upper)) || die 'Bad interval!';

    for ^$acc {                                          # accuracy steps
        if sign($equ($lower)) != sign($equ($middle))
            { $upper = $middle }
        else
            { $lower = $middle }
        $middle = ($upper + $lower) / 2;
    }
    return $middle;
}

my $equ = -> $x { $x * e ** $x  -  5 * (e ** $x - 1) };  # left side - right side
my $acc = 64;                                            # 64 bit accuracy
my Real $lower = 1;                                      # start search here
my Real $upper = 100;                                    # end search here

my $solution = solver $equ, $acc, $lower, $upper;

say 'result is ', $solution;
say 'Inserted in equation calculates to ', $equ($solution), ' (hopefully nearly zero)'

A: For Perl 5 there is Math::GSL::Roots - Find roots of arbitrary 1-D functions
https://metacpan.org/pod/Math::GSL::Roots
Raku has support for using Perl 5 code or can access the GSL C library directly, can't it?
$fspec = sub {
       my ( $x ) = shift;

       # here the function has to be inserted in the format
       # return leftside - rightside;

       return  ($x + $x**2) - 4;

     };

gsl_root_fsolver_alloc($T); # where T is the solver algorithm, see link for the 6 type constants, e.g. $$gsl_root_fsolver_brent
gsl_root_fsolver_set( $s, $fspec, $x_lower, $x_upper ); # [$x_lower; $x_upper] is search interval
gsl_root_fsolver_iterate($s);
gsl_root_fsolver_iterate($s);
gsl_root_fsolver_iterate($s);
gsl_root_fsolver_iterate($s);
gsl_root_fsolver_iterate($s);
my $result = gsl_root_fsolver_root($s);
gsl_root_fsolver_free (s);

There are enhanced algorithms available (gsl_root_fdfsolver_*), if the derivative of a function is available.
See also https://www.gnu.org/software/gsl/doc/html/roots.html#examples for general usage


text:
Q: Routing in Altium Here is a picture of board:

I want to route pad 23 to 48. But the path gap is narrow. So I am not able to route it. Auto routing also couldn't route. I changed the design rules for solder mask and track width as much as possible.
How can I achieve the routing?

A: There is no magic bullet here.  You either use smaller trace/space widths, route it a different way, or you don't route it at all.

A: Can you place a Via close to the Pad and then go on a lower layer? You might also want to look at typical fanouts: http://wiki.altium.com/display/ADOH/Fanout+and+Escape+Routes
Addition: You might want to plug that via to prevent tin from being sucked into the hole


text:
Q: TradingView [PINE]: Can I change study overlay dynamically via the settings? When defining a TradingView study, we have the following supported settings
study(title, shorttitle, overlay, format, precision, scale, max_bars_back, max_lines_count, max_labels_count, resolution, resolution_gaps, max_boxes_count) → void

where I am interested into the overlay property
overlay (const bool) - default is false.
- if true, the study will be added as an overlay for the main series.
- if false, it would be added on a separate chart pane.

What I am interested into is, can this property be set dynamically?
For example, in the indicator settings, I can add an input field from where the user should be able to choose either the current indicator to be shown in the main series overlay or either to be shown in a separate chart pane.
study_overlay = input(defval = "true", title = "Study Overlay", options = ["true", "false"])

When user is going to change the selected options there, the indicator should change the pane that is using, based on the selected option.
Is this feasible? I tried something like
study_overlay_string = input(defval = "true", title = "Study Overlay", options = ["true", "false"])
study_overlay_bool = true
if study_overlay_string == "false"
    study_overlay_bool = false
study("My Script", overlay = study_overlay_bool)

This study can be added to the chart, but when changing the setting, nothing happens!

A: No, the overlay argument is of the const bool type so you cannot use an input to pass a value to it. All input-based variables have an input type form; input is more narrow than const and cannot be converted into const.
Your script works because you use = instead of := in your if-block. Instead of assigning a value to the global scope study_overlay_bool variable, you create a separate local scope variable with the same name (note the compiler warning that should appear in the console). If you use := there instead, you'll get the expected type error.


text:
Q: Will the compiler only compile code that can get executed? I have a class library and am using only part of it. Is there a need to delete what isn't being used in order to shrink the size of the created code (in release configuration)?
As far as I've seen, the compiler takes care of that, and removing the code doesn't change the EXE file size. Will this always be true? Removing all unneeded code would take very long, so I want to know if there's need for that.
More information: there are methods and classes in the class library that aren't called from the executing code, but are referenced by other parts of code in the class library (which themselves are never called).

A: It all gets compiled. Regardless of whether it is called or not. The code may be called by an external library.
The only way to make the compiler ignore code is by using Compiler Preprocessor Directives. More about those here.

A: No, the compiler includes the "dead" code as well.  A simple reason for this is that it's not always possible to know exactly what code will and won't be executed.  For example, even a private method that is never referenced could be called via reflection, and public methods could be referenced by external assemblies.
You can use a tool to help you find and remove unused methods (including ones only called by other unused methods).  Try What tools and techniques do you use to find dead code? and Find unused code to get you started.

A: I doubt the compiler will remove anything. The fact is, the compiler can't tell what is used and what is not, as types can be instantiated and methods called by name, thanks to reflection.

A: Let's suppose there is a class library called Utility. You created a new project and added this class library to that project. Even if your EXE calls only 1-2 methods from the class library, it's never a good idea to delete the unreferenced code.
It would go against the principle of reusablity. Despite the fact that there would be some classes present in the library unreferenced from the EXE, it would not have any bad impact on performance or size of the program.

A: Determining all and only dead code is (if one makes the idealization that one has a "math world" like language) recursively undecidable, in most languages. (A few rare ones like the Blaise language are decidable.)

A: to the question of whether there is a "need to delete what isn't being used in order to shrink the size of the created code": i think this would only be useful to save network bandwidth. removing unused code is crucial in web applications to improve loading speeds etc.
if you're code is an exe or a library, the only reason i see to remove dead code, is to improve your code quality. so that someone looking at your code 2 years down the line won't scratch their heads wondering what it does.


text:
Q: How to parse webview for Oauth 2.0 code in android I'm trying to allow users in my android app to log in to their google account so i can access their contacts for the purpose of creating a friends list, and I'm trying to use OAuth to do this.
So far I have formed the URL and have created the webview which loads the page. I proceed to sign in but i dont know how to assign the code from the URL to the code value in my activity. also i don't know whether my Onpagestarted method is working correctly
Can someone either tell me either an alternate method/technique to authenticate with google using OAuth2 or tell me what are the issues with my current way as once I reach the page with the code my view remains the WebView and not the textview with the code as I want it to?
I would like to automate the entire process after the User has signed into the google page in my WebView but so far my code keeps getting stuck at the page with the Authcode which leads me to believe that the Authcode is not being detected by my program.
NOTE: I do not want to simply use the account that is signed into the Android Device (unless obviously the user chooses to enter the same account)
This is the code from the Activity in which I want to acquire the Auth Code/Token and get the Contacts for my User though I don't mind displaying the contacts in a later activity.
WebView browser;
final String username = "gotsingh@gmail.com";
 private myWebViewClient client;
String code;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_add_friends);
    browser = (WebView) findViewById(R.id.webview);
    client = new myWebViewClient();
    WebSettings webSettings = browser.getSettings();
    webSettings.setJavaScriptEnabled(true);
    browser.setWebViewClient(client);
    getAuthCode(client);

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.add_friends, menu);
    return true;

}

public void getAuthCode(myWebViewClient myClient){
    browser.loadUrl(url4);
    while (myClient.authCode!= null){
    showCode(myClient);}
}

public void showCode(myWebViewClient myClient){
        code = myClient.authCode;
        TextView text = new TextView(this);
        text.setText(code);
        setContentView(text);
}

Below is my modified WebViewClient class
public class myWebViewClient extends WebViewClient{
boolean authComplete = false;

String authCode = null;

@Override public void onPageStarted(WebView view, String url, Bitmap favicon){
    super.onPageStarted(view, url, favicon);
    if (url.contains("?code=") && authComplete != true) {

        int codeStart = url.indexOf("?code=")+6;

        authCode = url.substring(codeStart);

        Log.i("", "AUTHCODE : " + authCode);
        authComplete = true;

        System.out.println(authCode);

    }else if(url.contains("error=access_denied")){
        Log.i("", "ACCESS_DENIED_HERE");
        authComplete = true;
    }

   }

}

Also, if I could get some general guidance on doing POST/GET requests in java to recieve JSON data from google. I am very new to android development and I have close to 0 experience dealing with html/http requests.

A: Take a look at this sample. It is not against Google, but the principles are the same. You may want to consider using the "implicit" flow in OAuth to avoid storing secrets in the device.


text:
Q: Update method in web API: How to know which fields to update? I have a typical web API with a couple of PUT/UPDATE endpoints. These endpoints simply call the underlying service, and do the update.
The service layer, has the typical signature such as Object Update(Object object). What I then do is I basically run the following pseudo code:
var dbobject = _db.Object.Find(object.Id);
dbobject.Field1 = object.Field1;
dbobject.Field2 = object.Field2;
// continue for all fields

_db.SaveChanges();

return GetObjectById(object.Id);

However, this provides a challenge for me.
Lets say we have a consumer of our API. This consumer calls my PUT endpoint (/api/Object/{id}), and the payload is the updated Object.
However, lets say that the object we put don't know about example Field4, then this value would be NULL after the update has been run.
My question is:

*

*What do you do about all those fields the payload does NOT contain?
How do you handle not setting values to NULL you don't expect to be
NULL afterwards?

A: As one of the possible ways, here can be used mix of NotifyPropertyChanged with automapper
The Idea is to store in DTO object which fields exactly was set, and which stays filled with default value. And use collected data in mapping.
For example DTO object will be
public class Dto
{
    private List<string> Changed = new List<string>();
    public bool IsChanged(string field) => Changed.Contains(field);

    private int _age;
    private string _name;

    public string Name
    {
        get { return _name; }
        set
        {
            _name = value;
            // IMPORTANT: field name should fit main object field name
            Changed.Add("Name");
        }
    }

    public int Age
    {
        get { return _age; }
        set
        {
            _age = value;
            Changed.Add("Age");
        }
    }
}

I used Next class for test
public class Human
{
    public string Name { get; set; } = "DEFAULT";
    public int Age { get; set; } = -1;
}

and automapper configuration will looks like
cfg.CreateMap<Dto, Human>()
       .ForAllMembers(s=> s.Condition(d=>d.IsChanged(s.DestinationMember.Name)));

This is a simple example. But it still doesn't prevent to use function IsChanged for some complex/specific logic, use not just a strings but Expressions / MethodInfo, or add custom attributes and use them in automapper configuration (DestinationMember is MethodInfo)
Append
Instead of complex DTO object the information about passed field you can get from Request.Properties in your controller (key ms_querynamevaluepairs value of type Dictionary<string, string>).


text:
Q: HMACSHA256 Returning Incorrect Value I am new to cryptography however I need to use HMACSHA256 to has a message.
I wrote a test method to test my hash method. I used online generators to hash the word: Paul and they all have the same base64 value, however when I do it using the code below, I get a different value. I tried using different encodings but I can't get back the value, can you let me know where I maybe going wrong?
[TestClass]
public class HashGeneratorUnitTest
{
    [TestMethod]
    public void TestMethod1()
    {
        string message = "Paul";
        //Pass a string to method.
        string hashedMessage = ShaGenerator.GetHash(message);
        Assert.AreEqual("gYtcxfIdPm5OYHHAYpRSjURZUCIhhEbYt5ME0rdmMno=",
            hashedMessage);
    }
}

public static class ShaGenerator
{
    public static string GetHash(string message, string secret = "")
    {
        var enc = new System.Text.ASCIIEncoding();
        byte[] secretBytes = enc.GetBytes(secret);
        byte[] messageBytes = enc.GetBytes(message);

        using (var hmac = new HMACSHA256(secretBytes))
        {
            byte[] hashedBytes = hmac.ComputeHash(messageBytes);
            string hashedString = Convert.ToBase64String(hashedBytes);
            //Return HMACSHA256 string.
            return hashedString; //returns: "g9gc9FI2RcI3N9ApYePF+si9Uh0p0Q4u2Vm0Wy5qphk="
        }
    }
}

A: The web-based generator you are testing against is incorrect.
Your implementation is returning the correct result.
Here is a web-based tool that returns the proper result: https://quickhash.com/


text:
Q: Difficulty when using APIs in the support library in the new version of the SDK I'm a little turned around by what I'm reading and the errors that are occurring when I set the minSDK level to 4. You would think that when a new version of the platform is generated, it would be backward compatible with earlier versions; so if I create software in SDK 17, using its features will work on devices using an earlier version such as 4, or whatever. But this doesn't seem to be the case. Since I've bought a phone running version 2.3.6… of the android OS I would like to make sure the software I'm developing works on this and other older devices, as well as the newer OSs.  But it doesn't seem like backward compatibility is guaranteed. So, does one just develop for newer devices, or is there a way to ensure that what I write in the new environment will work on devices without having to jump through a bunch of hoops? I'm trying to use the support library, but it doesn't seem to have all the apis of the newer versions. Can one just import the needed apis into the support library in some way? And if so, can you point me to an article on doing that?
I'm trying to create an app that has tabs in the action bar, using both activities and fragments and I keep getting version mismatch errors, stating something like, "the minimum SDK level is 4. It should be 13".
I'm pretty certain I can get the app to work for newer devices, but I'm sure all potential users won't have a new phone. So, I'm seeking your insights on getting around what I see as an ongoing issue.
Your insights are appreciated.
Thanks

A:
You would think that when a new version of the platform is generated, it would be backward compatible with earlier versions; so if I create software in SDK 17, using its features will work on devices using an earlier version such as 4, or whatever

Features that existed in API Level 4 generally exist in API Level 17, and the code supporting those features is generally backwards compatible.
However, newer versions of Android have additional features. Those are not necessarily backwards compatible, as by definition, they are newer and additional.

So, does one just develop for newer devices, or is there a way to ensure that what I write in the new environment will work on devices without having to jump through a bunch of hoops?

One can most certainly develop apps that work on older devices and newer ones. APIs that exist on older and newer devices, you just use, typically without issue. APIs that exist only on newer devices you have to take care to not try using those capabilities on older devices. There are a variety of techniques for doing this, such as by examining Build.VERSION.SDK_INT and skipping the newer API stuff on older devices.
Since there is no canonical definition of "jump through a bunch of hoops", you will need to decide that for yourself. It does require you to be capable of reading documentation, as there is quite a bit of it on how to build backwards-compatible applications, such as this discussion of developing backwards-compatible UIs. There are also plenty of blog posts and the like covering specific aspects of backwards compatible development, available via your favorite search engine.

I'm trying to use the support library, but it doesn't seem to have all the apis of the newer versions

It is not supposed to, nor has it been advertised as having that. It has backports of some things, but not everything. Partly, that is simply a question of engineering time. Partly, that is because some things just cannot be backported, because they are core changes to the OS, not merely framework classes.

I'm trying to create an app that has tabs in the action bar, using both activities and fragments and I keep getting version mismatch errors, stating something like, "the minimum SDK level is 4. It should be 13".

As abbath noted, the action bar is not part of the Android Support package, though ActionBarSherlock fills that role. Similar backports are available for other things not found in the Android Support package and can be found on such sites as AndroidViews.net.

A: ActionBar is introduced not so long ago, that's why you need API level 13 to use it.
If you want to use an ActionBar with tabs, but also want to develop for lower sdk versions, try to use a compability library, such as ActionBarSherlock


text:
Q: Surfaces: behavior of Pluricanonical maps Let $S$ be an algebraic smooth surface (over $\Bbb{C}$).
Suppose we have some fibration $p\colon S\rightarrow C$ onto a smooth curve. Let $f$ be a fiber, a curve, say.
Let $K$ be a canonical divisor on $S$ and assume $K\cdot f=0$. My question is: can we conclude that each $m$-canonical map $\varphi_{mK}\colon S\rightarrow\Bbb{P}^N$, when defined, will contract $f$ to a point ?

A: If $|mK|$ is base point free and if $f$ is irreducible, then $\varphi_{mK}(f)$ is a point.
Otherwise, there exists $x$, $y\in f$ s.t. $\varphi_{mK}(x)\neq \varphi_{mK}(y)$. By the definition of $\varphi_{mK}$, it is equivalent to say that there exists $s\in H^0(S,\mathcal{O}_S(mK))$, such that $s(x)=0$ and $s(y)\neq 0$.
Let $D:=div(s)$, then $D$ is an effective divisor, linearly equivalent to $mK$, and satisfying $x\in \operatorname{Supp}(D)$ while $y\notin \operatorname{Supp}(D)$. Therefore $f$ is not a component of $D$ (since $y\notin \operatorname{Supp}(D)$), hence $D\cdot f\geq 1$ (since $D$, $f$ have no components in common and $x\in \operatorname{Supp}(D)\cap f$). So $mK\cdot f=D\cdot f\geq 1$, we get a contradiction.

A: One slick way to explain why the answer is yes uses the projection formula. For our purposes the following formulation is enough: if $f: X \rightarrow Y$ is a morphism between smooth projective varieties, $L$ is a line bundle on $Y$, and $C$ is a curve on $X$, then $$f^*L \cdot C = L \cdot f_*C$$ (where $f_*$ denotes the push-forward of cycles, and $\cdot$ is intersection of cycles).
By definition of the morphism $\varphi_L: X \rightarrow \mathbf{P}^n$ associated to a basepoint-free line bundle on a variety $X$, we have $\varphi_L^* \mathcal{O}(1) =L$. So if $C$ is any curve with $L \cdot C =0$, the projection formula gives $(\varphi_L)_*C \cdot \mathcal{O}(1)=0$. But $\mathcal{O}(1)$ has strictly positive degree on any curve in $\mathbf{P}^n$, so the 1-cycle $(\varphi_L)_*(C)$ must be zero: that is, $C$ must be contracted by $\varphi$.
Now just apply this in your case with $L=mK$. (Note that for each integer $m$, the conditions $K \cdot C=0$ and $mK \cdot C=0$ are equivalent.)


text:
Q: Displaying 1.10 as NUMBER and not Characters I try the below query
SELECT TO_NUMBER(1.10)
FROM DUAL;

The result was 1.1. It is possible that I can get this to display as 1.10 in number using TO_NUMBER function instead of using TO_CHAR function? This is because all the variables and cursor to store this were declare as NUMBER datatype and I do not wanted to change the declaration (as it will impact a lot of packages)
Thanks in advance!

A: TO_NUMBER() converts text to number. Number is usually not used for display but for calculations and saved data.
TO_CHAR() converts data to text (overloaded function), where you can control how your text looks like.
So TO_NUMBER(1.10) doesn't really do anything since you are converting a number to a number.
So when displaying a number (not a text) oracle does an implicit conversion to text using default display values. So you should always use to_char to control the display of number.
Take a look at this example:
declare
   l_number   number := 1.10;
   l_text     varchar2 (10) := '200.20';
begin
   dbms_output.put_line (l_number);
   dbms_output.put_line (to_char (l_number, '9D00'));
   dbms_output.put_line (l_text);
   dbms_output.put_line (to_number (l_text));
end;

outputs:
1.1
 1.10
200.20
200.2

You see that to_char adds a space padding to the formatting. So you should use trim() if you don't want that.


text:
Q: C# Object.Equals() with multiple or conditions How can I use the Equals method, so that it checks if the user ID equals any of the IDs in someIDs? In this case, I want to get all the users where the ID is the same as the IDs in someIDs.
List<int> someIDs = someList.Select(x => x.id).ToList();
List<User> result = allUsers.Where(x => x.id.Equals(someIDs)).ToList();

This is what works, however it is hardcoded. I want it to be similar.
List<int> someIDs = someList.Select(x => x.id).ToList();
List<User> result = allUsers.Where(x => x.id.Equals(someIDs[0]) ||
                                        x.id.Equals(someIDs[1]) ||
                                        x.id.Equals(someIDs[2])
).ToList();

A: You should not override Equals to provide a method for checking the id matches a list. Instead use what is already provided on an array/list
var result = allUsers.Where(x => someIDs.Contains(x.id)).ToList();


text:
Q: Modelling services provided at location of an organization Using FHIR resources (dstu2), how can I send in the response, the healthcare services provided at a particular location when search location request is made?
Following is the location resource that I use which has no provision to send services in response. (http://hl7.org/fhir/DSTU2/location.html)
In my use-case, I have to send out location details and as part of those details, I have to send out the services offered by that location. How can I combine these two resources in my response ? I already know services that location offers but there is no place holder to send this info in response if I use location resource as my response

A: Use the HealthcareService resource.  You can do a query on HealthcareService, filtering by Location.


text:
Q: working with Node js Await/Async functions This is  my axios Request to call the API.
export function axiosGet (url) {
      return opsutils.get(url)
        .then(function (response) {
            return response.data.data;
        })
        .catch(function (error) {
            return 'An error occured..' + error;
        })
    }

From here i'm calling it asynchrously
async getDirList(data){
      this.domainDir=data.domain_name
      var apiurl="some URL"
      var stat = await axiosGet(apiurl)
      if (status){
        this.domainlog= stat
    }

From here i'm calling the async func defined above
Notify(data){
    var filelist = this.getDirList(data)
    if(filelist){
           var status =  createNotification(data.domain_name,message_stripped,'Degrading web server performance')
}

The ideal should be like this that it should go forward only after the promise is resolved ,right now the var filelist got empty.
How do i get to solve this problem ?Thanks in advance

A: The problem is this.getDirList(data) is not being accessed asynchronously as well. Remember, because that is async now, it's returning a promise, so you either need to chain it with .then():
Notify(data){
    var filelist = this.getDirList(data)
        .then(data => {
            var status = createNotification(data.domain_name,message_stripped,'Degrading web server performance')
        });

}

Or turn Notify() into an async function as well:
async Notify(data){
    var filelist = await this.getDirList(data);
    if(filelist){
           var status =  createNotification(data.domain_name,message_stripped,'Degrading web server performance')
}

Additionally, make sure you're actually returning data from getDirList so you can utilize the return value when you await it.


text:
Q: What is the meaning of <> in mysql query? I have a MySQL query that includes <> in it. I don't know the exact usage of it.
SELECT * FROM table_laef WHERE id = ? AND genre_type <> 'LIVE'

P.S.: Im sorry for this basic syntax, since I have searched for this on Google. All they give is about <=>. Thanks anyway, guys!

A: <> means NOT EQUAL TO, != also means NOT EQUAL TO. It's just another syntactic sugar. both <> and != are same.
The below two examples are doing the same thing. Query publisher table to bring results which are NOT EQUAL TO <> != USA.
SELECT pub_name,country,pub_city,estd FROM publisher WHERE country <> "USA";
SELECT pub_name,country,pub_city,estd FROM publisher WHERE country != "USA";

A: In MySQL, I use <> to preferentially place specific rows at the front of a sort request.
For instance, under the column topic, I have the classifications of 'Chair', 'Metabolomics', 'Proteomics', and 'Endocrine'. I always want to list any individual(s) with the topic 'Chair', first, and then list the other members in alphabetical order based on their topic and then their name_last.
I do this with:
SELECT scicom_list ORDER BY topic <> 'Chair',topic,name_last;

This outputs the rows in the order of:
Chair
Endocrine
Metabolomics
Proteomics
Notice that topic <> 'Chair' is used to select all the rows with 'Chair' first. It then sorts the rows where topic = Chair by name_last.*
*This is a bit counterintuitive since <> equals != based on other feedback in this post.
This syntax can also be used to prioritize multiple categories. For instance, if I want to have "Chair" and then "Vice Chair" listed before the rest of the topics, I use the following
SELECT scicom_list ORDER BY topic <> 'Chair',topic <> 'Vice Chair',topic,name_last;

This outputs the rows in the order of:
Chair
Vice Chair
Endocrine
Metabolomics
Proteomics

A: In MySQL, <> means Not Equal To, just like !=.
mysql> SELECT '.01' <> '0.01';
        -> 1
mysql> SELECT .01 <> '0.01';
        -> 0
mysql> SELECT 'zapp' <> 'zappp';
        -> 1

see the docs for more info

A: <> means not equal to, != also means not equal to.
Documentation

A: <> is Standard SQL and stands for not equal or !=.

A: <> is equal to != i.e, both are used to represent the NOT EQUAL operation. For instance, email <> '' and email != '' are same.

A: I know im late to the game but maybe this will help somebody...
this is not true even though everyone wrote it
<> is equal to !=
it actually is less than or greater than
the exception is with NULL
column <> 3 will not get null columns
column != 3 will get null columns
hope it helps


text:
Q: eliminate unwanted output using awk and sed From the following command how can i eliminate all the lines that occur before
 Owner     RepoName             CreatedDate

EDIT Command:
find /opt/site/ -name '.log.txt' | xargs cat | awk '{$NF=""; print $0}' | sed '1i Owner RepoName CreatedDate' | column -t

The output is
find: Filesystem loop detected; `/nfs/.snapshot/nightly.4' has the same device number and inode as a directory which is 2 levels higher in the filesystem hierarchy.
find: Filesystem loop detected; `/nfs/.snapshot/nightly.5' has the same device number and inode as a directory which is 2 levels higher in the filesystem hierarchy.
find: Filesystem loop detected; `/nfs/.snapshot/nightly.6' has the same device number and inode as a directory which is 2 levels higher in the filesystem hierarchy.
Owner     RepoName             CreatedDate
val        abc                  Fri          Mar  16  17:01:07  PDT
p1         repo_pc              Wed          Mar  21  11:34:42  PDT
New        fm                   Mon          Mar  19  00:15:51  PD

Required output is only:
Owner     RepoName             CreatedDate
val        abc                  Fri          Mar  16  17:01:07  PDT
p1         repo_pc              Wed          Mar  21  11:34:42  PDT
New        fm                   Mon          Mar  19  00:15:51  PD

A: Those find errors will be on stderr, so bypass your chain entirely, you'll want to redirect the errors with 2>/dev/null, although that will prevent you seeing any other errors in the find command.
find /opt/site/ -name '.log.txt' 2>/dev/null | xargs cat | awk '{$NF=""; print $0}' | xargs sed "/Filesystem/d" | sed '1i Owner RepoName CreatedDate' | column -t

In general with a complicated command like this, you should break it down when you have errors so that you can work out where the problem is coming from.
Let's split up this command to see what it's doing:
find /opt/site/ -name '.log.txt' 2>/dev/null - find all the files under /opt/site/ named .log.txt
xargs cat - get all their contents, one after the other
awk '{$NF=""; print $0}' - delete the last column
xargs sed "/Filesystem/d" - Treat each entry as a file and delete any lines containing Filesystem from the contents of those files.
sed '1i Owner RepoName CreatedDate' - Insert Owner RepoName CreatedDate on the first line
column -t - Convert the given data into a table
I'd suggest building up the command, and checking the output is correct at each stage.
Several things are surprising about your command:

*

*The find one looks for files that are exactly .log.txt rather than an extension.

*The second xargs call - converting the contents of the .log.txt files into filenames.

A: You could eliminate the error output from find by appending 2>/dev/null to the find portion of you command, prior to the first pipe.  [Edit: this is the best way, and I've voted Douglas' up as he was here first ;) ]
But if you really want to do it with sed or awk (can't think why?), you could amend your awk script to skip lines beginning with 'find:':
awk '/^find:/ {next;} {$NF=""; print $0}'

A: Sadly, you seem to be using csh or tcsh, where redirecting standard error separate from standard output is difficult. Otherwise Douglas's answer would have worked. But try this:
(find /opt/site/ -name '.log.txt' | xargs cat | awk '{$NF=""; print $0}' | sed '1i Owner RepoName CreatedDate' | column -t > output) >&/dev/null

Note the parens surrounding the bulk of the command. Within those parens is a redirect to send standard output to a file called "output" instead of to your terminal (name it whatever you want -- or replace output with /dev/tty if you really want to see it in your terminal). Outside those parens is a redirect to send the remaining error messages to /dev/null.
The whole thing is a miserable commentary on the longevity of terrible shells.

A: Next sed command should do the job (use it with an input file or from a pipe):
sed -n '/^Owner/,$ p'

Explanation:
-n             # Disable auto-print.
/^Owner/       # From a line beginning with 'Owner'...
$              # ...until end of input...
p              # print

A: This is totally doable with Awk scripting...
#!/usr/bin/awk -f

BEGIN {
  for (i = 1; i < ARGC; i++) {
    if (ARGV[i] ~ "^--from=") {
      _from = substr(ARGV[i], 8)
      delete ARGV[i]
    }
  }

  if (!_from) {
    print "No '--from' argument provided!" > "/dev/stderr"
  }
}

{

  if (_flag) {
    print $0
  } else if ($0 ~ _from) {
    _flag = 1
    print $0
  }

}

Note; above script was adapted (trimmed down) from from-till.awk which'll print between --from and --till search expressions, so added command-line options and variable names may need adjusted for this specific use case.

... which allows for the use of files as inputs...
head-trimmer.awk --from="^Owner" file-path.txt

... or re-directions such as EOF or pipes...
head-trimmer.awk --from="^Owner" <<'EOF'
find: Filesystem loop detected; `/nfs/.snapshot/nightly.4' has the same device number and inode as a directory which is 2 levels higher in the filesystem hierarchy.
find: Filesystem loop detected; `/nfs/.snapshot/nightly.5' has the same device number and inode as a directory which is 2 levels higher in the filesystem hierarchy.
find: Filesystem loop detected; `/nfs/.snapshot/nightly.6' has the same device number and inode as a directory which is 2 levels higher in the filesystem hierarchy.
Owner     RepoName             CreatedDate
val        abc                  Fri          Mar  16  17:01:07  PDT
p1         repo_pc              Wed          Mar  21  11:34:42  PDT
New        fm                   Mon          Mar  19  00:15:51  PD
EOF

... and should parse things to something like...
Owner     RepoName             CreatedDate
val        abc                  Fri          Mar  16  17:01:07  PDT
p1         repo_pc              Wed          Mar  21  11:34:42  PDT
New        fm                   Mon          Mar  19  00:15:51  PD

... Awk scripting enables easier expansion and/or adaptation for other use cases, and using it properly means that one can eliminate unnecessary calls to other programs.
It should be possible to eliminate sed and column from your pipe-line with a few more hints

The BEGIN and END blocks with Awk run at the beginning and end of all inputs, eg. a list of files, so is really good for building the header and column mappings

Using while with getline within Awk allows for parsing output of commands...
#!/usr/bin/awk -f

BEGIN {
  for (i = 1; i < ARGC; i++) {
    if (ARGV[i] ~ "^--directory=") {
      _directory = substr(ARGV[i], 13)
      delete ARGV[i]
    }
    if (ARGV[i] ~ "^--name=") {
      _name = substr(ARGV[i], 8)
      delete ARGV[i]
    }
    # ... perhaps add other args to parse
  }

  # ... build/print header maybe

}

{

  cmd = "find " _directory " -name " _name " 2>/dev/null"
  while (( cmd | getline _line ) > 0) {
    print "_line ->", _line
    # ... do some fancy formatting, use a built-in, or another command
    #     to build desired column output from find results
  }
  close(cmd)

  # ...

}

This can be supper handy when tempted to write a Bash script that's just a wrapper of a command with some custom parsing.

There are quite a few handy built-in Awk functions (more so with GAwk), eg. split, length, and it's possible to add more via the function key-word within an Awk script.

Arrays/Dictionary variables are also possible with Awk, eg...
BEGIN {
  for (i = 1; i < ARGC; i++) {
    if (ARGV[i] ~ "^--from=") {
      _custom_args["from"] = substr(ARGV[i], 8)
      delete ARGV[i]
    } else if (ARGV[i] ~ "^--till=") {
      _custom_args["till"] = substr(ARGV[i], 8)
      delete ARGV[i]
    }
  }
}

{
  # ...
}

But (if I remember correctly), multidimensional arrays such as _something[0,1] should be avoided, because in Awk such things are really _something["0,1"]

Printing columns as nicely formatted tables with Awk is a bit tricky but also doable via printf formatting options...
#!/usr/bin/awk -f

BEGIN {
  printf("%-8s %-13s %s\n", "Owner", "RepoName", "CreatedDate")
}

Essentially the %-8s is telling Awk to reserve at least 8 characters of space regardless of string length of "Owner", %-13s reserves 13, and - tells Awk to pad longer stings with a separator on the right/end of string.

To forbid longer stings printf in combination with %.<n> may be of use...
#!/usr/bin/awk -f

BEGIN {
  printf("%.3s %-13s %s\n", "Owner", "RepoName", "CreatedDate")
}

If ya get stuck feel free to comment and I'll try to swing-by again with more tips.


text:
Q: Check traffic rules in openshift We've got an OpenShift cluster with Istio in which we want to debug routing rules. But in my container I don't even have iptables utility or iptables config file with rule chains. How can I check traffic rules from within container?
Thanks in advance.

A: Since you are using istio, I assume most of the traffic goes through istio-proxy container. You can exec into istio-proxy container with
kubectl exec -it <pod-name> -c istio-proxy -- bash

and check iptables there.

Optionally you can install Kiali with
kubectl apply -f https://raw.githubusercontent.com/istio/istio/release-1.12/samples/addons/kiali.yaml

and then open it with
istioctl dashboard kiali

This will give you an insight into your Istio mesh, and routing of each of the workloads.

A: First you have to check your istio configs like virtualServices then if you want to go deeper you can  use istioctl proxy-config routes <pod-name>.


text:
Q: Dependencies in Perl code I've been assigned to pick up a webapplication written in some old Perl Legacy code, get it working on our server to later extend it. The code was written 10 years ago by a solitary self-taught developer...
The code has weird stuff going on - they are not afraid to do lib-param.pl on line one, and later in the file do /lib-pl/lib-param.pl - which is offcourse a different file.
Including a.pl with methods b() and c() and later including d.pl with methods c() and e() seems to be quite popular too... Packages appear to be unknown, so you'll just find &c() somewhere in the code later.
Interesting questions:

*

*Is there a tool that can draw relations between perl-files? Show a list of files used by each other file?

*The same for MySQL databases and tables? Can it show which schema's/tables are used by which files?

*Is there an IDE that knows which c() is called - the one in a.pl or the one in d.pl?

*How would you start to try to understand the code?

I'm inclined to go through each file and refactor it, but am not allowed to do that - only the strict minimum to get the code working. (But since the code never uses strict, I don't know if I'm gonna...)

A: Not using strict is a mistake -- don't continue it. Move the stuff in d.pl to D.pm (or perhaps a better name alltogether), and if the code is procedural use Sub::Exporter to get those subs back into the calling package. strict is lexical, you can turn it on for just one package. Such as your new package D;. To find out which code is being called, use Devel::SimpleTrace.
perl -MDevel::SimpleTrace ./foo.pl

Now any warnings will be accompanied by a full back-log -- sprinkle warnings around the code and run it.
I think the MySQL question should be removed, from this. Schema Table mappings have nothing to do with perl, it seems an out of place distraction on this question.

A: I would write a utility to scan a complete list of all subs and which file they live in; then I would write a utility to give me a list of all function calls and which file they come from.
By the way - it is not terribly hard to write a fairly mindless static analysis tool to generate a call graph.
For many cases, in well-written code, that will be enough to help me out...


text:
Q: split a string without adjacent characters that matched regex in java i am first to this site.
I want to split a string without the characters that matched in regex of string split method in java.
The string for splitting is (for eg.) : "conditional&&operator and ampersand&Symbol."
My regex-expression for spit is : "[^\\&]\\&[^\\&]"
My expectation is : [conditional&&operator and ampersand, Symbol]
But, the output is : [conditional&&operator and *ampersan, ymbol*]
The code i used is:
String s = "conditional&&operator and ampersand&Symbol.";
String[] sarr = s.split("[^\\&]\\&[^\\&]");
System.out.println(Arrays.toString(sarr));

So, please tell me what regex i should use to get the expected output, that is without the additional characters removed.

A: Your question is very similar to this one.
What you need is a negative look-behind. In your case, you could use something like:
String s = "conditional&&operator and ampersand&Symbol.";
String[] sarr = s.split("(?<!&)&(?!&)");
System.out.println(Arrays.toString(sarr));
// output: [conditional&&operator and ampersand, Symbol.]

A: I suppose it's impossible to split your string by regex as you wish.
The problem is that [^\\&]\\&[^\\&] matches 3 characters -> d&S and it splits by 3 characters, so you have them removed.
You can use Pattern and Matcher to split a string in this way:
    String s = "conditional&&operator and ampersand&Symbol.";
    final Matcher matcher = Pattern.compile("[^&]&[^&]").matcher(s);
    if (matcher.find()) {
        final int indexOfMatchStart = matcher.start();
        final String firstPart = s.substring(0, indexOfMatchStart + 1); // + 1 to include first symbol of RegEx
        final String secondPart = s.substring(indexOfMatchStart + 2); // + 2  to skip &
        System.out.println(firstPart + secondPart); // will print conditional&&operator and ampersandSymbol.
    }

A: Try this,
Long code but Basic logic.
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class B {

    public static void main(final String[] args) {

        final String x = "conditional&&operator and ampersand&Symbol.";

        final String mydata = x;
        String delimString = "";
        final Pattern pattern = Pattern.compile("[^\\&]\\&[^\\&]");
        final Matcher m = pattern.matcher(mydata);
        while (m.find()){
            delimString = m.group(0);
        }

    final String[] result = x.split(delimString); // Split using 'd&S'
    final String[] conResult = delimString.split("&"); //Split d&S in d and s
    System.out.println(result[0]+""+conResult[0]); // append d at the end of string
    System.out.println(conResult[1]+""+result[1]); // append s at the start of string

    }
}


text:
Q: Antlr4 grammar actions run on discarded parses I'm building my own AST data structure by adding actions to a grammar (just like I did with yacc, long ago---but this time, using Antlr4).  While the generated parser builds correct ASTs, it's a terrible memory hog.  A little instrumentation shows that up to 95% of the objects constructed by my actions and returned by grammar rules are discarded and don't end up in the final tree.  I suspect this is due to the generated parser using a backtracking strategy instead of relying solely on lookahead.  Is there a way to disable backtracking so I can test this hypothesis?  I'm using the antlr-csharp-4.0.1 system under Visual Studio.

A: ANTLR 4 does not use backtracking or speculative execution of actions in any scenario. Actions are only ever executed on paths that are actually parsed. Note that if you have semantic predicates, those may be executed during prediction, and may be executed multiple times.
Your version of ANTLR 4 is significantly out of date. The latest version of the C# target can be found on this page:
https://github.com/tunnelvisionlabs/antlr4cs/releases/latest


text:
Q: Add and Remove Active Class on Click but preventDefault stop the action to the href (html) CSS
$(document).ready(function () {
$('.menu li a').click(function(e) {

    $('.menu li.active').removeClass('active');

    var $parent = $(this).parent();
    $parent.addClass('active');
    e.preventDefault();
 });\[enter image description here\](https://i.stack.imgur.com/v4C2I.png)
});

html

                                Home

                                Shop

                                Blog

when run, it is work on add and remove active, but it didn't show the categories.html when click SHOP. Please help me! Thank you!


text:
Q: Long running INSERT query on SQL Server 2005 I have been sniffing out forums and blogs lately, but need some help with a long running query. It's part of a system of stored procedures. This specified statement used to run in about 5 minutes, but lately has been running up to 72 hours!
Here's the setup:
SQL Server 2005 with 28GB memory. Two mountpoints to a SAN with shared disks consisting of 10 spindles. Data is on one mountpoint, Log on another, tempdb on data space. Just one userdatabase on this server.
Here's two tables, condit and condmod. Condit contains 800K records, condmod is initially empty. I issue a truncate mcmain.condmod before the process starts, for testing purposes.
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__condit__con_notm__000AF8CF]') AND type = 'D')
BEGIN
   ALTER TABLE [mcmain].[condit] DROP CONSTRAINT [DF__condit__con_notm__000AF8CF]
END
GO

/****** Object:  Table [mcmain].[condit]    Script Date: 02/07/2012 11:57:47 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[mcmain].[condit]') AND type in (N'U'))
  DROP TABLE [mcmain].[condit]
GO

/****** Object:  Table [mcmain].[condit]    Script Date: 02/07/2012 11:57:49 ******/
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[mcmain].[condit]') AND type in (N'U'))
BEGIN
CREATE TABLE [mcmain].[condit](
    [con_levgln] [char](13) NULL,
    [con_stat] [char](4) NULL,
    [con_dscgrp] [char](35) NULL,
    [con_levart] [char](20) NULL,
    [con_desc] [char](50) NULL,
    [con_disc1] [numeric](5, 0) NULL,
    [con_disc2] [numeric](5, 0) NULL,
    [con_disc3] [numeric](5, 0) NULL,
    [con_ntprce] [numeric](9, 0) NULL,
    [con_dtstrt] [datetime] NULL,
    [con_dtend] [datetime] NULL,
    [con_volc] [char](8) NULL,
    [con_updnmr] [char](20) NULL,
    [con_notmod] [bit] NULL,
    [con_ascver] [char](5) NULL,
    [con_prddat] [datetime] NULL,
    [con_cusgln] [char](13) NULL,
    [con_cusdeb] [char](40) NULL,
    [con_rowid] [int] IDENTITY(1,1) NOT NULL
) ON [PRIMARY]
END
GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__condit__con_notm__000AF8CF]') AND type = 'D')
BEGIN
  ALTER TABLE [mcmain].[condit] ADD  DEFAULT ((0)) FOR [con_notmod]
END
GO

IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__condmod__com_not__7E22B05D]') AND type = 'D')
BEGIN
  ALTER TABLE [mcmain].[condmod] DROP CONSTRAINT [DF__condmod__com_not__7E22B05D]
END
GO

/****** Object:  Table [mcmain].[condmod]    Script Date: 02/07/2012 11:57:56 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[mcmain].[condmod]') AND type in (N'U'))
  DROP TABLE [mcmain].[condmod]
GO

/****** Object:  Table [mcmain].[condmod]    Script Date: 02/07/2012 11:57:58 ******/
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[mcmain].[condmod]') AND type in (N'U'))
BEGIN
CREATE TABLE [mcmain].[condmod](
    [com_levgln] [char](13) NULL,
    [com_stat] [char](4) NULL,
    [com_dscgrp] [char](35) NULL,
    [com_levart] [char](20) NULL,
    [com_desc] [char](50) NULL,
    [com_disc1] [numeric](5, 0) NULL,
    [com_disc2] [numeric](5, 0) NULL,
    [com_disc3] [numeric](5, 0) NULL,
    [com_ntprce] [numeric](9, 0) NULL,
    [com_dtstrt] [datetime] NULL,
    [com_dtend] [datetime] NULL,
    [com_volc] [char](8) NULL,
    [com_updnmr] [char](20) NULL,
    [com_notmod] [bit] NULL,
    [com_ascver] [char](8) NULL,
    [com_prddat] [datetime] NULL,
    [com_cusgln] [char](13) NULL,
    [com_cusdeb] [char](40) NULL,
    [com_rowid] [int] IDENTITY(1,1) NOT NULL
) ON [PRIMARY]
END
GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__condmod__com_not__7E22B05D]') AND type = 'D')
BEGIN
  ALTER TABLE [mcmain].[condmod] ADD  DEFAULT ((0)) FOR [com_notmod]
END
GO

Here's the isolated code that runs a long time:
DECLARE @TempIdTable TABLE ([com_rowid] Int PRIMARY KEY)

INSERT @TempIdTable([com_rowid])
    SELECT cmd.[com_rowid]
    FROM [mcmain].[condmod] AS cmd
    LEFT OUTER JOIN [mcmain].[condit] AS cdt
      ON con_levgln = com_levgln
     AND IsNull(con_dscgrp,'')  = IsNull(com_dscgrp,'')
     AND IsNull(con_levart,'')  = IsNull(com_levart,'')
     AND IsNull(con_volc,'')    = IsNull(com_volc,'')
     AND IsNull(con_cusgln,'')  = IsNull(com_cusgln,'')
     AND IsNull(con_cusdeb,'')  = IsNull(com_cusdeb,'')
    WHERE con_levgln is NULL

    --select * from @TempIdTable
INSERT INTO mcmain.condit(con_levgln
                ,con_stat
                ,con_dscgrp
                ,con_levart
                ,con_desc
                ,con_disc1
                ,con_disc2
                ,con_disc3
                ,con_ntprce
                ,con_dtstrt
                ,con_dtend
                ,con_volc
                ,con_notmod
                ,con_updnmr
                ,con_ascver
                ,con_cusgln
                ,con_cusdeb)
        SELECT  com_levgln
                ,com_stat
                ,com_dscgrp
                ,com_levart
                ,com_desc
                ,com_disc1
                ,com_disc2
                ,com_disc3
                ,com_ntprce
                ,com_dtstrt
                ,com_dtend
                ,com_volc
                ,com_notmod
                ,com_updnmr
                ,com_ascver
                ,com_cusgln
                ,com_cusdeb
        FROM [mcmain].[condmod] AS cmd
        INNER JOIN @TempIdTable AS tit
          ON tit.com_rowid = cmd.com_rowid

The insert into the @TempIdTable takes forever. What can I do to speed up this process?
TIA
Cees Cappelle
p.s. I have clustered indexes on both tables, like:
/****** Object:  Index [condmodTest]    Script Date: 02/07/2012 13:24:34 ******/
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[mcmain].[condmod]') AND name = N'condmodTest')
CREATE CLUSTERED INDEX [condmodTest] ON [mcmain].[condmod]
(
    [com_levgln] ASC,
    [com_dscgrp] ASC,
    [com_levart] ASC,
    [com_volc] ASC,
    [com_cusgln] ASC,
    [com_cusdeb] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
GO

If I do a straight select (just now), it takes 2 seconds.
Here's the code:
SELECT  com_levgln
        ,com_stat
        ,com_dscgrp
        ,com_levart
        ,com_desc
        ,com_disc1
        ,com_disc2
        ,com_disc3
        ,com_ntprce
        ,com_dtstrt
        ,com_dtend
        ,com_volc
        ,com_notmod
        ,com_updnmr
        ,com_ascver
        ,com_cusgln
        ,com_cusdeb
FROM mcmain.condmod
LEFT OUTER JOIN mcmain.condit
    ON  con_levgln  = com_levgln
    AND IsNull(con_dscgrp,'')   = IsNull(com_dscgrp,'')
    AND IsNull(con_levart,'')   = IsNull(com_levart,'')
    AND IsNull(con_volc,'')     = IsNull(com_volc,'')
    AND IsNull(con_cusgln,'')   =   IsNull(com_cusgln,'')
    AND IsNull(con_cusdeb,'')   =   IsNull(com_cusdeb,'')
WHERE   con_levgln is NULL

I just did a Actial Execution plan with the following code. It took 3'16'' ???
truncate table mcmain.condit

CREATE TABLE #TempIdTable ([com_rowid]  Int PRIMARY KEY)
--      DECLARE @TempIdTable TABLE
--          ([com_rowid]    Int PRIMARY KEY)

        INSERT #TempIdTable
            ([com_rowid])
        SELECT cmd.[com_rowid]
        FROM [mcmain].[condmod] AS cmd
        LEFT OUTER JOIN [mcmain].[condit] AS cdt
          ON con_levgln = com_levgln
         AND IsNull(con_dscgrp,'')  = IsNull(com_dscgrp,'')
         AND IsNull(con_levart,'')  = IsNull(com_levart,'')
         AND IsNull(con_volc,'')    = IsNull(com_volc,'')
         AND IsNull(con_cusgln,'')  = IsNull(com_cusgln,'')
         AND IsNull(con_cusdeb,'')  = IsNull(com_cusdeb,'')
        WHERE con_levgln is NULL
        -- AND      com_updnmr = @plannummer

            INSERT INTO mcmain.condit
                    (con_levgln
                    ,con_stat
                    ,con_dscgrp
                    ,con_levart
                    ,con_desc
                    ,con_disc1
                    ,con_disc2
                    ,con_disc3
                    ,con_ntprce
                    ,con_dtstrt
                    ,con_dtend
                    ,con_volc
                    ,con_notmod
                    ,con_updnmr
                    ,con_ascver
                    ,con_cusgln
                    ,con_cusdeb)
            SELECT  com_levgln
                    ,com_stat
                    ,com_dscgrp
                    ,com_levart
                    ,com_desc
                    ,com_disc1
                    ,com_disc2
                    ,com_disc3
                    ,com_ntprce
                    ,com_dtstrt
                    ,com_dtend
                    ,com_volc
                    ,com_notmod
                    ,com_updnmr
                    ,com_ascver
                    ,com_cusgln
                    ,com_cusdeb
            FROM [mcmain].[condmod] AS cmd
            INNER JOIN #TempIdTable AS tit
              ON tit.com_rowid = cmd.com_rowid

Same statement but using a tablevariable took 1'39''
When I run the sp, the same statement takes hours and hours. Still don't get it.

A: If the SELECT itself takes a long time
You could consider using NOT EXISTS rather than OUTER JOIN ... NULL as this is often more efficient.
Also I would get rid of the non sargable ISNULL comparisons.
SELECT cmd.[com_rowid]
FROM   [mcmain].[condmod] AS cmd
WHERE  NOT EXISTS (SELECT *
                   FROM   [mcmain].[condit] AS cdt
                   WHERE  con_levgln = com_levgln
                          AND EXISTS (SELECT con_dscgrp,
                                             con_levart,
                                             con_volc,
                                             con_cusgln,
                                             con_cusdeb
                                      INTERSECT
                                      SELECT com_dscgrp,
                                             com_levart,
                                             com_volc,
                                             com_cusgln,
                                             com_cusdeb))

If the SELECT runs quite quickly on its own but just not when inserting to the table variable then check whether in the quick case you get a parallel plan.
Queries that insert to table variables do not get parallelised so if that is the issue you could consider changing to a #temp table.
If neither of these suggestions help then I suggest you start monitoring the wait types when this procedure runs. See the paper "SQL Server 2005 Waits and Queues"

A: Note:  the use of @tables uses tempdb.
You should try increasing the number of temp db files... you can start with the number of tempdb files equal to the number of procs you have... but as a good starting point just jump to 10... The problem you could be having is contention for tempdb files.  You should look for page latching in tempdb.
This article discusses how the generalization I wrote above is a misconception (but not necessarily wrong) but in doing so does a good job of explaining the issue.  It also points you to other articles which give informatoin on how to look for page latching.
A SQL Server DBA myth a day: (12/30) tempdb should always have one data file per processor core


text:
Q: Is there a closed formula for Vonnegut's "chronosynclastic infundibulum-ated" Winston Niles Rumfoord? In The Sirens of Titan, a major plot point surrounds the astronaut Winston Niles Rumfoord who purposefully steered his spaceship into a "chronosynclastic infundibulum" and consequently was turned into a type of spiral spread throughout the solar system. This allows him to exist at multiple points at the same time. In the book, it is mentioned that he simultaneously exists on four celestial bodies in our solar system: Mercury, Earth, Mars, and Titan. However, he only exists on these planets/moons when his spiral intercepts them.
We can make a simplistic model of the solar system, and thus the post-chronosynclastic-infundibulum Winston Niles Rumfoord with the following. In all cases we are assuming that every heavenly body has a perfectly circular orbit and is degenerated to a singular point. Assume that all planets begin aligned on the positive x-axis.

*

*Mercury orbits the Sun making one full revolution every $87.969$ days at a radius of $0.387$ AU. Winston's spiral intercepts Mercury's orbit every $14$ days.

*Earth orbits the Sun making one full revolution every $365.256$ days at a radius of $1.000$ AU. Winston's spiral intercepts Earth's orbit every $59$ days.

*Mars orbits the Sun making one full revolution every $686.980$ days at a radius of $1.524$ AU. Winston's spiral intercepts Mars' orbit every $111$ days.

*Saturn orbits the Sun making one full revolution every $10759.220$ days at a radius of $9.583$ AU. Furthermore, Titan orbits Saturn making one full revolution every $15.945$ days at a radius of $0.00816$ AU from Saturn. Part of Winston's spiral matches up one-to-one with Titan's orbit.

I will now here break Winston's spiral into two discrete curves, $C_1$ and $C_2$. $C_1$ is the part of Winston's spiral that aligns with the orbit of Titan relative to the Sun. This is easy enough to figure out given the above parameters. In particular, $C_1$ is parameterized by
$$x(t)=9.583\cos{\biggl(\frac{2\pi t}{10759.220}\biggr)}+0.00816\cos{\bigg(\frac{2\pi t}{15.945}\bigg)},\ y(t)=9.583\sin{\biggl(\frac{2\pi t}{10759.220}\biggr)}+0.00816\sin{\bigg(\frac{2\pi t}{15.945}\bigg)}$$
Meanwhile, we know that for $k=0,1,2...$, we know that $C_2$ passes through the following points:
$$\bigg(0.378\cos{\bigg(\frac{28k\pi}{87.969}\bigg)},\ 0.378\sin{\bigg(\frac{28k\pi}{87.969}\bigg)}\bigg)$$
$$\bigg(\cos{\bigg(\frac{108k\pi}{365.256}\bigg)},\ \sin{\bigg(\frac{108k\pi}{365.256}\bigg)}\bigg)$$
$$\bigg(1.524\cos{\bigg(\frac{222k\pi}{686.980}\bigg)},\ 1.524\sin{\bigg(\frac{222k\pi}{686.980}\bigg)}\bigg)$$
Given that we have three points that we want joined by a smooth curve, I think a natural instinct would be to join them with a parabola, but this feels inappropriate given the context. My next thought was a Bezier curve, but again, this doesn't feel right. Instead, I was hoping for something more akin to a spirographic curve, but I can't figure out how to start with this.
For what it's worth, I've made a little plaything here that shows the interceptions on Mercury, Earth, and Mars, respectively. I will say that the graph is a bit deceptive because it shows the first interceptions, then all the second interceptions, and then the third, and so on, when this may not accurately reflect the path taken. For example, here it may look like the pattern is always Mercury, Earth, and Mars in sequence, while really the pattern would start

Mercury, Mercury, Mercury, Mercury, Earth, Mercury, Mercury, Mercury, Earth, Mars, Mercury...

But, then again, Vonnegut never seemed too concerned about linear time, so that may be a non-issue here too ;)
I guess you could extend this to "is there a bespoke curve that passes through a sequence of given points that lay on a series of concentric circles", but I don't know if that would be easier or harder than the question as it is posed. Thank you for your time!


text:
Q: Probability of being healthy considering three risk factors There exist $3$ risk factors $A,B,C$ in order person to be sick.Probability a person to have one of them, but not the other two is $0.1$ for each factor.The probability to have two factors but not a third is $0.14$ for every two factors.The probability to have the three factors if he has A and B is $0.33$.What is the probability a person to have no factor, if he doesn't have A?
What I have tried - so we serach for $P(H|\overline{A})$ where H is the event the person is healthy(he doesn't have any factor ) and $\overline{A}$ is the person not having the risk factor $A$.
$P(H|\overline{A})=\frac{P(AH)}{P(A)}$
$P(\overline{A}) = 1 -0.9 =0.1$
so for $P(H|\overline{A})$ and $H = \overline{A} \cap \overline{B} \cap \overline{C}$
$P( \overline{A} \cap \overline{B} \cap \overline{C}|\overline{A})$ = $\frac{P( (\overline{A} \cap \overline{B} \cap \overline{C}) \cap\overline{A})}{P(\overline{A})}$  , but how should I continue?I am not  sure if this is the right approach and how to use then the probability given that if he has A and B then the probability of C is $0.33$ and the probability $0.14$?

A: Hint: Are you familiar with Venn diagrams? You can just plot the 3 circles in this example and then fill out all the fields from the given conditions. This lets you compute easily the desired probability.


text:
Q: How to convert INDArray to Json in java? INDArray image = loader.asMatrix(file);

How to convert INDArray to Json String and from Json String to INDArray. I searched in google it  is not showing any results recording this.

A: Fiddling around I see that INDArray has a data() method (See INDArray API)
This gives you a DataBuffer which in turn has methods to export it as a Java array (See DataBuffer API)
So I reckon you should these and do:
INDArray image = loader.asMatrix(file);
DataBuffer dataBuffer = image.data();
int[] array = dataBuffer.asInt(); // or any type you want

Now you have a Java array, you can use Gson to make a Json String
Gson gson = new Gson();
String jsonString = gson.toJson(array);

I assume you can probably do the same in the other way (JSON to INDArray)
Use Gson to transform your json string into java array then create an INDArray out of it. See user guide Creating NDArrays from Java arrays

A:     INDArray matrix=  imageLoader.asMatrix(file);

    System.out.println("INDArray Original: " + matrix);
    DataBuffer buff= matrix.data();
    double[] array= buff.asDouble();

    Gson gson= new Gson();
    String imageStr= gson.toJson(array);
    ArrayList<Double> result= gson.fromJson(imageStr, ArrayList.class);

    double[] r= ArrayUtil.toArrayDouble(result);

    int[] shape = matrix.shape();
    INDArray final_array= Nd4j.create(r, shape, 'c');
    System.out.println("After Java array to INDarray: " + final_array.toString());

Complete version of code to convert INDArray to Gson and from GSON to INDArray.

A: for 2d array:
INDArray matrix = YOUR_MATRIX;
double[][] java2dArray = matrix.toDoubleMatrix();

INDArray matrix = ND4j.create(java2dArray);


text:
Q: console cout animation - C++ I would like to animate a 40x20 block of characters that I am cout-ing.  I would like to clear the console with system("cls"); and then have the next block on character instantly appear.  Currently the next block is coming on typewriter style.
The most simplest answer to my question would just to have a 20 line by 40 character oss stream cout at once, instead of doing it typewriter style.
Main.cpp:
    mazeCreator.cout();
    Sleep(5000);
    system("cls");

cout()
void MazeCreator::cout() {
    char wallChar = (char) 219;
    char pavedChar = (char) 176;
    char lightChar = ' ';
    char startChar = 'S';
    char finishChar = 'F';
    char errorChar = '!';
    char removedWallChar = 'R';
    char landmarkLocationChar = 'L';

    ostringstream oss;
    for (int row = 0; row < rows; row++) {
        oss << " ";
        for (int col = 0; col < columns; col++) {
            if (mazeArray[row][col] == wall)
                oss << wallChar;
            else if (mazeArray[row][col] == paved)
                oss << pavedChar;
            else if (mazeArray[row][col] == light)
                oss << lightChar;
            else if (mazeArray[row][col] == start)
                oss << startChar;
            else if (mazeArray[row][col] == finish)
                oss << finishChar;
            else if (mazeArray[row][col] == removedWall)
                oss << removedWallChar;
            else if (mazeArray[row][col] == landmarkLocation)
                oss << landmarkLocationChar;
            else
                oss << errorChar;
        }
        oss << "\n";
    }
    oss << "\n\n";

    cout << oss.str();
}

A: You could maintain two 2D arrays in your code, one with the current block of characters on the screen (let's call it cur) and one with the next block (let's call it next).
Assume cur stores the block that's on screen right now. Set up the next block by writing into the next array. When you're ready to put it on the screen, loop through cur and next simultaneously, and only for characters where they differ, use SetConsoleCursorPosition to jump to that location and write the new character.
Once you've done that, copy the contents of next into cur and move on to the next block.
UPDATE: Here's an example:
class console_buffer
{
public:
    console_buffer(int rows, int columns)
                   // start out with spaces
                 : cur(rows, vector<char>(columns, ' ')),
                   next(rows, vector<char>(columns, ' '))
    {
    }

    void sync()
    {
        // Loop over all positions
        for (int row = 0; row < cur.size(); ++row)
            for (int col = 0; col < cur[row].size(); ++col)

                // If the character at this position has changed
                if (cur[row][col] != next[row][col])
                {
                    // Move cursor to position
                    COORD c = {row, col};
                    SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), c);

                    // Overwrite character
                    cout.put(next[row][col]);
                }

         // 'next' is the new 'cur'
         cur = next;
    }

    void put(char c, int row, int col)
    {
        next[row][col] = c;
    }
private:
    vector<vector<char> > cur;
    vector<vector<char> > next;
};

...

int main()
{
    console_buffer buf(40, 20);

    // set up first block
    ... some calls to buf.put() ...

    // make first block appear on screen
    buf.sync();

    // set up next block
    ... some calls to buf.put()

    // make next block appear on screen
    buf.sync();

    // etc.
}

A: You can implement double buffering using CreateConsoleScreenBuffer. Something along these lines should work. I've used this once, quite a while ago, so it might not be perfect.
HANDLE current = GetStdHandle (STD_OUTPUT_HANDLE);

HANDLE buffer = CreateConsoleScreenBuffer (
    GENERIC_WRITE,
    0,
    NULL,
    CONSOLE_TEXTMODE_BUFFER,
    NULL
);

WriteConsole (/*fill with what you're drawing*/);

system ("cls"); //clear this screen before swapping
SetConsoleActiveScreenBuffer (buffer);

WriteConsole (/*do it to the other one now*/);

system ("cls");
SetConsoleActiveScreenBuffer (current); //swap again

//repeat as needed

CloseHandle (buffer); //clean up


text:
Q: Adding a line at an interval in ChartJS? I have a chart on my web site that shows user per hour per day, but for ease of reading I'd like to put a line at each new day on the graph.
How do I go about doing this? I just really need a starting point but so far all of my Google searches are to broad.
Thanks in advance,
T.


text:
Q: Eclipse PDE - Plug-in, Feature, and Product Versioning I am having much confusion over the process of upgrading version numbers in dependent plug-ins, features, and products in a fairly large eclipse workspace.
I have made API changes to java code residing in an existing plug-in and thus requires an increase of the Major part of the version identifier.  This plug-in serves as a dependency to a given feature, where the feature is later included in a product.  From the documentation at http://wiki.eclipse.org/Version_Numbering, I understand (for the most part) when the proper number should be increased on the containing plug-in itself.
However, how would this Major version number change on the plug-in affect dependent, "down-the-line" items (e.g., features, products)?
For example, assume we have the typical "Hello World" setup as follows:
Plug-in: com.example.helloworld, version 1.0.0
Feature: com.example.helloworld.feature, version 1.0.0
Product: com.example.helloworld.product, version 1.0.0
If I were to make an API change in the plug-in, this would require a version update to be that of 2.0.0.  What would then be the version of the feature, 1.1.0?  The same question can be applied for the product level as well (e.g., if the feature is 1.1.0 OR 2.0.0, what is the product version number)?
I'm sure this is quite the newbie question so I apologize for wasting anyone's time and effort.  I have searched for this type of content but all I am finding is are examples showing how to develop a plug-in, feature, product, and update site for the first time.  The only other content related to my search has been developing feature patches and have not touched on the versioning aspect as much as I would prefer.  I am having difficulty coming into (for the first time) an Eclipse RCP / PDE environment and need to learn the proper way and / or best practices for making such versioning updates and how to best reflect this throughout other dependent projects in the workspace.

A: If you would like to apply the same versioning systems to feature and product, then you would set feature and product to 2.0.0 when one of the plugins go to 2.0.0. That would communicate to whoever is consuming your feature or product that there is a breaking API change inside it somewhere.
On the other hand, there is no requirement to apply the same versioning convention. You can version your bundles following that convention to properly communicate your API changes and then turn around and use more marketing-sensible versions for product/feature. Keep in mind that user will see product/feature version more than they will individual bundle version.
I've seen it done both ways effectively. There isn't really a right or wrong way on this.