text:
Q: JavaScript arrays with functions Planned output:
The array has 10 elements.
The average of the values is 36.1

I plan two functions: addNumber() and printInfo().
Function: addNumber() reads a value from a text input field on the HTML document (id="num") and adds it at the end of the array.
Another function: printInfo() outputs the amount of elements in the array to the console, then the average of their values.
HTML document has two buttons for calling the functions.
I wrote:
let arr = [];
arr.push (function addNumber() {
let element = document.getElementById("num");
})
function printInfo() {
console.log (arr.length );
}

How to use buttons for calling the functions in HTML?
How to count average of values in the array?

A: Hello here is a working example. https://jsfiddle.net/7t41y80m/
HTML Example
<fieldset>
  <legend>Array List</legend>
  <label id="lbl">1,2,3,4,5,6,7,8,9</label>
  <input type="number" id="input">
  <button onclick="AddNumber();">Add Number</button>
</fieldset>
<button onclick="CalculateAvg();">Print Averrage</button>

Javascript:
function CalculateAvg()
{
    const arr = document.getElementById('lbl').innerText.split(',').map(Number);
    const total = arr.reduce((x, y) => x + y, 0);
    const avg = total / arr.length || 0;
    alert(avg);
}

function AddNumber()
{
    document.getElementById('lbl').innerText += `,${document.getElementById('input').value}`;
}

A: You have a couple of errors in your code.
First create the function outside of arr.push().
Second, you should call the function from somewhere for it to work. Also, next time provide the HTML too. You can see a working example here:

let arr = [];

function addNumber() {
    const element = document.getElementById("num");
  const value = Number.isNaN(Number(element.value)) ? 0 :Number(element.value);
    arr.push(value)
    printInfo()
}

function printInfo() {
    console.log(`The array has ${arr.length} elements.`);
    const full = arr.reduce((acc, item) => (acc += item), 0)
    const average = full/arr.length

    console.log(`The average of the values is ${average}`)
}
<html>
<body>
<button id='main' onclick="addNumber()">
Click me
</button>
<input id="num" type="number"/>
</body>
</html>

I am adding also a minimal working example in fiddle https://jsfiddle.net/5ybz6Lmk/


text:
Q: Manually invoke $q in AngularJS From what I understand about $q in AngularJS it is run everything I refresh my page. This is similar to putting a function in ng-init.
Below is my $q.all code;
$q.all([$scope.getCart(), $scope.getCategory(), $scope.getMenu(), $scope.getRestaurant()]).then(function(data){
    $scope.cart = data[0].cart;
    $scope.cartItems = data[0].cartItems;
    $scope.delDay = data[0].delDay;
    $scope.delTime = data[0].delTime;
    $scope.cat = data[1];
    $scope.itemData = data[2];
    $scope.rest = data[3];
});

As you can see all the functions are called everytime I refresh a page and I get my data added to my $scope. This works as expected..
My question is how can I invoke $q through another function like below;
$scope.notEnoughTime = function () {
   if (year = 2015) {
    // invoke $q manually thereby calling
    // all the functions and updating all the data in my scopes
   }
}

A: as @Scott mentioned, you can put the call inside a function. With the request inside a function you can call the function whenever you'd like
var serverRequest = function() {
    $q.all()
}

$scope.notEnoughTime = function() {
   if (year = 2015) {
      serverRequest();
    }
}

// if you'd like the call the request when the controller is initialized you simple add the function call to your controller

serverRequest();

redpajama_set_name: RedPajamaStackExchange


text:
Q: Passing multiple arguments in vbscript I have to pass multiple arguments in my .vbs script but the problem is the script does not get executed from windows task schedular if I pass multiple arguments separated by white spaces. I am running the script like below,
cscript//nologo D:\test\CPWinOraBackup0.100.vbs test_db D:\Oracle\WINDOWSX64_193000_db_home rman_hot D:\Oracle\DB_Backup\test_db 1> D:\test\test.log
where the syntax is as below,
cscript//nologo Script_path ORACLE_HOME Backup_type Backup_directory retention_day
Thank you for your help in advance!
CKP

A: Try using brackets for multiple arguments.
  cscript//nologo "D:\test\CPWinOraBackup0.100.vbs test_db D:\Oracle\WINDOWSX64_193000_db_home rman_hot D:\Oracle\DB_Backup\test_db 1> D:\test\test.log"

If that does't work, try using a batch script.
@echo off
cscript//nologo "D:\test\CPWinOraBackup0.100.vbs test_db D:\Oracle\WINDOWSX64_193000_db_home rman_hot D:\Oracle\DB_Backup\test_db 1> D:\test\test.log"

How to create a batch script on Windows


text:
Q: Laravel 5.2 ajax login i have some problem with laravel v 5.2
i use ajax post request , server response 201 Ok, return data user, but when start redirect to
public function __construct()
{
    $this->middleware('auth');
}

public function index()
{
    return view('home');
}

i recive again login form ,,, and if i auth with blade form , work fine.
ajax send me
                success:function(){
               alert('okey all fine');

             window.location.href = "/home";

but /home page not see my session or ?? :) thanks

A: please update laravel/framework to 5.2.27 and backup your Auth\AuthController (in case you have make any changes) then issue a php artisan make:auth to replace the existing laravel generated auth features file with the latest bug fixed copy.
see if this solved your auth session not being persistent problem

A: may be the error as there are 2 missing pieces of middleware on  api route group. added the following 2 middlewares to the api middleware group and then added that group to  API routes
 \App\Http\Middleware\EncryptCookies::class,
\Illuminate\Session\Middleware\StartSession::class,

A: Okey lets see my files
kernel
<?php

namespace App\Http;

use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel
{
    /**
     * The application's global HTTP middleware stack.
     *
     * These middleware are run during every request to your application.
     *
     * @var array
     */
    protected $middleware = [
        \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
    ];

    /**
     * The application's route middleware groups.
     *
     * @var array
     */
    protected $middlewareGroups = [
        'web' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \App\Http\Middleware\VerifyCsrfToken::class,
        ],

        'api' => [
            'throttle:60,1',

        ],
    ];

    /**
     * The application's route middleware.
     *
     * These middleware may be assigned to groups or used individually.
     *
     * @var array
     */
    protected $routeMiddleware = [
        'auth' => \App\Http\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
    'jwt.auth' => \Tymon\JWTAuth\Middleware\GetUserFormToken::class,
    'jwt.refresh' => \Tymon\JWTAuth\Middleware\RefreshToken::class,
    'role' => \Zizaco\Entrust\Middleware\EntrustRole::class,
        'permission' => \Zizaco\Entrust\Middleware\EntrustPermission::class,
        'ability' => \Zizaco\Entrust\Middleware\EntrustAbility::class,

    ];
}

routes
<?php

/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the controller to call when that URI is requested.
|
*/

Route::group(['middleware' => ['web']], function () {

    Route::get('/', function () {
        return view('welcome');
    });

});

//Route::get('/register',array('as'=>'newRegister','uses'=>'MailController@index'));

Route::post('/auth', 'MailController@store');

Route::group(['prefix' => 'api', 'middleware' => 'auth:api'], function () {

    Route::resource('note', 'NoteController');
});

Route::group(['middleware' => 'web'], function () {
    Route::auth();
    Route::get('/backoffice', 'HomeController@home');

});

Route::group(['middleware' => 'web'], function () {
    Route::auth();
    Route::get('/home', 'LoginController@index');

});

request
<?php

namespace App\Http\Requests;

use App\Http\Requests\Request;

class LoginRequest extends Request
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            //
        ];
    }
}

controller
<?php

namespace App\Http\Controllers;

use Auth;
use Mail;
use Session;
use Redirect;
use App\Http\Requests;
Use App\Http\Requests\LoginRequest;
use Illuminate\Http\Request;

Use App\User;

class MailController extends Controller
{
   public function store(LoginRequest $request)
    {

     $credentials = $request->only('email', 'password');

     if (Auth::attempt($credentials)) {

    if (Auth::check()) {

        if (Auth::check()) return Redirect::to('/home');

     }
    }

       return response(['msg' => 'Error'], 401) // 401 Status Code: Forbidden, needs authentication
          ->header('Content-Type', 'application/json');

    }

     public function createRegister(Request $request)

    {
        $user = new User;
        $data['name']=$user->name=$request->username;
        $data['email']=$user->email=$request->email;
        $user->password=bcrypt($request->password);
        $user->remember_token=str_random(100);
        if ($request->password==$request->confirm_password){

        if ($user->save())
        {
            Mail::send('mail.register',['data'=>$data], function($mail) use ($data){
                $mail->to($data['email'],$data['name'])->from('info@ddrw.ru')->subject('Welcome to');
            });
        }}else { return "Password not match";}
        return back();
    }
}

and my form javascript
 var form1 = {
            view:"form", id:"log2", width:550, scroll:false,
            elements:[
                {  cols :[
                { view:"text", hidden:true, name:"_token", value:'{{ csrf_token() }}', labelWidth:50, label:"Email" },
                    { view:"text", name:"email", value:'', labelWidth:50, label:"Email" },
                    { view:"text", name:"password", value:'', type:"password", placeholder:"password" },
                    {view:"button",  width:100, label:"login", click:login}
                ]}
            ]
        };

  function login(){
            QW.message("Auth");
            var values = $$("log2").getValues();
            values = JSON.stringify(values);
            console.log(values)
            QW.ajax().sync().headers({'Content-Type':'application/json'}).post("/auth", values, {
                error:function(){
                             QW.alert('Oops');

                },
                success:function(){

                    QW.alert('Thanks All fine');

                     //    window.location.href = "/home";
        }
            });

        }

A: I'm found solution .
problem with routes... session not sign in my prev solution... but this correct.
Route::group(['middleware' => ['web']], function () {

    Route::get('/', function () {
        return view('welcome');
    });

    Route::get('/home', 'HomeController@index');
    Route::get('/redirect', 'SocialAuthController@redirect');
    Route::get('/callback', 'SocialAuthController@callback');
    Route::post('/auth', 'MailController@store');

});

Route::auth();

Route::get('/home', 'HomeController@index');


text:
Q: For Loop with list if statement to check if length item smaller then not working in for loop i got a input list that contains string/numbers example (1,100,200,300,5000,etc)
i want a for loop to go over it and check if x length is smaller then 4
i tried so many combination it just doesn't work when the if is in the for loop but i need to have it in there since it needs to test it on a bunch of numbers
@echo off
setlocal enabledelayedexpansion
    for %%x in ("1" "10" "100" "1000" "10000") do (
    if %%x:~4% == "" (
        echo "Length is not bigger than 4 characters."
    ) else (
        echo "Length is bigger than 4 characters."
    )
)
pause


text:
Q: How to require multiple permissions on a single broadcast? I'm working on an android Service that allows other applications to collect data received from a company's proprietary devices. The connection can be made over Bluetooth or USB. I allow other applications to access this data through broadcasted intents sent out by the service. I would like to force applications to have the bluetooth permission as well as another permission for accessing our data before they can receive the intent. I know I can force BroadcastReceivers to have one permission to receive my Broadcasted intent using sendBroadcast(Intent intent, String receiverPermission) but how do I require the receiver to have more than one permission to see my Broadcast?
Thanks in advance.


