text:
Q: User input choice with either head or tail command I want to prompt a user via command line & ask what specific rows need to be cut from a data file using either head or tail. My script will employ head and tail using the inputs as variables for both head and tail commands. This is what I have thus far along with the error message:
echo -n "What rows need to be cut from your data file: "
read before
read after
head -n $before /home/rent_list
tail -n $after /home/rent_list

Error message:
-bash: ./rent_list: bin/bash: bad interpreter: No such file or directory

Update: This is what I am getting now:
 What rows need to be cut from your data file: 4

Mack Tools  Milwaukee Wisconsin mj414@yahoo.com 414 2248893
Terry Tools Orlando Florida 407@yahoo.com 407 2439812
Park Tools  Riviera Beach Florida tp123@hotmail.com 516 5370923
Bike Tools  Orlando Florida baptiste41@gmail.com 407 3420983
tail: /home/renter_list: invalid number of lines

A: The error-message seems to be saying that your script starts with #!bin/bash instead of #!/bin/bash (that is, that you're missing a / before bin/bash).

Update: Your new error-message is because you're not entering a number. You have an echo, followed by two reads. For the first read, you're entering 4, but for the second, you're just hitting Enter. So the tail command is tail -n  /home/rent_list.
If you want to use the same number for both commands, you can write:
echo -n "What rows need to be cut from your data file: "
read num_rows
head -n $num_rows /home/rent_list
tail -n $num_rows /home/rent_list


text:
Q: CSV league showing some space at the beginning of the string even after being trimmed I am using https://csv.thephpleague.com/ and the code to read csv is:
if (!ini_get("auto_detect_line_endings")) {
    ini_set("auto_detect_line_endings", TRUE);
}

$csv = Reader::createFromPath($path, 'r');
$input_bom = $csv->getInputBOM();
if ($input_bom === Reader::BOM_UTF16_LE || $input_bom === Reader::BOM_UTF16_BE) {
    $csv->addStreamFilter('convert.iconv.UTF-16/UTF-8');
}
$csv->skipEmptyRecords();
$csv->setHeaderOffset($header_row);
$csv_header = $csv->getHeader();

/**unit_number **/
$unit_number_key = array_search('unit_number', $request->row);
$unit_number_results = $csv->fetchColumn($unit_number_key);
$unit_number_lists = iterator_to_array($unit_number_results, false);
if($header_row > 0){
    $unit_number_lists = array_slice($unit_number_lists,$header_row);
}
$unitNumbers = array();
$unit_numbers = array_filter(array_unique($unit_number_lists));

