Q: menu accordion with first voice open i have this menu
I can not copy the code of the menu on the topic , so I put everything on jsfiddle , Practically What I would like the menu stays open without clicking on ParalleloR so I would like the open class is fixed on the first menu item

(function ($) {
    $(document).ready(function () {
        $('#cssmenu li.has-sub>a').on('click', function () {
            $(this).removeAttr('href');
            var element = $(this).parent('li');
            if (element.hasClass('open')) {
                element.removeClass('open'); element.find('li').removeClass('open');
                element.find('ul').slideUp();
            }
            else {
                element.addClass('open');
                element.children('ul').slideDown(); element.siblings('li').children('ul').slideUp(); element.siblings('li').removeClass('open'); element.siblings('li').find('li').removeClass('open'); element.siblings('li').find('ul').slideUp();
            }
        });
        $('#cssmenu>ul>li.has-sub>a').append('');
        (function getColor() {
            var r, g, b;
            var textColor = $('#cssmenu').css('color');
            textColor = textColor.slice(4);
            r = textColor.slice(0, textColor.indexOf(','));
            textColor = textColor.slice(textColor.indexOf(' ') + 1);
            g = textColor.slice(0, textColor.indexOf(','));
            textColor = textColor.slice(textColor.indexOf(' ') + 1);
            b = textColor.slice(0, textColor.indexOf(')'));
            var l = rgbToHsl(r, g, b);
            if (l > 0.7) {
                $('#cssmenu>ul>li>a').css('text-shadow', '0 0px 0px rgba(0, 0, 0, .0)');

            }
            else {
                $('#cssmenu>ul>li>a').css('text-shadow', '0 0px 0 rgba(255, 255, 255, .0)');

            }
        })();
        function rgbToHsl(r, g, b) {
            r /= 255, g /= 255, b /= 255;
            var max = Math.max(r, g, b), min = Math.min(r, g, b);
            var h, s, l = (max + min) / 2;
            if (max == min) {
                h = s = 0;
            }
            else {
                var d = max - min;
                s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
                switch (max) {
                    case r: h = (g - b) / d + (g < b ? 6 : 0); break;
                    case g: h = (b - r) / d + 2; break;
                    case b: h = (r - g) / d + 4; break;
                }
                h /= 6;
            }
            return l;
        }
    });
})(jQuery);
.widget-area .widget {
    padding: 40px 10px 40px 0px;
}

#cssmenu,
#cssmenu ul,
#cssmenu ul li,
#cssmenu ul li a {
    margin: 0;
    padding: 0;
    border: 0;
    list-style: none;
    line-height: 1;
    display: block;
    position: relative;
    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    box-sizing: border-box;
}

#cssmenu {
    width: 100%;
    font-family: Roboto;
    color: #ffffff;
}

    #cssmenu ul ul {
        display: none;
    }

.align-right {
    float: right;
}

#cssmenu > ul > li > a {
    padding: 15px 25px 16px 10px;
    border-top: 1px solid #CACACA;
    cursor: pointer;
    z-index: 2;
    font-size: 12px;
    font-weight: 300;
    text-decoration: none;
    color: #000000;
    /*background: #F9F9F9;*/
}

    #cssmenu > ul > li > a:hover,
    #cssmenu > ul > li.active > a,
    #cssmenu > ul > li.open > a {
        color: #000000;
    }

#cssmenu > ul > li.open > a {
    box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.15), 0 1px 5px rgba(0, 0, 0, 0.15);
    border-bottom: 0px solid #1682ba;
}

#cssmenu > ul > li:last-child > a,
#cssmenu > ul > li.last > a {
    border-bottom: 0px solid #1682ba;
}

.holder {
    width: 0;
    height: 0;
    position: absolute;
    top: 0;
    right: -11px;
}

    .holder::after,
    .holder::before {
        display: block;
        position: absolute;
        content: "";
        width: 6px;
        height: 6px;
        right: 20px;
        z-index: 10;
        -webkit-transform: rotate(-135deg);
        -moz-transform: rotate(-135deg);
        -ms-transform: rotate(-135deg);
        -o-transform: rotate(-135deg);
        transform: rotate(-135deg);
    }

    .holder::after {
        top: 17px;
        border-top: 2px solid #000;
        border-left: 2px solid #000;
    }

#cssmenu > ul > li > a:hover > span::after,
#cssmenu > ul > li.active > a > span::after,
#cssmenu > ul > li.open > a > span::after {
    border-color: #eee;
}

.holder::before {
    top: 18px;
    border-top: 2px solid;
    border-left: 2px solid;
    border-top-color: inherit;
    border-left-color: inherit;
}

#cssmenu ul ul li a {
    cursor: pointer;
    border-bottom: 1px solid #F5F5F5;
    /* border-left: 1px solid #32373e; */
    /* border-right: 1px solid #32373e; */
    padding: 12px 42px 12px 16px;
    z-index: 1;
    text-decoration: none;
    font-size: 13px;
    color: #32373e;
    background: #FFFFFF;
    box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.1);
}

#cssmenu ul ul li:hover > a,
#cssmenu ul ul li.open > a,
#cssmenu ul ul li.active > a {
    background: rgb(255, 255, 255);
    color: #23282d;
}

#cssmenu ul ul li:first-child > a {
    box-shadow: none;
}

#cssmenu ul ul ul li:first-child > a {
    box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.1);
}

#cssmenu ul ul ul li a {
    padding-left: 30px;
}

#cssmenu > ul > li > ul > li:last-child > a,
#cssmenu > ul > li > ul > li.last > a {
    border-bottom: 0;
}

#cssmenu > ul > li > ul > li.open:last-child > a,
#cssmenu > ul > li > ul > li.last.open > a {
    border-bottom: 0px solid #32373e;
}

#cssmenu > ul > li > ul > li.open:last-child > ul > li:last-child > a {
    border-bottom: 0;
}

#cssmenu ul ul li.has-sub > a::after {
    display: block;
    position: absolute;
    content: "";
    width: 5px;
    height: 5px;
    right: 20px;
    z-index: 10;
    top: 11.5px;
    border-top: 2px solid #000;
    border-left: 2px solid #000;
    -webkit-transform: rotate(-135deg);
    -moz-transform: rotate(-135deg);
    -ms-transform: rotate(-135deg);
    -o-transform: rotate(-135deg);
    transform: rotate(-135deg);
}

#cssmenu ul ul li.active > a::after,
#cssmenu ul ul li.open > a::after,
#cssmenu ul ul li > a:hover::after {
    border-color: #000;
}

.subsubm {
    padding-left: 44px !important;
    background-color: #FFFFFF !important;
    border: 1px !important;
    color: black !important;
}

ParalleloR

Consulenza legale in outsourcing per aziende

Modello contratto di outsourcing

Temporary management

Consulenza società estere

Consulenza crisi aziendale

Consulenza risanamento aziendale e rilancio

Cpnsulenza ristrutturazione del debito

https://jsfiddle.net/exolon82/vpfLf78s/3/
I can not copy the code of the menu on the topic , so I put everything on jsfiddle , Practically What I would like the menu stays open without clicking on ParalleloR so I would like the open class is fixed on the first menu item

A: Just add this style
#cssmenu > ul > li > ul{display: block!important;}

Here is the FIDDLE

A: if you need the first menu to open on page load and you still want it to work as an accordion, trigger click event, on first menu item in top accordion, onload.
$('#cssmenu li.has-sub>a').on('click', function(){
...
});
$('#cssmenu>ul>li.has-sub>a').click();

check the fiddle


Q: PHP getting expiring time of a cookie Can I get the expiring time of a cookie which is already set?
For example, I have set a cookie:
setcookie("test_cookie","some value", time()+3600*24*30);

Now can i get the time when the test_cookie is expiring?
One option could be that when i set the test_cookie, i can set the expiring time in another cookie, but i'm wondering if there's alternative, better way without setting other cookie?
Thanks.

A: Setting it in another cookie is the best method, that or simply appending it to the end of the data you're storing with a delimeter such as #.

A: There's no way to get the expiry time because the browser doesn't send it. So the olny way is to store the time somewhere in another cookie or in session maybe.

A: Check this link How to get cookie's expire time
cookie expiration date can be set in another cookie.This cookie can then be read later to get the expiration date


Q: Integração do JSON com Swift Queria saber como eu faço para passar um JSON com a minha URL para Swift.
Eu tenho um como exemplo: http://peps.com.br/pips/teste2.json e se alguém puder fazer o começo da minha JSON na linguagem Swift já me ajudaria bastante pois não estou conseguindo sair do lugar.

então , na minha empresa a gente tem que integrar um JSON que eu passei o link na pergunta pra vocês verem e que faca aparecer no compilador do XCODE com a linguagem SWIFT as informações desta JSON , mas ta complicado , eu queria que pelo menos alguem fizesse a primeira parte disso para eu dar continuidade , pois ainda não me abriu a cabeça amplamente como integrar isso !

A: Outra solução:
Tente isso no seu Playground do Xcode 6.1.1. No Playground é rapido de testar, depois você migra pro seu projeto.
import Foundation
let jsonObject: [AnyObject] = [
  ["name": "João", "age": 20],
  ["name": "Pedro", "age": 45],
]
func JSONStringify(jsonObj: AnyObject) -> String {
  var e: NSError?
  let jsonData: NSData! = NSJSONSerialization.dataWithJSONObject(
    jsonObj,
    options: NSJSONWritingOptions(0),
    error: &e)
  if e != nil {
    return ""
  } else {
    return NSString(data: jsonData, encoding: NSUTF8StringEncoding)
  }
}
let jsonString = JSONStringify(jsonObject)
println(jsonString)

Funciona no Mavericks e no Yosemite
Desta forma funciona pois você está delegando o trabalho de serialização à classe NSJSONSerialization da biblioteca padrão
Ou seja, seu código Swift é apenas um Wrapper.
A deserialização também pode ser feita de forma análoga.

A: Rafael, em um de nossos projetos, que eh uma app bem complexa, utilizamos o SwiftyJSON. Sua utilizacao eh tao simples quanto
let json = JSON(data: dataFromNetworking)

Depois voce vai pegando os valores por subscript:
let userId = json["compromissos"][0]["usuario_id"].intValue
let userName = json["compromissos"][0]["usuario_nome"].stringValue

Isso de modo bem simplificado, porque voce provalmente vai utilizar arrays:
let appointments = json["compromissos"].arrayValue

Para fazer os requests utilizamos o AFNetworking, mas voce pode utilizar o Alamofire conforme esta na pagina do SwitfyJSON.

A: Rafael, tentei criar um exemplo para tentar sanar sua dúvida utilizando outra possibilidade o Codable, esse json representa um objeto que queremos utilizar no nosso projeto, na segunda imagem é como representaremos o objeto no código. Utilizando o Encodable, é possível você criar um json a partir de um objeto Swift e o Decodable é utilizado para você converter o json em um objeto no Swift. Para finalizar, como sua tarefa é apenas a realização da decodificação você deve pegar o Data obtido na sua requisição e tentar converte-lô para sua struct.

Caso continue com dúvidas, esse é o link da documentação oficial -https://developer.apple.com/documentation/foundation/archives_and_serialization/encoding_and_decoding_custom_types


Q: Why using array in command cancels output redirection? I have this (simplified) code:
elems="${array[@]}"
do_cmd "xxx" "for_each \"$elems\" func" ">> $log_file" || return $?

which redirects output to $log_file (as expected).
However, if the code above is simplified as:
do_cmd "xxx" "for_each \"${array[@]}\" func" ">> $log_file" || return $?

then the output is no longer redirected to $log_file (instead it outputs to stdout).
Any ideas why?
Note: internally do_cmd uses eval. The for_each is:
for_each()
{
  local elems=$1
  local func_and_args=$2

  for elem in $elems
  do
    $func_and_args $elem
  done
}