text:
Q: Why is this div with 100vh height not covering the whole viewport? The blue div in this code has a height of 100vh whereas the red div has the height of 5000px. Shouldn't the blue div extend itself to cover the whole viewport because of the 100vh height attribute?

body {
  margin: 0;
}

What I want to achieve from this is that suppose there's some text which overflows on sizing down the window then how should I get around that situation so that the 100vh height div again covers up the new window size?

A: Viewport height just means that the height of the element will be a percentage of the viewport.  The viewport being the window your viewing the page on.  So if it is a 1920x1080 screen the viewport height will be 1080px or whatever your browser window is, it may be less if you have a toolbar at the bottom of your screen.  The issue you are having is that if you want the sidebar to follow the main content down the page you need to disregard the viewport and have a wrapper around both of them like so:

.main-wrapper{
  display:flex;
}

aside{
   background:blue;
   color:#fff;
   width:200px;
}

main{
  background:green;
  height:5000px;
  flex:1
}

  Your sidebar
  Your Main Content

That being said you may want to check out the following fiddle Here.  I have made this fiddle responsive for mobile screens so you may have to resize the output window larger to view the sidebar layout.  The issue is you are absolutely positioning items and fixing items outside divs which is bad practice.  In your example you commented on above you have many layout and z-index issues that you will run into.  This fiddle is just an example but it should give you a good frame of reference on how the layout should be thought of.

A: It is happening because that's how vh works.
vh is based on the height of viewport. 1vh =  1% of viewport height.
https://www.sitepoint.com/css-viewport-units-quick-start/

A: 1vh is Relative to 1% of the height of the viewport*
so 100vh will correspond to 100% of the height of the viewport
demo here
For further details please refer to the CSS Units documentation.


text:
Q: Autohotkey DLLcall to CreateCaret returns 0 (The function failed) but A_LastError is also 0 (The function succeeded) I'm trying to use a simple AHK DLLCall to the user32 api function CreateCaret. I want it to give notepad a thick text caret.
caretWidth := 10
NULL := 0
Ptr := A_PtrSize ? "Ptr" : "UInt" ; If A_PtrSize is not defined, use UInt instead.
WinHwnd := WinExist("A")
result := Dllcall("CreateCaret", Ptr, WinHwnd, Ptr, NULL, "Int", caretWidth, "Int", 0)
msgbox % "LE " A_lasterror  ; Gives LE 0
msgbox % result  ; Gives 0

This should be equivalent to the following c++ call:
CreateCaret(0x37072c, NULL, 10, 0);

Purposefully screwing up the function name makes result blank, so I believe the function is being called correctly. I just don't know why it is failing
Using similar code for GetCursorBlinkRate returns a sensible number.
I have also tried with caretWidth := 0
Similar questions about GetLastError are c++ calls, and AHK supposedly ensures that GetLastError is called in a timely enough manner to ensure A_lasterror is set correctly. Why is it showing no error code when the function apparently fails?

A: You can't change the caret of an external process.
If you try this for example, you'll see it works just fine if you own the process:
#Persistent
Gui, +hwndHWND
Gui, Add, Edit
Gui, Show

DllCall("CreateCaret", Ptr, HWND, Ptr, 0, Int, 50, Int, 50)
DllCall("ShowCaret", Ptr, HWND)

ESC::
GuiClose:
ExitApp


text:
Q: How to use sub routes in react-router that match on query string or hash? More examples are definitely needed in the docs for this but basically I am after something like this for example:
<Route path="/" component={CoreLayout}>
  <IndexRoute component={IndexLayout} />
  <Route path="foo/bar" component={MyComponent}>
    <Route path="#baz=laa" component={SubComponent} />
  </Route>
</Route>

I've tried importing history attribute and all sorts and cannot get it to match. Our issue is that we are building a new mobile site, keep the same paths as the desktop site, however we have some routes which are new on mobile and we want to add those using the hash.
If anybody has any ideas, would be much appreciated. Thanks


text:
Q: I cannot start my camera, neither share my screen in Google Meet after upgrading Windows to Windows 11 Since I've upgraded my Windows to Windows 11, I am not able to use the Google Meet.
My camera is OK in other programs, but the message "A câmera está iniciando" is persistent (my language is portuguese).
Moreover, when I try to share my screen, no things occur. I only can share Jamboards, but not my screen.
I have the last version of the Google Chrome, but also tried in Edge and cannot get success.
I've checked the permissions, it's all allowed.

A: @Rubén and @John, I've finally get the right driver in https://support.lenovo.com/vn/en/downloads/ds551550-camera-driver-realtek-sonix-for-windows-11-64-bit-legion-7-16achg6. That worked. Thank you for the assistance.


text:
Q: .net core 2.0 Entity Framework - Add table relationship at db level and update model I'm working on an application who implements .net core 2.0 with Entity Framework.
I have generated the model by scaffolding the existent db using package manager console.
Now I have manually edited the database by adding a missing relationship between two tables.
What is the best way to update the model?
In this moment I'm deleting all the model files and I run the scaffolding command each time...
How to avoid this ?
Thanks to support

A: You can simply add the missing virtual fields to the objects.
If the columns have matching names, you can simply add them directly:
class Customer {
    public int CustomerId {get;set;} // PK that was already there

    // new navigation property
    public virtual ICollection<Account> Accounts { get; set; }
}

class Account {
    public int AccountId {get;set;}

    // new FK
    public int CustomerId { get;set; }
    // new navigation property
    public virtual Customer Customer {get;set;}
}

In case you have multiple fks to the same table, or names don't match, you may have to add some code to the OnModelCreating method on your DbContext.
The simpler way to see how this is done is to regenerate once your code with your tool and compare the old one with a tool like WinMerge. EF Core is much simpler than EF6, once you understand the idea you'll never have to use these tools again. I hand code all my entities and I find it much easier than using these tools.


text:
Q: Get value of input, but strip html syntax I have dynamically generated inputs off of a DB table, that lists multiple 'options'. I have a script that takes the entire list of options, then splits them based on a character of |. After I split them, they are left as span divs which i then apply to inputs dynamically.
One of these inputs looks like this:
<input class="filterable-content" type="checkbox" name="topics" value="Account" id="group3-Account">

I am updating the url on click of these checkboxes, but since I am getting value it is bringing this whole value Account. Is there anyway to drop the  of the value when it appends to my url?
Here is how I am getting values:
$(".filterable-content").on("change", function() {
        var hash = $(".filterable-content:checked").map(function() {
            return this.value;
        }).toArray();
        hash = hash.join("&");
        window.location.hash = 'query=' + hash;
    });

This is how the url should look:
www.website.com/query=account&profile.
This is what I am getting currently:
www.website.com/query=Account&Profile.
Any idea what I could do for this? Appreciate the help!

A: Use text() to get the text inside the span tag.

$(".filterable-content").on("change", function() {
    var hash = $(".filterable-content:checked").map(function() {
        return $(this.value).text();
    }).toArray();
    hash = hash.join("&");
    console.log(hash);
    window.location.hash = 'query=' + hash;
});

<input class="filterable-content" type="checkbox" name="topics" value="Account" id="group3-Account">
<input class="filterable-content" type="checkbox" name="topics" value="Profile" id="group3-Account">


text:
Q: Where are values stored in JavaScript? I've heard that in JavaScript, primitive types are stored on the stack and that objects are stored on the heap. Is that true for all cases even for values inside of a function's execution scope? Moreover, are all globally scoped variables and functions stored on the global object (window in the browser) in JavaScript and is that considered to be the "heap" or part of the heap? Or are the primitive types themselves stored on the stack and reference types on the heap and then the identifiers are added as properties to the global objects and point to those values on the stack/heap?

A: There is no heap and no stack. JavaScript's memory model is very abstract. How things end up in your computers memory is totally up to the engine. Given that modern engines perform a lot of optimizations, values might end up in different regions of the memory even in different optimization stages, so one really can't tell.


text:
Q: IOS UiView animation producing different effects on ios 5 and ios 6 devices i created the zooming animation in my ios application, its working fine in ios 6 devices, but when i run the same code on devices containing ios 5, its behaving differently, that is button (on which i put this effect) coming with stretching and delay effect. Can anyone please take a look on code and checkout what i'm mistaken.
Code
- (void) zoomEffect
{
    self.transform = CGAffineTransformScale(CGAffineTransformIdentity, 0, 0);
    [UIView animateWithDuration:0.3 animations:^{
        self.transform = CGAffineTransformScale(CGAffineTransformIdentity, 1.3, 1.3);
    } completion:^(BOOL finished){
        [UIView animateWithDuration:0.3 animations:^{
            self.transform = CGAffineTransformIdentity;
        } completion:^(BOOL finished){

        }];
    }];
}

A: I had same "issue"... :)
Try to change this line
self.transform = CGAffineTransformScale(CGAffineTransformIdentity, 0, 0);

in
self.transform = CGAffineTransformScale(CGAffineTransformIdentity, 0.0001, 0.0001);


text:
Q: bash cat exclude multiple files based on grep results I have the following cat command that I use in a bash script. I look for $SAMPLE.txt file in subfolders 20* and combine them into 1 output.txt
cat /$FOLDER/20*/$SAMPLE.txt > /$OUTPUTFOLDER/output.txt
I now want to exclude certain files conditionally.
I found the following here https://unix.stackexchange.com/questions/246048/cat-files-except-one
$ shopt -s extglob
$ cat -- !(DISCARD).txt > catKEPT

I want to do something like this.
Look for $SAMPLE and a pattern '$PAT1' in a $SAMPLEFILE. This $SAMPLEFILE is comma seperated. If there is a match, I want to store the first field of this line & use it to exclude files from cat
I would use this command to look for $SAMPLE and $PAT1 & then cut to keep my first field. I would assign that to a variable 'EXLUDE_FOLDER'
EXCLUDE_FOLDER=grep '$SAMPLE' $SAMPLEFILE | grep '$PAT1' | cut -d "," -f 1

And then use it like this
cat /$FOLDER/20*/$SAMPLE.txt -- !($FOLDER/$EXLUDE_FOLDER/$SAMPLE.txt) > /$OUTPUTFOLDER/output.txt

I'm stuck at putting this into an if/statement and dealing with situations where grep results in multiple matches, so multiple files should be excluded

A: If SAMPLE and PAT are variables, you presumably want them expanded to their contents, which means you must put them in double quotes, not single quotes. Example:
SAMPLE=3

# Compare single quotes versus double
echo '$SAMPLE'              # outputs $SAMPLE
echo "$SAMPLE"              # outputs 3

If SAMPLEFILE is the name of a file, you must double-quote it, else it will fail if your filename has spaces in it, so you must use:
grep "$SAMPLE" "$SAMPLEFILE"

So, now you can test if your grep works like this:
grep "$SAMPLE" "$SAMPLEFILE" | grep "$PAT1" | cut -d "," -f 1

So, if that works, the next thing is that you want to capture the output of the command, so you need to use $(...). That means:
EXCLUDE_FOLDER=$(grep "$SAMPLE" "$SAMPLEFILE" | grep "$PAT1" | cut -d "," -f 1)

So, see test if that works now:
echo "$EXCLUDE_FOLDER"