foreach($unit_numbers as $uk => $uv){
    $r_trimmed_uv = trim($uv);
    $str_len = strlen($r_trimmed_uv);
    if(!isset($unitNumbers[$str_len])){
        $unitNumbers[$str_len] = $r_trimmed_uv;
    }
dd($unitNumbers);

On dd it shows results as:

Here, we could confirm that there are 10 characters (6 space) and (4 digits). How could I fix it, I don't know if it is encoding in a different format and that's the issue or if I am missing to add some line as per CSV. But, I am not being able to remove this space from here.
And, here is the sample file: https://drive.google.com/file/d/1i3ry8AoGzfNG-K6AWpWvhzSQ8QkreOB0/view?usp=sharing

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to validate that an inputted email address does not come from a free provder? I would like to be sure that the email address somebody enters into my form isn't from a free email provider such as gmail, hotmail/live, yahoo, etc.
How would I do that? I know the FILTER_VALIDATE_EMAIL option doesn't work for this.

A: Like this:
$email_address = 'test@hotmail.com';
$not_allowed = array('hotmail.com', 'gmail.com', 'msn.ca');
$email = explode('@', $email_address);

if(in_array($email[1], $not_allowed)){
    echo 'Email not allowed';
}else{
    echo 'Email is good';
}


text:
Q: .htaccess rewriting url to a friendly format doesn't work I have tried so many codes from here and also googled a lot but none of them are working for me. I simply need to change http://www.domain.com/index.php?id=5 to http://www.domain.com/index.php/5
I know this has been asked many times but all the code I try doesn't work.
RewriteEngine On
RewriteBase /
RewriteRule ^/?index.php/([\d.a-zA-Z]*)$ /index.php?id=$1 [QSA,L]


text:
Q: How to use joern to analysis memory leak? How to query cpg of this code to find the location of un-free memory ?
int bad(void) {
    OutsideType my;
    my.p = MyAlloc();
    my.p = MyAlloc();
    MyFree(my.p);
    return 0;
}

Try using joern to find the place where the free function is called.


text:
Q: How to check folder size or containing files in Java without knowing the file name with java.nio.file? I had a similar question some time ago. Now I don't have any specific file name, because it is a preprocessor script. So I need to check the file size of a list of files or the size of a specific path.
the solution with the specific path was:
    var filePath = "//path//to//some//folder//file.name";
    try{
        var fileContent = java.nio.file.Files.size(java.nio.file.Paths.get(filePath));
        var fileSize = fileContent / 1048576;
        logger.debug("Filesize in MB: " + fileSize);
    }
    catch(e){
    ...

what I've already tried:
java.io.File(filePath).length();

here the size doesn't match what's actually in the folder.
and
java.nio.file.Files.list(filePath);

here I get a java.util.stream.ReferencePipeline$Head@... which I don't know how to read out in mirth
Maybe anyone could help or show me another solution to check the a file size before processing without reading in the file on Java Version "1.8.0._92" and Windows Server 2012R2 environment?

A: You can sum the sizes of all files within a directory using streams:
        long total = Files
           .list(Paths.get("c:/some/path/"))
           .mapToLong(p -> p.toFile().length())
           .sum();
        System.out.println(total);

Edit: The original answer above is in Java. In Mirth javascript it would look like this:
        var total = java.nio.file.Files
           .list(java.nio.file.Paths.get("c:/some/path/"))
           .mapToLong(function(p) {return p.toFile().length()})
           .sum();
        channelMap.put('total', total);

A: Try using
 import java.nio.channels.FileChannel;
FileChannel fileChannel = FileChannel.open(filePath);
        long fileSize = fileChannel.size();

A: found a solution that fits my demands (tested on Mirth 3.4.2.8129) Java Version "1.8.0._92" and Windows Server 2012R2 environment
    // Modify the message variable below to pre process data
    var folderPath = "C:////path//to//some//folder";
    var folder = new Packages.java.io.File(folderPath);
    var listOfFiles = folder.listFiles();
    var count = listOfFiles.length;

    for (i=0; i<count; i++){
        var ext = listOfFiles[i];
        if (ext.toString().endsWith(".name")){ //filter by extentions e.g. .xml
            var file = listOfFiles[i];
            var filestr = file.toString().replace("\\","//"); //adjust for UNC
            var fileSize = java.nio.file.Files.size(java.nio.file.Paths.get(filestr)) / 1048576;
            if (fileSize > 10){
                ChannelUtil.stopChannel(channelId); //stop channel if needed
                throw "File " + file + " is > "+ "10 MB"
            }
        }
    }
    return message;

If reading from different Server, the Mirth Server (User) must be allowed to read from (UNC) Path


text:
Q: Check if a radio button is selected I don't understand why this is not working
I have a radio button Yes or No.
Yes uses "id=statut1"
<label class="radio inline">
    <input type="radio" name="statut" id="statut1" value="1"<?php if($statut=='1') echo ' checked="checked"'; ?>> Actif
</label>

At some point, I would like to know if the Yes radio button is selected or not.
I used this
console.log($('#statut1'));
if($('#statut1').is('checked')){
    console.log("inside");
}

When I look into the log, whatever the checked value is (true or false) I never go inside the condition. I can't understand why this is not working.
I'm doing the same thing with a checkbox and I have no issue.
Looks like is('checked") doesn't work for radio button...but still I found many subjects here saying it's working.
Thanks for help.

A: I think you missed a colon. Use like this:
$('#statut1').is(':checked')

A: Try this:
Put colons inside (:)
$('#' + id).is(":checked")

A: Here are two solutions:
Using onchange event you can trigger function.
Vanilla JS:

function myFunction(e) {
 console.log(e.target.checked);
}
<label class="radio inline">
    <input type="radio" name="statut" id="statut1" value="1" onchange="myFunction(event);"> Actif
</label>

jQuery:

$('#statut1').on('change', e => {
  console.log(e.target.checked);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label class="radio inline">
    <input type="radio" name="statut" id="statut1" value="1"> Actif
</label>

OP's Solution:

$('#statut1').is(':checked')


text:
Q: Is it possible to use Google Apps for Work and host a website on the same domain? So this would mean using Google Apps for Work with http://example.com while hosting a website at http://example.com at the same time but not making use of subdomains.
If yes, what DNS records would this typically use? (generic examples are fine)
Assume the hosting provider permits editing DNS records.

A: Sure - set your MX records for example.com to whatever servers GApps instructs you to use, and then configure an A record for example.com for the website.


text:
Q: problems installing ReactiveUI via nuget I have a basically empty VS2012 class library project that I'm attempting to add ReactiveUI to. I've already used Nuget to install NLog and Reactive Extensions. When I try to install the ReactiveUI 3.99 I get the following error log.
UPDATE: I was able to add the ReactiveUI references manually w/o Nuget and they seem to work fine.
------- Installing...reactiveui 3.99.4-beta -------
Attempting to resolve dependency 'reactiveui-core (= 3.99.4-beta)'.
Attempting to resolve dependency 'Rx-Main (= 2.0.20823)'.
Attempting to resolve dependency 'Rx-Interfaces (≥ 2.0.20823)'.
Attempting to resolve dependency 'Rx-Core (≥ 2.0.20823)'.
Attempting to resolve dependency 'Rx-Linq (≥ 2.0.20823)'.
Attempting to resolve dependency 'Rx-PlatformServices (≥ 2.0.20823)'.
Attempting to resolve dependency 'reactiveui-nlog (= 3.99.4-beta)'.
Attempting to resolve dependency 'NLog (≥ 2.0.0.2000)'.
Attempting to resolve dependency 'reactiveui-xaml (= 3.99.4-beta)'.
Attempting to resolve dependency 'Rx-Xaml (= 2.0.20823)'.
Attempting to resolve dependency 'reactiveui-testing (= 3.99.4-beta)'.
Attempting to resolve dependency 'Rx-Testing (= 2.0.20823)'.
'reactiveui-core 3.99.4-beta' already installed.
'reactiveui-nlog 3.99.4-beta' already installed.
'Rx-Xaml 2.0.20823' already installed.
'reactiveui-xaml 3.99.4-beta' already installed.
'Rx-Testing 2.0.20823' already installed.
'reactiveui-testing 3.99.4-beta' already installed.
'reactiveui 3.99.4-beta' already installed.
Added file 'packages.config'.
Added file 'packages.config'.
Failed to add reference to 'ReactiveUI'.
==============================

Here is my project file's references:
  <ItemGroup>
    <Reference Include="NLog">
      <HintPath>..\packages\NLog.2.0.0.2000\lib\net40\NLog.dll</HintPath>
    </Reference>
    <Reference Include="PresentationCore" />
    <Reference Include="System" />
    <Reference Include="System.Core" />
    <Reference Include="System.Reactive.Core">
      <HintPath>..\packages\Rx-Core.2.0.20823\lib\Net45\System.Reactive.Core.dll</HintPath>
    </Reference>
    <Reference Include="System.Reactive.Interfaces">
      <HintPath>..\packages\Rx-Interfaces.2.0.20823\lib\Net45\System.Reactive.Interfaces.dll</HintPath>
    </Reference>
    <Reference Include="System.Reactive.Linq">
      <HintPath>..\packages\Rx-Linq.2.0.20823\lib\Net45\System.Reactive.Linq.dll</HintPath>
    </Reference>
    <Reference Include="System.Reactive.PlatformServices">
      <HintPath>..\packages\Rx-PlatformServices.2.0.20823\lib\Net45\System.Reactive.PlatformServices.dll</HintPath>
    </Reference>
    <Reference Include="System.Xml.Linq" />
    <Reference Include="System.Data.DataSetExtensions" />
    <Reference Include="Microsoft.CSharp" />
    <Reference Include="System.Data" />
    <Reference Include="System.Xml" />
    <Reference Include="WindowsBase" />
  </ItemGroup>

A: This is a bug at the moment, create either a .NET 4.0 project or a WinRT project, and it will work. Sorry about that.
Update: This is now fixed, check out ReactiveUI 4.0 Preview 5


text:
Q: What does while(i--) mean in javascript? I'm using swipejs from swipejs.com, the home page slider uses this logic to highlight the active un-ordered list element and I'd like to know how this while condition works.

    ....

var bullets = document.getElementById('bullets').getElementsByTagName('li');

var elem = document.getElementById('mySwipe');

window.mySwipe = Swipe(elem, {

callback: function(index, element) {
    var i = bullets.length;
    while (i--) {
      bullets[i].className = ' ';
    }
    bullets[index].className = 'on';
  }

});

A: It will first check i value (if not zero), then enter loop after having decremented i.
So, if i = 10, loop will be executed with i = 9, i = 8, .., i = 0 and then exit
(because in last i-- check, i will be already zero from previous loop run)

A: The number 0 is considered falsey in JavaScript, so the while loop will run until it hits 0. You would have to be sure that i is positive to start off with, otherwise you've got an infinite loop.

A: var i = bullets.length;
while (i--) {
    ...do stuff...
}

is essentially equivalent to:
var i = bullets.length;
while (true) {
    if (i === 0) {
        i = i - 1;
        break;
    }
    i = i - 1;
    ...do stuff...
}

This style of looping tends to be used where performance is super important, as it's slightly faster than iterating indices from 0 to length-1, and is relatively straight-forward to implement.
Generally speaking, you shouldn't use it unless you're improving a known bottleneck and have verified that it improves performance in a significant way.

A: while (i--) { code(); }
is shorthand for saying while (i > 0) { code(); i--; }

A: It means var i is decrementing itself until it reaches 0 (or false in Javascript)

A: It will iterate thru all integer is backward, because i-- will decrement i (you can do i++ to increment, go up) (make it go down by 1) so when it reaches 0, it will be considered false (all numbers except 0 are true when converted to bool), thus stopping the loop.

A: i-- sets the value of i as one less than i.  It is the opposite of i++ which increases I by one.

A: i-- or i++ is shorthand for i = i - 1 or i = i + 1, respectively.
So that while loop works like this: "while i = i - 1 does not equal 0, bullets[i].className = ' ';".

A: The i will decrease (As it the user expect the lenght to be a positive value) each loop.
As a consequence, i will be at a certain iteration equal to 0, and 0 is like false in a conditions.


text:
Q: Converting JS design pattern to CoffeScript occurred class error On the Russian wikipedia i found the code of Builder design pattern and try to convert it in to the coffeescript. Builder.js
This is the gist of Builder.coffee
// Abstract Builder
function PizzaBuilder() {
    var pizza = new Pizza();
    this.getPizza = function() {
        return pizza;
    };
    this.createNewPizzaProduct = function() {
        pizza.clear();
    };
    this.buildDough = function(val) { };
    this.buildSauce = function(val) { };
    this.buildTopping = function(val) { };
}
// ConcreteBuilder
function HawaiianPizzaBuilder() {
    PizzaBuilder.call(this);
    var pizza = this.getPizza(); // imitation protected
    this.buildDough = function() { pizza.setDough("cross"); };
    this.buildSauce = function() { pizza.setSauce("mild"); };
    this.buildTopping = function() { pizza.setTopping("ham+pineapple"); };
}

I changed every function which is called by the constructor (new FuncName) to class FuncName, but an error occurred with PizzaBuilder.call(this); inside the constructor function.
PizzaBuilder = ->
    pizza = new Pizza()
    @getPizza = -> pizza
    @createNewPizzaProduct = -> pizza.clear()
    @buildDough = (val) ->
    @buildSauce = (val) ->
    @buildTopping = (val) ->

class HawaiianPizzaBuilder
    PizzaBuilder.call this
    pizza = @getPizza() # imitation protected
    buildDough: -> pizza.setDough "cross"
    buildSauce: -> pizza.setSauce "mild"
    buildTopping: -> pizza.setTopping "ham+pineapple"

A: In javascript function HawaiianPizzaBuilder is a constructor of class. In Coffeescript you need to define it explicitly as constructor method, this way:
class HawaiianPizzaBuilder
    constructor: ->
       PizzaBuilder.call this
       pizza = @getPizza() # imitation protected
       @buildDough: -> pizza.setDough "cross"
       @buildSauce: -> pizza.setSauce "mild"
       @buildTopping: -> pizza.setTopping "ham+pineapple"

Also you forgot this. before build... function definitions.
However I would like to suggest another edition of same pattern example as coffeescript provides simpler class inheritance syntax, something like that:
class PizzaBuilder
    constructor: ->
        @pizza = new Pizza()
    buildDough: -> @
    buildSauce: -> @
    buildTopping: -> @

class HawaiianPizzaBuilder
    buildDough: ->
        @pizze.setDough "cross"
        @
    #...override other methods

 builder = new HawaiianPizzaBuilder
 myPizza = builder.buildDough().buildSauce().pizza


text:
Q: How to extract many groups of cells separated by a specified number of rows in excel using python and write it to an other file? I have a csv file which has around 58 million cells containing numerical data. I want to extract data from every 16 cells which are 49 rows apart.
Let me describe it clearly.
The data I need to extract
The above image shows the the first set of data that is to be extracted (rows 23 to 26, columns 92 to 95). This data has to be written in another file csv file (preferably in a row).
Then I will move down 49 rows (row 72), then extract 4rows x 4columns. Shown in image below.
Next set of data
Similarly, I need to keep going till I reach the end of the file.
Third set
The next set will be the image shown above.
I have to keep going till I reach the end of the file and extract thousands of such data.
I had written a code for this but its not working. I don't know where is the mistake. I will also attach it here.
import pandas as pd
import numpy
df = pd.read_csv('TS_trace31.csv')
# print(numpy.shape(df))
df = pd.read_csv('TS_trace31.csv')
# print(numpy.shape(df))
arrY = []
ex = 0
for i in range(len(df)):

if i == 0:
    for j in range(4):

        l = (df.iloc[j+21+i*(49), 91:95]).tolist()
        arrY.append(l)

else:
    for j in range(4):
        if j+22+i*(49) >= len(df):
            ex = 1
            break
        # print(j)
        l = (df.iloc[j+21+i*(49), 91:95]).tolist()
        arrY.append(l)

if ex == 1:
    break

# print(arrY)

a = []
for i in range(len(arrY) - 3):
    p = arrY[i]+arrY[i+1]+arrY[i+2]+arrY[i+3]
    a.append(p)
print(numpy.shape(a))
numpy.savetxt('myfile.csv', a, delimiter=',')

Using the above code, I didn't get the result I wanted.
Please help with this and correct where I have gone wrong.
I couldn't attach my csv file here, Please try to use any sample sheet that you have or can create a simple one.
Thanks in advance! Have a great day.

A: i don't know what exactly you are doing in your code
but i wrote my own
import csv
from itertools import chain

CSV_PATH = 'TS_trace31.csv'
new_data = []

with open(CSV_PATH, 'r') as csvfile:
    reader = csv.reader(csvfile)

    # row_num for storing big jumps e.g. 23, 72, 121 ...
    row_num = 23
    # n for storing the group number 0 - 3
    # with n we can find the 23, 24, 25, 26
    n = 0
    # row_group for storing every 4 group rows
    row_group = []

    # looping over every row in main file
    for row in reader:
        if reader.line_num == row_num + n:
            # for the first time this is going to be 23 + 0
            # then we add one number to the n
            # so the next cycle will be 24 and so on
            n += 1
            print(reader.line_num)

            # add each row to it group
            row_group.append(row[91:95])

            # check if we are at the end of the group e.g. 26
            if n == 4:
                # reset the group number
                n = 0
                # add the jump to main row number
                row_num += 49

                # combine all the row_group to a single row
                new_data.append(list(chain(*row_group)))

                # clear the row_group for next set of rows
                row_group.clear()
                print('='*50)
        else:
            continue

# and finally write all the rows in a new file
with open('myfile.csv', 'w') as new_csvfile:
    writer = csv.writer(new_csvfile)
    writer.writerows(new_data)


text:
Q: Cannot cast ContentResolver to a string error on the OnItemClickListener Method I am populating a Listview using a ContentProvider. Meanwhile, upon clicking on the OnItemClickListener() method, I obtain a "cannot cast ContentResolver to a java.lang.string" error. You will find the code regarding the Activity Class below. How could I change the code so that the OnItemClickListener method works properly?
public class MainActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<Cursor> {
private ListView alarmlv;
DBHelper mydb;

private static final String PROVIDER_NAME = "com.domain.app.alarms";
private static final Uri CONTENT_URI = Uri.parse("content://" + PROVIDER_NAME + "/alarms");

SimpleCursorAdapter dataAdapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    mydb = new DBHelper(this);

    Cursor cursor = getContentResolver().query(CONTENT_URI, null, null, null, "name");
    alarmlv = (ListView)findViewById(R.id.listViewAlarms);

    dataAdapter = new SimpleCursorAdapter(getBaseContext(), R.layout.listview_row, cursor,
            new String[]{ mydb.ALARMS_COLUMN_NAME }, new int[]{R.id.alarm_name}, 0);
    alarmlv.setAdapter(dataAdapter);
    getSupportLoaderManager().initLoader(0, null, this);

    alarmlv.setOnItemClickListener(new OnItemClickListener(){
        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                                long arg3) {
            //obj.getItemAtPosition(arg2);
            // TODO Auto-generated method stub

            String itemVal =(String) arg0.getItemAtPosition(arg2);

            Bundle dataBundle = new Bundle();
            dataBundle.putString("name", itemVal);
            Intent intent = new
                    Intent(getApplicationContext(),DisplayAlarm.class);
            intent.putExtras(dataBundle);
            startActivity(intent);
        }
    });

}

A: You got the error, because CursorAdapter do not contain String elements. It contains elements of type Cursor.
Try the following code:
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    Cursor cursor = (Cursor) getItemAtPosition(position);
    String itemVal = cursor.getString(cursor.getColumnIndex(mydb.ALARMS_COLUMN_NAME));

    Bundle dataBundle = new Bundle();
    dataBundle.putString("name", itemVal);
    Intent intent = new
            Intent(getApplicationContext(),DisplayAlarm.class);
    intent.putExtras(dataBundle);
    startActivity(intent);
}


text:
Q: Time multiplication per hourly wage I am writing a code for a flight school management software. Basically, I have to enter the Departure and Arrival flight time, make the difference between the two times and make the multiplication for the hourly flight instructor wage.
My code is something like this:
time_1 = datetime.strptime('05:00:00',"%H:%M:%S")
time_2 = datetime.strptime('10:00:00',"%H:%M:%S")

time_interval = time_2 - time_1
print(time_difference)

The problem I am facing, basically, is how to make the multiplication between the time_interval variable and the hourly wage of the flight instructor.
Does anybody have any suggestion about that?

A: Firstly, your time_difference variable is not defined.
For you to calculate the total wage:
You can take the difference of the times in seconds and convert it to hours(because you want to multiply it by hourly wage).
To convert from seconds, simply divide by 3600 (60*60)

To summarize, you can do:
(time_interval.total_seconds()/3600)*wage


text:
Q: Not asking for input I have this:
Scanner input = new Scanner ( System.in );
int selection = input.nextInt();
if (selection == 1) {
System.out.println("Please enter a string: ");
String code = input.nextLine();
}

However, when it gets to Please enter a string, it doesnt ask for any input. It just goes to the rest of the program.

A: The Scanner waits at nextInt() until the user has pressed enter.  When that happens, it consumes the digits but not the new line character(s) itself.  Thus, the next call to nextLine() returns immediately with an empty String as its result.
This should fix it:
int selection = input.nextInt();
input.nextLine();
if (selection == 1) {
   System.out.println("Please enter a string: ");
   String code = input.nextLine();

But my preferred way is to always use nextLine and do the parsing separately:
String selectionStr = input.nextLine();

//consider catching a NumberFormatException here to handle erroneous input
int selection = Integer.parseInt(selectionStr);

if (selection == 1) {
   System.out.println("Please enter a string: ");
   String code = input.nextLine();
   //...

A: try:
input.nextLine();

after your nextInt();
Scanner input = new Scanner(System.in);
int selection = input.nextInt();
input.nextLine();
System.out.println(selection);
if (selection == 1) {
    System.out.println("Please enter a string: ");
    String code = input.nextLine();
}

A: simple & graphical input :
String str=JOptionPane.showInputDialog(null,"Message","Title",JOptionPane.QUESTION_MESSAGE);


text: Q: Grand Theft Auto V "Not Optimum Mode" When I open GTAV it goes directly to a black screen with a floating box that says "Not Optimum Mode Recommended Mode 1920x1080 60 Hz". I have a Samsung S24d300 monitor which is set at 1920x1080. I've updated my NVIDIA hardware. Also, I played the first two missions before this issue occurred.


text:
Q: Flutter: custom model returning null "List is not a subtype of List" | "type 'Null' is not a subtype of type 'Product'" I am calling a function that returns a future of custom model Products from Futurebuilder, and I am getting an error saying:
type 'Null' is not a subtype of type 'Product'

This is my Product model:
class Product {
  @required
  final String? id;
  @required
  final String? title;
  @required
  final String? discription;
  @required
  final double? price;
  @required
  final List<String>? info;
  @required
  final List<String>? imageUrl;
  final String? category;
  final offPerCent;

  final String? seller;
  Product({
    this.id,
    this.discription,
    this.info,
    this.imageUrl,
    this.price,
    this.seller,
    this.title,
    this.category,
    this.offPerCent
  });
}

And this is the function:
Future<Product> getbyId(String id) async {
  var snapshot =
    await firestore.collection('products').where('id', isEqualTo: id).get();
  Map<String, dynamic> data = snapshot.docs[0].data();
  return new Product(
    id: data['id'],
    title: data['title'],
    price: data['price'],
    seller: data['seller'],
    category: data['category'],
    discription: data['discription'],
    imageUrl: data['imageUrl'],
    info: data['info'],
    offPerCent: data['offPerCent'],
  );
}

I think there is some problem with the info and imageUrl field, both them are List<String> when I comment on both that line everything works fine.
Can someone help me out here?

A: Try
info: List<String>.from(data['info'])

Do the same for image.
Explanation:
The error that happened which displayed a message saying product is null, is actually caused by another error.
This error arises while creating your product object. And it happens in the fields mentioned above, where you specified a List<String> will come from Firebase. But Firebase SDK lists objects as List<dynamic>.
So probably there was another error in debug console saying
List<dynamic> is not a subtype of List<String> as in cast.

When you tell it to create a List from the elements inside the List, it works well, as long as those elements are actually strings. If you go to firebase, and change any of the items into anything besides string, you'll have another error saying int is not a subtype of type string for example.
Because creating a Product object from the map returned from firebase, goes through the steps in your method fromMap() in the model, it stops when it hits the error explained above, and therefore a product object never finishes creating it from a map.
Then, the widget waiting for the Product object to be returned, never receives what it was waiting for, you get the error in your original question.
type 'Null' is not a subtype of type 'Product'

You can avoid the third scenario, to account for anything coming from firebase, which is not a string, for example someone inputs an integer or double or null, by doing this:
info: List<String>.from(data['info'].map((element)=> element.toString()).toList());

This is an example:
List a = ['a', 1, '2', null]; //this is List<dynamic>
// List<String> b = List<String>.from(a); //This will give you an error when it encounters the number 1, it won't even continue.

List<String> b = List<String>.from(a.map((element) => element.toString()).toList());
print(b); // prints this => [a, 1, 2, null]

//because all the elements inside were converted to a string first.


text:
Q: Disable legend based on another legend click - angular nvd3 chart I would like to disable a legend(breached95) based on the click of another legend(var95) in nvd3 chart.

Below script fires the legend click event which gives the click legend values but unable to disable another legend based on this event.  How to achieve the behavior?
 callback: function(chart) {
                       chart.legend.dispatch.legendClick = function(val, i){
                            if(val.originalKey==="VaR95Total"){
                                //hide 'breached95' legend
                            }
                        };
                    },


text:
Q: How do I find the first numerically sorted integer NOT in this list? I want to go through a list of numbers and find the first number missing when the list is sorted numerically.
For example, consider this resultant set of numbers from a query:
A
---
0
1
3
4
5

I need a query to go through this list in numerical order from lowest to highest and return the first number missing from the list of numbers that would otherwise be complete and numerically sorted. So in the above example, the query should return 2. Below are some more examples. Requirements: must start checking at value 0, must return the first value missing from the NUMERICALLY SORTED list, must only return 1 number.
A
---
1
3
4
5

/* return 0 */

A
---
0
1
2
3
4
5
8
9

/* return 6*/

A: Following query finds the first absent row in a sequence but fails to find numbers between zero and sequence start:
SELECT
  MIN(T1.a + 1)
  FROM A as T1 LEFT OUTER JOIN  A as T2 ON T1.a + 1  = T2.a
  WHERE T1.a > -1 AND T2.a IS NULL;

Basic idea - find all pairs row + previous row and use incomplete pairs to derive what value is missing.
Illustration:
CREATE TABLE A (a int);
INSERT INTO A VALUES (0) ;
INSERT INTO A VALUES (1) ;
INSERT INTO A VALUES (2) ;
INSERT INTO A VALUES (3) ;
--INSERT INTO A VALUES (4) ;
INSERT INTO A VALUES (5) ;
INSERT INTO A VALUES (6) ;
INSERT INTO A VALUES (7) ;

SELECT
  T1.a, T2.a FROM A as T1 LEFT OUTER JOIN  A as T2 ON T1.a + 1  = T2.a;

Output:
0   1
1   2
2   3
3   (null)
5   6
6   7
7   (null)

This solution is slower than NOT EXISTS on MS SQL. I find this fact fascinating, joins should be much easier to optimize.

A: Use not exists:
select top 1 a + 1
from t
where not exists (select 1 from t t2 where t2.a = t.a + 1)
order by a;

A: Use a recursive CTE:
declare @upperBound int
select @upperBound = max(x) from yourTable

;with a as (
select 0 x
union ALL
SELECT x + 1
from a
where a < @upperBound
)

select min(a.x)
from yourTable yt
 right join a
  on yt.x = a.x
where yt.x is null

A: I would use a numbers table, also called a tally table. You could create one on the fly as you need it, but that is really inefficient and the uses are common enough that I tend to have one already built on each server, fully indexed. There are plenty of articles about them - here's a quick example Number tables explained part 1
Assume you have built a TALLY table and the column is also called TALLY, your table is DATA and the column to check is ID
Find the highest number we need to check. (@Upperbound)
Then select every valid row from the tally table, left outer join your data table, and only keep the rows that do not have a match.  The lowest Tally left is the number you want
DECLARE @UpperBound int = (select MAX(ID) from DATA)

SELECT TOP 1 T.TALLY
FROM TALLY T
LEFT OUTER JOIN DATA D on D.ID = T.TALLY
WHERE T.TALLY >= 0  --Lowest number to check
AND T.TALLY < @UpperBound  --got to be smaller than this
AND D.ID IS NULL  --only want rows that don't match
ORDER BY T.TALLY ASC


text:
Q: Angular Factory "Cannot read property 'property' of undefined Using Angular 1.6.x
Having a really hard time getting a Factory to work with a login submit
login.controller.js
angular.module('appName').controller('LoginController',[
  '$scope',
  function($scope, Login){
    $scope.submitLogin = function(){
      console.log('login requested');
      Login.login();
    }
  }]);

login.factory.js
angular.module('appName').factory('Login', function (){
  var service = {};

  service.login = function(){
    console.log('Login Factory');
  }

  return service;
});

The error I'm getting is TypeError: Cannot read property 'login' of undefined
From all the examples I've looked at I'm injecting the factory into the controller, created an object in the factory, and returning that object back. What am I missing here?
Another question to is why am I unable to include the factory in my controller via?
angular.module('appName').controller('LoginController',[
  '$scope',
  Login, // <<<<<< This throws an error (scripts.min.js:1 Uncaught ReferenceError: Login is not defined)
  function($scope, Login){
    $scope.submitLogin = function(){
      console.log('login requested');
      Login.login();
    }
  }]);

The reason I'm injecting this way is to eliminate the possibilities of errors during minification.
Edit
Question answered with injecting Factory with Quotes.
angular.module('appName').controller('LoginController',[
  '$scope',
  'Login', // <<<< Was not using quotes
  function($scope, Login){
    $scope.submitLogin = function(){
      console.log('login requested');
      Login.login();
    }
  }]);

A: You have to inject Login factory and wrap it within quotes 'Login':
'$scope', 'Login',
function($scope, Login){

A: angular.module('appName').controller('LoginController',[
  '$scope',
  'Login', // <<<<<< you should inject within quotes
    $scope.submitLogin = function(){
      console.log('login requested');
      Login.login();
    }
  }]);

A: You need to enclose the factoryName within single quotes
angular.module('appName').controller('LoginController',[
  '$scope',
  'Login', // Change hereReferenceError: Login is not defined)
  function($scope, Login){
    $scope.submitLogin = function(){
      console.log('login requested');
      Login.login();
    }
  }]);

A: It should be, You are missing ''
angular.module('appName').controller('LoginController',[
  '$scope',
  'Login',
  function($scope, Login){

  }]);

A: Also note that the order of your injections with quotes needs to be consistent with the parameters. For example, the following will still give you an undefined:
angular.module('appName').controller('LoginController',
  ['$scope', 'Factory1', 'Factory2',
  function($scope, Factory2, Factory1){
     Factory1.something; // undefined
     Factory2.something; // undefined
  }]);

You need follow the sequence, like this:
angular.module('appName').controller('LoginController',
  ['$scope', 'Factory1', 'Factory2',
  function($scope, Factory1, Factory2){
     Factory1.something; // Yay!
     Factory2.something; // Woohoo!
  }]);


text:
Q: Use of preposition "from" after "across" I need a little help with these sentences:

The cafe is across from the tailor.
  The cafe is across the tailor.

Which one is correct? Thank you!

A: Someone may have a sash across his chest. "across from" is short for "The café is across the street when you come from the tailor's/ seen from the tailor's shop".

A: Of the two options given, the more accepted would be "The café is across from the tailor."
However, ultimately, it may be preferred that one would be more specific, such as, "The café is across the street from the tailor."

A:
The cafe is across the tailor.

This is dead wrong.


text:
Q: building singletons from an abstract class in a nutshell, i'm trying to build subclasses of an abstract class, all of which will be singletons.  i'd like to just place the singleton "logic" in the super class.  is this possible in Java?  here is the code:
public abstract class Table {
    //the static singleton instance.  this will be inherited by subclasses of this class.
    protected static Table m_Instance;

    /**
     * @param tableName the database table name.
     */
    protected Table(String tableName, List<Column> columns) {
        TABLE_NAME = tableName;
        if(columns != null) {
            if(!m_Columns.isEmpty())
                m_Columns.clear();
            m_Columns.addAll(columns);
        } else {
            throw new IllegalStateException("the columns list was null.  this is a developer error.  please report to support.");
        }
    }

    protected static Table getInstance() {
        if(m_Instance == null)
            m_Instance = <? extends Table>;
    }
}

and here is just a blurb for clarification of implementation:
public class CallTable extends Table {
    //this class would inherit 'getInstance()' and the method would return a 'CallTable' object
}

A: There will only ever be one copy of the Table class (setting aside multiple classloaders etc!), so there will only be a single value m_Instance.
This means you can't have a singleton of each subclass - only a singleton of any one of the subclasses.
It would be possible to handle multiple subclasses e.g. by storing them in a Map in the superclass and looking them up by class, but the complexity is probably not worth it.
In either case, the getInstance method will return a Table, so you lose type safety - you may need to keep casting from Table to CallTable, for example. Java's type system doesn't support this kind of situation.
Also note that the singleton pattern is controversial, to say the least, and many folks try to avoid it.

A:
i'd like to just place the singleton "logic" in the super class.

What logic? Simply follow the established idiom and define your Singletons with enums. It just works. No need to put Singleton logic in an abstract base class. enums already do all the work for you.


text:
Q: MySQL to generate daily profile views reports with filled gaps I'm about to plot daily profile views in chart.js. I have two table one for track every day profile visit named "stats_profile_views" and second one carries all date of an year named "calendar"

I would like to show last 7 days profile views when logged in each vendor.
Tried following query,
SELECT datefield  AS DATE ,`id`, `vendor_id`, `view_date`,IFNULL(view_count,0) AS view_count
FROM (`stats_profile_views` pv)
 RIGHT JOIN bp_calendar ON (DATE(view_date) = bp_calendar.datefield)
WHERE `vendor_id` =  '110'
AND bp_calendar.datefield BETWEEN DATE_SUB(NOW(), INTERVAL 7 DAY) AND NOW()

GROUP BY DATE
ORDER BY `view_date` asc

I like to get past 7 days records filled with view_count zero for non-available records in "stats_profile_views" table. But when apply WHERE vendor_id =  '110' it fails to return such record and gives only 3 records related with vendor_id =  '110'. But it work great without vendor_id filter.
How can I get last 7 days records filled with view_count as zero when filter using vendor_id. Anybody guide me to a solution please.

A: SELECT
      c.datefield AS DATE
    , pv.id
    , pv.vendor_id
    , pv.view_date
    , IFNULL(pv.view_count, 0) AS view_count
FROM bp_calendar c
      LEFT JOIN stats_profile_views pv ON (DATE(pv.view_date) = c.datefield)
                  AND pv.vendor_id = '110'
WHERE c.datefield BETWEEN DATE_SUB(NOW(), INTERVAL 7 DAY) AND NOW()
ORDER BY
      pv.view_date ASC

When using outer joins the where clause MUST be careful not to override the unmatched rows, otherwise you get the effect of an inner join instead. That's what happened in your original query; because EVERY row is required to have a vendor_id = '110' but an unmatched date cannot have any vendor_id.
Additionally it generally helps to write the query FROM (the table with the all the rows) LEFT JOIN (table with gaps in it). Then include the extra conditions of the left joined table as extra join conditions instead of the where clause.
If you want to group the results then you need to indicate what it is you are attempting to do. Perhaps summing the view_counts? However if you are intending to do that then you would not include columns like id in the result.
Also, please, include the table alias in EVERY reference to column.


text:
Q: Border box content changes position From my understanding, content inside of a block with box-sizing set to border-box, should not affect that block's positioning.
However, adding content to a box, appears to move that box downward. Can someone please explain what's going on here?

  div {
    display: inline-block;
    box-sizing: border-box;
    width: 64px;
    height: 64px;
    background-color: red;
  }

a

a

a

a


text:
Q: Multi-windows in Android 7.0 - Always get landscape layout even though device in multiwindows portrait mode I am developing an android application that supports multi-windows feature on Android 7.0.
I followed this guide on https://developer.android.com.
, imported sample project https://github.com/googlesamples/android-MultiWindowPlayground
I create a new resource named layout-land and did some testing. I recognized that landscape layout is inflated even though the device is in portrait mode.
Check out attached images.

How can I set portrait layout when device is in portrait mode.

A: Assume you have two screens. One is in landscape and one in portrait.
How can you say which one is in landscape and which one in portrait?
In portrait width of the screen is less than height.
And for landscape width of the screen is greater than height.
Agree?
So, here, when you enter multiwindow mode your app's window no longer fits screen - width is greater than height and it is considered as landscape.
That is why landscape layout resource is used.
There is no separate modifier for layout resource to be used in split-screen mode.
The only thing you can do to achieve portrait in your case is to remove layout-land.
Or you can create two separate layouts (without any modifiers such as -land) and in activity call activity.isInMultiWindowMode(); to choose corresponding layout you want to use.


text:
Q: Using repeater to display Thumbnail images that link to full images i'm using the Advanced Custom Fields plugin with the repeater field to display images in a masonry gallery, I want to be able to have the images in the gallery be displayed as thumbnails then when clicked they open into a lightbox, I have it all working other than the masonry images aren't showing as thumbnails (Meaning theres alot of full HD images being loaded when the page is opened causing slow loading times, heres the website page - http://vn.deckchairdesign.co.uk/wedding/weddings/ (I should add this is a Wordpress theme I am creating!).
Here's the code :
<?php if(get_field('images')): ?>
                <?php while(the_repeater_field('images')): ?>
                        <?php $image = wp_get_attachment_image_src(get_sub_field('image'), 'full'); ?>
                        <?php $thumb = wp_get_attachment_image_src(get_sub_field('image'), 'thumbnail'); ?>

                        <a href="<?php the_sub_field('image');?>" class="fancybox" rel="gallery_group">

                        <img src="<?php the_sub_field('image');?>"

                <?php endwhile; ?>

            <?php endif; ?>


text:
Q: Is Visual C++ a programming language or an IDE? I've created and finished a project using Visual Studio 2013 and C++ programming language. However this was the first time that I use Visual Studio. (I've created this project by New-> Visual C++ -> General-> Empty project) Before I had always programmed in Linux/Ubuntu.
Now, I need to make a GUI to this project and I decided to use plotLab.(http://www.mitov.com/products/plotlab#overview)
While I was searching in this website to find the libraries that I need to download, I saw the following :
Our component libraries come in 3 versions a VCL

*

*Firemonkey version (for Delphi / C++ Builder / RAD Studio XE3 to XE6)

*MFC compatible Visual C++ version,

*.NET 2.0-4.5 version (compatible with Visual Studio 2005 to 2013).

I'm confused a bit, because it is written Visual C++ version, and a .NET 2.0-4.5 version (compatible with Visual Studio 2005 to 2013). seperately. What should I do since I've never used .NET.
To other words, I'd like to use this PlotLab in my current C++ project which I've explained above but I'm not sure should I download libraries for Visual C++ or .NET 2.0-4.5 version?

A: .NET version applies to the .NET languages including  Visual Basic, C#, J# and C++/CLI. that the library supports. In short the text means you can either use .NET language of the versions listed or or C++ with one of the specified versions. The two things are separate. As for the question title - Visual Studio is an IDE, but it comes with a collection of compilers for different languages including C++ and all the .NET languages.


text:
Q: Is there a way to compare a date against a table that can sort it in one of three categories? I'm trying to compare a set of events that are date/time stamped against a table that can categorize it in three different buckets.
This table has four columns:
Column 1: Date
Column 2: Rotation 1
Column 3: Rotation 2
Column 4: Rotation 3

There are 356 rows (one for each day) and then each column has either 'Night shift', 'Day shift' or 'Days off'.
If I have a dataframe with a bunch of entries that have date and time, can I set a rule to compare it to this other table?

*

*If the time is betwee 5AM and 5PM, find that day in the other table and
   output the corresponding 'Rotation 1', 'Rotation 2' or 'Rotation 3'

*If the time is between 5PM and 5AM, do the same as above.
Then next to each datetime on the Pandas dataframe, I'm trying to have one more column appear with Rotation 1, 2 or 3 depending on which one fits there.
I was able to put together a Frankenstein v-lookup nightmare in excel, I'm new to Pandas but I feel it can be a much cleaner process.
Add one column to the dataframe with the corresponding rotation based on the date and time.


text:
Q: Passing a generic list to a multi-parameter method in C# Working on a program where I need to pass three pieces of information to a method that will, in turn, create a row for a table from the data passed in.
The variables are:
var runningTally = new Dictionary<string, Dictionary<string, int>>();
var comments = query.ToList();
var columns = query.ToList();

I'd call the method like this:
tReport.Rows.Add(row);
foreach (var key in _masterList.Keys)
{
    CreateRow(key, runningTally, columns);
}

I was hoping my method signature could look like this:
private void CreateRow(string key, IDictionary<string, Dictionary<string, int>>
 runningTally, List<T> columns)

But that doesn't work (the editor complains that the type 'T' can't be found).  I was hoping someone could tell me how to properly use a generic list as a parameter for a method. I appreciate any help and advice!

A: You need to mark the method as generic.
Like this:
private void CreateRow<T>(string key, IDictionary<string, Dictionary<string, int>>
 runningTally, List<T> columns)

Notice the method name itself has the generic parameter added to it.


text:
Q: MediaPlayer stream from url I have a simple app and I want to play a mp3 from a url.
when I add this code to OnCreate, the app crashes at opening:
try {
        mediaPlayer.setDataSource("http://www.freesfx.co.uk/rx2/mp3s/9/10183_1367780535.mp3");
        mediaPlayer.prepare();
    } catch (IOException e) {
        e.printStackTrace();
    }

Why? What's wrong with this part of the code?
Complete code:
  public class MediaStreamTest extends AppCompatActivity {
ImageButton bPlay;
ImageButton bStop;
MediaPlayer mediaPlayer;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_media_stream_test);

    bPlay = (ImageButton)findViewById(R.id.btnPlay);
    bStop = (ImageButton)findViewById(R.id.btnStop);
    try {
        mediaPlayer.setDataSource("http://www.freesfx.co.uk/rx2/mp3s/9/10183_1367780535.mp3");
        mediaPlayer.prepare();
    } catch (IOException e) {
        e.printStackTrace();
    }

    bPlay.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (mediaPlayer.isPlaying()) {
                bPlay.setBackgroundResource(R.drawable.ic_play_arrow_24dp);
                mediaPlayer.pause();
            }
            else {
                bPlay.setBackgroundResource(R.drawable.ic_pause_24dp);
                mediaPlayer.start();
            }
        }
    });
}

}