A: Why The Original Code Broke
When you put ${array[@]} in a context that can only ever evaluate to a single string, it acts just like ${array[*]}. This is what your "working" code was doing (and why it wouldn't keep looking like it was working if your array values had spaces in their values or were otherwise at all interesting).
When you put ${array[@]} in a context that evaluates to multiple words (like a command), it generates breaks between words at every boundary between the individual array items.
Thus, your string starting with for_each was split up into several different arguments, rather than passing the entire array's contents at once; so the redirection was no longer present in do_cmd's $3 at all.

How To Do This Well
Starting with some general points:

*

*Array contents are data. Data is not parsed as syntax (unless you use eval, and that opens a can of worms that the whole purpose of using arrays in bash is to avoid).

*Flattening your array into a string (string=${array[@]}) defeats all the benefits that might lead you to use an array in the first place; it behaves exactly like string=${array[*]}, destroying the original item boundaries.

*To safely inject data into an evaled context, it needs to be escaped with bash 5.0's ${var@Q}, or older versions' printf %q; there's a lot of care that needs to be taken to do that correctly, and it's much easier to analyze code for correctness/safety if one doesn't even try. (To expand a full array of items into a single string with eval-safe escaping for all in bash 5.0+, one uses ${var[*]@Q}).

Don't do any of that; the primitives you're trying to build can be accomplished without eval, without squashing arrays to strings, without blurring the boundary between data and syntax. To provide a concrete example:
appending_output_to() {
  local appending_output_to__dest=$1; shift
  "$@" >>"$appending_output_to__dest"
}

for_each() {
  local -n for_each__source=$1; shift
  local for_each__elem
  for for_each__elem in "${for_each__source[@]}"; do
    "$@" "$for_each__elem"
  done
}

cmd=( redirecting_to "$log_file" func )
array=( item1 item2 item3 )
for_each array "${cmd[@]}"

(The long variable names are to prevent conflicting with names used by the functions being wrapped; even a local is not quite without side effects when a function called from the function declaring the local is trying to reuse the same name).


Q: Android Studio - Failed to refresh Gradle project - failed to find target 4.4w
I'm trying to move my project from eclipse into android studio so that I can start building an android wear app.  I exported the app from eclipse and imported it into android studio.  However, when I try and add the android wear app, I start getting the error message "failed to find target 4.4w" see screen shot.
When creating a brand new project, this error does not occur.  I noticed that i'm still running on android api 19 for external libraries, but I can't upgrade it since it can't find it.
The 4.4w is installed via sdk manager, why can't android studio see this?

A: For some reason, the wear project had '4.4w' as the build target, i updated this to 20 and the error went away.


Q: How do I Add PHP code in WordPress POST without using a plugin I am trying to add php code(2000 lines) to WordPress post manually without using any plugin or third party tool. But I have not been successful in this... If anybody knows how I can do this please feel free to post an answer. So far I have been able to add my php code to WP Page but not WP Post. I will be looking forward to you! Thanks!

A: I was able to do this by creating a separate .php file in my theme "twentytwentytwo" folder and then I pasted the following code in it...
"<?php
/*

*

*Template Name: new Theme

*Template Post Type: post
*/
?>"
""
""
By doing this I created a Separate theme for my post. Then simple pasted my php code under the get_header() line....
After this I logged in to my WP admin and clicked on the edit post and in the template dropdown section I found my theme name "new Theme" just selected that and published. Job done!

A: Use 'the_content' filter https://developer.wordpress.org/reference/hooks/the_content/
example :
function custom_content($content)
{
    global $post;

    if ($post && $post->post_type == 'post') {

        if ($post->ID == '145'()) { // target a specific post by ID
            // do something
        }
    }

    return $content;
}
add_filter('the_content', 'custom_content');


Q: Lighted garage door pushbutton? I have seen lighted garage door opener pushbuttons for wall-mounted wired garage door openers. I think there is an LED inside.
What other components are needed? What is the circuit?

A: Measure the open circuit voltage across the switch contacts twice (a meter in both AC and DC modes) and report back.
Don't know about new ones, but many old openers ran the control system on 24 Vac or 28 Vac.  For mine (1972-ish), the open circuit voltage is 28 Vac, and the short circuit current (switch contacts closed) is 0.63 A.  This is the coil current for the relay that starts things moving.  I have to pull almost 100 mA through the loop before I hear a hum coming from the motor head (the relay armature starting to chatter).  Because of all of this, I have a door control system that uses less than 30 mA, and runs on the open circuit switch loop.
If any of this applies to your situation, you can have two LEDs, or one LED and one rectifier diode, back to back, in series with an appropriate current limiting resistor.

A: OK -- so I measured (system is from ~ 1996). There are 2 wires (red and black). Red is -18 V to Black (seems opposite to usual usage). Short circuit current is 10 mA. It requires a ~ 50 Ω short to trigger the button action (about 0.5 V across the switch or less); approaching this slowly doesn't seem to trigger.
So no other components are needed. Just a LED (with the correct polarity) across the wires (in parallel with the pushbutton) is OK. The LED's current will be about 10 mA (which is sufficiently bright), and the VF of the LED is well over 1.5 V, so the LED alone doesn't activate the button.


Q: Running two loops at the same time ? moving and traveling using loops I am a first year Computer Engineer so I am a little bit amatuer in coding C++, anyway I am creating a game where there are two spaceships shooting each other. I currently succeeded making the first spaceship move by using a while loop and the GetASyncKeyState function. but now I am making the bullets travel. I used  for loop, and I did succeed in making the bullet travel upward. But there's a problem, I can't move the spaceship until the for loop stop or the bullet reach the top of the console window (I am using console btw). is there a way to both run the for loop and while at the same time ? or to run two different function at the same time since GameMovement() is for the movement of spaceship and BulletTravel() is for the bullet. and I am calling BulletTravel() from GameMovement().
void GameMovements()
{
bool FirstInitialization = true;
int Player1XCoordinate = 55, Player2XCoordinate = 55;
int Player1YCoordinateU = 28, Player1YCoordinateD = 29;

while (true)
{
    BulletPattern(Player1XCoordinate);

    if (FirstInitialization == true)
    {
        GameBorderAndStatus();
        SetCoordinate(Player1XCoordinate, Player1YCoordinateU);
        cout << "   ^  \n";
        SetCoordinate(Player1XCoordinate, Player1YCoordinateD);
        cout << "^==|==^ \n";
        FirstInitialization = false;
    }

    //MOVEMENTS FOR PLAYER 1
    else if (GetAsyncKeyState(VK_LEFT) && Player1XCoordinate != 16)
    {
        system("cls");
        GameBorderAndStatus();

        Sleep(10);
        Player1XCoordinate -= 3;
        SetCoordinate(Player1XCoordinate, Player1YCoordinateU);
        cout << "   ^  \n";
        SetCoordinate(Player1XCoordinate, Player1YCoordinateD);
        cout << "^==|==^ \n";
    }
    else if (GetAsyncKeyState(VK_RIGHT) && Player1XCoordinate != 94)
    {
        system("cls");
        GameBorderAndStatus();
        Player1XCoordinate += 3;

        Sleep(10);
        SetCoordinate(Player1XCoordinate, Player1YCoordinateU);
        cout << "   ^  \n";
        SetCoordinate(Player1XCoordinate, Player1YCoordinateD);
        cout << "^==|==^ \n";
    }
    else if (GetAsyncKeyState(VK_UP) && Player1YCoordinateU != 24)
    {
        system("cls");
        GameBorderAndStatus();
        Player1YCoordinateU -= 2;
        Player1YCoordinateD -= 2;

        Sleep(10);
        SetCoordinate(Player1XCoordinate, Player1YCoordinateU);
        cout << "   ^  \n";
        SetCoordinate(Player1XCoordinate, Player1YCoordinateD);
        cout << "^==|==^ \n";
    }
    else if (GetAsyncKeyState(VK_DOWN) && Player1YCoordinateU != 28)
    {
        system("cls");
        GameBorderAndStatus();
        Player1YCoordinateU += 2;
        Player1YCoordinateD += 2;

        Sleep(10);
        SetCoordinate(Player1XCoordinate, Player1YCoordinateU);
        cout << "   ^  \n";
        SetCoordinate(Player1XCoordinate, Player1YCoordinateD);
        cout << "^==|==^ \n";
    }

 }
}

void GameBorderAndStatus()
{
       //Draw game border
      for (int i = 0; i < 31; i++)
      {
         SetCoordinate(15, i);
         cout << "|";
         SetCoordinate(104, i);
         cout << "|";
      }

 }

void BulletPattern(int Player1MuzzleLocation)
{
    for (int i = 25; i != 3; i--)
    {
       Sleep(100);
       SetCoordinate(Player1MuzzleLocation + 3, i);

    }
}

 void SetCoordinate(int CoordinateX, int CoordinateY)
 {
     COORD Coordinate;
     Coordinate.X = CoordinateX;
     Coordinate.Y = CoordinateY;
     SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), Coordinate);
 }