text:
Q: Any shortcut to remember least upper bound $\vee$ and greatest lower bound $\wedge$ in Lattice concept I know this is silly but I am every time forgetting lub (least upper bound) in lattice as $\vee$ and glb (greatest lower bound) as $\wedge$. Is there any shortcut  or mnemonic for remembering which one is join and which one is meet? Is there any historical reason for choosing such symbols?

A: If you think about logical operations as binary operations on $\{0,1\}$ under the identification $\text{True}=1$ and $\text{False}=0$, then $\land$ coincides with $\min$ and $\lor$ coincides with $\max$.

A: I too have struggled with this notation when I first learned about lattice theory. I am glad to see that I am not alone in this confusion. Something making the notation particularly confusing is there is a "v" shape in the Hasse diagram of a lattice formed by $x \wedge y$, $x$ and $y$ (if $x$ and $y$ are incomparable yadda yadda...) and a wedge shape in the Hasse diagram of a lattice formed by $x \vee y$, $x$ and $y$. But something I have not thought about until now is that if we draw Hasse diagrams upside-down, this is no longer an issue.
Like Angina mentioned, $\cup$ and $\cap$ mimic the shape of $\vee$ and $\wedge$. My hypothesis is that, since Boolean algebras were studied before general lattices, that $\cup$ and $\cap$ were the only notation. Then, somewhere along the way, the symbols were drawn a bit differently to distinguish between sets and elements of an abstract lattice.
In my opinion, the symbol $\wedge$ is used way to frequently in mathematics. E.g. the smash product in topology, exterior algebra of a vector space (in particular, differential forms), lattice meet, logical AND etc. (there are probably more, maybe a use in analysis?). Unfortunately, while you and I may not like the meet/join notation, we are stuck with it as the notation has stood the test of time.


text:
Q: How to specify play-services-location I would like to use googlePlayServicesVersion 16.1.0, but than I get

Could not find com.google.android.gms:play-services-location:16.1.0

I have tried adding implementation 'com.google.android.gms:play-services-location:16.0.0' inside app/build.gradle dependencies
I have added googlePlayServicesVersion = "16.1.0" inside android/build.gradle

A: The version com.google.android.gms:play-services-location:16.1.0 doesn't exist.
You can use one of these:
com.google.android.gms:play-services-location:16.0.0
com.google.android.gms:play-services-location:17.0.0

You can also check the in maven google repo:


text:
Q: Display Table data in Gridview Here I am trying to display the data which is entered by user in table. I want to add this data in Gridview. Like in Table, user will enter data then this data has to save in Gridview and as well as it has to save in DataBase. Now I am trying to save this data in Gridview.
Here Table code for Entering the data. here user will enter the data.
    <asp:Table> //Table
    <asp:TableRow>
                            <asp:TableCell>
                                <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
                                </asp:TableCell>
                             <asp:TableCell>
                                <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
                                </asp:TableCell>
                             <asp:TableCell>
                                <asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
                                </asp:TableCell>
                             <asp:TableCell>
                                 <asp:TextBox ID="FromDate" runat="server"></asp:TextBox>
                             </asp:TableCell>
                             <asp:TableCell>
                                 <asp:TextBox ID="ToDate" runat="server"></asp:TextBox>
                             </asp:TableCell>
                             <asp:TableCell>
                                <asp:TextBox ID="TextBox6" runat="server"></asp:TextBox>
                                </asp:TableCell>
                        </asp:TableRow>
                    </asp:Table>

Here is the button for adding the table data in Gridview.. When user clicks this button the data which entered by user in Table should display in gridview.
     <button id="AddMore_Button" class="btn btn-primary" onclick="Save_Info()">Add More</button>  //button

Here is the code for Gridview to show the information in table which entered by User. This gridview will display the data wich is entered in Table.
 <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
                                    <Columns>
                                        <asp:BoundField HeaderText="Name" />
                                        <asp:BoundField HeaderText="Address" />
                                        <asp:BoundField HeaderText="Contact" />
                                        <asp:BoundField HeaderText="From Date" />
                                        <asp:BoundField HeaderText="To Date" />
                                        <asp:BoundField HeaderText="Website" />
                                    </Columns>

Here is the C# code for Display the data.. Here the data from table which entered by User will display in gridview.
    protected void Save_Info(object sender, EventArgs e)
            {
                DataTable dt = new DataTable(); //Datatable

                dt.Columns.Add(TextBox1.Text);
                dt.Columns.Add(TextBox2.Text);
                dt.Columns.Add(TextBox3.Text);
                dt.Columns.Add(FromDate.Text);
                dt.Columns.Add(ToDate.Text);
                dt.Columns.Add(TextBox6.Text);
                GridView1.DataSource = dt;  //Gridview
                GridView1.DataBind(); //binding data to Gridview
               }

When I click on "Add_More" button it is not saving the data in Gridview and not displaying the data. How can I achieve this using C#.
        Any wrong in this code..?? Please tell me.

A: <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" >
    <Columns>
        <asp:BoundField HeaderText="Name" DataField="Name" />
        <asp:BoundField HeaderText="Address" DataField="Address"/>
        <asp:BoundField HeaderText="Contact" DataField="Contact" />
        <asp:BoundField HeaderText="From Date" DataField="FromDate" />
        <asp:BoundField HeaderText="To Date" DataField="ToDate" />
        <asp:BoundField HeaderText="Website"  DataField="Website"/>
    </Columns>
</asp:GridView>

Place this code in your button click event:
{
    DataTable dt = new DataTable();
    dt.Columns.Add("Name");
    dt.Columns.Add("Address");
    dt.Columns.Add("Contact");
    dt.Columns.Add("FromDate");
    dt.Columns.Add("ToDate");
    dt.Columns.Add("Website");

    DataRow dr1 = dt.NewRow();

    dr1["Name"] = TextBox1.Text;
    dr1["Address"] = TextBox2.Text;
    dr1["Contact"] = TextBox3.Text;
    dr1["FromDate"] = FromDate.Text;
    dr1["ToDate"] = ToDate.Text;
    dr1["Website"] = TextBox6.Text;

    dt.Rows.Add(dr1);
    GridView1.DataSource = dt;
    GridView1.DataBind();
}

This is working piece of code.

A:  <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
   <Columns>
      <asp:BoundField HeaderText="Name" DataField="Name" />
      <asp:BoundField HeaderText="Address" DataField="Address"/>
      <asp:BoundField HeaderText="Contact" DataField="Contact"/>
      <asp:BoundField HeaderText="From Date" DataField="FromDate"/>
      <asp:BoundField HeaderText="To Date" DataField="ToDate"/>
      <asp:BoundField HeaderText="Website" DataField="Website"/>
   </Columns>

in C# code side you can do like this
DataTable dt = new DataTable();
protected void Save_Info(object sender, EventArgs e)
  {
    DataRow dr1 = dt.NewRow();

    dr1["Name"] =TextBox1.Text;
    dr1["Address"] =TextBox2.Text;
    dr1["Contact"] =TextBox3.Text;
    dr1["FromDate"] =FromDate.Text;
    dr1["ToDate"] =ToDate.Text;
    dr1["Website"] =TextBox6.Text;
    dt.Rows.Add(dr1);
    GridView1.DataSource = dt;  //Gridview
    GridView1.DataBind(); //binding data to Gridview
 }


text:
Q: Observed fact: 70% of the newborn babies are girls, what are the chances that the ratio of boy girl remain the same? I am a nurse working in a hospital, and from my observation, out of $p$ number of babies born in year 2016, 70% of them are girls.
Given this, what are the chances that the ratio of boy:girl remain $50:50$ for new born baby in year 2016? Assuming that the total number of born baby in the world in year 2016 is $X$
PS: I am asking this because I suspect that there might be a deeper reason why more girls are born than boys this year.

A: I'm not sure this question can be answered as asked, but...
If we assume male/female births are equally likely (not true [males are born more frequently], but close), we would expect p/2 female births with a variance of p/4 and a standard deviation of Sqrt[p]/2.
Percentagewise, this is 50% female births with a 1/2/Sqrt[p] standard deviation.
So, 20% would be (20/100)/(1/2/Sqrt[p]) or (2/5)*Sqrt[p] deviations from the mean.
Thus, if more than 25 babies were born total, having 17.5 (ie, 18) or more females is only 5% likely.
If more than 56.25 (ie, 56) babies were born total, having more than 39.375 (ie, 40) born female is only 0.5% likely.
So, depending on the value of p, this circumstance may or may not be remarkable (though I suspect many other factors apply, so this is only a theoretical answer).
Of course, unless p is very large compared to X (unlikely in a single hospital), the world population, it won't have a significant effect on the world ratio of male/female births.

A: Very, very, likely there is no deeper reason.
You are probably experiencing what Daniel Kahneman calls "the law of small numbers" (in his "Thinking, Fast and Slow"). We expect small samples to have the same behaviour as the underlying, large, universe they are drawn from. So we may expect to have also roughly 50:50 birth distribution on a small sample, because we know that is so on the large scale. Yet that is not the case, "strange" things this happen, more so on the small scale.
A couple of quick reasonings.
There are some 135 million births per year (2016 data, from wikipedia). IF you split those in batches of 100 (I do not know how many you have observed), that means we have about 1.35 million batches. Now note that something as (un)likely as 1 in 1.35 million (0.00007%) is quite likely (63%) to happen in at least one of those batches.
Another approach, a quick Bayesian estimate of the birth distribution updated by your observation. Using a prior knowledge of binomial distribution with 67.5 million newborns of each gender, that is a probability of 50% of having a girl on a birth. A updated best guess for the newborn girl probability, using 0.7*p girls out of p births, would be:
$$P(girl,p)=\frac{67,500,000+0.7*p}{135,000,000+p}$$
For $p=100, P(girl,p) \approx 50.000015%$.
Finaly, last assume in the previous 4 years you had a birth distribution of 45:55, (girls:boys). I bet you would not take any special note of it. Now if you join those more or less normal years and add them to this strange year, you get $(4*45+1*70):(4*55+1*30) \rightarrow 250:250 \rightarrow 50:50$, that is, a completely normal 5 year period.