A: The issue is because the MediaPlayer is not being initialized. That's why you are getting a null pointer exception when trying to use it.
Just add:
mediaPlayer = new MediaPlayer();

Before calling MediaPlayer.setDataSource method


text:
Q: Running node sqlite3 code synchronously I'm having trouble adjusting to the async-first nature of node / js / typescript. This intent of this little function should be pretty clear: it takes a database and returns an array of courses that are listed in that database.
The problem is that the return statement gets run before any of the database operations have run, and I get an empty list. When I set a breakpoint inside the database each loop, I can see that the rows are being found and that courses are being put into ret one by one, but these courses never become visible in the scope where courseList() was called.
const courseList = (database: sqlite3.Database): Course[] => {
    let ret = new Array<Course>();

    database.serialize();
    database.each("select ID, Title from Course", (err: Error, row: Object) => {
        ret.push(new Course(
            row.ID,
            row.Title
        ))
    })

    return ret;
}

Suggestions?
The calling code just wants to print information about courses. For example:
let courses = courseList(db);
console.log(courses.length); // logs 0, even though the db contains courses

A: database.each takes a complete callback. Use that to resume e.g.
const courseList = (database: sqlite3.Database, complete): Course[] => {
    let ret = new Array<Course>();

    database.serialize();
    database.each("select ID, Title from Course", (err: Error, row: Object) => {
        ret.push(new Course(
            row.ID,
            row.Title
        ))
    }, complete);

    return ret;
}
let courses = courseList(db, () => {
    console.log(courses.length);
});