A: Rather than using two different functions and moving one object within each, you might find better results keeping track of where each object should be, and using one function to draw both.
It's a little hard to tell what's going on in your code since some functions and variable declarations are missing (I don't see you ever actually drawing a bullet, for example - might be a bug in your BulletPattern?), but something like this might do the trick:
void GameMovements()
{
    while (true)
    {
        //MOVEMENTS FOR PLAYER 1
        if (GetAsyncKeyState(VK_LEFT) && Player1XCoordinate != GAMEBOARD_LEFT)
        {
            Player1XCoordinate -= 3;
        }
        else if (GetAsyncKeyState(VK_RIGHT) && Player1XCoordinate != GAMEBOARD_RIGHT)
        {
            Player1XCoordinate += 3;
        }
        else if (GetAsyncKeyState(VK_UP) && Player1YCoordinate != SPACESHIP_TOP)
        {
            Player1YCoordinate -= 2;
        }
        else if (GetAsyncKeyState(VK_DOWN) && Player1YCoordinate != SPACESHIP_BOTTOM)
        {
            Player1YCoordinate += 2;
        }

        Sleep(10);

        UpdateBulletPosition();
        DrawObjects();
    }
}

void UpdateBulletPosition()
{
  //if the bullet hits the top of the screen, remove it
  if (bulletYCoordinate == GAMEBOARD_TOP)
  {
      bulletXCoordinate = 0;
      bulletYCoordinate = 0;
  }

  //I assume you're automatically generating bullets whenever possible; you'll have to adjust this conditional if that's not the case

  //no bullet? generate one
  if (bulletXCoordinate == 0)
  {
      bulletXCoordinate = Player1XCoordinate + 3;
      bulletYCoordinate = 25;
  }
  else
  {
      bulletYCoordinate--;

      Sleep(100);
  }
}

void DrawObjects()
{
        //wipe the screen and show status first
        system("cls");
        GameBorderAndStatus();

        SetCoordinate(Player1XCoordinate, Player1YCoordinate);
        cout << "   ^  \n";
        SetCoordinate(Player1XCoordinate, Player1YCoordinate + 1);
        cout << "^==|==^ \n";

        //only draw the bullet if there's a bullet there to draw
        if (bulletXCoordinate != 0)
        {
            SetCoordinate(bulletXCoordinate, bulletYCoordinate);
            cout << ".\n";
        }
}

const int GAMEBOARD_LEFT = 16;
const int GAMEBOARD_RIGHT = 94;
const int GAMEBOARD_TOP = 3;
const int SPACESHIP_TOP = 24;
const int SPACESHIP_BOTTOM = 28;

int Player1XCoordinate = 55, Player2XCoordinate = 55;
int Player1YCoordinate = 28;
int bulletXCoordinate = 0, bulletYCoordinate = 0;

I also made some tweaks to the rest of your code. Every case in your if-else block used the same basic drawing code, so I pulled that out of the if-else entirely. That also let me drop the entire initialization if-else.
I also dropped one of your vertical coordinates for the spaceship. You really don't need two; just keep track of the upper coordinate and draw the lower half of the ship at Player1YCoordinate + 1.
Finally, I replaced your hardcoded board edges with constants. Magic numbers are generally frowned upon; using named constants makes it easier to determine why you're using a given value in a given location, as well as making it easier to update the code in the future (perhaps you need to update for a different console size).


Q: LUIS not returning the correct entity values I am trying to learn how to use LUIS to train for an intent to search my data on my database using NLP. I created an Intent UIM.Search and added the following Utterance for which the token view is as below:

I mapped them to the entities so that I can get the actual user values for API based queries as shown below

Issue I am having is when I use the testing panel and enter texts like:
show customers in paris for chocolatemagic the entities it returns are as below

where as when I enter an exact phrase used for training I get the correct result like:
show me cakemagic customers from bangalore
returns

Can someone please help me understand what am I missing here to translate the user query to actual intent and then get the query parameters as entities to convert to SQL queries.
EDIT1:
Adding the Model details, but this time including the Phrases, which actually works. But this is not something i would like to do as then i'll have to add all possible combinations of words that can be used in the query
    {
  "luis_schema_version": "3.1.0",
  "versionId": "0.1",
  "name": "UIM",
  "desc": "",
  "culture": "en-us",
  "intents": [
    {
      "name": "None"
    },
    {
      "name": "UIM.Search"
    }
  ],
  "entities": [
    {
      "name": "address.city",
      "roles": []
    },
    {
      "name": "address.country",
      "roles": []
    },
    {
      "name": "count",
      "roles": []
    },
    {
      "name": "search.order",
      "roles": []
    },
    {
      "name": "search.type",
      "roles": []
    },
    {
      "name": "subsidiary",
      "roles": []
    }
  ],
  "composites": [
    {
      "name": "address",
      "children": [
        "address.city",
        "address.country"
      ],
      "roles": []
    }
  ],
  "closedLists": [],
  "patternAnyEntities": [],
  "regex_entities": [],
  "prebuiltEntities": [
    {
      "name": "number",
      "roles": []
    }
  ],
  "model_features": [
    {
      "name": "company Names",
      "mode": true,
      "words": "honeywell,chocolatemagic,boeing,jeppesen,cakemagic",
      "activated": true
    },
    {
      "name": "City Names",
      "mode": true,
      "words": "bangalore,paris,london,bellevue,berlin,amsterdam,rome,new york,madrid,moscow,sydney,tokyo,kirkland,redmond,frankfurt,barcelona,milan,vienna,prague,brussels,athens,lisbon,stockholm,munich,zurich,budapest,warsaw,copenhagen,dublin,hamburg,istanbul,oslo,bucharest,venice,helsinki,shanghai,geneva,beijing,zagreb,malaga,luxembourg,sofia,kiev,manchester,buenos aires,bangkok,singapore,tallinn,riga,seoul,melbourne,vilnius,toronto,cairo,dubai,los angeles,san francisco,montreal,vancouver,chicago,boston,mumbai,johannesburg,rio de janeiro,miami,seattle,new orleans,san diego,las vegas,houston,philadelphia,atlanta,dallas,denver,orlando,tampa,jacksonville,washington,detroit,phoenix,memphis,cleveland,pittsburgh,portland,baltimore,richmond,madison,nashville,san antonio,sacramento,charlotte,austin,indianapolis,minneapolis,columbus,buffalo,oakland,louisville,cincinnati,newark,milwaukee,san jose,birmingham,raleigh",
      "activated": true
    },
    {
      "name": "Country Names",
      "mode": true,
      "words": "india,usa,uk,france,australia,germany,u.s.a.,u.k.,ireland,austria,finland,denmark,spain,netherlands,sweden,italy,poland,norway,greece,cyprus,belgium,belfast,switzerland,russia,malta,romania,hungary,slovenia,croatia,portugal,european,iceland,slovakia,bulgaria,prague,serbia,estonia,lithuania,latvia,ukraine,albania,armenia,moldova,belarus,kazakhstan,ghana,uruguay,azerbaijan,moscow,paraguay,montenegro,eurovision,venezuela,algeria,burkina,cameroon,tunisia,guatemala,honduras,lesotho,angola,bolivia,nicaragua,grenada,liberia,tanzania,ecuador,cuba,tobago,zimbabwe,ethiopia,rwanda,trinidad,fiji,mozambique,guyana,namibia,belize,haiti,barbados,cambodia,mauritania,mauritius,uganda,maldives,nigeria,kenya,botswana,bahamas,vanuatu,seychelles,africa",
      "activated": true
    },
    {
      "name": "Entity Names",
      "mode": true,
      "words": "customers,suppliers,fleets,transactions,companies,services,employees,retailers,manufacturers,partners,fleet,products,transaction,events,contact,projects,clients,programs,facilities,client,consultant",
      "activated": true
    },
    {
      "name": "Services Names",
      "mode": true,
      "words": "parts,services,planes,applications,components,systems,subsystems,sensors,software,equipment,accessories,electronics,cakes",
      "activated": true
    }
  ],
  "regex_features": [],
  "patterns": [
    {
      "pattern": "show me {subsidiary} from {search.type} in {address.city}",
      "intent": "UIM.Search"
    },
    {
      "pattern": "show me {count} {search.type} from {address.city} in {address.country}",
      "intent": "UIM.Search"
    },
    {
      "pattern": "show me all {search.type} from {address.city}",
      "intent": "UIM.Search"
    }
  ],
  "utterances": [
    {
      "text": "show 4 customers who bought cakes",
      "intent": "UIM.Search",
      "entities": [
        {
          "entity": "search.type",
          "startPos": 7,
          "endPos": 15
        },
        {
          "entity": "search.order",
          "startPos": 28,
          "endPos": 32
        }
      ]
    },
    {
      "text": "show 5 customers who bought cakes from bangalore",
      "intent": "UIM.Search",
      "entities": [
        {
          "entity": "search.type",
          "startPos": 7,
          "endPos": 15
        },
        {
          "entity": "search.order",
          "startPos": 28,
          "endPos": 32
        },
        {
          "entity": "address.city",
          "startPos": 39,
          "endPos": 47
        }
      ]
    },
    {
      "text": "show all customers form bangalore",
      "intent": "UIM.Search",
      "entities": [
        {
          "entity": "search.type",
          "startPos": 9,
          "endPos": 17
        },
        {
          "entity": "address.city",
          "startPos": 24,
          "endPos": 32
        }
      ]
    },
    {
      "text": "show customers in bangalore for cakemagic",
      "intent": "UIM.Search",
      "entities": [
        {
          "entity": "search.type",
          "startPos": 5,
          "endPos": 13
        },
        {
          "entity": "address.city",
          "startPos": 18,
          "endPos": 26
        },
        {
          "entity": "subsidiary",
          "startPos": 32,
          "endPos": 40
        }
      ]
    },
    {
      "text": "show me all indian customers for cakemagic",
      "intent": "UIM.Search",
      "entities": [
        {
          "entity": "address.country",
          "startPos": 12,
          "endPos": 17
        },
        {
          "entity": "search.type",
          "startPos": 19,
          "endPos": 27
        },
        {
          "entity": "search.order",
          "startPos": 33,
          "endPos": 41
        }
      ]
    },
    {
      "text": "show me cakemagic customers from bangalore",
      "intent": "UIM.Search",
      "entities": [
        {
          "entity": "subsidiary",
          "startPos": 8,
          "endPos": 16
        },
        {
          "entity": "search.type",
          "startPos": 18,
          "endPos": 26
        },
        {
          "entity": "address.city",
          "startPos": 33,
          "endPos": 41
        }
      ]
    },
    {
      "text": "show me customers from bangalore who liked our cakes",
      "intent": "UIM.Search",
      "entities": [
        {
          "entity": "search.type",
          "startPos": 8,
          "endPos": 16
        },
        {
          "entity": "address.city",
          "startPos": 23,
          "endPos": 31
        },
        {
          "entity": "search.order",
          "startPos": 47,
          "endPos": 51
        }
      ]
    },
    {
      "text": "show me customers from usa",
      "intent": "UIM.Search",
      "entities": [
        {
          "entity": "search.type",
          "startPos": 8,
          "endPos": 16
        },
        {
          "entity": "address.country",
          "startPos": 23,
          "endPos": 25
        }
      ]
    },
    {
      "text": "show me customers who have ordered cake",
      "intent": "UIM.Search",
      "entities": [
        {
          "entity": "search.type",
          "startPos": 8,
          "endPos": 16
        },
        {
          "entity": "search.order",
          "startPos": 35,
          "endPos": 38
        }
      ]
    },
    {
      "text": "show me customers who likes our cake",
      "intent": "None",
      "entities": [
        {
          "entity": "search.type",
          "startPos": 8,
          "endPos": 16
        },
        {
          "entity": "search.order",
          "startPos": 32,
          "endPos": 35
        }
      ]
    },
    {
      "text": "show me top 3 customers from bangalore in india",
      "intent": "UIM.Search",
      "entities": [
        {
          "entity": "search.type",
          "startPos": 14,
          "endPos": 22
        },
        {
          "entity": "address.city",
          "startPos": 29,
          "endPos": 37
        },
        {
          "entity": "address.country",
          "startPos": 42,
          "endPos": 46
        }
      ]
    },
    {
      "text": "show me top 3 customers from india",
      "intent": "UIM.Search",
      "entities": [
        {
          "entity": "search.type",
          "startPos": 14,
          "endPos": 22
        },
        {
          "entity": "address.country",
          "startPos": 29,
          "endPos": 33
        }
      ]
    },
    {
      "text": "show top 3 customers form bangalore who have ordered cakes in last 3 months",
      "intent": "UIM.Search",
      "entities": [
        {
          "entity": "search.type",
          "startPos": 11,
          "endPos": 19
        },
        {
          "entity": "address.city",
          "startPos": 26,
          "endPos": 34
        },
        {
          "entity": "search.order",
          "startPos": 53,
          "endPos": 57
        }
      ]
    },
    {
      "text": "which customers from usa bought cakes from me",
      "intent": "UIM.Search",
      "entities": [
        {
          "entity": "search.type",
          "startPos": 6,
          "endPos": 14
        },
        {
          "entity": "address.country",
          "startPos": 21,
          "endPos": 23
        },
        {
          "entity": "search.order",
          "startPos": 32,
          "endPos": 36
        }
      ]
    }
  ],
  "settings": []
}

Regards
Kiran

A: Kiran, the issue is you only have two utterances in your app that contain the subsidiary entity. Additional to that, the word 'cakemagic' is not a real word and, thus, LUIS doesn't know how to handle that word. The option is to either include more utterances from which you can train LUIS with (i.e. more examples of context, where the entity can show up in the utterance, or different values the subsidiary can be), use real words LUIS would naturally recognize, or build out the phrase list to include all the words you are looking to have included.


Q: Using ODBC connection with Azure Data Studio In order to connect to an IBM DB2 database, I am using DBeaver with an ODBC type of connection. But since I found Azure Data Studio very lightweight and portable, I want to ask if there is a way to connect to such databases because all I get is Microsoft SQL Server as connection type.


Q: Trouble Compiling Systemd standalone binaries Source: systemd-stable-251: https://github.com/systemd/systemd-stable
wget https://github.com/systemd/systemd-stable/archive/refs/heads/v251-stable.zip
unzip v251-stable.zip
cd systemd-stable-251-stable/

Using command:
./configure --auto-features=disabled \
            --default-library=static \
            -D standalone-binaries=true \
            -D static-libsystemd=true \
            -D static-libudev=true \
            -D link-udev-shared=false \
            -D link-systemctl-shared=false \
            -D link-networkd-shared=false \
            -D link-timesyncd-shared=false \
            -D link-boot-shared=false && make

Also tried with just the static libraries and with just the standalone option enabled.
Configuration:
  Features
enabled  : IMA, SELinux, SMACK, blkid, gcrypt, gnutls, libidn2, openssl, p11kit, xkbcommon, xz, zlib, bzip2, backlight, binfmt, coredump, environment.d, efi, firstboot, hibernate, hostnamed, hwdb, initrd, kernel-install, localed, logind, machined, networkd, nss-myhostname, nss-mymachines, nss-resolve, nss-systemd, oomd, portabled, pstore, quotacheck, randomseed, resolve, rfkill, sysext, systemd-analyze, sysusers, timedated, timesyncd, tmpfiles, userdb, vconsole, xdg-autostart, idn, polkit, nscd, dbus, glib, tpm, SysV compat, utmp, ldconfig, adm group, wheel group, gshadow, standalone-binaries, static-libsystemd(true), static-libudev(true), cryptolib(gcrypt), DNS-over-TLS(openssl)
disabled : ACL, AUDIT, AppArmor, PAM, SECCOMP, elfutils, libbpf, libcryptsetup, libcryptsetup-plugins, libcurl, libfdisk, libfido2, libidn, libiptc, microhttpd, pcre2, pwquality, qrencode, tpm2, zstd, lz4, bpf-framework, gnu-efi, homed, importd, repart, sysupdate, legacy-pkla, kmod, man pages, html pages, man page indices, compat-mutable-uid-boundaries, debug hashmap, debug mmap cache, debug siphash, valgrind, trace logging, install tests, link-udev-shared, link-systemctl-shared, link-networkd-shared, link-timesyncd-shared, link-boot-shared, fexecve, coverage

User defined options
auto_features                  : disabled
default_library                : static
link-boot-shared               : false
link-networkd-shared           : false
link-systemctl-shared          : false
link-timesyncd-shared          : false
link-udev-shared               : false
standalone-binaries            : true
static-libsystemd              : true
static-libudev                 : true
Shared Object:
# file build/udevadm
build/udevadm: ELF 64-bit LSB shared object, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, for GNU/Linux 3.2.0, BuildID[sha1]=f6b7c1a3509d45ebcafda9b49f4dd2332e786738, with debug_info, not stripped

I'm expecting to see an ELF executable instead of shared object files.

A: The documentation for the standalone-binaries options says:

also build standalone versions of supported binaries

That seems ambiguous at best. Looking at the meson_build file, we find:
        if have_standalone_binaries
                exe = executable(
                        'systemd-sysusers.standalone',

[...]

        if have_standalone_binaries
                exe = executable(
                        'systemd-tmpfiles.standalone',

[...]

That seems to suggest that the option only influences systemd-sysusers and systemd-tmpfiles, and indeed, when the build is complete, we see:
$ ls build/*.standalone
build/systemd-sysusers.standalone build/systemd-tmpfiles.standalone

It looks like things are operating as designed.


Q: Implicitly redirect in Apache I have Apache and want to implicitly redirect http request to a file.
That is, when a user hits http://example.com/foo/bar, I wish a user to see a content on .xml file under /some/folder/file.xml and at the same time a user must see http://example.com/foo/bar in the address bar.
Redirect instruction in httpd.conf makes a URL being changed once it gets redirected, but I want to keep the URL same.

A: Try this.
RewriteEngine  on
RewriteRule    "/foo/bar$"  "/some/folder/file.xml" [PT]

you can even specify mime-type.
RewriteRule    "/foo/bar$"  "/some/folder/file.xml" [PT,H=application/xml]

You need internal remapping.


Q: General topology: if $A \subset B$ and $B$ is closed then $\partial A \subset B$ I am not quite sure how to go about proving this, will you please provide some guidance? I want to show that if $A\subset B$ and $B$ is closed,then $\partial A \subset B$.

A: Since $B$ is closed, $B=\overline{B}$. Hence
$$
\partial A \subset \overline A \subset \overline B = B.
$$


Q: Unable to extract JSON fields in Splunk I'm trying to extract JSON fields from syslog inputs.
In ./etc/system/default/props.conf I've added the following lines:
[mylogtype]
SEDCMD-StripHeader = s/^[^{]+//
INDEXED_EXTRACTIONS = json
KV_MODE = none
pulldown_type = true

The SEDCMD works; the syslogs headers are removed.

But the JSON fields are not parsed.
Any ideas?

A: Resolved. Use the following configuration in props.conf
[yourlogtype]
SEDCMD-StripHeader = s/^[^{]+//
KV_MODE = json
pulldown_type = true


Q: Storing class files in dll and using the dll for multiple websites in asp.net I want to create a class file in VS2005 and be able to use it in other websites on my computer / production server. How do I create this dll and store it in a common place where I can reference it while developing and also on the production server ?

A: Avoid the GAC unless you have full administration rights on the host server.
What you could do is create a project containing the source for your shared DLL. You can then add this project into each of your web site solutions, and add a reference in your site solutions to the project. This has the added advantage of enabling you to step into your shared source during debugging.

A: First add a class library project to your solution. Add this class into this library. And deploy this class to Global Assembly Cache (GAC). You can follow these steps to install your assembly to GAC.


Q: Convert time string in XSLT How do I convert a time string like
20101115083000 +0200

to
2010-11-15 08:30:00 +0200

using XSLT?

A: If you have XSLT 2.0, you can use date parsing and formatting functions.
If you have XSLT 1.0, but can use EXSLT, it provides similar functions.
These would be less transparent to use than @Peter's explicit code, but maybe more robust if your input format can vary.

A: Here is a most generic formatDateTime processing. Input and output format are completely configyrable and passed as parameters:
<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>

 <xsl:template match="/">
  <xsl:call-template name="convertDateTime">
   <xsl:with-param name="pDateTime" select="."/>
  </xsl:call-template>
 </xsl:template>

 <xsl:template name="convertDateTime">
  <xsl:param name="pDateTime"/>
  <xsl:param name="pInFormat">
    <year offset="0" length="4"/>
    <month offset="4" length="2"/>
    <day offset="6" length="2"/>
    <hour offset="8" length="2"/>
    <minutes offset="10" length="2"/>
    <seconds offset="12" length="2"/>
    <zone offset="15" length="5"/>
  </xsl:param>

  <xsl:param name="pOutFormat">
   <y/>-<mo/>-<d/> <h/>:<m/>:<s/> <z/>
  </xsl:param>

  <xsl:variable name="vInFormat" select=
   "document('')/*/xsl:template[@name='convertDateTime']
                       /xsl:param[@name='pInFormat']"/>
  <xsl:variable name="vOutFormat" select=
   "document('')/*/xsl:template[@name='convertDateTime']
                       /xsl:param[@name='pOutFormat']"/>
  <xsl:apply-templates select="$vOutFormat/node()"
       mode="_convertDateTime">
    <xsl:with-param name="pDateTime" select="$pDateTime"/>
    <xsl:with-param name="pInFormat" select="$vInFormat"/>
   </xsl:apply-templates>
 </xsl:template>

 <xsl:template match="y" mode="_convertDateTime">
  <xsl:param name="pDateTime"/>
  <xsl:param name="pInFormat"/>

  <xsl:value-of select=
     "substring($pDateTime,
                1+$pInFormat/year/@offset,
                $pInFormat/year/@length)"/>
 </xsl:template>

 <xsl:template match="mo" mode="_convertDateTime">
  <xsl:param name="pDateTime"/>
  <xsl:param name="pInFormat"/>

  <xsl:value-of select=
     "substring($pDateTime,
                1+$pInFormat/month/@offset,
                $pInFormat/month/@length)"/>
 </xsl:template>

 <xsl:template match="d" mode="_convertDateTime">
  <xsl:param name="pDateTime"/>
  <xsl:param name="pInFormat"/>

  <xsl:value-of select=
     "substring($pDateTime,
                1+$pInFormat/day/@offset,
                $pInFormat/day/@length)"/>
 </xsl:template>

 <xsl:template match="h" mode="_convertDateTime">
  <xsl:param name="pDateTime"/>
  <xsl:param name="pInFormat"/>

  <xsl:value-of select=
     "substring($pDateTime,
                1+$pInFormat/hour/@offset,
                $pInFormat/hour/@length)"/>
 </xsl:template>

 <xsl:template match="m" mode="_convertDateTime">
  <xsl:param name="pDateTime"/>
  <xsl:param name="pInFormat"/>

  <xsl:value-of select=
     "substring($pDateTime,
                1+$pInFormat/minutes/@offset,
                $pInFormat/minutes/@length)"/>
 </xsl:template>

 <xsl:template match="s" mode="_convertDateTime">
  <xsl:param name="pDateTime"/>
  <xsl:param name="pInFormat"/>

  <xsl:value-of select=
     "substring($pDateTime,
                1+$pInFormat/seconds/@offset,
                $pInFormat/seconds/@length)"/>
 </xsl:template>

 <xsl:template match="z" mode="_convertDateTime">
  <xsl:param name="pDateTime"/>
  <xsl:param name="pInFormat"/>

  <xsl:value-of select=
     "substring($pDateTime,
                1+$pInFormat/zone/@offset,
                $pInFormat/zone/@length)"/>
 </xsl:template>