text:
Q: Is a finite group action on a finite set determined by its fixed points? Suppose I am given a finite group $G$, and a finite set $X$, and told that $G$ acts on $X$, but not told how.
However, suppose for every subgroup $H\le G$, I am given the subset $X^H\subset X$ of elements fixed by everything in $H$.
Does the above data allow us to determine the action of $G$ on $X$ up to isomorphism? Ie, could two nonisomorphic actions give rise to the same collection of fixed points $\{X^H : H\le G\}$? (Here two actions "." and "$\cdot$" of $G$ on $X$ are isomorphic if there is a self-bijection $f : X\rightarrow X$ with $f(g.x) = g\cdot f(x)$

A: If $G$ acts transitively on $X$, and $x_{0}$ is a fixed element of $X$, your information will yield the stabilizer $G_{x_{0}}$, as the largest subgroup $H$ such that $x_{0} \in X^{H}$. So you will know that the action of $G$ on $X$ is isomorphic to that of $G$ on the cosets of $G_{x_{0}}$.

A: I believe that the answer is yes. In fact I think that it is enough to assume that the sizes of the fixed point sets of each $H \le G$ are the same in both actions.
Here is a rough argument. I think what you call isomorphic actions are usually called equivalent actions so I will do so. The aim is define an equivalence $\tau:X \to X$ between the two actions $\alpha$ and $\beta$. It is more convenient to let the two actions be on sets $X_1$ and $X_2$ with $X_1=X_2=X$.
Firstly, the fixed points of $G$ under $\alpha$  can be mapped bijectively by $\tau$ to the fixed points under $\beta$, so we can now forget about those,
and remove the fixed points under the two actions from $X_1$ and $X_2$. (So $X_1$ and $X_2$ might now be different.)
Now let $H$ be a maximal subgroup of $G$. Then, each fixed point of $H$ under an action must correspond to an orbit of the action that is equivalent to the action by multiplication on the cosets of $H$, as in Andreas Caranti's answer. There is exactly one fixed point for each such orbit. So we can now define $\tau$ on each of these orbits under $\alpha$, mapping them to corresponding orbits under $\beta$. We can do that for each of the maximal subgroups, and after doing that, we can remove the points in all of these orbits from $X_1$ and $X_2$. (In fact when we define the correspondence between two such orbits we are dealing with all maximal subgroups in a conjugacy class.)
Now we consider the two-step maximal subgroups $H$ of $G$ i.e. maximal subgroups of maximal subgroups. Since we have removed orbits in which a point stabilizer is maximal, all fixed points of such subgroups must correspond to orbits on the cosets of those subgroups. Now there could be more than one fixed point of $H$ in each orbit, but there will be the same number in each orbit, so we can define $\tau$ on these orbits as before.
Then we consider $3$-step maximal subgroups, and carry on until like that until $\tau$ is defined on the whole of $X_1$.

A: So the answer is yes, and it is equivalent (by the Galois correspondence) to the positive answer to this question:
Is a locally constant etale sheaf determined by its sections over finite etale neighbhorhoods?


text:
Q: Problem with imports/exports/declarations component in Angular I have a component created, as you can see in the code sample, I import it, export it and even declare it, but it doesn't take me. Can you please tell me what the problem may be?
Error:
Appears in the NgModule.imports of SalesModule, but could not be resolved to an NgModule class.
Is it missing an @NgModule annotation?
9 export class PaymentStatusComponent implements OnInit {
sales.module.ts:
@NgModule({
    exports: [PaymentStatusComponent],
    imports: [PaymentStatusComponent],
    declarations: [PaymentStatusComponent]
})
export class SalesModule {}

A: Thankfully this is a simple fix.
Remove PaymentStatusComponent from the imports array.
Why?
Because it's a component and the imports array only takes modules.


text:
Q: shell scripts to pattern(s) search and list file(s) in a directory I used ls | agrep "<search pattern #1>;<search pattern #2>;...;<search pattern #n>" to quickly and/or effectively perform a search/list of some file(s) in a directory with some search pattern(s). As an illustration, I created an empty directory and filled it with some empty files using the touch command as shown below:
~ ls -l
total 0
-rw-r--r-- 1 me users 0 May  7 14:00 animals-bird_dog_cat.txt
-rw-r--r-- 1 me users 0 May  7 14:00 animals-bird_dog.txt
-rw-r--r-- 1 me users 0 May  7 14:00 animals-bird.txt
-rw-r--r-- 1 me users 0 May  7 14:00 animals-cat_dog_bird.txt
-rw-r--r-- 1 me users 0 May  7 14:00 animals-cat_dog.txt
-rw-r--r-- 1 me users 0 May  7 14:00 animals-cat.txt
-rw-r--r-- 1 me users 0 May  7 14:00 animals-dog_bird.txt
-rw-r--r-- 1 me users 0 May  7 14:00 animals-dog_cat_bird.txt
-rw-r--r-- 1 me users 0 May  7 14:00 animals-dog_cat.txt
-rw-r--r-- 1 me users 0 May  7 14:00 animals-dog.txt

Then, using ls -l | agrep "cat;bird", I have no problem to search/find file(s) whose name(s) contain only cat and bird as shown below.
~ ls -l | agrep 'cat;bird'
-rw-r--r-- 1 me users 0 May  7 14:00 animals-bird_dog_cat.txt
-rw-r--r-- 1 me users 0 May  7 14:00 animals-cat_dog_bird.txt
-rw-r--r-- 1 me users 0 May  7 14:00 animals-dog_cat_bird.txt

AFAICT, this method is pretty fast and effective (I am all ears for a better solution). Since I do this a lot on a daily base, I thought it may be better to write a simple shell script to perform such a task by simply giving the search pattern(s) in CLI. For instance, I wrote a simple shell scripts as shown below and named it mls and make it executable:
#!/bin/bash
bold=$(tput bold)
italic=$(tput sitm)
normal=$(tput sgr0)
if [ "$#" -lt 1 ]; then
    echo "${bold}Usage${normal}: $0 <search string 0> [... <search string n>]"
    exit 0
fi
patterns=""
for ((i=1;i<$#;i++))
do
    patterns+="${!i};"
done
patterns+="${!#}"
/usr/bin/ls -lart | agrep '${patterns}${!#}'

Then, when I executed the above shell script with a search pattern of mls cat bird, it returns nothing as shown below.
~ ls -l | agrep 'cat;bird'
-rw-r--r-- 1 me users 0 May  7 14:00 animals-bird_dog_cat.txt
-rw-r--r-- 1 me users 0 May  7 14:00 animals-cat_dog_bird.txt
-rw-r--r-- 1 me users 0 May  7 14:00 animals-dog_cat_bird.txt
~ mls cat bird
~

Did I miss something?

A: You could switch to zsh here whose globs support OR, AND (well AND-NOT and NOT) and approximation
$  set -o extendedglob # best in ~/.zshrc
$ ls -ld -- (#a1)*dig*~^(#a1)*bard*
-rw-rw-r-- 1 chazelas chazelas 0 May  8 16:24 animals-bird_dog_cat.txt
-rw-rw-r-- 1 chazelas chazelas 0 May  8 16:24 animals-bird_dog.txt
-rw-rw-r-- 1 chazelas chazelas 0 May  8 16:24 animals-cat_dog_bird.txt
-rw-rw-r-- 1 chazelas chazelas 0 May  8 16:24 animals-dog_bird.txt
-rw-rw-r-- 1 chazelas chazelas 0 May  8 16:24 animals-dog_cat_bird.txt

A: Aside from the single quote problem, you're adding the last element twice
patterns+="${!#}"
/usr/bin/ls -lart | agrep "${patterns}${!#}"

Run the program with bash -x mls cat bird to see

But you don't need a loop: the "$*" special parameter joins the positional parameters using the first character of IFS. If we temporarily define a new value for IFS, we can do
patterns=$( IFS=';'; echo "$*" )

If you don't need the "approximate" part of agrep, bash can do this by itself using extended glob patterns.
pattern=$( IFS='|'; echo "$*" )
shopt -s extglob
ls *@($pattern)*


text:
Q: Issues with Inserting uneven data from datagridview into database c# Hi i have this codes that insert data from datagridview to database
for (int i = 0; i < ADODB.Rows.Count - 1; i++)
        {
            SqlCommand cmd = new SqlCommand("INSERT INTO Employee VALUES(@Team, @SIC, @EID,@EmployeeName,@Username,@Password,@Designation,@Department,@Email,@HireDate,@TakenAL,@Status)", con);

            cmd.Parameters.AddWithValue("@Team", ADODB.Rows[i].Cells[0].Value);
            cmd.Parameters.AddWithValue("@SIC", ADODB.Rows[i].Cells[1].Value);
            cmd.Parameters.AddWithValue("@EID", ADODB.Rows[i].Cells[2].Value);
            cmd.Parameters.AddWithValue("@EmployeeName", ADODB.Rows[i].Cells[3].Value);
            cmd.Parameters.AddWithValue("@Username", ADODB.Rows[i].Cells[4].Value);
            cmd.Parameters.AddWithValue("@Password", ADODB.Rows[i].Cells[5].Value);
            cmd.Parameters.AddWithValue("@Designation", ADODB.Rows[i].Cells[6].Value);
            cmd.Parameters.AddWithValue("@Department", ADODB.Rows[i].Cells[7].Value);
            cmd.Parameters.AddWithValue("@Email", ADODB.Rows[i].Cells[8].Value);
            cmd.Parameters.AddWithValue("@HireDate", ADODB.Rows[i].Cells[9].Value);
            cmd.Parameters.AddWithValue("@TakenAL", ADODB.Rows[i].Cells[10].Value);
            cmd.Parameters.AddWithValue("@Status", ADODB.Rows[i].Cells[11].Value);
            con.Open();
            cmd.ExecuteNonQuery();
            con.Close();
        }

I would like to ask what if i have 12 columns in my datagridview but my database has 13 columns. It would prompt an error due to the the difference in things that are added. How do i solve this problem?
Thanks in advance

A: Use name reference for the columns, i.e.
        cmd.Parameters.AddWithValue("@Team", ADODB.Rows[i].Cells["Team"].Value);
        cmd.Parameters.AddWithValue("@SIC", ADODB.Rows[i].Cells["SIC"].Value);
        cmd.Parameters.AddWithValue("@EID", ADODB.Rows[i].Cells["EID"].Value);

The columns will receive their name from the database column, when you load data from database. Other way is to set and name the columns via GUI in VS, or via code, i.e.:
DataGridView1.Column[2].Name = "EID"

If you design your column scheme of datagridview in GUI or code first, make sure you use
DataGridView1.AutoGenerateColumns = False

and that your use that name reference when loading data, using DataPropertyName:
DataGridView1.Column[2].DataPropertyName = "EID"


text:
Q: Magento Admin not referencing any JS or CSS Magento 1.6.2
Dedicated Server
This morning I installed Fooman Speedster, everything turned to back immediately. Uninstalling it did no seem to undo the destruction.
Following a lot of posts, I have cleared all cache files and checked file/folder permissions.
Currently, I have got the frontend is functioning properly and orders are being placed.
The problem left is with the CMS. No CSS or JS files are being called.
Therefore, no buttons within the admin are working and nothing can be done from within there.
CSS is there on the admin login and MagentoConnect parts. But the main admin part is not working.
Any ideas on how to get the admin calling CSS and JS again?
Thanks

A: this compress and combines all css and js . Have you taken any backup? Have u installed it from mage connect ?


text:
Q: Returning row with zero instead of no result I have a query which looks exactly like this:
SELECT aid,
  COALESCE(SUM(s.amount),0) AS total_spend
FROM rt_spends AS s
WHERE `aid` = 7
  AND `date` BETWEEN '2013-12-01' AND '2013-12-09'
GROUP BY s.aid

Which returns something along the lines of:
aid | total_spend
7       100.00

However in the event there are zero records in that daterange. I would like to output something such as
aid | total_spend
7       0.00

Would this be better suited for PHP or MySQL?

A: This will work, and given that it's pretty complicated for a simple SUM query I think it also illustrates that you may be better off handling "no results" in PHP :)
SELECT aid, SUM(s.amount) AS total_spend
FROM (
  SELECT amount FROM rt_spends
    WHERE aid = 7 AND `date` BETWEEN '2013-12-01' AND '2013-12-09'
  UNION SELECT 7, 0
) s
GROUP BY s.aid

A: Change COALESCE to IFNULL.
Coalesce is for comparisons, you're selecting.

A: Illustrating arkascha's comment:
SELECT *
FROM (
  (SELECT aid,
    COALESCE(SUM(s.amount),0) AS total_spend
  FROM rt_spends AS s
  WHERE `aid` = 7
    AND `date` BETWEEN '2013-12-01' AND '2013-12-09'
  GROUP BY s.aid)

  UNION ALL

  (SELECT aid, 0 AS total_spend WHERE `aid` = '7')
) sub_query
LIMIT 1

A: I would have gone along the route of this but my memory for syntax is not the best:
SELECT aid,
  COALESCE(sub.total_spent,0) AS total_spend
FROM rt_spends AS s
    LEFT JOIN (
        SELECT SUM(rt_spends.amount) AS total_spent
        FROM rt_spends
        WHERE `aid` = 7
            AND `date` BETWEEN '2013-12-01' AND '2013-12-09'
        GROUP BY rt_spends.aid
    ) AS sub
WHERE `aid` = 7
GROUP BY s.aid

IMO though, you are probably better off doing this in the PHP as why get MySQL to do the work when there is nothing to get!?
You are passing the aid anyway so if 'total' is null do whatever you wanted to. The only reason I can think you would need to handle this in the query is if you are pulling more information out from the database and this is just one element of it i.e. you need the record to return other stuff even if there is no spend amounts but if there are amounts you need the total but just between the dates - which is why I would go down a subquery route.


text:
Q: "Role model" Vs "Exemplar"
*

*
Role model:
  Someone whose behaviour, attitudes etc people try to copy because they admire them.

*
Exemplar:
  An exemplar is someone or something that is considered to be so good that they should be copied or imitated.

My question:
I was wondering how these two differ in meaning and can change the meaning of a sentence?
Example:

*

*
I have always wanted to be a positive and good  ___________ for my brother.

a. role model
b. exemplar
Based on dictionary definitions I think they both mean the same and work interchangeably in this example.
Please kindly enlighten me.

A: According to the Cambridge Dictionary, exemplar can only be applied to a thing, not a person. Merriam-Webster is not clear whether it can be applied to a person, but Collins and Oxford Dictionary state that it can be. I personally have never heard of it used about a person, although if you google it you can find a few written references- mainly in religious texts.
As the Cambridge Dictionary states, exemplar is a formal word: I think you would be much better off using role model.
Note that the definition of role model does not state whether the behaviour of the role model is good or bad- only that somebody else admires them. Somebody could have a mass murderer as a role model, and go on to become a mass murderer themselves.
Conversely, exemplar is always good, so you don't need to include the words positive and good in your sentence:

I have always wanted to be an exemplar for my brother.


text:
Q: Force reload of environment variables in IntelliJ... without restarting? The title says it all.
I have modified an environment variable which is used in my java project via, for example, this line in my pom.xml:
<url>${env.DB_CONNECTION_URL}</url>

For this change to take effect, I must manually restart IntelliJ.
Interestingly, I installed an IntelliJ plugin to "Restart" IntelliJ, which it does, but the environment variables are not refreshed.
Is there a way to do this, without restarting?

A: If you started IntelliJ through "JetBrains Toolbox", then in order to reload the environment variables you need to close them both (IntelliJ & Toolbox), start the toolbox, and then start IntelliJ via the toolbox.

A: Not possible. Once you start a process in Windows or in Unix, you can't read updated environment variables from outside. You can only change environment variables inside your process.
This IntelliJ plugin might not be completely restarting the app, but is i.e. using a different class loader instead.

A: There is a method to do that without restarting IDE by creating a new local terminal in your IDE, and that does the job.

*

*click right bouton in the terminal of the IDE

*click New session

That worked for me in Pycharm, and the environment variables are reloaded with new paths

A: Seems that Intellij caches those veriables even restarted. The Vars in my case has been refreshed after relogin on Windows. Not sure if it does the same on Linux/Mac Os but I worked around it on Windows by going to
File -> Settings -> Build, Execution, Development -> Build Tools -> Maven -> Runner.
Then clicked small document icon inside Environment variables textbox. Now while Include system environment variables is ticked I could modify relevant variable or I could add one to User environment variables.
IntelliJ consumed them immediately without restarting/reloading/relogging
Like here

A: Once you update an environment variable after Intellij launched, you can't load the latest value within Intellij.
Below is my solution FYR:

*quit Intellij

*open a new terminal, ensure the latest updated env var is there

*launch Intellij from this terminal in command line, say, idea

*check the env var in Intellij

btw, to use env var in your maven run, follow the steps:
Runs -> Edit Configurations... -> your maven run -> Runner -> Environment variables: -> Include system environment variables:
Good luck~

A: In Linux/UNIX, possibly a shell can source profile by for example:
. /etc/profile
Refresh the env without exiting the current shell.


text:
Q: How can I count only specific values in tabluea? I have a medal column, there are 4 different values in the medal column gold, silver,bronze, and NA, I don't want to count the NA column in the calculated field in tableau
I want to do something like this
Count(Medals(not including NA))/count(Medals)

A: if you want to exclude NA, Try to use this:
IF ISNULL([medal: NA]) THEN [medal] END

nb. if table name is medal, and expression are gold, silver,bronze, and NA
then you can use count

A: One solution is
SUM(INT([Medal] <> "NA")) / COUNT("*")


text:
Q: How to start a GUI app from the command line in the background? I'm using start cmd.exe /c to start new command line processes in the background. But when I execute GUI apps this way, it creates an unnecessary command line window.

A: Just say start myprogram.exe. It'll return immediately and it won't start an unnecessary instance of the shell.

A: If the program you want to start needs to be quoted since it contains spaces or shell metacharacters in its path, then you need to supply an empty quoted argument to start:
start "" "C:\Program Files\SomeProgram\Some program.exe"

That's because start interprets the first quoted argument as the title for a new console window, running cmd.


text:
Q: Rank each row in a table and group the rows for duplicates without resetting the rank for each group I have the below table created with me:
dishname         rating rank
Fish Fry          5.0    1
Tandoori Chicken  4.8    2
Tandoori Chicken  4.6    3
Paneer Tikka      4.5    4
Baby Corn         4.2    5
Fish Fry          4.1    6
Paneer Tikka      3.9    7
Baby Corn         3.1    8
Fish Fry          2.9    9
Paneer Tikka      2.3   10

*Assume that each dish is from a different restaurant
Code used:
Select dishname,
       rating,
       Row_Number() Over(Order By rating desc) as Rank
From DISH

This is what I want to achieve:
dishname          rating  rank
Fish Fry           5.0     1
Fish Fry           4.1     6
Fish Fry           2.9     9
Tandoori Chicken   4.8     2
Tandoori Chicken   4.6     3
Paneer Tikka       4.5     4
Paneer Tikka       3.9     7
Paneer Tikka       2.3     10
Baby Corn          4.2     5
Baby Corn          3.1     8

I want the dish with rank 1 to be on the top of the table followed by the same dish (with different rank as shown above). Once this is done, then the criteria to select the next dish should be to check for the next rank (for a different dish). The first dish of each group is selected based on the Rank column and within the group the dishes should be order by rank.
CURRENT TABLE WITH FOUR DISHES
Please click for picture
WHAT I AM EXPECTING
Please click for picture

A: You can do it like this:
I use CROSS APPLY to select the minimum rank, and use that as an sortorder.
       declare @myt table (dishname  nvarchar(50),       rating float, rank int)
insert into @myt
values

('Fish Fry'          ,5.0  , 1),
('Tandoori Chicken'  ,4.8  , 2),
('Tandoori Chicken'  ,4.6  , 3),
('Paneer Tikka'      ,4.5  , 4),
('Baby Corn'         ,4.2  , 5),
('Fish Fry'          ,4.1  , 6),
('Paneer Tikka'      ,3.9  , 7),
('Baby Corn'         ,3.1  , 8),
('Fish Fry'          ,2.9  , 9),
('Paneer Tikka'      ,2.3  ,10)

select z.Dishname,rating,[rank] from (
select *,ROW_NUMBER() over(partition by dishname order by [Rank] asc,rating desc) rn from (

Select dishname,
       rating,
       Row_Number() Over(Order By rating desc) as [Rank]
From @myt
)X
) z

cross apply (select  MIN(rank) as sortorder,dishname from @myt s

where s.dishname = z.dishname group by dishname) f

order by sortorder,rn

Result

A: Process here is to be able to join between the rankings and the best ranking for each dish. Then can sort on the best ranking first.
with ranking as (
    select dishname, rating, rank() over(order by rating) as dr
    from Dish
), topRanking as (
    select dishname, max(dr) as maxRank
    from ranking
    group by dishname
)
select r.dishname, r.rating
from ranking r
    inner join topRanking tr on tr.dishname = r.dishname
order by maxRank desc, rating desc

A: You can use this.
DECLARE @DISH TABLE ( dishname varchar(20), rating decimal(18,2) )
INSERT INTO @DISH VALUES
('Fish Fry'          ,5.0),
('Tandoori Chicken'  ,4.8),
('Tandoori Chicken'  ,4.6),
('Paneer Tikka'      ,4.5),
('Baby Corn'         ,4.2),
('Fish Fry'          ,4.1),
('Paneer Tikka'      ,3.9),
('Baby Corn'         ,3.1),
('Fish Fry'          ,2.9),
('Fish Fry'          ,1.9),
('Paneer Tikka'      ,2.3),
('Tandoori Chicken'  ,3.2),
('Tandoori Chicken'  ,1.7),
('Paneer Tikka'      ,2.0)

SELECT dishname, rating, Rank
FROM (
    SELECT *,
        Row_Number() Over(Order By SubRank, rating desc) as Rank,
        MAX(rating) OVER(PARTITION BY SubRank, dishname) as FirstOrdeR
    FROM (
        Select dishname,
               rating,
               ((Row_Number() Over(PARTITION BY dishname ORDER BY rating desc))-1) / 3 as SubRank
        From @DISH
    ) AS T
) AS X
ORDER BY SubRank, FirstOrder DESC, Rank

Result:
dishname             rating                                  Rank
-------------------- --------------------------------------- --------------------
Fish Fry             5.00                                    1
Fish Fry             4.10                                    6
Fish Fry             2.90                                    10
Tandoori Chicken     4.80                                    2
Tandoori Chicken     4.60                                    3
Tandoori Chicken     3.20                                    8
Paneer Tikka         4.50                                    4
Paneer Tikka         3.90                                    7
Paneer Tikka         2.30                                    11
Baby Corn            4.20                                    5
Baby Corn            3.10                                    9
Paneer Tikka         2.00                                    12
Fish Fry             1.90                                    13
Tandoori Chicken     1.70                                    14

A: A single-CTE based approach, though possibly a little less efficient than other answers:
--DECLARE @TABLE TABLE(dishname varchar(10), rating decimal(2,1))
--INSERT INTO @TABLE VALUES ('Fish', 5.0), ('Chicken', 4.8), ('Chicken', 4.6), ('Tikka', 4.5), ('Corn', 4.2), ('Fish', 4.1), ('Tikka', 3.9), ('Corn', 3.1), ('Fish', 2.9), ('Tikka', 2.3) /* extra records */ , ('Fish', 1.9), ('Chicken', 3.2), ('Chicken', 1.7), ('Tikka', 2.0)

;WITH CTE AS (
    SELECT
        *
      , [Rank] = ROW_NUMBER() OVER(ORDER BY rating DESC)
      , [Group] = (ROW_NUMBER() OVER(PARTITION BY dishname ORDER BY rating DESC) - 1) / 3
    FROM @TABLE
)
SELECT *
FROM CTE AS A
ORDER BY [Group], (SELECT MIN([Rank]) FROM CTE AS B WHERE A.dishname = B.dishname AND A.[Group] = B.[Group]), rating DESC

A: Select dishname,rating, Row_Number() Over as Rank From DISH where order by dishname('Fish Fry','Tandoori Chicken','Panner Tikka','Baby Corn') order by Over DESC;

This is specific to MySQl


text:
Q: Android studio not asking to open project in new window Android Studio used to ask me every time I went to open an existing project if I wanted to open this project in a new window but now it doesn't ask and just opens the project in my existing android studio window. So I want to be able to have two projects up at once. Anyone know how to get that prompt to come back up again?

A: Windows:
Go to: File -> Settings -> Appearance & Behavior -> System Settings -> Project Opening.
macOS:
Preferences -> Appearance & Behavior -> System Settings -> Project.
Shortcut (⌘ ,)
Check "Confirm window to open project in"

now restart your Android Studio


text:
Q: If the pressure between the cross-sections of a pipe is equal, will $P_1$ and $P_2$ be cancelled out of Bernoulli's Equation?
a). Water is flowing through a pipe of two circular cross- sections area $A_1$ and $A_2$ lying horizontally as shown in figure below. The pressure difference between the cross-section $A_1$ and $A_2$ is 7500 Pascals. If the velocity of the water through cross-section $A_1$ is $3.25\ \mathrm{m/s}$, what would be the velocity of the water through cross-section $A_2$?

Using Bernoulli's Equation, I tried rearranging the equation so that it can be used to answer a problem like the one above.
$$P_1 + \rho gh_1 + 1/2 \rho v^2_1 = P_1 + \rho gh_2 + 1/2 \rho v^2_2$$
Height is constant. Therefore equation will be:
$$P_1 + 1/2 \rho v^2_1 = P_2 + 1/2 \rho v^2_2$$
My question: Since the pressure is constant, will $P_1$ and $P_2$ be removed from the equation?

A: Summary of discussion on this question between AugieJavax98, philip_0008 and sammy_gerbil :
$P_1$ is not equal to $P_2$.  The question says that there is a "pressure difference" between $A_1$ and $A_2$.  The height $h$ is assumed to be the same at both ends (the pipe is lying horizontally).  The difference in area causes a difference in flow speed (continuity equation) and a difference in pressure (Bernoulli equation).
The illustration suggests that $A_2 > A_1$. Therefore $P_2 > P_1$.  However, this leads to an imaginary value for $v_2$, the speed through $A_2$.
However, the illustration could be misleading.  The text does not state that $A_2 > A_1$.  Assuming instead that $A_1 > A_2$ and therefore $P_1 > P_2$ leads to a real (and realistic) value for $v_2$ :
 $$P_1 + \frac{1}{2} \rho v^2_1 = P_2 + \frac{1}{2} \rho v^2_2$$
$$P_1 - P_2  = \frac{1}{2} \rho (v^2_2 - v_1^2)$$
$$7500Pa = \frac{1}{2} (1000kg/m^3)(v^2_2 - (3.25m/s)^2)$$
which gives $$v=5.06m/s$$.


text:
Q: Actual meaning of refraction of light The definition of refraction which I found on wikipedia is

In physics, refraction is the change in direction of a wave passing from one medium to another or from a gradual change in the medium.

But in the below case, there is no change in direction of light. So, is this also refraction?

A: I really feel like I genuinely understand your question.  In essence you are asking "do we count it as refraction when there is no refraction in virtue of the angle of incidence being 90 degrees (or zero degrees, however you look at it).
The example you give is an example of something that is vacuously true.  It's a bit like a child claiming that he ate all of his vegetables because there were in fact, no vegetables served on his plate this evening.
I suppose that you are correct that there is no refraction, but only in virtue of the fact that the angle of incidence is 90 degrees.  But in physics, we try to avoid conundrums involving vacuous statements like this.  They don't really improve our understanding of the how and why of the physical world.  It's a bit like asking "if a tree falls in the forest, but no one is there to hear it, does it make a sound".  The question, by its very construction, is designed to generate endless debate rather than move our understanding forward.
Your question is a great one - it shows inquisitiveness and curiosity, and shows your interest in pushing the envelope.  When I was working on my undergraduate degree in physics I used to ask questions like this all the time.

A: Actually refraction is the phenomenon in which speed of light changes when it passes from one medium to another. The change in direction can be explained by Fermat's principle which you  can check on Wikipedia.

A: Refraction describes the change of direction of a light beam in geometrical optics. Since your the light beam does not change it's propagation direction, there is no refraction.
I guess you are somehow mixing the phenomena and its explanation: The change of angle is a phenomena. Its explanation is that the speed of light changes according to $c_0/n$. We are not allowed to reverse this "logic".


text:
Q: LXC Bridge not working on ubuntu 15.04 I'm trying to get lxc containers running with a bridged network connection so the container get ip addresses like the host does from a dhcp server.
I red several tutorials, but I couldn't find one that explicitly mentions 15.04. Mostly they were about ubuntu 12. So maybe that's the problem somehow?
Here is what I tried:

*

*install ubuntu 15.04 server

*sudo apt-get install lxc lxctl lxc-templates

*install lxc webpanel as root: wget http://lxc-webpanel.github.io/tools/install.sh -O - | bash
/etc/network/interfaces change to the following:
auto lo
iface lo inet loopback

auto eth0
iface eth0 inet manual

auto br0
iface br0 inet dhcp
bridge_ports eth0
bridge_stp off
bridge_fd 0
bridge_maxwait 0

*

*After rebooting I have lxcbr0 and br0 in ifconfig

*create a lxc container in the webpanel with ubuntu in it

*in the webpanel, configure the new container to use br0 instead of lxcbr0

*start the container

=> the new container's MAC is not seen in the dhcp servers lease list as well logging in to the container with lxc-console and running ifconfig shows that it doesn't get an IP address.
Btw. If I keep lxcbr0 the container gets an IP address, but that is masqueraded and not accessible from the outside. But that works.
What's the thing I'm missing here? Maybe some security issue?
[edit]
brctl show shows this:
bridge name     bridge id               STP enabled     interfaces
br0             8000.000c29e793a1       no              eth0
                                                        vethSCX4N3
lxcbr0          8000.000000000000       no

Also, the ubuntu 15.04 server is running on an esxi 6.0.
[/edit]

A: yaegashi's VMWare comment pushed me in the right direction. I had to enable promiscuous mode on the Virtual Machine Port Group on the esxi host. Otherwise, the virtual switch won't allow traffic through the port with a mac address different from the the virtual adapter's mac address.


text:
Q: Ant - sf:compileAndTest I can't find any documentation for the ant command "sf:compileAndTest", yet I see references to it in several places. Example.
When I try to run it in a ant target I get doodly squat:
[sf:compileAndTest] compileAndTest on https://test.salesforce.com, compiling 0 classes and 0 triggers, deleting 0 classes and 0 triggers

(This is after a successful deploy, I know there are classes and triggers in the target Org)
Is this ant command supported? Or are we forced to bundle test running with deployment, eg
<sf:deploy ------------ runAllTests="true"/>

A: I don't know much about sf:compileAndTest but:
sf:deploy can be used to do a compile and test by using the checkOnly attribute. Setting this attribute to true will mean that nothing will get saved to the server.
<sf:deploy
       username="username@username.com"
       password="password"
       serverurl="https://test.salesforce.com"
       runAllTests="true"
       checkOnly="true"/>


text:
Q: When to write custom components appropriately? While designing my jsf pages I realized that some of the components are being re-used at least twice or thrice in my application's different layouts. For example, as a hypothetical situation consider the vote-up button on SO which is included numerous times in a topic questions page(this is not in actual case) and (in a different layout) on each post on a specific question page.
So my concern is that, since a few of  my components are being re-used twice (in different layouts), (like voteup buttons or options bar on posts) should I go with putting up my markup in custom components and use those components instead of writing same code at more than one place. Is there a performance issue to consider while chosing custom components for frequently rendered components?
And also is the markup for JSF components converted into html, during the build time or during the render time ?

A: On the easiest part of your question, I would say there is no appreciable performance issue with regard to using a custom component verses the in-line facelet tags.   Although it looks complicated to you the Faclets servlet still has to pick through and compile about the same number of XML elements either way.
Aside from the issues discussed in the topic that BalusC linked to, I would add the primary purpose of JSF extensibility is to allow the developer to re-use code as much as possible.  A related benefit is that your Facelet client page (one that uses a template) will be as compact and succinct as it is possible for XML markup to be.
My experience has been this can be a double-edged sword.   You can burn a lot of development time sitting and tweaking custom components where you would have been better off just "compromising" and doing the cut-and paste thing from a working page to another page just to get the job done.  This is where your trade-off really is.  You really don't want to get into another Faces Component Library development project if you want to get your app deployed anytime soon.
My advice is to ignore as much as possible all the whiz-bang stuff (Javascript interactive graphics, etc.) and code your application with just boring old JSF basic components as much as possible.  Get it working with the least-complicated components that will do the job.  After the app is working you can go back and rework the presentation layer (Facelets markup) to optimize into reusable components or higher-function components like those from RichFaces, IceFaces, PrimeFaces, or *Faces.


text:
Q: List all commits that don't include a specific file It's basically a play on List all commits for a specific file question. I want to list all commits that don't include a specific file (or files). Is that possible to do?

A: If don't include means the file is not changed in the commit, Set A is git log --pretty=%h --follow <file>, Set B is git log --%h, and B - A = {sha1 values of commits that don't include the file}.
git log --pretty=%h --follow *file* > a.txt
git log --pretty=%h *file* > b.txt
sort b.txt a.txt a.txt | uniq -u


text:
Q: Contain top-bar contents to grid with Foundation 6 Is it somehow possible to contain the contents of a top-bar to the grid with Foundation 6?
In Foundation 5 this was possible to get with the contain-to-grid class but unfortunately this isn't available anymore.
I've already tried to use a grid-container with grid-x and two 6 cells in it instead of top-bar-left and top-bar-right, but somehow the grid-container shrinks to its minimum size when placed inside a top-bar.


text:
Q: How frequently is RandomAccessFile length updated? I have a Java RandomAccessFile. I check the length of the file frequently. The file is coming from an scp. Therefore, the file is getting appended.
I want to know how frequently the RandomAccessFile is updated. Whenever I check RandomAccessFile.length, will get I the accurate length?

A: Since the method is native, I'd recommend taking a look in the OpenJDK source code. It's the closest thing you'll get to the actual implementation (unless you work for Oracle ;-).
The source can be found here (it's shared between all OS): src/share/native/java/io/RandomAccessFile.c
tl;dr Yes, it will try to find the end of the file descriptor the RandomAccessFile is referring to.


text:
Q: Android: RecyclerView inside RecyclerView, scroll to bottom This is my case:

Explanation
I have a RecyclerView, let's call it parent
It has 2 items:

*

*A static view, with static height etc

*Another RV, let's call it child RV

Somewhere in the screen there is an ADD ITEM button. Clicking this button adds a new item in the child RV.
Basically, the parent RV will always have only 2 items, that is the static view on top and the child RV.
The child RV will have a dynamic number of items (depending how many times you click the add button).
Now, when I click ADD ITEM button, I update my dataset and call notifyDataSetChanged() in parent to show the new item added. I need to call this in parent RV, because there are views inside the static container (1st item of parent RV) which are affected by the add new item action.
What I want to achieve is that after calling notifyDataSetChanged() I want the whole view to scroll to the very bottom.
I have already tried all options with:

*

*smoothScrollToPosition

*scrollToPosition

*stackFromEnd = true

etc... but nothing is working.
Do you know how to force the parent RV to scroll to the bottom of its content after notifyDataSetChanged() ?

A: You could use just one RecyclerView with two different view types, the first being your static view.
I assume that your dataset is populated by a generic Item object, substitute this value with your dataset object type.
I think that the problem is related to the fact that by nesting a recycler view into another the scrolling methods do not work properly.
I'll post my code in Kotlin, let me know if you need the Java version of it.
This is the recycler view adapter to use:
    // Global variables
    private var itemList = mutableListOf<Item>()

    enum class ViewType {
        STATIC_VIEW,
        ITEM_VIEW
    }

    inner class RecyclerViewAdapter : RecyclerView.Adapter<RecyclerView.ViewHolder>() {

        override fun getItemCount(): Int = itemList.size + 1

        override fun getItemViewType(position: Int): Int {
            if (position == 0) {
                return ViewType.STATIC_VIEW.ordinal
            }

            return RowMenuType.ITEM_VIEW.ordinal
        }

        override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
            if (getItemViewType(position) == RowMenuType.STATIC_VIEW.ordinal) {
                (holder as ViewHolderStaticView).bind()
            } else {
                (holder as ViewHolderItemList).bind(itemList[position - 1])
            }
        }

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
            if (viewType == RowMenuType.STATIC_VIEW.ordinal) {
                val view = layoutInflater.inflate(<your-static-view-layout>, parent, false)
                return ViewHolderStaticView(view)
            }

            val view = layoutInflater.inflate(<your-item-list-layout>, parent, false)
            return ViewHolderItemList(view)
        }

        inner class ViewHolderStaticView(itemView: View) : RecyclerView.ViewHolder(itemView) {
            fun bind() = with(itemView) {
                // Setup your static view layout
            }
        }

        inner class ViewHolderItemList(itemView: View) : RecyclerView.ViewHolder(itemView) {
            fun bind(item: Item) = with(itemView) {
                // Setup your list items
            }
        }

To setup your recycler view call:
    parent_recycler_view.layoutManager = LinearLayoutManager(this)
    parent_recycler_view.adapter = RecyclerViewAdapter()

To add a new element you'll need to call:
    itemList.add(Item())
    parent_recycler_view.adapter.notifyDataSetChanged()

You should be able to scroll to the bottom of the recycler view by calling:
    parent_recycler_view.smoothScrollToPosition(itemList.size)

A: I have had a very similar case to this one. While @Luca's answer would be optimal, yet if it is not possible to have a single RecyclerView, like my case, the solution that I found was to requestFocus() at the last item of the child RecyclerView.
I had an EditText inside child recyclerview's items and what I did was:
inner class ChildRVViewHolderItemList(itemView: View) : RecyclerView.ViewHolder(itemView) {
    fun bind(item: Item) = with(itemView) {
        if (isLastItemToShow) {
          itemView.mEditText.requestFocus()
        }
    }
}

This way whenever the isLastItemToShow condition was met, the EditText located inside the last item of my child recyclerview would get the focus, and eventually make the RecyclerView to scroll to the bottom.


text:
Q: When using the @SequenceGenerator/@GeneratedValue in JPA - is a database trigger redundant/unnecessary? I saw this post (JPA Entity Lifecycle Events vs database trigger), but it didn't ask quite as explicitly as I am here:
Am I required to have a sequence AND a trigger for when I insert a row with a PK with a value of (null)?
Or will JPA somehow interpret the sequence annotations as a signal to grab .nextVal?

A: If you define a sequence on your primary key (@Id annotated field) and you map the sequence using the annotations @GeneratedValue and @SequenceGenerator, you can persist an entity with a null primary key. JPA will automatically call the sequence to get the next value (or get it from its cache).
The primary key declaration should look like.
@Id
@Column(name = "TABLE_PK")
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "SEQUENCE_GENERATOR_NAME")
@SequenceGenerator(name = "SEQUENCE_GENERATOR", sequenceName = "SEQUENCE_NAME")
private Integer id;


text:
Q: Is it possible to animate HTML  placeholder text change I've been told that animating a change between showing and hiding the text, such as an alpha change is not possible.

A: http://jsfiddle.net/qNmjw/1/
When you have an input as such
<input type="text" placeholder="the placeholder">

you can wrap it in a label in order to "move" the placeholder text from the input to the label span:

  <input type="text" placeholder="">
  the placeholder

I wrote a small jquery function that does this rearrangement for any input with a placeholder attribute defined.
If your input has the required attribute, then you can take advantage of the CSS invalid selector and you don't need a keyup event. See here: http://jsfiddle.net/qNmjw/2/

A: Yes, well- kind of...
This should work on most the new browsers, and it uses vendor specific selectors. I would recommend to test it by yourself to make sure it covers your chosen browsers (& versions)...
Consider the HTML:
<input type="text" placeholder="placeholder's text" />

With the next CSS:
input {transition:color 1s;}
input::-webkit-input-placeholder { /* WebKit browsers */
    color:#0000ff;transition:color 1s;
}
input::-moz-placeholder { /* Mozilla Firefox */
    color:blue;transition:color 1s;
}
input:-ms-input-placeholder { /* IE 10+ */
    color:blue;transition:color 1s;
}
input:focus::-webkit-input-placeholder {color:#ff0000;}

Play with it here: http://jsfiddle.net/3g2J7/1/


text:
Q: Creating test data for custom parent object and child object in test class I am writing test class where I need to create test data for standard case object  object and parent object for a custom field in case object. When I do the test run it is giving error at the statement where Case object is associated to parent object
Case is linked to BuildingPermit1 with PermitName field.
Please help.
private static Contact Contact1;
private static Case Case1;
private static Building_Permit__c  BuildingPermit;

    //create account
    Account1 = new Account();
    Account1.Name = 'Test Company';
    insert Account1;

    //create Contact
   Contact1 = new Contact();
    Contact1.FirstName = 'Testname';
    Contact1.LastName = 'TLname';
    Contact1.Phone = '6667897867';
    Contact1.Email = 'test@gmail.com';

    //create building permit
    Buildingpermit1 = new Building_permit__c();
       Buildingpermit1.permit_name__c = 'testPermit';
    insert Buildingpermit1;

   Case1 = new Case();
   Case1.Origin = 'Phone';
    Case1.Status = 'New';
   Case1.ContactId = mainContact.Id;
   Case1.Subject = 'test subject';
   Case1.Description = 'test desc';
    if (buildingpermit1.Id != null)
  {
  Case1.Buildingpermit1= Buildingpermit1.Id;  //This is the statement where
                                               //error shows up
  }
    Insert Case1;

A: You need to use the API name for the field:
Case1.Permit_Name__c = Buildingpermit1.Id;


text:
Q: Spacing on rotatebox in tabular environment Could someone explain the spacing in this table?

*

*Why do some of the rotated boxes have 0, 1, 2, or 3 characters separated by the baseline?

*Why are there leading/trailing spaces in some of the boxes?

I don't understand what mechanisms control these things.
\documentclass{article}

\usepackage{array}
\usepackage{rotating}

\renewcommand{\arraystretch}{0}%
\setlength{\fboxsep}{0pt}%

\newcommand{\testBox}[2]{%
  \setlength{\fboxsep}{0pt}%
  \fboxrule=.1pt%
  \fbox{%
    \rotatebox[origin=#1]{#2}%
      {#1 #2}%
  }%
}

\begin{document}

\noindent
\tt

\begin{tabular}%
{@{}|llll|llll|llll|@{}}%
  \hline%
  \rlap{\rule{211pt}{.1pt}}%
  \testBox{rt}{090}&%
  \testBox{rb}{090}&%
  \testBox{rt}{270}&%
  \testBox{rb}{270}&%
  %
  \testBox{ct}{090}&%
  \testBox{cb}{090}&%
  \testBox{ct}{270}&%
  \testBox{cb}{270}&%
  %
  \testBox{lt}{090}&%
  \testBox{lb}{090}&%
  \testBox{lt}{270}&%
  \testBox{lb}{270}\\%
  \hline%
\end{tabular}

\end{document}

A: As I commented, it makes sense to me. The designated rotation origin, e.g., right-bottom, of the [original] box, remains at the same vertical position before and after rotation. The only quirk is that if a rotated box would end up with a gap between the baseline and the box (as in, for example, right-top 270), the box is extended to the baseline, without relocation of the text.
To show what I mean, I have adjusted your MWE somewhat to overlay the unrotated and rotated boxes, where the rotation point is overlapped in both pre- and post- image.
\documentclass{article}

\usepackage{array}
\usepackage{rotating}

\renewcommand{\arraystretch}{0}%
\setlength{\fboxsep}{0pt}%

\newcommand{\testBox}[3][0]{%
  \setlength{\fboxsep}{0pt}%
  \fboxrule=.1pt%
  \setbox0=\hbox{\fbox{#2 #3}}%
  \fbox{%
      {#2 #3}%
  }\kern-\wd0%
  \rlap{\makebox[\dimexpr\wd0+#1\ht0][r]{\fbox{%
    \rotatebox[origin=#2]{#3}%
      {#2 #3}%
  }}}%
  \kern\wd0%
}

\begin{document}

\noindent
\tt

  \leavevmode\rlap{\rule{211pt}{.1pt}}
  \testBox[1]{rt}{090}\quad
  \testBox{rb}{090}\quad
  \testBox{rt}{270}\quad
  \testBox[1]{rb}{270}

\renewcommand{\testBox}[3][0]{%
  \setlength{\fboxsep}{0pt}%
  \fboxrule=.1pt%
  \setbox0=\hbox{\fbox{#2 #3}}%
  \fbox{%
      {#2 #3}%
  }\kern-\wd0%
  \rlap{\makebox[\dimexpr\wd0+#1\ht0][c]{\fbox{%
    \rotatebox[origin=#2]{#3}%
      {#2 #3}%
  }}}%
  \kern\wd0%
}
  \leavevmode\rlap{\rule{211pt}{.1pt}}
  \testBox[1]{ct}{090}\quad
  \testBox[-1]{cb}{090}\quad
  \testBox[-1]{ct}{270}\quad
  \testBox[1]{cb}{270}

\renewcommand{\testBox}[3][0]{%
  \setlength{\fboxsep}{0pt}%
  \fboxrule=.1pt%
  \setbox0=\hbox{\fbox{#2 #3}}%
  \fbox{%
      {#2 #3}%
  }\kern-\dimexpr\wd0+#1\ht0\relax%
  \rlap{\makebox[\wd0][l]{\fbox{%
    \rotatebox[origin=#2]{#3}%
      {#2 #3}%
  }}}%
  \kern+\dimexpr\wd0+#1\ht0\relax%%
}
  \leavevmode\rlap{\rule{211pt}{.1pt}}
  \testBox{lt}{090}\quad
  \testBox[1]{lb}{090}\quad
  \testBox[1]{lt}{270}\quad
  \testBox{lb}{270}

\end{document}

For clarification, I manually added (outside of LaTeX) red marks at the origin of rotation.


text:
Q: Issue with my random number generator I want to create a random number generator where you enter the min and max values. However, when I enter in let's say 0 as the min and 100 as the max I get value like 270, 690, 180, 580, 70, 240, etc.

function random_number(min, max) {
  max = $("#max_num").val();
  min = $("#min_num").val();
  document.getElementById("random_num").innerHTML = Math.floor(Math.random() * (max - min)) + min;
}

Enter max number: <input type="text" id="max_num">
 Enter min number: <input type="text" id="min_num">

  <button type="button" onclick="random_number()">Random number</button>

A: You need to coerce the values of your inputs (strings) to numbers using the unary + operator:

function random_number(min,max){
    max = +$("#max_num").val();
    min = +$("#min_num").val();
    document.getElementById("random_num").textContent = Math.floor(Math.random() * (max - min)) + min;
}

Enter max number: <input type="text" id="max_num">

Enter min number: <input type="text" id="min_num">

<button type="button" onclick="random_number()">Random number</button>


text:
Q: HttpServerUtility.UrlTokenDecode only seems to return null I seem to be having an issue with the HttpServerUtility.UrlTokenDecode(string), as it is constantly returning null, causing the program to crash.
From what I have gathered, this method will convert a string to it's base64 Byte-Array. Unfortunately, the original developer of the code is no longer with us, and it seems not many people in my office are familiar with the code.
public string DecodeUrlData(string urlData)
{
    string lsReturnVal = string.Empty;
    byte[] decodedrtfBytes = HttpServerUtility.UrlTokenDecode(urlData);

    lsReturnVal = System.Text.ASCIIEncoding.ASCII.GetString(decodedrtfBytes);
    return lsReturnVal;
}

That is the code that has been written, and urlData has the following value:
urlData = "pdfSignature template testing."

(It should also be known that urlData may have either a "string" value, or a rtfformatted string)
But what ends up happening is when the HttpServerUtility.UrlTokenDecode(urlData) line is executed, the byte array ends up being null (causing an exception in the following line).
Is there another way to convert the string to base64 that would work, or why does it keep producing a null value?

A: According to the HttpServerUtility.UrlTokenDecode documentation, the input parameter should be a Url token previously encoded via UrlTokenEncode.
Quote:

The UrlTokenDecode method converts a
  URL string token, which encodes binary
  data as base 64 digits, to its
  equivalent byte array representation.
  Use the UrlTokenDecode method to
  decode tokens transmitted on the URL
  and encoded by using the
  UrlTokenEncode.


text:
Q: How to 2d truncate a 3d python list with no imports NO numpy
So I have here a 3d list:
list = [
        [
            # red (5 rows x 10 columns)
            [10, 10, 10, 10, 10, 10, 10, 10, 10, 10],
            [10, 10, 10, 10, 10, 10, 10, 10, 10, 10],
            [10, 10, 10, 10, 10, 10, 10, 10, 10, 10],
            [10, 10, 10, 10, 10, 10, 10, 10, 10, 10],
            [10, 10, 10, 10, 10, 10, 10, 10, 10, 10],
        ],
        [
            # green (5 rows x 10 columns)
            [10, 10, 10, 10, 10, 10, 10, 10, 10, 10],
            [10, 10, 10, 10, 10, 10, 10, 10, 10, 10],
            [10, 10, 10, 10, 10, 10, 10, 10, 10, 10],
            [10, 10, 10, 10, 10, 10, 10, 10, 10, 10],
            [10, 10, 10, 10, 10, 10, 10, 10, 10, 10],
        ],
        [
            # blue (5 rows x 10 columns)
            [10, 10, 10, 10, 10, 10, 10, 10, 10, 10],
            [10, 10, 10, 10, 10, 10, 10, 10, 10, 10],
            [10, 10, 10, 10, 10, 10, 10, 10, 10, 10],
            [10, 10, 10, 10, 10, 10, 10, 10, 10, 10],
            [10, 10, 10, 10, 10, 10, 10, 10, 10, 10],
        ],
    ]

Basically each index (x,y) in (row,column) is a pixel with r,g,b. This list has 5x10=50 pixels. I want to truncate it so that the columns and rows to a specified amount like row=3, column=7 like this:
list = [
        [
            # red (3 rows x 7 columns)
            [10, 10, 10, 10, 10, 10, 10],
            [10, 10, 10, 10, 10, 10, 10],
            [10, 10, 10, 10, 10, 10, 10],
        ],
        [
            # green (3 rows x 7 columns)
            [10, 10, 10, 10, 10, 10, 10],
            [10, 10, 10, 10, 10, 10, 10],
            [10, 10, 10, 10, 10, 10, 10],
        ],
        [
            # blue (3 rows x 7 columns)
            [10, 10, 10, 10, 10, 10, 10],
            [10, 10, 10, 10, 10, 10, 10],
            [10, 10, 10, 10, 10, 10, 10],
        ],
    ]

A: truncated = [[row[:7] for row in color[:3]] for color in list]

You shouldn't use list as a variable name as you are overwriting the built-in list and this may cause unexpected behaviour in code that comes after this

A: desired_rows = 3
desired_columns = 7
for i in range(len(list)):
    list[i] = list[i][:desired_rows]  # will give a 3x10 array
    for j in (range(desired_rows)):
        list[i][j] = list[i][j][:desired_columns] # will give a 3x7 array
print(list)


text:
Q: YT getPlayerState() not a function I need to access the YouTube states through JS to control a video slideshow. For some reason I am getting the getPlayerState() is not a function messages. I can access the playerState property directly though I would like to do it the 'correct' way as stated in the docs. Does anyone know what issue may be causing this?
Pertinent code:
if (window.YTIframeAPIReady) {
  ytPlayers[this.id] = new YT.Player(this.id, {
    events: {
      'onStateChange': youtubeStateChange,
    }
  }
}

function youtubeStateChange(event) {
  // This returns the player state.
  console.log(event.target.v.playerState);
  // This returns Uncaught TypeError: event.target.getPlayerState is not a function
  console.log(event.target.getPlayerState());
}

I have similar code in another part of the site that still seems to be working with the getPlayerState() so I am a bit stumped. Any help is greatly appreciated,

A: You have do a check to see if getPlayerState is a function.
getPlayerState() is a number, which makes it even more fun!
For example:
if (typeof players[0].getPlayerState === "function") {
    console.log(event.target.getPlayerState());
}


text:
Q: Parallel resistance command I've been looking for a way to typeset the parallel of two resistances. I'm aware of the \parallel symbol, but it has the limitation that it won't adapt its size; i.e., the following MWE won't compile:
\documentclass{article}
\begin{document}
    \[
        \left.\frac{1}{g_m}\right\parallel\frac{1}{g_m}
    \]
\end{document}

I tried defining a new command
\documentclass{article}
\newcommand{\parallelTwo}[2]{\left.#1\right|\left|#2\right.}
\begin{document}
    \[
        \left.\frac{1}{g_m}\right\parallel\frac{1}{g_m}
    \]
\end{document}

but clearly the result is not what I intend, because the size of each line is different:

How could this be refined? Ideally, the command would accept an arbitrary number of arguments and adapt the parallel symbol to the size of the biggest argument, using the correct spacing.
Here is a remotely related question: How to draw the "parallel circuits" sign "//"?

A: See if the following solve your problem:
\documentclass{article}

\newcommand{\parallelTwo}[2]{\left.#1\,\middle|\!\middle|\,#2\right.}

\begin{document}
    \[
        \parallelTwo{R}{\frac{1}{g_m}}
    \]
\end{document}

Edit: Added fine tuning of spaces around of "parallel" symbol. Similarly can be defined \newcommand for three parallel elements. For more parallel elemets one way is to define:
\newcommand{\parallelE}{\,\middle|\!\middle|\,}

and use it on the following way:
\[
    \left.R_1\parallelE R_2 \parallelE \frac{1}{g_m}\right.
\]

A: You can use \DeclarePairedDelimiterX from mathtools, with an adjustment because the command doesn't really like empty delimiters:
\documentclass{article}
\usepackage{mathtools,xparse}

\DeclarePairedDelimiterX{\parallelTwoAux}[2]{.}{.}{%
  #1\nonscript\;\delimsize\Vert\nonscript\;#2%
}

\NewDocumentCommand{\parallelTwo}{somm}{%
  \IfBooleanTF{#1}
    {\parallelTwoAux*{#3}{#4}}
    {\IfNoValueTF{#2}
       {#3 \parallel #4}
       {\parallelTwoAux[#2]{#3}{#4}}%
    }%
}

\begin{document}

\[
\parallelTwo{R}{x}
\quad
\parallelTwo[\Big]{R}{\frac{1}{g_m}}
\quad
\parallelTwo*{R}{\frac{1}{g_m}}
\]

\end{document}


text:
Q: NUnit 3 test not using parameters in testcase source I'm attempting to use NUnit 3 to write a test that takes a list of double[] and tests the return of an extension method. But I can't get the test to take the testcasedata as parameters. It always runs once with a null parameter.
I've copied the example in the wiki almost exactly so I'm not sure where I'm going wrong. I'm coming from nunit 2.6 so not used to the new way of doing things. So it's probably something very obvious.
Any help appreciated.
[TestFixture]
public class DoubleExtensionsTest
{
    [Test, TestCaseSource(typeof(DoubleExtensionsTestData), "CoordinatesData")]
    public bool IsValidCoordinatesWorksCorrectly(double[] values)
    {
        return values.IsValidCoordinates();
    }

}

public class DoubleExtensionsTestData
{
    public static IEnumerable CoordinatesData
    {
        get
        {
            yield return new TestCaseData(new[] { 51.441860d, -0.066243d }).Returns(true);
            yield return new TestCaseData(new[] { 48.856614d, 2.352222d }).Returns(true);
            yield return new TestCaseData(new[] { -1.292066d, 36.821946d }).Returns(true);
        }
    }
}

A: Older 3rdParty runners such as Resharper, very old NUnit 2 Visual Studio adapters and others do not run NUnit 3 tests correctly. The symptoms are usually things like OneTimeSetup not getting run, or in this case, TestCaseSource not getting applied. Even more onerous are false positives that you will never see.
Whenever checking the behaviour of your tests, you should always run your tests with the runner that ships with the test framework, in this case nunit3-console.exe. That will tell you if it is a problem with your tests, or with your selected runner.
In this case, the tests were being run using TestDriven.NET which requires that you install the NUnitTDNet NuGet package to run NUnit 3 tests correctly.
An other option is the NUnit 3 Test Adapter for Visual Studio.