More

*

*There are better ways to write this. Use promises https://basarat.gitbooks.io/typescript/content/docs/promise.html

*The documentation is horrible : https://github.com/mapbox/node-sqlite3/wiki I would be tempted to look elsewhere (TS First) for a database solution. Its not worth the pain for me personally. YMMV.


text:
Q: find sum of $BatterRuns variable in laravel-8 I want to find the sum of the $BatterRuns variable how to do this?
Note;_ I am just beginner of laravel
This is my index.blade.php
@foreach ($data as $key => $row)

@php
        $BatterRuns = $row->scoreupdateone->one + $row->scoreupdatetwo->two * 2 +
        $row->scoreupdatethree->three * 3 + $row->scoreupdatefour->four * 4 +
        $row->scoreupdatesix->six * 6;
@endphp
         {{ $key + 1 }}
         {{ $row->matchh->match_name }}
         {{ $row->team->team_name }}
         {{ $row->player->player_name }}
         {{ $BatterRuns }}
         {{ $row->scoreupdate->out_type }}
         {{ $row->scoreupdateoutbytype->out_by_type }}
         {{ $row->scoreupdateone->one }}
         {{ $row->scoreupdatetwo->two }}
         {{ $row->scoreupdatethree->three }}
         {{ $row->scoreupdatefour->four }}
         {{ $row->scoreupdatesix->six }}
         {{ $row->scoreupdateballsplayed->balls_played }}