</xsl:stylesheet>

when this transformation is applied to the following XML document:
<dateTime>20101115083000 +0200</dateTime>

the wanted, correct result is produced:
   2010-11-15 08:30:00 +0200

A: We use templates:
<xsl:template name="format-date-time">
    <xsl:param name="date" select="'%Y-%m-%dT%H:%M:%S%z'"/>
    <xsl:value-of select="substring($date, 9, 2)"/>
    <xsl:text>/</xsl:text>
    <xsl:value-of select="substring($date, 6, 2)"/>
    <xsl:text>/</xsl:text>
    <xsl:value-of select="substring($date, 1, 4)"/>
    <xsl:text> </xsl:text>
    <xsl:value-of select="substring($date, 12, 2)"/>
    <xsl:text>:</xsl:text>
    <xsl:value-of select="substring($date, 15, 2)"/>
    <xsl:text>:</xsl:text>
    <xsl:value-of select="substring($date, 18, 2)"/>
</xsl:template>

We call these templates like this:
<xsl:call-template name="format-date-time">
    <xsl:with-param name="date" select="./Startdate"/>
</xsl:call-template>

./Startdate is an XML date, but with the substring technique, I think you could solve your problem too.


Q: What is dynamic DAO? This blog talked about using dynamic DAO instead of activerecord. What exactly is meant by "dynamic" DAO in the context of statically typed languages? Does this apply only to statically typed languages on a VM or also to compiled languages?

A: Both DAO and ActiveRecord are patterns to access data in a Database. DAO stands for "Data Acess Object". Following are the links to the relevant Wikipedia pages to read more about the individual patterns.

*

*ActiveRecord: http://en.wikipedia.org/wiki/Active_record_pattern

*DAO: http://en.wikipedia.org/wiki/Data_access_object
Note that the ruby gem activerecord is an implementation of the "Active Record" patterns, which happens to have the same name as the pattern.


Q: Changing file associations in GNOME? This blog post talks about how to change the default application to handle a file type in Nautilus for individual file types (right-click on the file, "open with", and select the new default application), but is there a way to list all current associations and configure them in one go, similar to the Windows "folder options | file types" tab?  There seem to be a bunch of default associations that I want to change (all various image files are being opened in IceWeasel instead of the image viewer), and I don't want to have to change them one-by-one in the file manager.  If there's no GUI for doing this, then where does Nautilus store its file associations?  Can I edit them with a text editor?

A: All of your file associations are stored in $HOME/.local/share/applications/mimeapps.list. Some of them are not in your personal mimeapps.list file. There's a system wide file with all the default associations in /usr/share/applications/mimeapps.list and/or in /usr/share/applications/defaults.list.
For more info check out Specifications/mime-actions-spec
Edit:
In Fedora 14 I have these settings files:
/var/lib/gdm/.local/share/applications/mimeapps.list
/usr/share/applications/defaults.list
/usr/local/share/applications/defaults.list
$HOME/.local/share/applications/defaults.list
$HOME/.local/share/applications/mimeapps.list

A: On my system (Debian Jessie) I found all the normal methods of specifying a default application wouldn't override the one hiding in ~/.config/mimeapps.list.
Thunar insisted on opening a particular file with gedit even after I told it to make the correct application the default. When I removed the setting from ~/.config/mimeapps.list, it started working properly again.

A: I am using Ubuntu 13.10.
The file you need to edit is /etc/gnome/defaults.list.


Q: How to ignore empty cell in google script function I'm trying to create a function that highlights any cells when they are changed ignoring any changes to empty cells, the function below does highlight changes but to ALL cells including empty ones, any help would be greatly appreciated.
function onEdit() {

var sheetsToWatch = ['IC', 'FTE'];

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var cell = sheet.getActiveCell();
var val = cell.getValue();

var sheetName = sheet.getName();
var matchFound = false;
for (var i = 0; i < sheetsToWatch.length; i++) {
if (sheetName.match(sheetsToWatch[i])) matchFound = true;
  }

if (val && matchFound){

var rowColLabel =
sheet.getRange(cell.getRow(),cell.getColumn()).setBackground('#faec15');

I tried a bunch of different if statements to try filter empty cells but nothing changes the result

A: Take advantage of the event object e, like this:
function onEdit(e) {
  if (!e) {
    throw new Error('Do not run this code in the script editor.');
  }
  if (!e.oldValue
    || !e.range.getSheet().getName().match(/^(IC|FTE)$/i)) {
    return;
  }
  e.range.setBackground('#faec15');
}

See Apps Script at Stack Overflow, Clean Code JavaScript, and these onEdit(e) optimization tips.

A: some ways to ignore empty data in apps-script:

// 1. assume you have one column of data:

  // if your data may contains 0 or false:
function test1() {
  const values = [
    ['value_1'],
    [0],
    ['value_2'],
    [false],
    ['value_3'],
    [''],
    ['value_4']
  ]

  for(const row of values) {
    if(row[0]==undefined || row[0]=='') continue;
    console.log(row);
  }
}

function test2() {
  // if your data do not contains 0 or false:
  const values = [
    ['value_1'],
    [''],
    ['value_2'],
    [''],
    ['value_3'],
    [''],
    ['value_4']
  ]

  for(const row of values) {
    if(!row[0]) continue;
    console.log(row);
  }
}

test1()
/** output:
["value_1"]
["value_2"]
["value_3"]
["value_4"]
*/

test2()
/** output:
["value_1"]
["value_2"]
["value_3"]
["value_4"]
*/

// 2. Assume you have a set rows and columns as data:
  // Assume all the test samples below does not contains 0 or false:
function test3(arg) {
  const values = [
    ['value_1-1','value_1-2','value_1-3'],
    ['','value_2-2','value_2-3'],
    ['value_3-1','','value_3-3'],
    ['value_4-1','value_4-2',''],
    ['','',''],
    ['value_5-1','value_5-2','value_5-3']
  ];

  switch(arg) {
    case 1: // 2-1. if you only want to check one column:
      {
        for(row of values) {
          if(!row[1]) continue; // check only column B of each row.
          console.log(row);
        }
      }
      break;
    case 2: // 2-2. if you need to check the whole row and skip only if the entire row is empty:
    {
      for(row of values) {
       if(row.every(col => !col)) continue; // check every columns of each row.
       console.log(row);
      }
    }
    break;
    case 3: // 2-3. if you need to check the whole row and skip if that row contains 1 or more empty cell:
    {
      for(row of values) {
       if(row.some(col => !col)) continue; // check every columns of each row.
       console.log(row);
      }
    }
    break;
  }
}

test3(1)
/** output:
["value_1-1","value_1-2","value_1-3"]
["","value_2-2","value_2-3"]
["value_4-1","value_4-2",""]
["value_5-1","value_5-2","value_5-3"]
*/

test3(2)
/** output:
["value_1-1","value_1-2","value_1-3"]
["","value_2-2","value_2-3"]
["value_3-1","","value_3-3"]
["value_4-1","value_4-2",""]
["value_5-1","value_5-2","value_5-3"]
*/

test3(3)
/** output:
["value_1-1","value_1-2","value_1-3"]
["value_5-1","value_5-2","value_5-3"]
*/


Q: Can you use TFS API with only query strings? Trying to queue build from Slack Using On-Premise TFS 2017 and Slack.  Just trying to find a way for people to manually queue builds.  Slack Slash Commands will almost work, but can't seem to send JSON bodies, so I'm trying to find out how to send credentials and definition IDs using only query strings...
Some background:

*

*Our people cannot run unsigned Powershell Scripts because of Group Policy overrides for ExecutionPolicy.

*Don't want to give people access to queue builds through web interface.

*We are using CI/CD, but need to manually queue for QA/Demo builds.

*Wanted to avoid using another app as a go-between if possible, since new environments for hosting are hard to come by here.

Is there a way to hit the TFS API through Slack Slash Commands?


Q: Django Model Foreign Key Casting Integer to Char Edited
I have two tables Table1 and Table2. Table1 has a field x of type int and Table2 has primary key y of type char. I am trying to do x = models.ForeignKey(Table2, ...) but it tries to cast y to an int first. In doing so, this overflows the int. I am wondering if it is possible to first cast x to a char and then do the foreign key relationship.


Q: What is the purpose of & in (a & 1) I am trying to solve a problem in codefights, after browsing the net, i found this solution.But i am not clear how it works.
    a * (a & 1) ^ b * !(b & 1) ^ !!(((a ^ b) + 1) & 2)

A: A single & is a bitwise AND, which means that the result is the bits that are set on BOTH left and right side of the operator.
As an example 15 & 7 or as they are represented in binary:
1111
&
0111

The bitwise AND will result in the a number with the common bits set:
1111 & 0111 = 0111

When you make the (a & 1) you are testing whether the least significant bit (lsb) is set, since you are performing a test like this:
a
&
00000001

If a had the bitwise value: 00000110 then the result would be 0, since there are no common bits set, if a had the bitwise value: 00000111 then the result would be 1 since the lsb is set on a.
This is used for different situations, if the lsb is set you know that the number is odd, so this test is really whether the number is odd or not (1, 3, 5, 7, ...).
Looking at the first part of your solution: a * (a & 1) you are multiplying a with the value of (0 or 1 remember), 1 if a is odd, and 0 if it is even.

A: Here & is a Bitwise Operator(works on bits and perform bit-by-bit operation).For more details see this and this


Q: How to scale out screen size on Windows 10 I use Win 10 with scaling 100%...

My monitor is LCD Lenovo.
I feel that the LCD display is so big. Maybe larger than 15"
I like to scale out my screen size maybe 80% or 70%
I can do this on Win 7, but I can not do it in Win 10.
I need a suggestion what program/application is needed to scale out my screen size at 80%


Q: Search Using IN Condition in MySql I am writing Web services for IOS In cakePhp and stuck in IN condition.
I have a table dog_temperaments and it has values "happy,dependent,shy".
Now if IOS send me array (happy,shy) Then I search Like this
Select dog_temperaments.* where temperaments IN(happy,shy)
Its work fine but if IOS send me array 0 or any(means search by any temperament) Then How I will Search........
Any means Search by all temperaments

A: If it is 0 or any any then no need for that condition as it ishould return all of them.
So aassuming $type will contain the temperaments as an array and 0/any will be single element for that case.
if(count($type) == 1 && in_array(($type[0], array('0', 'any'))) {
    $condition = "";
} else {
    $condition = "WHERE temperaments IN ('" . implode("','", $type) . "')";
}

And the query will be like -
"Select dog_temperaments.* from dog_temperaments ".$condition

A: Either you can check that the array is empty or not like
if(is_array($array)) {
    Use
    Select dog_temperaments.* where temperaments IN('happy','shy');
} else {
    notify Enter proper search key
}

Else you anyways get the empty results by using the same query if the array is empty like
Select dog_temperaments.* where temperaments IN(0);


Q: Python copying multiple files simultaneously (Multithreading) I have some python code that I use to copy files from one directly to another, however it is a very slow process and is sequential. I would like to find a way to do multithreading, copying more that one by one file, but rather have 10 or 100 processes running doing this. Here is my current core that process one by one file:
import os
import shutil

directory = "All_files"

with open('files.txt','w') as f:
    for filename in os.listdir(directory):
        src = directory+"/"+filename+"/02-Partners.pdf"
        file_exists = os.path.exists(src)
        if file_exists == True:
            dst="part/"+filename+"_"+"02-Partners.pdf"
            shutil.copyfile(src,dst)
            f.write('%s \n' % (filename))

Any assistance in getting multiple files copying at the same time will be appreciated.

A: Take a look at python's threading basic package and see if it fits you.
https://docs.python.org/3/library/threading.html


Q: Functional equation polynomial problem: $x^2f(x-1)=(x-1)^2f(x)$
Let $f(x)$ be a polynomial such that $$x^2f(x-1)=(x-1)^2f(x)$$
which one of the polynomials $(a)$ $x(x-1)$, $(b)$ $2016x$ or $(c)$ $2016x^2$ can $f(x)$ be?

How should one approach this? I cannot see any options to use other than trying to find some roots, but even that seems very hard here.

A: $\frac {f(x-1)}{(x-1)^2}= \frac{f(x)}{x^2}$
$ \\ \Rightarrow  \frac{f(x)}{x^2}= C \\
or \ f(x) = C{x^2}$

A: Evaluating
$$x^2f(x-1)=(x-1)^2f(x)$$
at $x=0$ implies $f(0)=0$. Now by differentiating both sides of the equation we find
$$2xf(x-1)+x^2f'(x-1)=2(x-1)f(x)+(x-1)^2f'(x).$$
Again, plug $x=0$ to deduce $f'(0)=0$. Hence, the only possible candidate is $f(x)=2016x^2$.


Q: Python Module issues Im pretty new to python, and have been having a rough time learning it. I have a main file
import Tests
from Tests import CashAMDSale

CashAMDSale.AMDSale()

and CashAMDSale
import pyodbc
import DataFunctions
import automa
from DataFunctions import *
from automa.api import *

def AMDSale():
    AMDInstance = DataFunctions.GetValidAMD()

And here is GetValidAMD
import pyodbc

def ValidAMD(GetValidAMD):
     (short method talking to a database)

My error comes up on the line that has AMDInstance = DataFunctions.GetValidAMD()
I get the error AttributeError: 'module' object has no attribute 'GetValidAMD'
I have looked and looked for an answer, and nothing has worked. Any ideas? Thanks!

A: When you create the file foo.py, you create a python module. When you do import foo, Python evaluates that file and places any variables, functions and classes it defines into a module object, which it assigns to the name foo.
# foo.py
x = 1
def foo():
    print 'foo'

>>> import foo
>>> type(foo)
<type 'module'>
>>> foo.x
1
>>> foo.foo()
foo

When you create the directory bar with an __init__.py file, you create a python package. When you do import bar, Python evaluates the __init__.py file and places any variables, functions and classes it defines into a module object, which it assigns to the name bar.
# bar/__init__.py
y = 2
def bar():
    print 'bar'

>>> import bar
>>> type(bar)
<type 'module'>
>>> bar.y
2
>>> bar.bar()
bar

When you create python modules inside a python package (that is, files ending with .py inside directory containing __init__.py), you must import these modules via this package:
>>> # place foo.py in bar/
>>> import foo
Traceback (most recent call last):
    ...
ImportError: No module named foo
>>> import bar.foo
>>> bar.foo.x
1
>>> bar.foo.foo()
foo

Now, assuming your project structure is:
main.py
DataFunctions/
    __init__.py
    CashAMDSale.py
        def AMDSale(): ...
    GetValidAMD.py
        def ValidAMD(GetValidAMD): ...

your main script can import DataFunctions.CashAMDSale and use DataFunctions.CashAMDSale.AMDSale(), and import DataFunctions.GetValidAMD and use DataFunctions.GetValidAMD.ValidAMD().

A: DataFunctions is a folder, which means it is a package and must contain an __init__.py file for python to recognise it as such.
when you import * from a package, you do not automatically import all it's modules. This is documented in the docs
so for your code to work, you either need to explicitly import the modules you need:
import DataFunctions.GetValidAMD

or you need to add the following to the __init__.py of DataFunctions:
__all__ = ["GetValidAMD"]

then you can import * from the package and everything listen in __all__ will be imported

A: Check out this.
It's the same problem. You are importing DataFunctions which is a module. I expct there to be a class called DataFunctions in that module which needs to be imported with
from DataFunctions import DataFunctions
...
AMDInstance = DataFunctions.GetValidAMD()


Q: Ubuntu 22.04 keyboard language layout toggle I've just updated to Ubuntu 22.04 LTS version and my keyboard behavior changed after that.
During the update process I was asked to choose "Method for toggling between national and Latin mode" and i chose left Alt.
Now I want to disable this toggle because all my keyboard shortcuts with left Alt key not working anymore, how can I do it?

A: Reset your xkb options using the command:
gsettings reset org.gnome.desktop.input-sources xkb-options

This will disable left Alt toggling the keyboard layout.
If desired, you can change keyboard options with "Tweaks" (not installed by default), "Keyboard & Mouse" tab, button "Additional Layout Options".


Q: how to insert an array into database in python? I have a database called my_python and I have a table called my_transport. There are 3 columns in the table: id, transport, and fee. for the first columns "id", I make it auto increment so that I don't have to insert any value into it. My question is how to insert the value of  my_trans and my_fee into the database table?
    import mysql.connector

    my_trans=['car','train','ship','train']
    my_fee=[200,300,150,200]

    try:
        connection = mysql.connector.connect(host='localhost',
                                 database='my-python',
                                 user='root',
                                 password='')
        sql_insert_query = """INSERT INTO my_transport
                               (`transport`, `fee`) VALUES (my_trans, my_fee)"""
        cursor = connection.cursor()
        result = cursor.execute(sql_insert_query)
        connection.commit()
        print ("Record inserted successfully into table")  except mysql.connector.Error as error :
        connection.rollback() #rollback if any exception occured
        print("Failed inserting record into table {}".format(error))  finally:
         #closing database connection.
        if(connection.is_connected()):
            cursor.close()
            connection.close()
            print("MySQL connection is closed")

I have try below code but it said:
"Failed inserting record into table 1054 (42S22): Unknown column 'my_trans' in 'field list'"

A: use .executemany to insert array of records as mentioned here
my_trans = []
my_trans.append('car', 200)
my_trans.append('train', 300)
my_trans.append('ship', 150)
my_trans.append('train', 200)

sql_insert_query = 'INSERT INTO my_transport
                               (transport, fee) VALUES (%s, %s)'
cursor = connection.cursor()
result = cursor.executemany(sql_insert_query, my_trans)


Q: how to make autocommit false work in kafkajs scenario:
im setting autocommit false,
producing 12 messages
consuming them.. (say from offset 100)
shutting down consumer
start  a new consumer
in that stage, I expect to the 2nd consumer to read all messages again starting offset 100 (because no committing was done)
but when producing new messages I see that the 2nd consumer starts from the new offset (113) i.e the commit still occurs somehow..
what do I get wrong?
that is my consumer code
const { Kafka } = require('kafkajs');
const kafka = new Kafka({
  clientId: 'my-app',
  brokers: ['192.168.14.10:9095']
});
const admin = kafka.admin();
const consumer = kafka.consumer({ groupId: 'test-group' });
const run = async () => {
  // admin
  await admin.connect();
  // Consuming
  await consumer.connect();
  await consumer.subscribe({ topic: 'topic-test2'});
  await consumer.run({
    autoCommit: false,
    eachMessage: async ({ topic, partition, message }) => {
      console.log({
        partition,
        offset: message.offset,
        value: message.value.toString()
      });
      }
    }
  });
};
run().catch(console.error);


Q: Cannot use the count() function in a query containing subquery I have the below query working fine.
SELECT
   (SELECT MAX(LOG_DATE) FROM LOGTABLE WHERE ID=A.ID AND STATUS = 'NEW') AS DATE1,
   (SELECT MAX(LOG_DATE) FROM LOGTABLE WHERE ID=A.ID AND STATUS= 'OLD') AS DATE
FROM TABLE1 A
WHERE
   A.STATUS ('NEW') OR
   A.ID IN (
      SELECT DISTINCT ID
      FROM LOGTABLE
      WHERE LOG_DATE BETWEEN @DATETIME AND @DATETIME AND STATUS = 'OLD'
  )

Now I wanted to count the MAX(LOG_DATE).
Below is what I have tried.

SELECT
   COUNT((SELECT MAX(LOG_DATE) FROM LOGTABLE WHERE ID=A.ID AND STATUS = 'NEW')) AS DATE1,
   COUNT((SELECT MAX(LOG_DATE) FROM LOGTABLE WHERE ID=A.ID AND STATUS= 'OLD')) AS DATE
FROM TABLE1 A

WHERE
   A.STATUS ('NEW') OR
   A.ID IN (
      SELECT DISTINCT ID
      FROM LOGTABLE
      WHERE LOG_DATE BETWEEN @DATETIME AND @DATETIME AND STATUS = 'OLD'
   )

It resulted in a below error:

Cannot perform an aggregate function on an expression containing an
aggregate or a subquery.

A: I think filtering the Raw data and after that applying, the count would be good option,
;WITH CTE AS (SELECT
   (SELECT MAX(LOG_DATE) FROM LOGTABLE WHERE ID=A.ID AND STATUS = 'NEW') AS DATE1,
   (SELECT MAX(LOG_DATE) FROM LOGTABLE WHERE ID=A.ID AND STATUS= 'OLD') AS DATE
FROM TABLE1 A
WHERE
   A.STATUS ('NEW') OR
   A.ID IN (
      SELECT DISTINCT ID
      FROM LOGTABLE
      WHERE LOG_DATE BETWEEN @DATETIME AND @DATETIME AND STATUS = 'OLD'
  ))

SELECT COUNT(DATE1),COUNT(Date)   FROM CTE


Q: How to fix 'PHP code not working in laravel public folder' I embed a php in one of my views with:

In this file I have the following code:

I get the following error:
Uncaught SyntaxError: Unexpected token '{'
I already tried to use {{ Auth::user()->name }} etc.
I also tried to embed a link that used a route to another view but with this I got a 403 forbidden error.
Does anyone know how I could fix this? or have another solution for me?

A: First, iframe src is never .blade.php file. You can create a route /game and map that route to controller which then returns the .blade.php view. So, in your view:

And then in web.php
Route::get('game', 'HomeController@game');

And in HomeController.php:
public function game(){
    return view('game');
}

In which file are you writing  tag? What's the full error that you are getting? Maybe enclosing your variables inside quotes like this will solve the problem.


Q: Beginner Scoring program button development in Java I'm trying to add a "green team" to an example scoring GUI I found online. For some reason, the code compiles, but it runs with only the original two teams. I've tried playing around with the sizes/locations somewhat clumsily, and since no change was observed with these modications (NO change at ALL), I admit that I must be missing some necessary property or something. Any help? Here's the code:
import javax.swing.*;

import java.awt.Color;

import java.awt.event.ActionListener;

import java.awt.event.ActionEvent;

public class ButtonDemo_Extended3 implements  ActionListener{

    // Definition of global values and items that are part of the GUI.

    int redScoreAmount = 0;

    int blueScoreAmount = 0;
    int greenScoreAmount = 0;

    JPanel titlePanel, scorePanel, buttonPanel;

    JLabel redLabel, blueLabel,greenLabel, redScore, blueScore, greenScore;

    JButton redButton, blueButton, greenButton,resetButton;

    public JPanel createContentPane (){

        // We create a bottom JPanel to place everything on.

        JPanel totalGUI = new JPanel();

        totalGUI.setLayout(null);

        // Creation of a Panel to contain the title labels

        titlePanel = new JPanel();

        titlePanel.setLayout(null);

        titlePanel.setLocation(0, 0);

        titlePanel.setSize(500, 500);

        totalGUI.add(titlePanel);

        redLabel = new JLabel("Red Team");

        redLabel.setLocation(300, 0);

        redLabel.setSize(100, 30);

        redLabel.setHorizontalAlignment(0);

        redLabel.setForeground(Color.red);

        titlePanel.add(redLabel);

        blueLabel = new JLabel("Blue Team");

        blueLabel.setLocation(900, 0);

        blueLabel.setSize(100, 30);

        blueLabel.setHorizontalAlignment(0);

        blueLabel.setForeground(Color.blue);

        titlePanel.add(blueLabel);

    greenLabel = new JLabel("Green Team");

        greenLabel.setLocation(600, 0);

        greenLabel.setSize(100, 30);

        greenLabel.setHorizontalAlignment(0);

        greenLabel.setForeground(Color.green);

        titlePanel.add(greenLabel);

        // Creation of a Panel to contain the score labels.

        scorePanel = new JPanel();

        scorePanel.setLayout(null);

        scorePanel.setLocation(10, 40);

        scorePanel.setSize(500, 30);

        totalGUI.add(scorePanel);

        redScore = new JLabel(""+redScoreAmount);

        redScore.setLocation(0, 0);

        redScore.setSize(40, 30);

        redScore.setHorizontalAlignment(0);

        scorePanel.add(redScore);

    greenScore = new JLabel(""+greenScoreAmount);

        greenScore.setLocation(60, 0);

        greenScore.setSize(40, 30);

        greenScore.setHorizontalAlignment(0);

        scorePanel.add(greenScore);

        blueScore = new JLabel(""+blueScoreAmount);

        blueScore.setLocation(130, 0);

        blueScore.setSize(40, 30);

        blueScore.setHorizontalAlignment(0);

        scorePanel.add(blueScore);

        // Creation of a Panel to contain all the JButtons.

        buttonPanel = new JPanel();

        buttonPanel.setLayout(null);

        buttonPanel.setLocation(10, 80);

        buttonPanel.setSize(2600, 70);

        totalGUI.add(buttonPanel);

        // We create a button and manipulate it using the syntax we have

        // used before. Now each button has an ActionListener which posts

        // its action out when the button is pressed.

        redButton = new JButton("Red Score!");

        redButton.setLocation(0, 0);

        redButton.setSize(30, 30);

        redButton.addActionListener(this);

        buttonPanel.add(redButton);

        blueButton = new JButton("Blue Score!");

        blueButton.setLocation(150, 0);

        blueButton.setSize(30, 30);

        blueButton.addActionListener(this);

        buttonPanel.add(blueButton);

    greenButton = new JButton("Green Score!");

        greenButton.setLocation(250, 0);

        greenButton.setSize(30, 30);

        greenButton.addActionListener(this);

        buttonPanel.add(greenButton);

        resetButton = new JButton("Reset Score");

        resetButton.setLocation(0, 100);

        resetButton.setSize(50, 30);

        resetButton.addActionListener(this);

        buttonPanel.add(resetButton);

        totalGUI.setOpaque(true);

        return totalGUI;

    }

    // This is the new ActionPerformed Method.

    // It catches any events with an ActionListener attached.

    // Using an if statement, we can determine which button was pressed

    // and change the appropriate values in our GUI.

    public void actionPerformed(ActionEvent e) {

        if(e.getSource() == redButton)

        {

            redScoreAmount = redScoreAmount + 1;

            redScore.setText(""+redScoreAmount);

        }

        else if(e.getSource() == blueButton)

        {

            blueScoreAmount = blueScoreAmount + 1;

            blueScore.setText(""+blueScoreAmount);

        }
    else if(e.getSource() == greenButton)

        {

            greenScoreAmount = greenScoreAmount + 1;

            greenScore.setText(""+greenScoreAmount);

        }

        else if(e.getSource() == resetButton)

        {

            redScoreAmount = 0;

            blueScoreAmount = 0;
        greenScoreAmount = 0;

            redScore.setText(""+redScoreAmount);

            blueScore.setText(""+blueScoreAmount);
        greenScore.setText(""+greenScoreAmount);

        }

    }

    private static void createAndShowGUI() {

        JFrame.setDefaultLookAndFeelDecorated(true);

        JFrame frame = new JFrame("[=] JButton Scores! [=]");

        //Create and set up the content pane.

        ButtonDemo_Extended demo = new ButtonDemo_Extended();

        frame.setContentPane(demo.createContentPane());

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        frame.setSize(1024, 768);

        frame.setVisible(true);

    }

    public static void main(String[] args) {

        //Schedule a job for the event-dispatching thread:

        //creating and showing this application's GUI.

        SwingUtilities.invokeLater(new Runnable() {

            public void run() {

                createAndShowGUI();

            }

        });

    }

}

A: import javax.swing.*;

import java.awt.Color;
import java.awt.FlowLayout;

import java.awt.event.ActionListener;

import java.awt.event.ActionEvent;

public class ButtonDemo_Extended3 implements  ActionListener{

// Definition of global values and items that are part of the GUI.

int redScoreAmount = 0;

int blueScoreAmount = 0;
int greenScoreAmount = 0;

JPanel titlePanel, scorePanel, buttonPanel;

JLabel redLabel, blueLabel,greenLabel, redScore, blueScore, greenScore;

JButton redButton, blueButton, greenButton,resetButton;

public JPanel createContentPane (){

    // We create a bottom JPanel to place everything on.

    JPanel totalGUI = new JPanel();

    totalGUI.setLayout(null);

    // Creation of a Panel to contain the title labels

    titlePanel = new JPanel();

    titlePanel.setLayout(new FlowLayout());

    titlePanel.setLocation(0, 0);

    titlePanel.setSize(500, 500);

    redLabel = new JLabel("Red Team");

    redLabel.setLocation(300, 0);

    redLabel.setSize(100, 30);

    redLabel.setHorizontalAlignment(0);

    redLabel.setForeground(Color.red);

    titlePanel.add(redLabel, 0 );

    blueLabel = new JLabel("Blue Team");

    blueLabel.setLocation(900, 0);

    blueLabel.setSize(100, 30);

    blueLabel.setHorizontalAlignment(0);

    blueLabel.setForeground(Color.blue);

    titlePanel.add(blueLabel, 1);

greenLabel = new JLabel("Green Team");

    greenLabel.setLocation(600, 0);

    greenLabel.setSize(100, 30);

    greenLabel.setHorizontalAlignment(0);

    greenLabel.setForeground(Color.green);

    titlePanel.add(greenLabel);

    // Creation of a Panel to contain the score labels.

    scorePanel = new JPanel();

    scorePanel.setLayout(null);

    scorePanel.setLocation(10, 40);

    scorePanel.setSize(500, 30);

    redScore = new JLabel(""+redScoreAmount);

    redScore.setLocation(0, 0);

    redScore.setSize(40, 30);

    redScore.setHorizontalAlignment(0);

    scorePanel.add(redScore);

greenScore = new JLabel(""+greenScoreAmount);

    greenScore.setLocation(60, 0);

    greenScore.setSize(40, 30);

    greenScore.setHorizontalAlignment(0);

    scorePanel.add(greenScore);

    blueScore = new JLabel(""+blueScoreAmount);

    blueScore.setLocation(130, 0);

    blueScore.setSize(40, 30);

    blueScore.setHorizontalAlignment(0);

    scorePanel.add(blueScore);

    // Creation of a Panel to contain all the JButtons.

    buttonPanel = new JPanel();

    buttonPanel.setLayout(null);

    buttonPanel.setLocation(10, 80);

    buttonPanel.setSize(2600, 70);

    // We create a button and manipulate it using the syntax we have

    // used before. Now each button has an ActionListener which posts

    // its action out when the button is pressed.

    redButton = new JButton("Red Score!");

    redButton.setLocation(0, 0);

    redButton.setSize(30, 30);

    redButton.addActionListener(this);

    buttonPanel.add(redButton);

    blueButton = new JButton("Blue Score!");

    blueButton.setLocation(150, 0);

    blueButton.setSize(30, 30);

    blueButton.addActionListener(this);

    buttonPanel.add(blueButton);

greenButton = new JButton("Green Score!");

    greenButton.setLocation(250, 0);

    greenButton.setSize(30, 30);

    greenButton.addActionListener(this);

    buttonPanel.add(greenButton);

    resetButton = new JButton("Reset Score");

    resetButton.setLocation(0, 100);

    resetButton.setSize(50, 30);

    resetButton.addActionListener(this);

    buttonPanel.add(resetButton);

    totalGUI.setOpaque(true);

    totalGUI.add(buttonPanel);
    totalGUI.add(scorePanel);
    totalGUI.add(titlePanel);

    return totalGUI;

}

// This is the new ActionPerformed Method.

// It catches any events with an ActionListener attached.

// Using an if statement, we can determine which button was pressed

// and change the appropriate values in our GUI.

public void actionPerformed(ActionEvent e) {

    if(e.getSource() == redButton)

    {

        redScoreAmount = redScoreAmount + 1;

        redScore.setText(""+redScoreAmount);

    }

    else if(e.getSource() == blueButton)

    {

        blueScoreAmount = blueScoreAmount + 1;

        blueScore.setText(""+blueScoreAmount);

    }
else if(e.getSource() == greenButton)

    {

        greenScoreAmount = greenScoreAmount + 1;

        greenScore.setText(""+greenScoreAmount);

    }

    else if(e.getSource() == resetButton)

    {

        redScoreAmount = 0;

        blueScoreAmount = 0;
    greenScoreAmount = 0;

        redScore.setText(""+redScoreAmount);

        blueScore.setText(""+blueScoreAmount);
    greenScore.setText(""+greenScoreAmount);

    }

}

private static void createAndShowGUI() {

    JFrame.setDefaultLookAndFeelDecorated(true);

    JFrame frame = new JFrame("[=] JButton Scores! [=]");

    //Create and set up the content pane.

    ButtonDemo_Extended3 demo = new ButtonDemo_Extended3();

    frame.setContentPane(demo.createContentPane());

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    frame.setSize(1024, 768);

    frame.setVisible(true);

}

public static void main(String[] args) {

    //Schedule a job for the event-dispatching thread:

    //creating and showing this application's GUI.

    SwingUtilities.invokeLater(new Runnable() {

        public void run() {

            createAndShowGUI();

        }

    });

}

}

You have to use a layout manager in order to display your widgets. In this case I used a FlowLayout(). Also, make sure that you add the elements first in the panel and then you add the panel to its parent panel.
Now, the code works as you probably want, but again you should use a particular layout in order to arrange the panels inside the frame.

A: If I run your code unmodified, I see just the "Red Team" label, and some buttons which are too small to read the text (and some of them only appear when moused over).
If you comment out all the null layouts:
    //buttonPanel.setLayout(null);

then all three buttons and labels appear properly.
Doing without a layout manager, and using absolute positioning, is possible (see the Java Swing tutorial page on this exact topic) but not usually recommended. There is a lot of information on using layout managers in the Laying Out Components Within a Container lesson of the Swing tutorials.


Q: function calls not working on baremetal c code for cortex m0 with gnu toolchain I am building a custom soc based on the arm cortex m0 design start. The SOC now has a cortex mo core attached to a AHB lite bus with some ram on it and a gpio module. I am currently struggling to write and compiling code for it using the gnu tool chain. The function calls are not working. I tried many things but nothing seems to work. The interesting part is if i compile the same code with keil, it works. I guess the problem is somewhere in how i am setting up the stack and/or the liker script or I am missing some compiler/linker options.
This works
#include<stdint.h>

volatile uint8_t* led_reg;

int main() {
   led_reg=(uint8_t*)0x50000000;
    while (1) {
        *led_reg=0x8;
        for(int i=0;i<=0x2FFFFF;i++);
        *led_reg=0x4;
        for(int i=0;i<=0x2FFFFF;i++);
        *led_reg=0x2;
        for(int i=0;i<=0x2FFFFF;i++);
        *led_reg=0x1;
        for(int i=0;i<=0x2FFFFF;i++);
    }
 }

But this doesn't
#include<stdint.h>

volatile uint8_t* led_reg;

void wait(void){
    for(int i=0;i<=0x2FFFFF;i++);

}

void on(uint8_t pat){
    *led_reg=pat;
}

int main() {
    led_reg=(uint8_t*)0x50000000;
    while (1){
        on(0x8);
        wait();
        on(0x4);
        wait();
        on(0x2);
        wait();
        on(0x1);
        wait();
    }
}

This is the linker script
ENTRY(Reset_Handler)

STACK_SIZE = 0x1000;

SECTIONS
{
  . = 0x00000000;

  .ram :
    {
        . = ALIGN(4);
        _stext = .;
        KEEP(*(.vectors .vectors.*))
        *(.text .text.*)
        *(.rodata .rodata*)

        . = ALIGN(4);
         _sbss = . ;
        *(.bss .bss.*)
        *(COMMON)
        . = ALIGN(4);
        _ebss = . ;

        . = ALIGN(4);
        _sdata = .;
        *(.data .data.*);
        . = ALIGN(4);
        _edata = .;

        . = ALIGN(8);
        _sstack = .;
        . = . + STACK_SIZE;
        . = ALIGN(8);
        _estack = .;
        . = ALIGN(4);
        _end = . ;
    }

}

Relevant portion of the startup code
/* Exception Table */
__attribute__ ((section(".vectors")))
const DeviceVectors exception_table = {

        /* Configure Initial Stack Pointer, using linker-generated symbols */
        .pvStack                = (void*) (&_estack),

        .pfnReset_Handler       = (void*) Reset_Handler,
        .pfnNMI_Handler         = (void*) NMI_Handler,
        .pfnHardFault_Handler   = (void*) HardFault_Handler,

Here is the compiling and linking command examples
arm-none-eabi-gcc -Wall -Werror -g -O0 -std=c99 -ffreestanding -ffunction-sections -fdata-sections  -mcpu=cortex-m0 -mfloat-abi=soft -march=armv6-m   -mthumb  -Wall -Iinclude/headers   -o build/main.o -c src/main.c
arm-none-eabi-gcc -Wall -Werror -g -O0 -std=c99 -ffreestanding -ffunction-sections -fdata-sections  -mcpu=cortex-m0 -mfloat-abi=soft -march=armv6-m   -mthumb  -Wall -Iinclude/headers   -Wl,-Map=build/firmware.map,--gc-sections -T vcoresoc.lds --specs=nano.specs build/main.o build/startup_vcoresoc.o build/syscall.o -o build/firmware.elf

A: You have several smaller bugs in this code. It is likely that gcc optimizes the code better than Keil and therefore the function could simply be removed. In some cases you are missing volatile which may break the code:

*

*led_reg=(uint8_t*)0x50000000; should be led_reg=(volatile uint8_t*)0x50000000u;, see How to access a hardware register from firmware?

*void wait(void){ for(int i=0;i<=0x2FFFFF;i++); } should be volatile as well or the loop will just get removed.

Additionally, I don't know if you wrote the startup code or if the tool vendor did, but it has bugs. Namely .pvStack = (void*) (&_estack) invokes undefined behavior, since C doesn't allow conversions from function pointers to object pointers. Instead of void* you need to use an unsigned integer or a function pointer type. As mentioned in comments, putting some alignment keyword on a Cortex M vector table is fishy - it should be at address 0 so how can it be misaligned? It would be interesting to see the definition of DeviceVectors.
Also, bare metal microcontroller systems do not return from main(). You should not use int main(), since that is likely to cause a bit of stack overhead needlessly. Use an implementation-defined form such as void main (void) then compile for embedded ("freestanding") systems. With gcc that is -ffreestanding.


Q: Can I use delete clause in Case Clause in teradata I am newbie to teradata.
I need to delete a row once the case condition is satisfied.
Eg: case condition true delete the selected row.

A: Maybe I am misinterpreting what you are trying to accomplish with the CASE statement, but based on my understanding you can use the WHERE clause to conditionally remove data from a table:
DELETE
FROM MyDB.MyTable
WHERE Col1 = 31
  AND "Desc" = 'xxxxxx';

EDIT:
Based on your comment then you need to apply the CASE logic to each column returned in the SELECT statement that you wish to obscure.
SELECT CASE WHEN Col1 = 31 and "DESC" = 'yyyyy'
            THEN NULL
            ELSE ColA
       END AS ColA_,
    /* Repeat for each column you wish to "delete" */
  FROM MyDB.MyTable;


Q: HttpModule fires several times I have ASP.NET MVC 4 with an HttpModule. I am aware that module's Init method may be called several times, once for each HttpApplication object, but I expect the actual BeginRequest event to fire only ONCE for each incoming web request. That's not what's happening.
I noticed that BeginRequest consistently fires twice for a simple POST I am sending to the server. I am sure I am sending only one request -- there are no images.
Why would BeginRequest be called multiple times for a simple POST to the server?
Thanks.

A: Its fire on every request, it may be images, scripts, handlers, pages, what ever.
If you debug and step on it you can see what files calls it. You can also place this line inside to see what is calling it live.
Debug.Write("call from: " + HttpContext.Current.Request.Path);


Q: Why forwarding unit in MIPS processor does not store always data from WB stage to ID stage? Hey to everyone I am trying to understand 5 stage pipeline MIPS with forwarding unit
So I found a problem which has raw data hazards
The problem is the following :
Ι1 and $1, $1, $2
Ι2 add $2, $1, $2
Ι3 lw  $2, –20($3)
Ι4 sub $4, $2, $4

Dependencies : (Ι1, Ι2, $1) ,  (Ι3, Ι4, $2)
the pipeline with hazards is the following :
enter image description here
The solution of the forwarding unit is :
enter image description here
But I could not understand why forwarding unit store data from (EX to EX , WB to EX) And not to WB to ID for these two dependencies
Also why we have to use a NOP instruction between I3 and I4 instruction
My solution is the following :
enter image description here


Q: redis redis.client rq Queue job.result # => None I'm trying to figure out rq queuing with redis. I have simple test_job function which I want to use in queue.
def test_job():
    return "OK"

And the script taken mainly from rq documentation:
#!/usr/bin/env python

import redis.client
from rq import Queue
import time

from helpers import test_job

def main():

    q = Queue(connection=redis.client.Redis('localhost',6379))

    job = q.enqueue(test_job)
    print job.result   # => None

    while not job.result:
        time.sleep(2)
        print job.result   # => None

if __name__ == "__main__":
    main()

The problem is that I'm not leaving while loop. job.result remains None. However, redis connection seems to work, according to log:
[1279] 30 Dec 12:08:20.041 - 0 clients connected (0 slaves), 612560 bytes in use
[1279] 30 Dec 12:08:21.371 - Accepted 127.0.0.1:58541
[1279] 30 Dec 12:08:25.337 - DB 0: 23 keys (0 volatile) in 32 slots HT.
[1279] 30 Dec 12:08:25.337 - 1 clients connected (0 slaves), 633664 bytes in use

A: Did you start a worker to process the task?
It looks like no worker is running (as only your client connected to Redis). Run rqworker from your project's root.


Q: How to use excel_sheets() for multiple .xls files in a folder? I'm trying to use excel_sheets() from the read.xl package to get the workbook info from multiple Excel sheets in a folder. Here's the folder:

I can use excel_sheets() to process one file, and then then continue with lapply():
library(readxl)
path = "/Users/cgill22/Desktop/GTEx_WGCNA_sex_combined_signed/Adipose-Subcutaneous_0.8125Pathway_Enrichment_all_results.xls"

sheets <- excel_sheets(path)
data <- lapply(sheets, function(x) read_excel(path, sheet = x))
names(data) <- sheets

But when I try to create a for loop using a data frame with the files, I get this error:
files <- data.frame(filename = list.files("/Users/cgill22/Desktop/GTEx_WGCNA_sex_combined_signed",
                                          pattern = "*.xls",
                                          full.names = TRUE))
for(i in files){
  sheets <- excel_sheets(i)
  data <- apply(sheets, function(x) read_excel(i, sheet = x))
  names(data) <- sheets

Error: `path` must be a string

How would I create a for loop that generates a string path for each file in this folder?


Q: Relationship between scale, ppi, and map resolution Wanting to know the screen resolution (pixels per inch) of my device, I displayed my map resolution and scale using this openlayers code:
console.log("resolution: " + map.getResolution());
console.log("scale: " +map.getScale());

which gave the result below:
"resolution: 611.4962261962891" mapTest.html:119
"scale: 1733376.0653978775"

Then I used this formula (from https://msdn.microsoft.com/en-us/library/aa940990.aspx):

Map scale = 1 : (ScreenRes pixels/inch * 39.37 inches/meter *
  156543.04 meters/pixel * cos(latitude) / (2 ^ zoomlevel))

With my values:
1733376.065 = (ScreenRes ppi * 39.37 inches/meter * 611.496 meters/pixel * cos(51.02)) / (2^8)

The latitude I used is 51.20. But the formula produced 28889.6. I think this is pixels per meter so I divided by 39.37 to get pixels per inch. But that resulted in 733.797 which is an unrealistic pixels per inch. I was expecting value between 72 to 96.
What is going on here? Did I do something wrong or is the formula is wrong? The image is an OpenStreetMap image and the projection used is 900913. I hope some one can help.

A: You have indeed made some errors in your calculation. 156543.04 meters/pixel is a constant "based on the diameter of the Earth and the equations Microsoft used to set the zoom levels" used in two equations on the page you reference - it's not a variable. Your mistake was in substituting the map resolution your openlayers code returned for the constant. The first equation is:

Map resolution = 156543.04 meters/pixel * cos(latitude) / (2 ^
  zoomlevel)

In theory, according to the table provided at the page you linked, this would be 611.5 m/p at zoom level 8, at the equator. That's almost exactly the number you were given by your openlayers code, but if you solve that equation at 51.02 lat it comes out to be closer to 384.7 m/p. That matches up with the sentence under their chart, which gives an example (at a different zoom level) for a lat other than the equator. However it is a bit odd that your openlayers code is returning 611.5 for zoom level 8 at 51.02 and not 384.7. That suggests to me that the equation may not hold for openlayers [actually it looks like very similar numbers in the openlayers docs] - the page you link to is specific to Bing maps and as noted above is based on their equations to set zoom levels. Or it may just be that code returns the at-the-equator value, regardless of where you're actually looking, while the displayed scalebar takes the lat into account.
The formula you actually want to solve (theoretically, with your values) should be:
1733376.065 = [(ScreenRes ppi * 39.37 inches/meter * 156543.04 meters/pixel * cos(51.02)) / (2^8)]

Now, as I mentioned in my comment, your true screen resolution in terms of ppi is hardware/device dependent and varies from display to display. If you want to find it, it may be a published specification or you may have to calculate it. You first need the native 'resolution' of the display. This would be more properly termed pixel dimensions, because resolution is actually the density of pixels (ppi) - but we use resolution interchangeably.
So let's say 1920x1080, a standard HD display (and note this needs to be the native number, NOT what it's being run at). Since we need the diagonal pixel dimension, simple a^2 + b^2 = c^2 gives us 2202.9 diagonal pixels. Now we need the actual diagonal dimension of the display. For instance a 24" display may only be 23.8" - this is pretty much always in the specs (usually as 'viewable' or some similar adjective). Diagonal pixels divided by diagonal inches gives us 92.6 ppi. Were it a 27" display at the same resolution, it would be 81.6 ppi. A 5" gives 440.6 ppi. I found a handy calculator on the web that can do this math for you if you have the right numbers.
This will give you a much more accurate (possibly even correct) result than trying to use the Microsoft equation and should be easier. The relationship, per your question title, is somewhat complex - we're talking about scaled scales essentially. And if you run a resolution (or rather pixel dimension) different than native, it gets even more complicated.
Go back to what scale is - unit x on map representing unit y in the real world. In computers there is no scale relative to anything but pixels. That's the first equation, what they term map resolution. Say 100 pixels represents 600m. On a phone display those 100 pixels may only be 0.25 inch, while on a 30" computer monitor they might be 1 inch - but they still both represent 600m. That's why the page has the second equation - because most people don't think of map scale in terms of pixels, they want a inch : mile ratio (or whatever units). The problem is that ratio changes depending on what display you're looking at while the pixel : real world unit ratio doesn't, assuming the same pixel dimensions and zoom on the image.


Q: Insert static rows in Target Table
So I have a scenario based on the picture attached.
In my source table, I only have TIER 1 available value and will be inserted in the target table.
But the requirement requires that even if TIER 2 to 7 is not available, I should still insert it to the target table regardless if there is a value or not, and append a value of 0.
I tried making another flow and putting the condition in router but it seems to be tedious as the Department is dynamic and can be multiple depending on the source.
I would like to ask if there is another approach for this

A: There are two ways you can do it that I know of. First is to use a java transformation, where you can check how many rows are coming from source and generate the remaining using the generateRow() function within a for loop. The second option is to use a active lookup transformation, with a query like below. In the condition put rec_cnt>=src_cnt where src_cnt being the number records from source.
select rownum as rec_cnt
from dual
connect by rownum <= 7


Q: Understanding scope correctly in PHP (versus Javascript) I know that scope works differently in PHP and in Javascript.
When I first started learning Javascript (after a couple of years learning PHP), I did not initially realise that variables declared outside a function were also accessible from inside the function.
Now (after a few years of focusing much more on Javascript), I am stumped by how to return a PHP function-scope variable back to the extra-function environment.
Example:
$myArray = array();

function addItemsToMyArray($myArray) {

    $myArray[] = 'apple';
    $myArray[] = 'banana';
    $myArray[] = 'coconut';

    return $myArray;
}

addItemsToMyArray($myArray);

echo count($myArray);    /* Gives 0 */

Why does count($myArray) give 0 instead of 3?

A: The function addItemsToMyArray() has correctly been set up to return the array to the main PHP code but you forgot to catch that return value and put it in a variable. One way to write this code and make the difference easier to see could be like this:
function addItemsToMyArray($tmpArray) {

    $tmpArray[] = 'apple';
    $tmpArray[] = 'banana';
    $tmpArray[] = 'coconut';

    return $tmpArray;
}

$myArray = array();
$myArray = addItemsToMyArray($myArray);

echo count($myArray);    /* Gives 3 */

The variable used inside the function is a different variable than the $myArray variable outside of the function.

A: Unless you specify otherwise, function/method arguments are pass-by-value, meaning you get a copy of them inside the function. If you want the function to change the variable that was passed to it, you need to pass-by-reference. As described here:

By default, function arguments are passed by value (so that if the
value of the argument within the function is changed, it does not get
changed outside of the function). To allow a function to modify its
arguments, they must be passed by reference.
To have an argument to a function always passed by reference, prepend
an ampersand (&) to the argument name in the function definition:

Note the ampersand before $array in the doc page for sorting functions like asort() and ksort():

bool asort ( array &$array [, int $sort_flags = SORT_REGULAR ] )
bool ksort ( array &$array [, int $sort_flags = SORT_REGULAR ] )