@php
         $Balls = $row->scoreupdateballsplayed->balls_played;
@endphp

@endforeach

This Is what I get you can see the Runs column which i get form $BatterRuns variable.
You can see there is different values in Runs column like 4,6,0 I want sam values of 4+6+0 = 10. I want something like $sum = SUM($BatterRuns); How to do this

A: You can do something like this on your code.
@php
 $totalRun = 0;
@endphp
@foreach ($data as $key => $row)

@php
        $BatterRuns = $row->scoreupdateone->one + $row->scoreupdatetwo->two * 2 +
        $row->scoreupdatethree->three * 3 + $row->scoreupdatefour->four * 4 +
        $row->scoreupdatesix->six * 6;
        $totalRun = $totalRun + $BattersRuns;

@endphp
         {{ $key + 1 }}
         {{ $row->matchh->match_name }}
         {{ $row->team->team_name }}
         {{ $row->player->player_name }}
         {{ $BatterRuns }}
         {{ $row->scoreupdate->out_type }}
         {{ $row->scoreupdateoutbytype->out_by_type }}
         {{ $row->scoreupdateone->one }}
         {{ $row->scoreupdatetwo->two }}
         {{ $row->scoreupdatethree->three }}
         {{ $row->scoreupdatefour->four }}
         {{ $row->scoreupdatesix->six }}
         {{ $row->scoreupdateballsplayed->balls_played }}
@php
         $Balls = $row->scoreupdateballsplayed->balls_played;
@endphp

@endforeach

 {{ $totalRuns }}

Declare a php vairable before for-loop and use the same variable inside for-loop to sum up the runs. And use the variable $totalRuns to display sum of $battersRun


text:
Q: CSS3 Animation is getting problems I am using a small example to demonstrate CSS animations. Though the color is changing but the rotation is not executed. Pls help fix it!

This is a paragraph.

A: The semicolon is misplaced in (180deg;), should be outside the parenthesis (180deg);

    p {
      width: 100px;
      height: 100px;
      background: red;
      animation-name: peter;
      animation-duration: 5s
    }

    @keyframes peter {
      from {
        background: orange;
      }
      to {
        background: yellow;
        transform: rotate(180deg);
      }
    }

This is a paragraph.

A: Try adding a rotate to from and also vendor prefixes to ensure fallback for all browsers.
from {
 background: orange;
 -webkit-transform: rotate(0deg);
 -moz-transform: rotate(0deg);
 -o-transform: rotate(0deg);
 transform: rotate(0deg);
}
to {
 background: yellow;
 -webkit-transform: rotate(180deg);
 -moz-transform: rotate(180deg);
 -o-transform: rotate(180deg);
 transform: rotate(180deg);
}


text:
Q: Variance of sample moments - clarification on Serfling (1980) In "Serfling, R. J. (1980). Approximation theorems of mathematical statistics", we read

In Theorem A, as one suspects, $k=1,2,...$, indicating the integer-moments, while $n$ is the sample size. As regards the $m_k$ and $\mu_k$ symbols, we have, drawing i.i.d from the distribution of some random variable $X$,
$$m_k = \frac 1n \sum_{i=1}^n (X_i-\bar X)^k, \;\;\;\mu_k = E[(X-E(X)]^k$$
Theorem A is concerned with each separate central sample moment, Theorem B is concerned with their joint limiting distribution.
Suppose that $k=3$. Then, from Theorem A we have
$$\text{AVar}(m_3) = \mu_6 - \mu_3^2 - 6\mu_2\mu_4 + 9\mu_2^3$$
But from Theorem B, setting $i=j=3$ we get
$$\text{AVar}(m_3) = \mu_8 - \mu_4^2 - 8\mu_3\mu_5 + 16\mu_3^2\mu_2$$
I don't see how the two can coincide, and some quick simulated checks show that they don't.
Question:is it possible that the expression in Theorem B is meant only for the off-diagonal covariance terms and not for the diagonal variance terms?
The author makes no such clarification.

A: Posting questions on CV has this magic effect many times: a little after you post them, you find the answer.
ANSWER: both expressions are correct, and the expression in Theorem B holds also for the diagonal variance terms. The catch?
...In the variance-covariance matrix expression, we realize that the numbering of the variables starts from $2$, while the $i,j$ indices start from $1$.
This means that when we want to obtain the variance of $m_3$ we must set $i=j=2$, and when we want to obtain, say, the covariance of $(m_3, m_4)$, we must set $i=2, j=3$.
In general, for $k,\ell$ moments, set $i=k-1, j=\ell-1$ in the variance-covariance expression.


text:
Q: .NET SDK's Not Installing Correctly I am getting an issue with installing the .NET SDK, at first when I went into visual studio 2019 it said that I was missing the dotnet runtime sdk so I installed it like it asked and restarted my computer. I then went on to visual studio 2019 again, and the same issue arose, I went into my command prompt and typed dotnet --list-sdks and it displayed no sdks. I have all of the runtimes installed, but it says No SDKs were found. image . I tried re-installing the sdks but the same problem stuck. I even went as far as to re-install IIS. I can't do anything without this being fixed please help soon!

A: Before you try a manual install, I'd check if the Path in the system's environment variables is correctly configured for your system.
Given that there's always one shared host that moves forward, it will either pick the x86 or the x64 version on your machine. This issue of not picking the right one might happen if you install multiple/different versions.
Run the where.exe dotnet command to see where the host is looking for the SDK (it's the first entry returned). If you're on a x64 machine, you want to have C:\Program Files\dotnet listed first.
If it's not, edit the Path system's environment variable to have the location you want showing up higher. Doing that should fix the issue of the SDK versions you installed not showing up when you run dotnet --info.
See The latest installed .NET SDK not found for complete instructions.

A: Answer above by Maira is correct and fixed the issue however for those that need a little help go to start menu, type "path" and select "Edit the System Environment variables". When that opens, under the "Advanced" tab click "Environment Variables".
Under System Variables find the "Path" variable and click "Edit". Find "C:\Program Files\dotnet" and click "Move Up" so that it is above the (x86) variable.

A: I managed to find the answer to this problem, and anyone else who is having this problem can most likely fix it with this solution too! So the reason it breaks is because of the way the .NET Core SDK installer works, it does not install the SDK correctly for some reason, so you have to do it manually. Go to this link, where you would normally get the installer for the SDK but rather than downloading the normal version, download the binaries version. It should download as a .zip, so extract it and then copy the contents of the folder. Go to C:\Program Files (x86)\dotnet\ and then remove it's contents, finally paste your clipboard into the folder. Now try it out, open a new command prompt or PowerShell, and type dotnet --info. It should tell you that you have all the SDK's and Runtimes installed. Keep in mind, you will have to download the newest version of the binaries, that way you have the latest version of the SDK's.
The reason this works is that you are manually pasting the SDK's into the folder, if anyone could start a ticket for the installer to Microsoft, {EDIT: MS created an internal ticket and this answer is wrong. See next answer End Edit} that would be great, and link them to this post so that they can understand what's going on. Some of you might have come here because you are fed up with reading Microsoft documentation and to be honest, so was I! Now this might not fix all the problems you are having, for example, I am still having problems with visual studio and their .NET implementation but if I or anyone figures it out, I will add it to this answer. Hope you have a great day, bye!

A: dotnet do not seem to match well with SDKs / runtimes with 32-bits and 64-bits. If you have both variants and want to only use the 64-bits (or generally, cant list up any SDK-s), you can try this :

*

*Inside folder : C:\Program Files (x86)

*Rename folder 'dotnet' to 'dotnet_x68'

*Inside a shell (remember to either run command 'refreshenv' from Chocolatey for example to refresh your environment, if you have choco installed.. )

*Enter now this command :

*dotnet --info

*Also list the SDKS :

*dotnet --list-sdks

*
This fixed up my development environment. Note that if you want to use dotnet against x86 system, you might consider to instead uninstall x64 variants of dotnet runtime and sdks as dotnet do not seem to work very good from command line with a mix of them both (and avoid renaming the x86 folder of dotnet of course as suggested above.

A: I found that I had two program files, One called Program Files (x86) and one called Program Files. I went to Settings, About and looked at my System Type. I have a 64-Bit operating system and so I went into Program Files (x86) and found another dotnet folder. I deleted the dotnet folder and restarted Visual Studio. It Worked after that.

A: If you get this issue like I did on a ARM based Mac M1 or M2 then do the following.

*

*remove this directory completely /usr/local/share/dotnet

*run the installer package again

I believe this issue happened when I accidentally installed dotnet-ef x64 instead of arm64.


text:
Q: PHP no me guarda datos en la BBD MySQL Bien, tengo una ficha de pagos para facturas. Uno de los campos es "Fecha" al que le tengo asociado un botón para que, al pulsar, me de la fecha de hoy. Correcto.
Creo una nueva columna en phpMyAdmin con los mismos parámetros que "FECHA" porque quiero añadir otro campo que se llame "Pago" para referirnos a la fecha en la que se ha realizado el pago.
Bien, con la configuración siguiente, cuando le doy al botón "HOY" me modifica la fecha de la factura, pero el nuevo campo "pago" no se actualiza (no cambia y sigue con 000-00-00).
A ver si me podéis echar una mano (al cuello)
La estructura en la bbdd es:
Nombre: fecha
Tipo: Date
Predeterminado: Ninguno
La nueva:
Nombre: pago
Tipo: Date
Predeterminado: Ninguno.
El php es este:

                        <?
                            $nomcolumns = array('ID','Fecha','Cliente','Correo','IRPF','IVA','Precio','Pagada','Fecha de Pago');
                            $nomcolumnsdb = array('idmostrado','fecha','cliente','correo','irpf','iva','precio','pagada','pago');

                            // type of the column
                            // text 1, select 2, radio boolean 3, textarea 4, date 5, 6 select clientes, 7 precio
                            $typecolumns = array(1,5,6,1,1,1,7,3,5);
                        ?>

                            <?
                                $result = getclients();
                                for($i=0;$i<count($nomcolumns);$i++){?>

                                        <?=$nomcolumns[$i]?>
                                        <?
                                            switch($typecolumns[$i]){

                                                case 1:
                                                    {?><input type="text" name="<?=$nomcolumnsdb[$i]?>" value="<?=$factura[$nomcolumnsdb[$i]]?>" id="myinput">	<?}
                                                    break;

                                                case 2:
                                                    {?><select name="<?=$nomcolumnsdb[$i]?>" id="myselectmonth"><?}
                                                    for($j=0;$j<count($valuesselect);$j++){
                                                        if($factura[$nomcolumnsdb[$i]]==$valuesselect[$j]){?><option value="<?=$valuesselect[$j]?>" selected><?=$namesselect[$j]?></option><?}
                                                        else{?><option value="<?=$valuesselect[$j]?>"><?=$namesselect[$j]?></option><?}
                                                    }
                                                    {?></select>
                                                     <input type="button" class="btn" onclick="javascript:changemonth('myselectmonth',1)" value="Hoy"/>
                                                    	<?}
                                                    break;

                                                case 3:
                                                    if($factura[$nomcolumnsdb[$i]]==0) $sel = array('checked','');
                                                    else $sel = array('','checked');
                                                    {?>
                                                        <input type="radio" name="<?=$nomcolumnsdb[$i]?>" value="0" <?=$sel[0]?>> No

                                                        <input type="radio" name="<?=$nomcolumnsdb[$i]?>" value="1" <?=$sel[1]?>> Sí
                                                        	<?}
                                                    break;

                                                case 4:
                                                    {?><textarea class="ckeditor" name="<?=$nomcolumnsdb[$i]?>" rows="10" cols="97%"><?=$factura[$nomcolumnsdb[$i]]?></textarea> 	<?}
                                                    break;

                                                case 5:
                                                    {?><input type="date" name="<?=$nomcolumnsdb[$i]?>" value="<?=$factura[$nomcolumnsdb[$i]]?>" size="100%" id="datepicker" >
                                                     <input type="button" class="btn" onclick="javascript:changedate('datepicker',1)" value="Hoy"/>
                                                    	<?}
                                                    break;

                                                case 6:
                                                    {?><select name="<?=$nomcolumnsdb[$i]?>" id="myselect"><?}
                                                    while($row = mysqli_fetch_array($result)){
                                                        if($factura[$nomcolumnsdb[$i]]==$row['id']){?><option value="<?=$row['id']?>" selected><?=$row['razonsocial']?></option><?}
                                                        else{?><option value="<?=$row['id']?>"><?=$row['razonsocial']?></option><?}

                                                    }
                                                    {?></select>
                                                        	<?}
                                                    mysqli_data_seek($result, 0);
                                                    break;

                                                case 7:
                                                    {?><input type="text" name="<?=$nomcolumnsdb[$i]?>" value="<?=$factura[$nomcolumnsdb[$i]]?>" id="myinput">
                                                     <input type="button" class="btn" onclick="javascript:updateprice('<?=$nomcolumnsdb[$i]?>','irpf','iva')" value="Actualizar"/>
                                                    	<?}
                                                    break;

                                            }
                                        ?>


text:
Q: Use other pairwise distance metrics in scikit-learn for KNN besides p-norm For scikit-learn's KNN package, can one specify a pairwise distance metric (from the package sklearn.metrics.pairwise) that isn't the p-norm, or Minkowski distance? For example, could I use the RBF kernel? Or even the cosine distance?

A: Unfortunately the BallTree algorithm that is used to compute fast exact NN search on low to medium number of dimensions cannot work with arbitrary metrics.


text:
Q: Textview won't display data which has been updated in model (MVC) I've tried the following approaches to try to get the TextView to update from the model:

*

*TextChangeListeners - error

*Other Threads

*asynctask

*Added a refresh button which updates the data, I force the click

Scenario is as follows:

*

*Standard thread running which updates the Model (MVC) object every second, which works perfectly.

*When the Model object is updated, it notifies all classes which implement "Observer".

*My GolfHomeScreen extends Activity and implements Observer (code below).

*The GolfHomeScreen.update (Observable observable, Object data) method works perfectly. It executes every second as expected and S.O.P the correct data (see --> //* #1 *).

*This then kicks off a Thread. I read on this site that you have to UI Thread to execute code which updates widgets and then run the "runOnUiThread" method - the code looked something like I have done below but I found it a little hard to follow. Anyway, this thread runs (see --> //* #2 ) which then executes method onClick(View v) (see --> // #3 *).

*System.out.println("driverType :" + mvcModel.getDriverName()); (see --> //* #4 *) works perfectly.

*//* #5 * - it MUST update but it doesn't.

*If I actually physically click the button, the data is displayed correctly on the screen. My only guess is that the screen must not refresh on the forced click or else I am not using the UI thread to make the update.

NOTE: If the code below is missing something, it is because I removed a ton of code to simplify the understanding of what's going on.
public class GolfHomeScreen extends Activity implements Observer
{
    GolfHomeScreen golfHomeScreen = null;
    TextView driverName = null; // Type of driver used by golfer (eg: 1 wood)
    Button refreshData = null;

  @Override public void onClick(View v) //*** #3 ***
  {
    if ((v.getId()) == 12345) // ID of wood (12345 = 1 wood)
    {
                    //*** #4 ***
        System.out.println("driverType              :" + mvcModel.getDriverName()); //THIS PRINTS OUT THE LATEST DATA!!!

                    //*** #5 ***
                    driverName.setText(String.valueOf(mvcModel.getDriverName()));   //THIS DOESN'T AFFECT THE SCREEN?? WHY  :-(
    }
  }

  @Override public void onCreate(Bundle savedInstanceState)
  {
    golfHomeScreen = this;
    refreshData = indViewById(R.id.golfhomescreen_button_refreshData);
    driverName = (TextView) findViewById(R.id.golfhomescreen_text_drivername);
  }

  @Override public void update(Observable observable, Object data)
  {
     // #1 ***
    System.out.println("driverType              :" + mvcModel.getDriverName());

    golfHomeScreen.runOnUiThread(new Runnable()
    {
        @Override
        public void run()
        {
            refreshData.performClick(); //*** #2 ***
        }
    });
  }

}

A: I'll run a few suggestions and a few fixes and hopefully your problem will be gone.
I'm saying that because conceptually you do have some wrong stuff, and my answer is kind of fixing those concepts:

*

*remove GolfHomeScreen golfHomeScreen = null; and golfHomeScreen = this; you don't need an object referencing to itself. It's just making confusion. This line golfHomeScreen.runOnUiThread(new Runnable() you should just call runOnUiThread(new Runnable()

*Change System.out.pr*** to Log.d(TAG, MESSAGE); that's just because that is Android specialised way of dumping logs and it won't really matter for your result. It's nicer than standard Java System.out because allows you to filter those logs by TAG and severity.

*Do never call refreshData.performClick(); or anything similar to that because you want the action inside that button to be performed. If you want a certain thing to happen from more than one source, create a method doThatThing(), put the actions in there, and from the Click and from the Update, you call the method. The way you're doing is a bit of a "Rube Goldberg machine" that is updating something, to click a button, to change a text. Just change the text.

*do never compare a view ID with a number if ((v.getId()) == 12345) the ID of views created from XML are generated by the system during compilation and you can't know if it's a fixed number. You should compare with the static int ID of that view, like this : if(v.getId() == R.id.golfhomescreen_text_drivername). If the view was not created in XML (which is not the case here), you can compare with the actual object if(v.equals(driverName))
with those changes I believe your code will work. Make sure to let me know and mark as correct answer if in fact does.


text:
Q: Should "music" be capitalised? Should the word "music" be capitalized in the following sentence?

...after spending some time in Music and studies.

A: It depends on the context in which it is used. If it is the name of a subject (e.g. English, Maths, History), then, yes, capitalise it. Otherwise it should be in lowercase.

'Did you have Music today?' (Capitalised here because it is a subject/class and hence a proper noun)
'No, but I like listening to music.' (Lowercase here because it is not a proper noun)


text:
Q: How to pivot all columns in Tableau
I have this data set in Tableau and I want to pivot all the columns. The only option I have is to select one by one is there any option?
This is how it should look like:

A: Do it like the GIF below.  Actually you can use shift+ click to select all column at once.  And yes, it can be done in tableau desktop.  Note you cannot unpivot (pivot_wider) in Tableau desktop though, for which you have to use Prep.


text:
Q: Stack Overflow Careers and Internships? http://careers.stackoverflow.com/
With the launch of this new career connection, I had a question concerning student signups. I know the primary goal is full time positions, but will internships be a part of this service? Is this not a good idea to mix with job postings? Maybe a future add on? Dedicated students are always looking for internship opportunities as they are great experience and a foot in the door in many cases.
Yes? No? maybe? 6-8 weeks?

A: In candidate search employers can search specifically for interns.
If you're interested in being found for internships you can indicate that in the "search settings" section of your profile:

*

*Click "employer view" then "edit search settings".

*Tick the "Internship or Co-op" box.

*Click the "save" button.

Then when employers search for interns (and you match their other criteria) you'll show up.


text:
Q: multiple dynamic javascript upload buttons I need help dynamically creating upload buttons.
I've created a function to create the input and label elements for the buttons and formatted the label with CSS so that a label is clicked to open the upload file dialog window while the main input element is hidden.
When I fun the function, it successfully generates a upload button with the first button working fine, but because the label's htmlfor tag is looking for a unique id, i I can't seem to dynamically create more upload buttons.
I've tried replacing the htmlFor id with label.htmlFor = label.previousElementSibling; but that doesn't work.
Here is what i have:
function addButton() {
var upload = document.createElement("input");

var col11 = document.createElement("td")

var upload = document.createElement("input");
    upload.type = "file";
    upload.id = "receipt";
    upload.className = "uploadClass";

    var label = document.createElement("label")
    label.innerHTML = `<i class='material-icons center'>file_upload</i>`;
    label.htmlFor = label.previousElementSibling;
    label.className = "custom-file-upload";

    col11.appendChild(upload)
    col11.appendChild(label)

Here is the CSS code:
input[type="file"]{
display: none;
}

.custom-file-upload{
border: 1px solid #ccc;
display: inline-block;
padding: 6px 6px;
cursor: pointer;
}

It seems that the issue is creating dynamic htmlFor tags for each button label?

A: Try this, I'm using Date's getTime method to generate an id for file input. Feel free to use whatever solution you like when generating a unique ID.

function generateInputId() {
   return new Date().getTime();
}

function addButton(inputId) {
    const input = document.createElement("input");
    const td = document.createElement("td")
    const label = document.createElement("label")

    input.type = "file";
    input.id = inputId;
    input.className = "uploadClass";

    label.innerHTML = `<i class='material-icons center'>file_upload</i>`;
    label.htmlFor = inputId;
    label.className = "custom-file-upload";

    td.appendChild(input)
    td.appendChild(label)
    return td;
}

const row = document.getElementById("row")
const fragment = document.createDocumentFragment();

Array(3).fill(0).forEach(() => fragment.appendChild(addButton(generateInputId())));

row.appendChild(fragment);
input[type="file"]{
display: none;
}

.custom-file-upload{
border: 1px solid #ccc;
display: inline-block;
padding: 6px 6px;
cursor: pointer;
}

      One
      Two
      Three


text:
Q: How to change default bulletdots and add an image instead I am new to css and I am trying to change the bullet style of ul>li as follows:

Sorry for the less quality image, it is a green tick inside a circle.
My code so far is:

ul {
    display: flex;
    flex-direction: column;
    list-style-type: square;
}

Ullamco laboris nisi ut aliquip ex ea commodo consequat.

Duis aute irure dolor in reprehenderit in voluptate velit.

      Ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute
      irure dolor in reprehenderit in voluptate velit esse cillum dolore
     eu fugiat nulla pariatur.

A: As I mentioned in my comment, check the given snippet on how to change the bullet styles with an image using pseudo classes.
I have used ::before here to append the tick image before each li.
Let me know if this works.

ul {
    display: flex;
    flex-direction: column;
    list-style: none;
}

li {
  display: flex;
}

li::before {
    content: '';
    display: inline-block;
    height: 15px;
    width: 15px;
    min-width: 15px;
    background-image: url('https://www.citypng.com/public/uploads/preview/-316225804095zek9ufozk.png');
    background-size: 70%;
    margin-right: 5px;
    background-repeat: no-repeat;
    border-radius: 50%;
    border: 2px solid green;
    background-position: center;
}

Ullamco laboris nisi ut aliquip ex ea commodo consequat.

Duis aute irure dolor in reprehenderit in voluptate velit.

      Ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute
      irure dolor in reprehenderit in voluptate velit esse cillum dolore
     eu fugiat nulla pariatur.

A: You can do as

Ullamco laboris nisi ut aliquip ex ea commodo consequat.

Duis aute irure dolor in reprehenderit in voluptate velit.

      Ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute
      irure dolor in reprehenderit in voluptate velit esse cillum dolore
     eu fugiat nulla pariatur.

then in css you can style it using list-style-image: url('your-image.png');
ul.my-image{
 list-style-image: url('your-image.png');
}


text:
Q: How do you detect changes in url with a chrome extension? I am learning to make chrome extensions. I ran into a problem where context scripts that I want to run, even just alert("test");, are unable to when onload is not activated. This also occurs when you press the back arrow to visit the last visited page. I notice that the url changed, but nothing activates. How do I detect this? If the answer is with service workers, a detailed explanation would be greatly appreciated.

A: maifest version 2.0

Try using chrome.tabs.onUpdated.addListener((id, change, tab)=>{}). This should run every time the URL changes! Here is a minimalistic example of some code that injects js to a site when the URL changes.
background.js:
// inject code on change
chrome.tabs.onUpdated.addListener((id, change, tab) => {

    // inject js file called 'inject.js'
    chrome.tabs.executeScript(id, {
        file: 'inject.js'
    });
});

mainfest version 3.0

You can do it by using chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {}). However, this will actually trigger multiple times when a page URL is changed So you need to add a check for the URL in the changeInfo variable, so it only triggers once!
manifest.json:
{
    "name": "URL change detector",
    "description": "detect a URL change in a tab, and inject a script to the page!",
    "version": "1.0",

    "manifest_version": 3,
    "permissions": [
        "scripting",
        "tabs"
    ],
    "host_permissions": [
        "http://*/*",
        "https://*/*"
    ],

    "background": {
        "service_worker": "background.js"
    }
}

background.js:
// function that injects code to a specific tab
function injectScript(tabId) {

    chrome.scripting.executeScript(
        {
            target: {tabId: tabId},
            files: ['inject.js'],
        }
    );

}

// adds a listener to tab change
chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {

    // check for a URL in the changeInfo parameter (url is only added when it is changed)
    if (changeInfo.url) {

        // calls the inject function
        injectScript(tabId);

    }
});

inject.js:
// you can write the code here that you want to inject
alert('Hello world!');


text:
Q: inheriting python method with a call to super inside the method I am developing a system, which has a series of single multilevel inheritance hierarachy. one of the methods (applicable to all the classes) has to perform the same thing for most of the classes, which is to pass a list to its parent class.
I know that if one doesn't define a method in one of the inherited classes, its parents' methods are used. But when we use the super method, we need to mention the name of the class being called.
One method I know to achieve this is to redefine the method at every class with class name as argument. Is there any elegant method where I can define it once at the topmost parent, and then override it only when necessary?
The implementation right now looks like this
class a(object):

    def __init__(self):
        self.myL = list()
        print 'hello'

class b(a):

    def __init__(self):
        super(b,self).__init__()

    def resolve(self, passVal):
        print passVal
        self.myL.append(passVal)
        super(b,self).resolve(passVal+1)

class c(b):

    def __init__(self):
        super(c,self).__init__()
    def resolve(self, passVal):
        print passVal
        self.myL.append(passVal)
        super(c,self).resolve(passVal+1)

Instead if I can define resolve in class a, and then all other classes inherit the method from it. I understand a will never be able to use it. but redefining the method seems a lot unnecessary extra work.


text:
Q: MYSQL stored procedure cursor returning null value I have a Session table in Mysql. I am trying to fetch the result from this table using mysql stored procedure cursor but everytime it's returning null. Here is the code what I am trying to fetch resultset.
CREATE PROCEDURE `getSession`()
BEGIN
    DECLARE done INTEGER DEFAULT 0;
    DECLARE site_id INTEGER(20);
    DECLARE sess CURSOR FOR
    SELECT siteid FROM Sessions WHERE cstate=1;
    DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;

    OPEN sess;
    get_session: LOOP
        FETCH sess INTO site_id;
        IF done = 1 THEN
            LEAVE get_session;
        END IF;
        SELECT site_id;
    END LOOP get_session;

   CLOSE sess;
END


text:
Q: Javafx RotateTransition rendering smooth I'm making some trials with JavaFX RotateTransition, applying a simple model found on a jfx itself documentation file:
    rotateTransition = RotateTransitionBuilder.create()
            .node(elements)
            .duration(Duration.seconds(4))
            .fromAngle(0)
            .toAngle(720)
            .cycleCount(3)
            .autoReverse(true)
            .build();

Above, elements is a Group of bare Arc primitives.
When this group has a limited number of nodes, say 20, the animation goes smooth but when I increase the number of nodes to 500 (nested actually, Group of Group) the animation still works but does not result any more fluid.
The question is: does this nodes limit can be considered too much for this task? How to speed up the rendering?
I have found the thread below that in a similar context asserts that could be a matter of using the right Animation class, but I'm not sure that the proposed AnimationTimer does apply well to a rotation.
http://mail.openjdk.java.net/pipermail/openjfx-dev/2013-June/008104.html
I have also tried to use setCache(true) to every node with no visible improvements.
Thank you!
Edit: Arc generation. No strange things but a binder and a EventHandler.
Arc arc = new Arc();
arc.centerXProperty().bind(plotRadiusBinding);
arc.centerYProperty().bind(plotRadiusBinding);
arc.radiusXProperty().bind(plotRadiusBinding);
arc.radiusYProperty().bind(plotRadiusBinding);
arc.setStartAngle(startAngle * 180 / PI);
arc.setLength(radiansLength * 180 / PI);

arc.setType(ArcType.ROUND);
arc.setStroke(defaultArcColor);
arc.setStrokeType(StrokeType.INSIDE);
arc.setFill(null);

arc.setOnMouseClicked(arcEventHandler);

A: I had similar issues when moving images around when I used KeyFrames (KeyFrames)
I could improve it by using
I had success with implementing the stuff by myself:
Animation animation = new Transition() {

  {
    setCycleDuration(Duration.millis(1000));
  }

   @Override
   protected void interpolate(double frac) {
     // your rotation code here
   }
}

If you could provide your arc generation source code it might be helpful.

A: for me this works flawlessly for 500 arcs:
package application;

import java.util.Random;

import javafx.animation.RotateTransition;
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.scene.shape.Arc;
import javafx.stage.Stage;
import javafx.util.Duration;

public class Main extends Application {
    @Override
    public void start(Stage primaryStage) {
        try {
            Pane root = new Pane();

            Group group = new Group();

            Random rand = new Random();

            for(int i=0; i<1000; i++){
                Arc c = new Arc(200 + rand.nextInt(400), 200 + rand.nextInt(400), 10, 10, 0, 360);

                group.getChildren().add(c);
            }

            root.getChildren().add(group);

            RotateTransition  rotateTransition = new RotateTransition(Duration.millis(5000), group);
            rotateTransition.setFromAngle(0);
            rotateTransition.setToAngle(720);
            rotateTransition.setCycleCount(3);
            rotateTransition.setAutoReverse(true);

            rotateTransition.play();

            Scene scene = new Scene(root,800,800);
            scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
            primaryStage.setScene(scene);
            primaryStage.show();
        } catch(Exception e) {
            e.printStackTrace();
        }
    }

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

if this is still to laggy and you only want to draw arcs you could directly invoke the graphics-context of a canvas.


text:
Q: Jquery show and hide elements according to position I am trying to make a carousel of sorts. I am kind of stuck with hiding and displaying the next and precious buttons once a div moves to the far left and right of its container.
I think i have everything correct regarding calculating the widths but for some reason when you click the buttons, elements stay hidden irrespective of the conditional comments which should dictate when they should be hidden or shown.
Here is a link to what i have thus far. Click the MoveLeft and MoveRight buttons. http://www.ehbeat.com/test/
<script type="text/javascript">
    $(document).ready(function () {

        //Check width of Gallery div
        var galleryWidth = $("#Gallery").innerWidth();

        //Check width of GalleryItem
        var galleryItemWidth = $(".GalleryItem").innerWidth();

        //Check distance from left
        var position = $('.GalleryItem').position();
        var galleryItemLeft = position.left;

        $(".MoveRight").click(function () {
            $(".GalleryItem").animate({
                "left": "+=50px"
            }, "slow");
            $(".GalleryItem2").animate({
                "left": "+=100px"
            }, "slow");
        });

        $(".MoveLeft").click(function () {
            $(".GalleryItem").animate({
                "left": "-=50px"
            }, "slow");
            $(".GalleryItem2").animate({
                "left": "-=100px"
            }, "slow");
        });

        $(".Controls").live('click', function () {
            if (galleryItemLeft >= "0") {
                $('.MoveRight').hide();
            }
            else {
                $('.MoveRight').show();
            }
        });

        if (galleryItemWidth == galleryWidth - galleryItemWidth) {
            $('.MoveLeft').hide();
        }

    });
</script>

A: It looks like you setup all of your variables inside the $(document).ready() call.
This means that while they're being set on load, they're not getting updated with each click.
Your galleryItemLeft, galleryItemWidth and galleryItemWidth variables need to be updated on each click, so I'd recommend re-assigning the values in each click (by moving the assignment into the live functions)
Edit Also, as your last if statement is excluded from any click function, it'll need to be relocated to inside the live click events as well.
-Chris

A: Chris is right, code should look like this:
$(".Controls").live('click', function() {
    position = $('.GalleryItem').position();
    galleryItemLeft = position.left;

    if(galleryItemLeft > "0") {
        $('.MoveRight').hide();}
    else{
        $('.MoveRight').show();
    }

    if(galleryItemWidth == galleryWidth - galleryItemWidth) {
        $('.MoveLeft').hide();
    }
});


text:
Q: success and error function in the controller for a service I have the following code in a service and I am calling fetchData function from the controller.
Service
app.service("geturl", function($http) {
    urllist = [];
    geturl.fetchData = function() {
        var data = [];
        for (i = 0; i < urllist.length; i++) {
          (function(index) {
            return $http.get(geturl.urllist[index], {
              timeout: 8000
            })
            .then(function(response) {
              data[index] = response.data;
            });
          }(i);
          return data;
        });
    };
});

I want to write the success and error function of $http.get in the controller since it is needed in the UI, how can I go about it?

A:
..I want to write the success and error function of $http.get in the
  controller..

Usually, the .then() function takes two function arguments. The first argument is the success handler and the second as an error handler.
$http.get(url,options).then(function (response){
    //success handler function
    },function(error){
  //error handler function
  })

Alternatively, you can specify the .success and .error functions separately.
$http.get(url,options).success(function (response){
    //success handler function
    }).error(function(error){
  //error handler function
  })

UPDATE:
From your code, it seems that you intend to return something from your service geturl and providing the callbacks there itself. This is not how it is supposed to be done. You should return a promise from your service .
   ...
   app.service("geturl",function($http){
     ...
     getData:function(){
        return $http.get(url,options);
     }
     ...
   });
   ...

and handle the success/error callbacks in the module where you are consuming the service
geturl.getData().success(function(){
//handle success
}).error(function(){
//handle error
})

In case you need to make multiple http requests, never ever use the for loop . Remember, everything is asynchronous and you are not guaranteed to get the response from one of the previous request before you make a new one. In such scenarios, you should use $q service. See @pankajparkar's answer for more details

A: Seems like you want to return a data after all the ajax gets completed, You could achieve this by using $q.all()
Service
app.service("geturl", function($http, $q) {
    this.urllist = [];
    this.fetchData = function() {
        var data = [], promises = [];
        for (i = 0; i < urllist.length; i++) {
          (function(index) {
            var promise = $http.get(geturl.urllist[index], {
              timeout: 8000
            })
            .then(function(response) {
              data[index] = response.data;
            });
            promises.push(promise); //creating promise array
          }(i);
        };
        return $q.all(promises).then(function(resp){
            return data; //returning data after all promises completed
        });
    };
});


text:
Q: How to Hide or Show Custom attribute based on other custom attribute in Product detail/edit page from Adminpanel Magento 2.4? I have created the Product's custom attributes programmatically(Setup->Installdata.php).
 $eavSetup->addAttribute(
            \Magento\Catalog\Model\Product::ENTITY,
            'serial_code_use_customer',
            [
                'type' => 'int',
                'backend' => '',
                'frontend' => '',
                'label' => 'Issue By Customer Group',
                'input' => 'boolean',
                'class' => '',
                'source' => \Magento\Eav\Model\Entity\Attribute\Source\Boolean::class,
                'global' => \Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface::SCOPE_STORE,
                'visible' => true,
                'required' => false,
                'user_defined' => true,
                'default' => '0',
                'searchable' => false,
                'filterable' => false,
                'comparable' => false,
                'visible_on_front' => false,
                'used_in_product_listing' => false,
                'unique' => false,
                'apply_to' => 'simple,configurable,virtual,bundle,downloadable',
                'group' => self::GROUP_LABEL,
                'sort_order' => 3,
                'note' => 'Enable automatic issuing of codes based on customer group.'
            ]
        );

        $eavSetup->addAttribute(
            \Magento\Catalog\Model\Product::ENTITY,
            'serial_code_customer_groups',
            [
                'type' => 'varchar',
                'backend' => '',
                'frontend' => '',
                'label' => 'Select Customer Groups',
                'input' => 'multiselect',
                'class' => '',
                'source' => \Magento\Customer\Model\Customer\Attribute\Source\Group::class,
                'global' => \Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface::SCOPE_STORE,
                'visible' => true,
                'required' => false,
                'user_defined' => true,
                'default' => '0',
                'searchable' => false,
                'filterable' => false,
                'comparable' => false,
                'visible_on_front' => false,
                'used_in_product_listing' => false,
                'unique' => false,
                'apply_to' => 'simple,configurable,virtual,bundle,downloadable',
                'group' => self::GROUP_LABEL,
                'sort_order' => 4,
                'note' => 'Customers in selected groups will be issued codes automatically when product is ordered.'
            ]
        );

I want to Hide or Show a Custom attribute based on other custom attributes in the Product detail/edit page from Adminpanel Magento 2.4.x?
For example, there is a toggle on click (yes/no) the Customer Groups will be Hide / Show.

A: To hide custom product attributes from the admin product detail page you need to create UpgradeData.php in the My/Catalog/Setup directory.
Code:

$eavSetup->updateAttribute(Product::ENTITY, $attrCode, 'is_visible',
'0');


text:
Q: SAS EG is unable to connect to SAS APP Sever context also unable to validate sas Logical workspace server and sas grid server in management console SAS Environment details  sas 9.4_M3
2 metadata server 19 grid nodes 1 grid master 2 web servers
issue in grid:
sas eg is unable to connect to sasAPP/ sasAPPgrid  server context. error message "Unable to establish connection with SAS APP.
also when tried to validate servers in SMC below server failed
SASApp Logical grid Server and SASApp Logical Workspace Server
Below were the error in Object spawner Logs.

2017-11-03T15:28:06,157 ERROR [00532573] :saspmgr0 -
  2017-11-03T15:28:06,000 (gridrun.c:1047) - processStartJob: Error
  starting job, status=0x81ffe803 2017-11-03T15:28:06,157 ERROR
  [00532573] :saspmgr0 -  PROVIDER(Platform): Bad host name, host group
  name or cluster name 2017-11-03T15:28:06,157 ERROR [00532573]
  :saspmgr0 -  Grid job failed to run. 2017-11-03T15:28:06,157 ERROR
  [00532556] :f401099 - Grid job failed to run. 2017-11-03T15:28:06,157
  ERROR [00532556] :f401099 - The launch of server SASApp - Workspace
  Server for user f401099 failed. 2017-11-03T15:28:06,158 ERROR
  [00532556] :f401099 - The specified uuid
  9762CD6B-30D8-7341-9821-5D7A337756D2 did not match any process managed
  by this spawner. 2017-11-03T15:28:06,158 INFO  [00532556] :saspmgr0 -
  Client connection 4112 for user f401099 closed.

I also see error in connect spawner Logs.
issue though resolved after restarting LSF however i want to understand the root cause since this issue occurred thrice in 7 days.


text:
Q: Python regex to check if a string contains a method call I am parsing an xml file in python. I fetch the attribute values of xml nodes for processing.
<set name="flashScope.emailSuggestion" value="userBean.createEmailSuggestion(flowRequestContext)" />

Using ElementTree, I get the attribute of the node
node.attrib['value']

which gives me
userBean.createEmailSuggestion(flowRequestContext)

Now how do I check if this string contains paranthesis ()? (I mean, to know that it is a method call)..Can anyone suggest a regex pattern for this?

A: This should work in general:
^\w+(\.\w+)+\(.*\)$