text:
Q: ORA-01735: invalid ALTER TABLE option - Toad When i execute below SQL in Toad its throws "ORA-01735: invalid ALTER TABLE option".
ALTER TABLE CALCULATE
  ADD (CAL_METHOD VARCHAR2(50), REMARKS VARCHAR2(500));

But when execute in SQL Developer its running successful, Is there any issue with SQL / Toad. Please advice me.

A: Your SQL is correct but the problem is TOAD restrict Statements and Scripts for each button. I assume the cause of the error is you are trying to run ALTER TABLE command using Execute Statement or F9 key. First of all, let's see what is different between Statement and Script

Execute Statement will give you a list of all the results in a
  sortable table. It will also only run the statement under the cursor
  (or highlighted). You will be prompted for bind variables when you run
  the statement (any placeholder: in front of it).
E.g.
select * from customers where customer_id = :id

will prompt for a value for id
Execute Script will execute all statements in the worksheet,
  and give a text readout of the results. It will not prompt you for the
  values of bind variables.

https://stackoverflow.com/a/479443/2940265
As you can understand ALTER TABLE returns only a text output. So you have to use Execute as Script or F5

A: In TOAD I suppose, you need to execute it as a script (press F5) rather that running it as a statement.

A: try this:
ALTER TABLE CALCULATE
  ADD (CAL_METHOD VARCHAR2(50));

ALTER TABLE CALCULATE
  ADD (
 REMARKS VARCHAR2(500));

A: I am using TOAD 11.0.6 and Oracle database version is 11gR2
See the below scripts which I am able to execute by F5 or by clicking the green arrow as shown in the enclosed screenshot
CREATE TABLE calculate (col NUMBER);

ALTER TABLE calculate
  ADD (cal_method VARCHAR2(50), remarks VARCHAR2(500));

SELECT * FROM calculate;

A: I end up drop the column first then add back
ALTER TABLE  SITE_NUMBER DROP COLUMN CREATOR_ID;
ALTER TABLE  SITE_NUMBER ADD (CREATOR_ID varchar2(12))


text:
Q: Bootstrap: How to fix two overlapping content I am trying to create a website using this codepen(enter link description here).
The problem I'm having is when I make the window size smaller, the profile section and main content section start to overlap. I think the codepen is using bootstrap grid system here so I don't really understand why this is happening.
content overlapping image
Here are the codes.
HTML

    Bootstrap

               Log out

              Jason Davis

              Developer

            <button type="button" class="btn btn-success btn-sm">Follow</button>
            <button type="button" class="btn btn-danger btn-sm">Message</button>

                            Overview

                            Account Settings

                            Tasks

                            Help

          Some user related content goes here...

test

test

test

test

test

test

test

test

test

test

test

test

test

test

      Copyright © Your Website 2018

          Privacy Policy

          Terms of Use

CSS
html, body {
  height: 100%;
}
body {
  display: flex;
  flex-direction: column;
  background: #F1F3FA;
}
body {
  overflow-x:hidden;
}
#mainNav {
  background-color: darkslategrey;
  color:white;
}
#mainNav .navbar-brand {
  color: #fed136;
  font-family: 'Kaushan Script', 'Helvetica Neue', Helvetica, Arial, cursive;
}

.content {
  flex: 1 0 auto;
}
.footer {
  flex-shrink: 0;
}

footer {
  text-align: center;
  background-color: white;
}
.ft{
  padding-left:22px;
  padding-right:31px;
}

footer span.copyright {
  font-size: 90%;
  line-height: 40px;
  text-transform: none;
  font-family: 'Montserrat', 'Helvetica Neue', Helvetica, Arial, sans-serif;
  color:blak;
}

footer ul.quicklinks {
  font-size: 90%;
  line-height: 40px;
  margin-bottom: 0;
  text-transform: none;
  font-family: 'Montserrat', 'Helvetica Neue', Helvetica, Arial, sans-serif;
}

ul.social-buttons {
  margin-bottom: 0;
}

ul.social-buttons li a {
  font-size: 20px;
  line-height: 40px;
  display: block;
  width: 40px;
  height: 40px;
  -webkit-transition: all 0.3s;
  -moz-transition: all 0.3s;
  transition: all 0.3s;
  color: white;
  border-radius: 100%;
  outline: none;
  background-color: #212529;
}

ul.social-buttons li a:active, ul.social-buttons li a:focus, ul.social-buttons li a:hover {
  background-color: #fed136;
}
.content{
   margin-top:60px;
 }

/* Profile container */
.profile {
  margin: 20px 0;
}

/* Profile sidebar */
.profile-sidebar {
  padding: 20px 0 10px 0;
  background: #fff;
}

.profile-userpic img {
  float: none;
  display:block;
    margin:auto;
  width: 50%;
  height: 50%;
  -webkit-border-radius: 50% !important;
  -moz-border-radius: 50% !important;
  border-radius: 50% !important;
}

.profile-usertitle {
  text-align: center;
  margin-top: 20px;
}

.profile-usertitle-name {
  color: #5a7391;
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 7px;
}

.profile-usertitle-job {
  text-transform: uppercase;
  color: #5b9bd1;
  font-size: 12px;
  font-weight: 600;
  margin-bottom: 15px;
}

.profile-userbuttons {
  text-align: center;
  margin-top: 10px;
}

.profile-userbuttons .btn {
  text-transform: uppercase;
  font-size: 11px;
  font-weight: 600;
  padding: 6px 15px;
  margin-right: 5px;
}

.profile-userbuttons .btn:last-child {
  margin-right: 0px;
}

.profile-usermenu {
  margin-top: 30px;
}

.profile-usermenu ul li {
  border-bottom: 1px solid #f0f4f7;
}

.profile-usermenu ul li:last-child {
  border-bottom: none;
}

.profile-usermenu ul li a {
  color: #93a3b5;
  font-size: 14px;
  font-weight: 400;
}

.profile-usermenu ul li a i {
  margin-right: 8px;
  font-size: 14px;
}

.profile-usermenu ul li a:hover {
  background-color: #fafcfd;
  color: #5b9bd1;
}

.profile-usermenu ul li.active {
  border-bottom: none;
}

.profile-usermenu ul li.active a {
  color: #5b9bd1;
  background-color: #f6f9fb;
  border-left: 2px solid #5b9bd1;
  margin-left: -2px;
}

/* Profile Content */
.profile-content {
  padding: 20px;
  background: #fff;
  min-height: 460px;
}

.nav>li {
    position: relative;
    display: block;
}

Any help would be appreciated as I have tried multiple methods with no success.
Thank you in advance.

A: I see you have added a class position-fixed to the element with class profile-sidebar, so this element will remain fixed no matter what.
You could remove the class position-fixed and handle everything in the CSS, using media queries to set its position for smaller and larger screens.

A:

The position-fixed does not allow your profile-sidebar to move away.
It works otherwise https://jsfiddle.net/f9hot4yk/
Instead of adding the position fixed class you can add profile-sidebar into a min-width location in your CSS where you add the fixed property to the sidebar.
Like this:
@media only screen and (min-width: 1200px) {
  .profile-sidebar {
    position: fixed;
  }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Print user defined variable inside a HTML page with Email-ext plugin in Jenkins I am using email ext in the jenkins pipeline script with email body reference to a file. I want to know how to pass user defined variable.
Ex:- I want to pass the variables "mySonarURL" and "myData" to the HTML file.
    def committer = getGitCommitterEmail()
    def mySonarURL = "My Sonar URL"
    def myData = "My Data"

    emailext (
        to: committer,
        subject: "Jenkins Build ${branchName} #${env.BUILD_NUMBER} [${currentBuild.result}]",
        body: '${FILE,path="email.html"}',
        mimeType: 'text/html'
    )
}

HTML file

My Data:	"${myData}"

Sonar URL:	Sonar URL

I have tried using as above HTML file but they were returning just the string "${myData}" and "${mySonarURL}"

A: Mention type as Script in body of mail as guided in official Jenkins wiki
body: '${SCRIPT, template="email.html"}'


text:
Q: Bash - parsing ini file, finding section name by values within I have a config.ini file which looks like this (updated):
[group1]
base=100
hwadd=0x20
doorstatus=100
lock=101
bookingnr=010100
kode=1111
inuse=0

[group2]
base=100
hwadd=0x20
doorstatus=100
lock=102
bookingnr= 010101
kode=1111
inuse=0

[group3]
base=100
hwadd=0x20
doorstatus=100
lock=103
bookingnr=010103
kode=1111
inuse=0

[group4]
base=100
hwadd=0x20
doorstatus=100
lock=105
bookingnr=010105
kode=1111
inuse=0

[group5]
base=100
hwadd=0x20
doorstatus=100
lock=106
bookingnr=010106
kode=1111
inuse=0

[group6]
base=100
hwadd=0x20
doorstatus=100
lock=107
bookingnr=010107
kode=1111
inuse=0

[group7]
base=100
hwadd=0x21
doorstatus=100
lock=101
bookingnr=010108
kode=1111
inuse=0

[group8]
base=100
hwadd=0x21
doorstatus=100
lock=102
bookingnr=010109
kode=1111
inuse=0
...

I need to get the room number where 3 given values (base, hwadd, lock) match the script parameters. So lets say the bash script was called like this:
script.sh 100 0x20 105

the script would return 4 (since all 3 parameters match group4)
Finding a single value is a piece of cake
source config.ini

and every value is available under $valX but this is not parsing the section names so it is useless in this case..

A: Could you please try following, it is in form of shell script which person needs to run by providing arguments to script(tested and written with shown samples).
cat script.ksh
val="$@"

awk -v arg="$val" '
BEGIN{
  FS="="
  num=split(arg,array," ")
  for(i=1;i<=num;i++){
    array1[array[i]]
  }
}
/group/{
  if(sum==num){
    print group_value
  }
  sum=""
  gsub(/[^0-9]*/,"")
  group_value=$0
  next
}
($NF in array1){
  sum++
}
END{
  if(sum==num){
    print group_value
  }
}
'  Input_file

When I run it like:
./script.ksh xyz xyy zyx
3

Explanation: Adding detailed explanation for above code here.
cat script.ksh
val="$@"                         ##Creating a shell variable named val which has all values of arguments passed to script.
awk -v arg="$val" '              ##Starting an awk program from here and creating a variable arg whose value is shell variable val here.
BEGIN{                           ##Starting BEGIN section from here.
  FS="="                         ##Setting FS as = here.
  num=split(arg,array," ")       ##Splitting arg variable into an array with delimiter as space here.
  for(i=1;i<=num;i++){           ##Running for loop from i=1 to till value of num here.
    array1[array[i]]             ##Creating an array named array1 with index of value of array with index i here.
  }
}
/group/{                         ##Checking condition if line contains group string then do following.
  if(sum==num){                  ##Checking condition if sum==num then do following.
    print group_value            ##Printing variable group_value here.
  }
  sum=""                         ##Nullifying variable sum here.
  gsub(/[^0-9]*/,"")             ##Globally substituting everything apart from digits with NULL here in current line.
  group_value=$0                 ##Setting variable group_value value to current line value here.
  next                           ##next will skip all further statements from here.
}
($NF in array1){                 ##Checking condition if last field of current line is present in array1 then do following.
  sum++                          ##Increase count of sum variable with 1 here.
}
END{                             ##Starting END block for this code here.
  if(sum==num){                  ##Checking condition if sum==num then do following.
    print group_value            ##Printing variable group_value here.
  }
}
'  Input_file                    ##Mentioning Input_file name here.

A: You may use this awk:
val='100 0x20 105'

awk -F= -v vals="$val" 'BEGIN {
   n = split(vals, w, /[ \t]+/)
   for (i=1; i<=n; i++)
      values[w[i]] = 1
}
/^\[group[0-9]+]$/ {
   if (n == found)
      print grp
   delete seen
   found = 0
   grp = $0
   gsub(/^\[group|\]$/, "", grp)
}
NF == 2 && values[$2] && !seen[$2]++ {
   found++
}
END {
   if (n == found)
      print grp
}' file

4

Code Demo

A: Your script script.sh could be this:
#!/bin/bash

sed '/^\[/p;/^base/p;/^hwadd/p;/^lock/p;d' config.ini |   # keep relevant lines
awk '
  BEGIN{RS = "["; FS = "\n"}
  {print $1, $2, $3, $4}
' |                                   # awk puts each block on one line
grep "base=$1 hwadd=$2 lock=$3" |     # filter line matching all records
sed -e 's/^group//' -e 's/\].*$//'    # extract group # from matching line

If you issue ./script.sh  100 0x20 105 with the updated config.ini file above, the output will be:
4

It is necessary that the entries base=..., hwaddr=... and lock=... always appear in this order in config.ini for a match. If this is not the case, please ask me to adapt the script.

A: Whenever your input data has name-value pairs it's best to first create an array (f[] below) that maps those names to their values and then at the end of every record you can simply compare the values by their names in whatever combination you like and print whatever values you like in whatever order you like just referencing them by their names.
$ cat tst.awk
BEGIN { FS=" *= *"; OFS="=" }
NF {
    if ( /]/ ) {
        gsub(/[^0-9]/,"")
        f["group"] = $0
    }
    else {
        f[$1] = $2
    }
    next
}
{ prt() }
END { prt() }

function prt() {
    if ( (f["base"] == base) && (f["hwadd"] == hwadd) && (f["lock"] == lock) ) {
        print f["group"]
    }
    delete f
}

$ awk -v base=100 -v hwadd=0x20 -v lock=105 -f tst.awk file
4

A: Sed variant
#!/bin/bash
val1=$1 # get value1
val2=$2 # get value2
val3=$3 # get value3
file="config.ini"   # ini file
raw=$(cat "$file")  # read file to this var
raw=${raw//$'\n'/ } # change new line to space
raw=${raw//[/'\n'}  # change [ to new line
# print through sed, sed prints number of group in matched string
printf "$raw" | sed -n "s/group\([0-9]*\).*$val1.*$val2.*$val3.*/\1/p"

Usage
$ ./test xyz xyy zyx
4


text:
Q: Standard answers for a speech in a AI I am building a project where there is a software, It should answer to questions as "Hi","What your name?", "How are you?", ecc. Is there a standard answers I can embed on my project? Otherwise I should write every answers.
P.S. I am using Python 3.10
Thanks


text:
Q: How I can use refs to change styling class in ReactJS? I'm trying to change background of a div when color value changes. Here is my function which receives color value:
ChangeColor(oColor) {
    this.props.ChangeColor(oColor);
    console.log("Refs: ", this.refs.colorPicker.className);
  },

Here is css class
.colorPicker {
    padding-right: 25px;
    background: #000;
    display: inline;
    margin-right: 5px;
  }

and here is my div element whose background needs to update on run-time.

I'm not sure about refs synatx so please help to fix this issue. Thanks.

A: If somebody is looking for the hooks version

export const YourComponent = (props) => {
  const divRef: = useRef(null);

  yourTriggerEvent = () => {
    divRef.current.style.background = 'red';
  }

  return (

  );
}

A: Also, you can change the color of the div with the ref element. For example:
const myReference = this.colorPicker.current // The DOM element
myReference.style.backgroundColor = "red"; // The style you want to apply

A: I found it. Here is answer:
  ChangeColor(oColor) {
    this.props.ChangeColor(oColor);
    this.refs.colorPicker.style.background = oColor; //this is how background will be updated

  },


text:
Q: Excel/VBA changing date when there are changes to the workbook is it possible in Excel to insert today's date into a Workbook/sheet only when the data inside the sheet is changed.
So what I mean by this is that there is a workbook with several sheets and if somebody makes changes to this sheets I want to have my date updated that is in a specific cell. For better understanding lets just say that this cell is C5 of the first worksheet.
Thank you in advance

A: Try the code below:
Private Sub Worksheet_Change(ByVal Target As Range)

' check that the cell changed is not "C5"
If Intersect(Target, Range("C5")) Is Nothing Then
    Application.EnableEvents = False

    Range("C5").Value = Date
End If
Application.EnableEvents = True

End Sub


text:
Q: .getStringExtra returning null value instead String Getting value in putExtra But cant retrieve in getStringExtra.
public class StartNotificationReceiver extends BroadcastReceiver{

private void sendTodayNotification() {
    DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
    Date todateDate = new Date();
    String TodayDate_String = dateFormat.format(todateDate);
    String Val=AppSettingsPref.getStringValue(context, AppSettingsPref.KEY_TODAY_DATE_AND_TIME, "");
    if(!Val.equals(TodayDate_String))
    {
        AppSettingsPref.saveString(context, AppSettingsPref.KEY_TODAY_DATE_AND_TIME, TodayDate_String);

        final HGDate englishDate = new HGDate(context);
        englishDate.setGregorian(Calendar.YEAR, Calendar.MONTH + 1, 1);
        final HGDate islamicDateToday = new HGDate(englishDate);
        islamicDateToday.toHigri();
        int islamicDayToday = islamicDateToday.getDay();
        int islamicMonthToday = islamicDateToday.getMonth();

        String otherMonth = Dates.islamicMonthName(context, islamicDateToday.getMonth() - 1);
        int adjustedDate = AppSettingsPref.getIntValue(context, AppSettingsPref.CURRENT_ADJUSTMENT_KEY, 0);
        String todayDateTimeinhijri = islamicDateToday.getDay() + (adjustedDate) + " "
                + otherMonth + " " + islamicDateToday.getYear();

        Intent intent = new Intent(context,NotificationReceiver.class);
    -------->intent.putExtra("todayDateTimeinhijri", todayDateTimeinhijri.toString());<-----------

        databaseAccess = DatabaseAccess.getInstance(context);
        databaseAccess.open();
        ArrayList<Event> events = databaseAccess.showEventsByMuslimType(muslimType);
        for (int i = 0; i < events.size(); i++) {
            Event event = events.get(i);
            String[] date = event.getHejriDate().split("-");
            int islamicDayOfEvent = Integer.parseInt(date[0].trim());
            int islamicMonthOfEvent = Integer.parseInt(date[1].trim());
            boolean isViladat = event.isVilaadat;
            if (islamicDayToday == islamicDayOfEvent && islamicMonthToday == islamicMonthOfEvent) {
                makeNotification(event);
            }
        }
    }

intent.putExtra("todayDateTimeinhijri", todayDateTimeinhijri.toString());
This is where .getStringExtra is getting null value
public class NotificationReceiver extends BroadcastReceiver{

 public void onReceive(Context context, Intent intent) {
        this.context = context;
}
        todayDateTime2 = intent.getStringExtra("todayDateTimeinhijri");

}
The extra code is removed for better understanding
Thanks in advance
Help will be appreciated.
cant find solution.

A: Where do you send (or start) the intent with the parameter "todayDateTimeinhijri"?
If you don't send the intent the NotificationReceiver isn't able to receive anything.
//example activity using receiver and send intent via broadcast ( sendBroadcast(intent) )

public class Example extends AppCompatActivity {

    private NotificationReceiver mNotificationReceiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mNotificationReceiver = new NotificationReceiver();
        IntentFilter intentFilter = new IntentFilter("your_action");
        registerReceiver(mNotificationReceiver, intentFilter);

        StartNotificationReceiver mStartNotificationReceiver = new StartNotificationReceiver(getApplicationContext());
        mStartNotificationReceiver.sendTodayNotification();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mNotificationReceiver != null) {
            unregisterReceiver(mNotificationReceiver);
        }
    }

    private class NotificationReceiver extends BroadcastReceiver {
        Context context;
        @Override
        public void onReceive(Context context, Intent intent) {
            this.context = context;
            String action = intent.getAction();// should be "your_action"
            String todayDateTime2 = intent.getStringExtra("todayDateTimeinhijri");
            Log.i("NotificationReceiver","action: " + action );
            Log.i("NotificationReceiver","dateTime: " + todayDateTime2 );
        }
    }

    public class StartNotificationReceiver {

        private Context context;

        public StartNotificationReceiver(Context ctx){
            this.context = ctx;
        }

        public void sendTodayNotification() {
            Intent intent = new Intent("your_action");
            intent.putExtra("todayDateTimeinhijri", "your String value");
            context.sendBroadcast(intent);
        }
    }
}

A: Putting the extra in the intent does not send it. There sould be a sendBroadcast() call or similar somewhere.


text:
Q: Cannot install therubyracer, gcc version update on OSX Leopard? So after making my first scaffold using Rails, I tried to access some of the pages it created, and got the following error:
     ExecJS::RuntimeError in Users#index

     Showing /Users/Alice/Desktop/sample_app/app/views/layouts/application.html.erb where line #6 raised:

     dyld: unknown required load command 0x80000022

     (in /Users/Alice/Desktop/sample_app/app/assets/javascripts/users.js.coffee)
     Extracted source (around line #6):

     3: <head>
     4:   <title>SampleApp</title>
     5:   <%= stylesheet_link_tag    "application", :media => "all" %>
     6:   <%= javascript_include_tag "application" %>
     7:   <%= csrf_meta_tags %>
     8: </head>
     9: <body></code>

I looked up this error and I concluded that I needed to install therubyracer gem.  I tried to do this via gem install therubyracer.
Then I got the error:
    ERROR:  Error installing therubyracer:
    ERROR: Failed to build gem native extension.
    /Users/Alice/.rvm/rubies/ruby-1.9.3-p362/bin/ruby extconf.rb
    creating Makefile
    Unable to find a compiler officially supported by v8.
    It is recommended to use GCC v4.4 or higher
    Using compiler: g++
    File "./gyp-mac-tool", line 167
    fd = os.open(lockfile, os.O_RDONLY|os.O_NOCTTY|os.O_CREAT, 0o666)
                                                               ^
    SyntaxError: invalid syntax

So I run gcc -version, and I see that my version is i686-apple-darwin9-gcc-4.0.1
I've tried to update my gcc using MacPorts, and I can't seem to make it work at all...
I'm running OSX Leopard, which I'm guessing is the cause of all my grief.
What do I do from here?

A: Try another one. https://github.com/sstephenson/execjs
Look at the list, these basically all do the same thing. I'm sure you'll find one that works.


text:
Q: jQuery and Knockout in IE9 I have a problem with using jQuery to show/hide elements when the elements contain something with a knockout binding. If I try to show/hide an element on the same page that doesn't contain any bindings it works fine. This is how it looks:

This problem only occurs in IE9, and when I "select" something or click on the page the content rerenders. One thing to know is that if I put IE9 in compability mode this works fine.
Any ideas?
EDIT:
I've found a workaround that seems to work in IE9.
My code looked like this when the problems occurred:

  Yayda yada with Knockout-bindings.

 Total kostnad:  kr

Just hiding the #yada div with jQuery would cause the problems I described, but wrapping the text inside a div solved the issue.

  Yayda yada with Knockout-bindings.

 Total kostnad:  kr

Just wanted to let you all know.


text:
Q: How to implement a function that adds to a class' string and another function that returns it in php? I am working on this problem:
The user interface contains two types of user input controls: TextInput, which accepts all texts and NumericInput, which accepts only digits.
Implement the class TextInput that contains:
Public function add($text) - adds the given text to the current value.
Public function getValue() - returns the current value (string).
Implement the class NumericInput that:
Inherits from TextInput.
Overrides the add method so that each non-numeric text is ignored.
For example, the following code should output '10':
$input = new NumericInput();
$input->add('1');
$input->add('a');
$input->add('0');
echo $input->getValue();

Now, I thought the following would be sufficent enough to implement the TextInput class as a minimum as the instructions say

class TextInput
{
    private $str = '';

    public function add($text) {
        $str .= $text;
    }
    public function getValue() {
        return $str;
    }
}

class NumericInput extends TextInput
{

    public function add($text) {
        if ( is_numeric($text)) {
            $str .= $text;
        }
    }
}

It doesn't seem to be working but I thought at the very least the part for class TextInput was done correctly.

A: $str is just a local variable; in your code, it exists only within the scope of a given method. You want to use the class property that you declared with private $str.... That is, you need to refer to the property $str of the object using $this->str.
In addition to that, a private property is not accessible in a child class. That is, instances of NumericInput will not have access to the $str property of TextInput. It would be better to make that property protected, rather than private.
Your classes should look like:
class TextInput
{
    protected $str = '';

    public function add($text) {
        $this->str .= $text;
    }
    public function getValue() {
        return $this->str;
    }
}

class NumericInput extends TextInput
{

    public function add($text) {
        if ( is_numeric($text)) {
            $this->str .= $text;
        }
    }
}

You can read more in the documentation about properties and the documentation about visibility.


text:
Q: how to prove $(-1)\cdot(-1)=1$ based only on the field axioms? How do I prove $(-1)\cdot(-1)=1$ (or in other words that $-1$ is the multiplicative inverse of itself), based only on the field axioms?
Thanks

A: This is to get the result of the multiplication $ \cdot $ of $- 1 $ by $-1$. The number $-1$ is the  symmetric of $1$ with respect to addition $ + $. The axioms that relate addition $+$ to multiplication $\cdot$ are distributivity to the left and right distributivity. Any way to prove this result has to pass through the axiom distributive property which connects the multiplication operation with the addition operation. These equality is a relatively easy exercise.
\begin{align}
(-1)\cdot (-1)= & (-1)\cdot(-1)+\color{red}{0}\\
              = & (-1)\cdot(-1)+\color{red}{[(-1)+1]}\\
              = & (-1)(-1)+\color{red}{\Big(1\cdot(-1)+1\cdot 1\Big)}\\
= & \color{blue}{\Big((-1)(-1)+1\cdot(-1)\Big)}+\color{red}{1\cdot 1} \\
= & \color{blue}{\Big([(-1)+1]\cdot(-1)\Big)}+\color{red}{1} \\
= & \color{blue}{\Big(0\cdot(-1)\Big)}+\color{red}{1} \\
= &\color{blue}{0}+ \color{red}{1}\\
=&1
\end{align}

A: $\textbf{Hint:}$ Think about $(1-1)(1-1)$.

A: Principles of Mathematical Analysis - Walter Rudin, 3rd Ed, p7:

A: $(-1) \cdot (-1)=(-1) \cdot (-1)+(-1) \cdot (1)-(-1) \cdot 1=(-1) \cdot (-1+1)-(-1)=1.$

A: $-1\cdot\text{sth.}=\text{additive inverse of sth.}$,thus $-1\cdot(-1)=1$, as $1$ is the additive inverse of $-1$.


text:
Q: Overriding clean() method of Parent django form in child/inherited form I am really having a hard time figuring this out. The bottom problem is that I need to somehow either set initial value for password field or override the way the method validate_member is called.
I have this form, which is called when a member needs to register to the system directly:
class NewMemberForm(forms.Form):
    '''
    Called when user wants to register with our system from web/mobile. Ask password here

    '''

    firstName=forms.CharField(max_length=25,required=True,widget=forms.TextInput())
    lastName=forms.CharField(max_length=25,required=True,widget=forms.TextInput())
    birthdate=forms.DateField(required=True)
    gender=forms.ChoiceField(choices=Profile.GENDER,required=True)
    idnumber=forms.CharField(required=False,max_length=25)
    phone=forms.IntegerField(required=True)
    email=forms.EmailField(required=True)
    password=forms.CharField(max_length=16,widget=forms.PasswordInput())
    memberType=forms.ChoiceField(choices=Profile.TYPE_OF_MEMBER,widget=forms.Select())
    maritalStatus=forms.ChoiceField(choices=Profile.MARITAL_STATUS,widget=forms.Select())

    def clean(self):
        '''
        Grouped cleaning
        '''
        self.cleaned_data=super(NewMemberForm,self).clean()

        validate_member_form=validate_member(self.cleaned_data,False)

        #do we have error messages now?

        if len(validate_member_form[0])>0: #yes we have error messages
            raise forms.ValidationError(_(validate_member_form[0]),code='invalid')

        return validate_member_form[1]

the validate_member function is used during editing and adding information, thus cleaned the clean() to keep things DRY. Now, I have another scenario in which a member could be registered by another member (with some rights). In that case, the password and membertype fields are not needed with one new field added to the form named role; so I decided to inherit the form:
class MemberAddForm(NewMemberForm):

    #memberType=forms.CharField(initial='Individual',required=False,widget=forms.Select()) #iignored: here to simple override the Required declaraton in memberform
    #password=forms.CharField(max_length=16,widget=forms.PasswordInput(),required=False,initial='111111') #note pwd is ignored during saving and a new is generated
    role=forms.ModelChoiceField(widget=forms.Select(),required=True,queryset=Activity.objects.filter(active='Active').only('id','name'),empty_label=None)

    def __init__(self,*args,**kwargs):
        super(MemberAddForm,self).__init__(*args,**kwargs)
        self.fields['password'].initial='123456' #note this is meangingless and in place to pass validate_member
        self.fields['password'].required=False
        self.fields['memberType'].initial='Individual'
        self.fields['memberType'].required=False

    def clean(self):
        '''
        This is not been used at all.
        '''

        self.cleaned_data=super(MemberAddForm,self).clean()
        self.cleaned_data['password']='!983.kIl'

        #validate_member_form=validate_member(self.cleaned_data,False,False)

        #do we have error messages now?

        if len(validate_member_form[0])>0: #yes we have error messages
            raise forms.ValidationError(_(validate_member_form[0]),code='invalid')

Now, I noticed the clean() method in the child class is ignored entirely and validation is being taken care of from parent.clean() only. I would really need to pass the third parameter as False in the validate_member method (it is True in the Parent class). The validate_member checks password complexity and stuff. Setting the required=False helps partly because 'this field is required' error is no more shown; however, the password is still checked complexity. As you can see, I set the password to initial value that passes password setting but still I get error no matter what I do.

A: This line in child class is causing that parent's clean method is called:
self.cleaned_data=super(MemberAddForm,self).clean()

As the two are almost the same, it looks like the child's one is not called, i.e. if parent's clean passes successfully also the child's one will.
Solution for your problem would be to modify the paren's clean method to:
   def clean(self, validate_member=True):
        '''
        Grouped cleaning
        '''
        self.cleaned_data=super(NewMemberForm,self).clean()

        if validate_member:
            validate_member_form=validate_member(self.cleaned_data, False)

        # Do we have error messages now?
        if len(validate_member_form[0]) > 0:  # yes we have error messages
            raise forms.ValidationError(_(validate_member_form[0]), code='invalid')

        return validate_member_form[1]

And then all you have to do in child's clean method is:
def clean(self):
    return super(NewMemberForm,self).clean(validate_member=False)

A: There is another option
# dynamic form creation
class CreateUpdateView(FormView):
    template_name = 'apps/frontend/create_update_view.j2'
    def get_form_class(self):
        # url like: /user/(?P<mode>[^/]+)/ - /user/register/ or /user/update/
        is_password_required = self.kwargs.get('mode') == 'register'

        class _Form(forms.Form):
            if is_password_required:
                password = forms.CharField(widget=forms.PasswordInput)

            first_name = forms.CharField(max_length=25, required=True)

        return _Form


text:
Q: How to find good start values for nls function? I don't understand why I can't have a nls function for these data.
I have tried with a lot of different start values and I have always the same error.
Here is what I have been doing:
expFct2 = function (x, a, b,c)
{
  a*(1-exp(-x/b)) + c
}
vec_x <- c(77.87,87.76,68.6,66.29)
vec_y <- c(1,1,0.8,0.6)
dt <- data.frame(vec_x=vec_x,vec_y=vec_y)
ggplot(data = dt,aes(x = vec_x, y = vec_y)) +  geom_point() +
     geom_smooth(data=dt, method="nls", formula=y~expFct2(x, a, b, c),
       se=F, start=list(a=1, b=75, c=-5)

I have always this error:
Error in method(formula, data = data, weights = weight, ...) :
  singular gradient

A: This can be written with two linear parameters (.lin1 and .lin2) and one nonlinear parameter (b) like this:
a*(1-exp(-x/b)) + c
= (a+c) - a * exp(-x/b)
= .lin1 + .lin2 * exp(-x/b)

where .lin1 = a+c and .lin2 = -a (so a = - .lin2 and c = .lin1 + .lin2)  This lets us use "plinear" which only requires specification of a starting value for the single nonlinear parameter (eliminating the problem of how to set the starting values for the other parameters) and which converges despite the starting value of b=75 being far from that of the solution:
nls(y ~ cbind(1, exp(-x/b)), start = list(b = 75), alg = "plinear")

Here is the result of a run from which we can see from the size of .lin2 that the problem is badly scaled:
> x <- c(77.87,87.76,68.6,66.29)
> y <- c(1,1,0.8,0.6)
> nls(y ~ cbind(1, exp(-x/b)), start = list(b = 75), alg = "plinear")
Nonlinear regression model
  model:  y ~ cbind(1, exp(-x/b))
   data:  parent.frame()
         b      .lin1      .lin2
 3.351e+00  1.006e+00 -1.589e+08
 residual sum-of-squares: 7.909e-05

Number of iterations to convergence: 9
Achieved convergence tolerance: 9.887e-07
> R.version.string
[1] "R version 2.14.2 Patched (2012-02-29 r58660)"
> win.version()
[1] "Windows Vista (build 6002) Service Pack 2"

EDIT: added sample run and comment on scaling.

A: I struggle to find an interpretation to your parameters:
a is a slope, b the speed of convergence, and a+c the limit,
but c by itself does not seem to mean much.
After reparametrizing your function, the problem disappears.
f <- function (x, a,b,c) a + c * exp(-x/abs(b))
nls(y~f(x, a, b, c), data=dt, start=list(a=1, b=75, c=-5), trace=TRUE)

However, the value of c looks very, very high:
that is probably why the model initially failed to converge.
Nonlinear regression model
  model:  y ~ f(x, a, b, c)
   data:  dt
         a          b          c
 1.006e+00  3.351e+00 -1.589e+08
 residual sum-of-squares: 7.909e-05

Number of iterations to convergence: 9
Achieved convergence tolerance: 2.232e-06

Here is another, more reasonable parametrization of the same function.
g <- function (x, a,b,c) a * (1-exp(-(x-c)/abs(b)))
nls(y~g(x, a, b, c), data=dt, start=list(a=1, b=75, c=-5), trace=TRUE)

Nonlinear regression model
  model:  y ~ g(x, a, b, c)
   data:  dt
     a      b      c
 1.006  3.351 63.257
 residual sum-of-squares: 7.909e-05

Number of iterations to convergence: 10
Achieved convergence tolerance: 1.782e-06

A: Fitting a three-parameter nonlinear model to four data points is going to be moderately challenging in any case, although in this case the data are well behaved.  Point #1 is that your starting value for your c parameter (-5) was way off.  Drawing a picture of the curve corresponding to your starting parameters (see below) would help you understand this (so would recognizing that the curve you get will range from c at its minimum to c+a at its maximum, and the range of your data is from 0.6 to 1 ...)
However, even with a better starting guess I found myself fussing with control parameters (i.e. control=nls.control(maxiter=200)), followed by more warnings -- nls is not known for its robustness.  So I tried the SSasympOff model, which implements a self-starting version of the curve you want to fit.
start1 <- list(a=1, b=75, c=-5)
start2 <- list(a=0.5, b=75, c=0.5)  ## a better guess

pfun <- function(params) {
  data.frame(vec_x=60:90,
             vec_y=do.call(expFct2,c(list(x=60:90),params)))
}
library(ggplot2)
ggplot(data = dt,aes(x = vec_x, y = vec_y)) +  geom_point() +
  geom_line(data=pfun(start1))+
  geom_line(data=pfun(start2),colour="red")+
  geom_smooth(data=dt, method="nls", formula=y~SSasympOff(x, a, b, c),
              se=FALSE)

My advice in general is that it's easier to figure out what's going on and fix problems if you fit nls outside of geom_smooth and construct the curve you want to add using predict.nls ...
More generally, the way to get good starting parameters is to understand the geometry of the function you are fitting, and which parameters control which aspects of the curve.  As I mentioned above, c is the minimum value of the shifted saturating-exponential curve, a is the range, and b is a scale parameter (you can see that when x=b, the curve is 1-exp(-1) or approximately 2/3 of the way from the minimum to the maximum).  Either a bit of algebra and calculus (i.e. taking limits), or playing around with the curve() function, are good ways to gather this information.


text:
Q: How to get the Status of a Windows Process (Running or Terminated) using C language? I want to know weather the Process on Windows task manager is Terminated?
(that means I want to make a function like database trigger)
at the moment that some particular Process is terminated I want to do some task.
I tired it since day before yesterday in so many ways. but I did't get correct fit.
Thank you in Advance.
#include "stdio.h"
#include "Windows.h"

int main()
{
HANDLE jvminst = GetCurrentProcess();

printf("%d %d \n",jvminst,WaitForSingleObject(jvminst,0));

return 0;
}

A: Get the HANDLE of the process and use WaitForSingleObject.


text:
Q: merge two sorted files using awk or python I have two files depending on only 1st column value.
File 1:
2.3 5 3 66
5.5 2 3 54
6.2 4 1 33

File 2:
1.2 3 7 22
4.5 2 6 77
8.9 4 2 54

I want to merge these two files with final sorted file as
1.2 3 7 22
2.3 5 3 66
4.5 2 6 77
5.5 2 3 54
6.2 4 1 33
8.9 4 2 54

A: How about using sort -m (merge sorted files):
sort -m -n file1 file2 > file3

A: Your question is a good one, but I think it got down voted, because you didn't provide enough details. If I can assume that the files are already sorted by column 1, that you want the final output to be sorted by column 1 and there are no duplicate values in column 1, then this solution works:
cat file1 \
| awk 'BEGIN{
 cmd="cat file2"; cmd | getline line2; split(line2,a," "); key2=a[1]} {
 key1=$1; while(key2<key1) {
   print line2; cmd | getline line2; split(line2,a," "); key2=a[1]};
 print $0} END{
 if(key2>key1) print line2}'

You don't need to pipe cat file1 to awk, but I just prefer to have the input file at the beginning of the command instead of at the end. I am often criticised for this redundant use of cat.
Your question is tagged with Python, so here is a Python3 solution as well, which utilises heapq.merge():
import heapq
with open('file1') as fd1, open('file2') as fd2:
    for line in heapq.merge(fd1, fd2):
       print(line, end='')

I found the answer, when searching for "merge sorted files in python". Among other pages this one showed up: heapq.merge() function to list of sorted files


text:
Q: Method that returns a Block Is there any way we can have a method that returns a Block? I have two activity objects to whom I have to send the same completion block. In the completion block I am using the reference to the MyTester object also. I wanted to have the block code at a single place only so that if there is any change in it, it could be changed at one place itself.
__block MyTester *aBlockSelf = self;
self.myActivity1.completionBlock = ^(NSDictionary *iData) {
                if (([[iData valueForKey:@"value"] length] > 0)) {
                    [aBlockSelf handleThis:iData];
                } else {
                    // Some Logic
                }

                // Some Logic
            };

self.myActivity2.completionBlock = ^(NSDictionary *iData) {
                if (([[iData valueForKey:@"value"] length] > 0)) {
                    [aBlockSelf handleThis:iData];
                } else {
                    // Some Logic
                }

                // Some Logic
            };


text:
Q: JSON Array parsing in ROR I am getting JSON in following format from my Android application
{"list":[{"itemno":"w01","name":"t01","amount":"120","status":"done"},{"itemno":"w02","name":"t02","amount":"120","status":"done"},{"itemno":"w03","name":"t03,"amount":"120","status":"done""}]}

I need to parse this to insert into mysql table "list". I modified "create" code in my controller as below
def create
lists = params[:list].collect{|key,list_attributes| List.new(list_attributes) }
    all_list_valid = true
    lists.each_with_index do |list,index|
     unless list.valid?
      all_list_valid = false
      invalid_list = lists[index]
     end
    end

    if all_list_valid
     @lists = []
     lists.each do |list|
       list.save
       @lists << list
     end
      format.html { redirect_to @list, notice: 'List was successfully created.' }
      format.json { render json: @list, status: :created, location: @list }
    else
      format.html { render action: "new" }
      format.json { render json: @list.errors, status: :unprocessable_entity }
    end
  end

But its unable to parse the JSON, so not calling the create method. I am very new to ROR and tried above code too from web. Not sure if the entire piece above is incorrect or I am missing something. Please advise. Thanks.

A: Also, you can refactor your code a little bit:
# This part of code
@lists = []
lists.each do |list|
  list.save
  @lists << list
end
# Can be shortened:
lists.map(&:save)
@lists = lists

The whole action can be refactored like this:
def create
  lists = params[:list].each{ |list_attributes| List.new(list_attributes) }
  valid, not_valid = lists.partition{ |list| list.valid? }

  if not_valid.blank?
    lists.map(&:save)
    @lists = lists
    format.html { redirect_to @list, notice: 'List was successfully created.' }
    format.json { render json: @list, status: :created, location: @list }
  else
    format.html { render action: "new" }
    format.json { render json: @list.errors, status: :unprocessable_entity }
  end
end


text:
Q: Working with Data.Sequence in Haskell I wrote a program that turned out to be far too slow using lists so I'm trying to switch over to sequences. However, I can't seem to figure out the correct syntax after looking at the documentation.
So far I'm trying to learn with this simple code:
import Control.Monad
import qualified Data.Sequence as S

main :: IO ()
main = do
       let testSeq = S.empty
       testSeq S.|> 5
       testSeq S.|> 20
       testSeq S.|> 3
       let newSeq = S.update 2 3 testSeq
       let x = lookup 2 testSeq
       print x

I've played around with the syntax for a while with no luck but it still has a ton of errors:
test.hs:9:8:
    Couldn't match expected type 'IO a0'
                with actual type 'S.Seq Integer'
    In a stmt of a 'do' block: testSeq S.|> 5
    In the expression:
      do { let testSeq = S.empty;
           testSeq S.|> 5;
           testSeq S.|> 20;
           testSeq S.|> 3;
           .... }
    In an equation for 'main':
        main
          = do { let testSeq = ...;
                 testSeq S.|> 5;
                 testSeq S.|> 20;
                 .... }

test.hs:10:8:
    Couldn't match expected type 'IO a1'
                with actual type 'S.Seq Integer'
    In a stmt of a 'do' block: testSeq S.|> 20
    In the expression:
      do { let testSeq = S.empty;
           testSeq S.|> 5;
           testSeq S.|> 20;
           testSeq S.|> 3;
           .... }
    In an equation for 'main':
        main
          = do { let testSeq = ...;
                 testSeq S.|> 5;
                 testSeq S.|> 20;
                 .... }

test.hs:11:8:
    Couldn't match expected type 'IO a2'
                with actual type 'S.Seq Integer'
    In a stmt of a 'do' block: testSeq S.|> 3
    In the expression:
      do { let testSeq = S.empty;
           testSeq S.|> 5;
           testSeq S.|> 20;
           testSeq S.|> 3;
           .... }
    In an equation for 'main':
        main
          = do { let testSeq = ...;
                 testSeq S.|> 5;
                 testSeq S.|> 20;
                 .... }

test.hs:13:25:
    Couldn't match expected type '[(Integer, b)]'
                with actual type 'S.Seq a3'
    Relevant bindings include x :: Maybe b (bound at test.hs:13:12)
    In the second argument of 'lookup', namely 'testSeq'
    In the expression: lookup 2 testSeq

I'm new to Haskell so any help would be greatly appreciated!

A: Like almost everything in Haskell, Seq is a purely functional data structure. It's not like an imperative stack where you push stuff to, mutating the original structure. Rather, like ordinary lists, you just generate new container-values which have the extra elements, but this does not affect the old shorter seqs in any way. So, the program you've asked about should just be
testSeq :: S.Seq Int
testSeq = S.update 2 3 $ S.empty S.|> 5 S.|> 20 S.|> 30

main :: IO ()
main = print $ S.lookup 2 testSeq

(It has to be S.lookup, or equivalently S.!?. By itself, lookup is a function that works on plain lists!)
Note that this doesn't really give you any advantage over
testSeq = S.update 2 3 $ S.fromList [5,20,30]

In fact, lists are usually faster than Seq, they just don't allow efficient random access.


text:
Q: MySQL SUM by field an then GROUP BY user? I have this table:

What's the correct query to get this result:
ID | Type | Total
1  |   A  | 300
1  |   B  | 100
2  |   A  | 30
2  |   B  | 40

Which means sum by type first and then group by user id?

A: Your aggregate functions, such as SUM, are performed on your groups; so there is no "SUM by type first then group by user_id", you are wanting to group by user_id and type.
Like so: GROUP BY user_id, type
If you want to guarantee that ordering in the future also have an ORDER BY user_id, type clause as well. Currently, GROUP BY also orders, but I believe that feature has been marked as deprecated recently.


text:
Q: Java base64 encoding output from Apache Common the "wrong" result I am trying to use the Base64 encoding functionality from Apache Common. But I seem to get the "wrong" result. The doc is here.
My code is like this:
import org.apache.commons.codec.binary.Base64;
String data = "hi,all,how can this happen?";

byte[] databytes = Base64.encodeBase64(data.getBytes());
data = databytes.toString();

System.out.println(data);
//the result is:
//[B@121cc40

However I encode the same string using Python, the code is:
import base64
print base64.b64encode("hi,all,how can this happen?")
#The result is aGksYWxsLGhvdyBjYW4gdGhpcyBoYXBwZW4/

How can there be such difference?

A: That's not how you print a byte (or any other type of) array in Java, if you want to view its contents.
This is:
System.out.println(Arrays.toString(data));

A:  import org.apache.commons.codec.binary.Base64;

    public class Codec {
      public static void main(String[] args) {
        try {
          String data = "hi,all,how can this happen?";
          String encodedText;

          // Base64
          encodedText = new String(Base64.encodeBase64(data.getBytes()));
          System.out.println("Encoded: " + encodedText);
          System.out.println("Decoded:"
              + new String(Base64.decodeBase64(encodedText.getBytes())));

        }
        catch (Exception e) {
          e.printStackTrace();
        }
      }
    }

Now it will encode your String data

A: You are printing the address.
If you want to print the String data, you can use,
String password = new String(databytes);
System.out.println("Encoded String "+ password)


text:
Q: Letters appear out of the comment box in php site after comment is added. How to limit the shown letters per line? I have made a site here : http://aasiskos.webpages.auth.gr/1905_YPA/Rating.php . You can enter the system in the loginbox by putting the following:
user: mpa@mpa.com
pass: 123a
And if you press the green box , you can add a comment. The thing is that if you write many letters then they appear to be out of the comment box. I have tried everything and I can't thing any useful tags in order to solve the problem. If you scroll down the page you can see that the letters of a comment I made, appear out of the box. How am i going to solve it  and in which page ? The current page (Rating.php) ,the add new comment page (new_comment.php) or in the css ?

A: Add word-wrap:break-word to your CSS.

A: You have a few mistakes in your code to begin with;

*

*ID's have to be unique according to JS standards

*Your div's arent closed </div>
But It's your party
And add to CSS:
word-wrap:break-word

Good luck!


text:
Q: How to make remaining time NOT show duration? This is my website. if you know how to make md dropdowns pls tell me, but here it is.

//this is a long but working workaround javascript being horrible at decimals. BTW stackoverflow, if i put this in a question, FU. you made me add 99 lines of code to a simple site.
math = (type, parameters)=>{
  var tops = []
  switch(type){
    case "+":
      parameters.forEach((parameter)=>{
        if(typeof parameter !== "number"){
          throw "this isnt algebra, not even value "+index;
        }
        if((parameter.toString().split(".").length) > 1){
          tops.push(parameter.toString().split(".")[1].length);
        }else{
          tops.push(0);
        }
      });
      tops.sort(function(a, b){return b-a});
      parameters = parameters.map((parameter)=>{
        return parameter*(10**tops[0]);
      });
      var result = 0;
      parameters.forEach((parameter)=>{
        result += parameter;
      });
      return result/(10**tops[0]);
      break;
    case "-":
      parameters.forEach((parameter, index)=>{
        if(typeof parameter !== "number"){
          throw "this isnt algebra, not even value "+index;
        }
        if((parameter.toString().split(".").length) > 1){
          tops.push(parameter.toString().split(".")[1].length);
        }else{
          tops.push(0);
        }
      });
      tops.sort(function(a, b){return b-a});
      parameters = parameters.map((parameter)=>{
        return parameter*(10**tops[0]);
      });
      var result = 0;
      parameters.forEach((parameter, index)=>{
        if(index === 0){
          result+= parameter;
        }else{
          result-=parameter;
        }
      });
      return result/(10**tops[0]);
      break;
    case "*":
      parameters.forEach((parameter)=>{
        if(typeof parameter !== "number"){
          throw "this isnt algebra, not even value "+index;
        }
        if((parameter.toString().split(".").length) > 1){
          tops.push(parameter.toString().split(".")[1].length);
        }else{
          tops.push(0);
        }
      });
      tops.sort(function(a, b){return b-a});
      parameters = parameters.map((parameter)=>{
        return parameter*(10**tops[0]);
      });
      var result = 1;
      parameters.forEach((parameter)=>{
        result *= parameter;
      });
      return result/(10**tops[0]);
      break;
    case "/":
      parameters.forEach((parameter)=>{
        if(typeof parameter !== "number"){
          throw "this isnt algebra, not even value "+index;
        }
        if((parameter.toString().split(".").length) > 1){
          tops.push(parameter.toString().split(".")[1].length);
        }else{
          tops.push(0);
        }
      });
      tops.sort(function(a, b){return b-a});
      parameters = parameters.map((parameter)=>{
        return parameter*(10**tops[0]);
      });
      var result = 0;
      parameters.forEach((parameter, index)=>{
        if(index === 0){
          result+= parameter;
        }else{
          result/=parameter;
        }
      });
      return result/(10**tops[0]);
      break;
  }
}

pp = document.querySelector("#pp");
fi = document.createElement("input");
fi.type = "file";
bt = document.querySelector("#bt");
tt = document.querySelector("#tt");
cr = document.querySelector("#cr");
ts = document.querySelector("#ts");
tj = document.querySelector("#tj");
au = new Audio();
ly = document.querySelector("#ly");
sl = document.querySelector("#sl");
cr.addEventListener("click", ()=>{
  try{
    clearInterval(iv);
  }catch(USLISERROOR){}
  fl = null;
  au.pause();
  au = new Audio();
  pp.innerText = "▶";
  ts.value = null;
  tj.hidden = true;
  tt.value = null;
  sl.value = null;
  sl.disabled = true;
  sl.readonly = false;
  sl.placeholder = "nothing is playing";
  ly.disabled = true;
  ly.value = "edt";
});
cr.click();
pp.addEventListener("click", ()=>{
  if(fl !== null){
    if(au.paused){
      au.play();
      pp.innerText = "⏸";
      iv = setInterval(()=>{
        ts.value = au.currentTime;
        tj.value = au.currentTime;
        tt.value = math("-", [au.duration, au.currentTime]);
      }, 1);
    }else{
      au.pause();
      pp.innerText = "▶";
      clearInterval(iv);
    }
  }else{
    bt.innerText = "waiting for input..."
    fi.click();
    fi.addEventListener("input", ()=>{
      fl = fi.files[0];
      bt.innerText = "checking file type...";
      if(fl.type.startsWith("audio/")){
        bt.innerText = "reading file...";
        rd = new FileReader();
        rd.readAsBinaryString(fl);
        rd.addEventListener("loadend", ()=>{
          au.src = "data:"+fl.type+";base64,"+btoa(rd.result);
          bt.innerText = "reconstructing audio ..."
          ts.value = 0;
          tj.hidden = false;
          tj.value = 0;
          sl.disabled = false;
          ly.disabled = false;
          sl.placeholder = "input lyrics";
          au.addEventListener("canplaythrough", ()=>{
            bt.innerText = "";
            tj.max = au.duration;   //Math.trunc(au.duration)+1;
            tt.value = au.duration;
          })
        });
      }else{
        bt.innerText = "please input audio only.";
        fl = null;
      }
    });
  }
});
imput = ()=>{
  ts.value = tj.value;
  tt.value = math("-", [au.duration, JSON.parse(tj.value)]);
}
tj.addEventListener("mousedown", ()=>{
  paused = au.paused;
  au.pause();
  pp.innerText = "↔";
  try{
    clearInterval(iv);
  }catch(USLISERROOR){}
  tj.addEventListener("input", imput);
});
tj.addEventListener("mouseup", ()=>{
  tj.removeEventListener("input", imput);
  au.currentTime = JSON.parse(tj.value);
  if(!paused){
    au.play();
    iv = setInterval(()=>{
      ts.value = au.currentTime;
      tj.value = au.currentTime;
      tt.value = math("-", [au.duration, au.currentTime]);
    }, 1);
    pp.innerText = "⏸"
  }else{
    pp.innerText = "▶";
    ts.value = au.currentTime;
    tt.value = math("-", [au.duration, au.currentTime]);
  }
});
au.addEventListener("ended", ()=>{
  pp.innerText = "";
  clearInterval(iv);
});

ly.addEventListener("input", ()=>{
  switch(ly.value){
    case "edt":
      sl.disabled = false;
      sl.placeholder = "input lyrics";
      break;
    case "dmo":
      sl.style.color = "#000000"
      sl.disabled = true;
      sl.placeholder = "lyrics at pause";
  }
});
lyrics = [];
times = [];
sl.addEventListener("keyup", (event)=>{
  if (event.key === "Enter"){
    lyrics.push({
      ts: ts.value,
      lyrics: sl.value
    });
    times.push(ts.value);
    times.sort((a, b)=>{return a-b});
    sl.value = null;
  }
});
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>Pley Myoozik</title>

      Audio control

      <button id="pp" style="font-size: 200%; padding-top: 3px; padding-bottom: 7px; padding-left: 5px; padding-right: 5px;">▶</button>

      <input type="number" readonly placeholder="nothing is playing" id="ts" style="width: 97%;">
      <input type="range" id="tj" min="0" max="0" step="0.000001" hidden style="width: 97%;">
      <input type="number" readonly placeholder="nothing is playing" id="tt" style="width: 97%;">

      <button id="cr">clear file</button>

      <select id="ly" disabled>
        <option value="edt">LyricEdit'r</option>
        <option value="dmo">LyricDemo'r</option>
      </select>

      <input type="text" placeholder="nothing is playing" id="sl" disabled style="position: absolute; bottom: 3%; width: 100%; font-size: 200%;">

its purpose is to play music from a file.
to use it, press the play button and upload a file.
the problem I'm looking to solve is that #tj(range input)'s mouseup event is making #tt(bottom number input)show the duration of the audio, not the leftover time. The issue is gone after pressing the play button(you have to have this paused in order to remake the problem), but returns after adjusting tj again.(still, audio must be paused to see)
according to the debugger (not going to lie, i had no idea how it works, but i think i do?),
this happened in line 206, but it makes no sense....
how can i fix this, and why is this happening?
its been nearly two days, havent made one edit on my public site.... im bumping. sorry. dont upvote unless you plan to answer

A: Setting currentTime on the audio file causes the system to start buffering data from that location.
When it has buffered enough to play (which happens pretty dang fast), it triggers the canplaythrough event.
You have an event handler on that event, that always sets tt to the duration. You need to subtract the currentTime in that handler and not assume it only happens when currentTime is zero.
au.addEventListener("canplaythrough", ()=>{
            bt.innerText = "";
            tj.max = au.duration;
            tt.value = math("-", [au.duration, au.currentTime]);
          })


text:
Q: Why do this code only delete the first rows of the datagridview? private void deleteToolStripMenuItem_Click(object sender, EventArgs e)
{
    int Index = 0;
    if (MessageBox.Show("Are you sure?", "Confirm", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
    {
        string delete = dataGridView1.Rows[Index].Cells[1].Value.ToString();
        SqlCeCommand cmd = new SqlCeCommand("delete from Contact_List where Name='" + delete + "'", con);
        con.Open();
        int result = cmd.ExecuteNonQuery();
        if (result == 1)
        {
            MessageBox.Show("Record Deleted Successfully");
            filldata();
        }
        else
        {
            MessageBox.Show("Record not Deleted....Please try again.");
        }
    }
}
    con.Close();

why do this code only delete the first rows when i selected the second rows?
Please help!!

A: You have assigned Index = 0 in the first line.  So, every time you call that method, it always deletes the first row, which is Index 0.
If you want to remove the selected row, you have to use, SelectedIndex.  Consider below sample code:
string delete = dataGridView1.Rows[dataGridView1.SelectedIndex].Cells[1].Value.ToString();

A: The variable Index was initialized with 0 and the value will not get updated during the execution, so each time the first row get Deleted. so what you want to do is, update the variable Index with current row index like the following:
Index= datagridview.CurrentCell.RowIndex;
string itemToDelete = dataGridView1.Rows[Index].Cells[1].Value.ToString();
// this will be the `Cells[1]` value at the selected index


text:
Q: Run a service in the background forever..? Android I am doing a Battery Consuming research on the Android phone. I want to run a Battery Check every 10 min till the battery totally dies. I have been having problems to make it work.
At my first try, I use a timer in a service class, and schedule the battery check every 10 mins. But soon I found that the service got paused when the screen goes off.
Then I try to use AlarmService, I use a alarm call to wake my service every 10 mins and to check the battery level and save the data to a file on the sdcard. It works with the screen off. However, I only got data of 9 hours...it seems that the AlarmService stop at some point after several hours. I don't know why it is like this, has the system killed it for memory issues?
So my question is, has anyone written some service to run (like forever) in the background before? How do you do it and I'd appreciate very much for a sample code?
I am currently reading some posts saying that there's a partial wake lock I can use to keep the service alive.. is this the correct way to do it?
Thanks a lot and I hope I can get some useful answers here.

A: http://github.com/commonsguy/cw-advandroid/tree/master/SystemServices/Alarm/

A:
At my first try, I use a timer in a
  service class, and schedule the
  battery check every 10 mins. But soon
  I found that the service got paused
  when the screen goes off.

You probably did not hold a WakeLock, so the device fell asleep.

it seems that the AlarmService stop at
  some point after several hours

I rather doubt it.

So my question is, has anyone written
  some service to run (like forever) in
  the background before?

It is not possible to create a service that will run forever. It should be possible to create a scheduled task via AlarmManager that will be invoked "forever".

I am currently reading some posts
  saying that there's a partial wake
  lock I can use to keep the service
  alive.. is this the correct way to do
  it?

I'm not sure what "it" is. But, if you want to keep the device awake -- whether for your first approach or just while you are doing work triggered by an AlarmManager -- you need to hold a WakeLock.
Here is a project that does almost exactly what you describe for the AlarmManager, minus checking the battery level, but using a WakefulIntentService to ensure the device stays awake. If you cannot get this code to run until the battery shuts down, join the cw-android Google Group and report your findings, and I'll take a look at it.


text:
Q: Load SQL Server Database into memory with Python I have to do a lot of querys to a big SQL server database and the process is very slow.
I can do something like
import pyodbc

#database connection
tsql = "SELECT * FROM table1"
with cursor.execute(tsql):
    rows = cursor.fetchall()

But how can I do stuff like SELECT specific rows after it's loaded in memory? Because I have a lot of queries that depends of other queries and I think it's not very efficient iterate of thousands of rows to filter specific data so I think there might be a better approach to do that.
Thanks in advance.

A: If you truly have a "big SQL server database" then you don't want to load entire tables into memory. Instead, for each task just load the columns of interest from the relevant rows using standard SQL methods, e.g.,
crsr.execute("SELECT firstname, lastname FROM table1 WHERE country = 'Canada'")
rows = crsr.fetchall()

If you need information from several related tables then search the web for basic SQL tutorials that describe how to use the JOIN keyword to accomplish that.


text:
Q: How is my app starting on boot? (Ubuntu) I am not very Linux literate. I have a node app that I installed a couple of years ago on a server. I can't remember how I set it up to start on boot. If I execute
ls /etc/init.d

I don't see anything related to my application. There must be a script somewhere that has the commands
cd /opt/siteServer
node app.js


text:
Q: Sort object of months in chronological order? I have an object that contains months with some number and I want to sort that in chronological order of months. I have the following data:
currentMeetingTimes= {
  May: 2464,
  September: 2265,
  June: 1656,
  April: 1595,
  August: 2111,
  July: 2005,
  October: 649
}

I want this like:
currentMeetingTimes= {
  April: 1595,
  May: 2464,
  June: 1656,
  July: 2005,
  August: 2111,
  September: 2265,
  October: 649
}

I've tried by using Object#keys but not getting the correct result.
const monthNames = {
        "January": 1,
        "February": 2,
        "March": 3,
        "April": 4,
        "May": 5,
        "June": 6,
        "July": 7,
        "August": 8,
        "September": 9,
        "October": 10,
        "November": 11,
        "December": 12
      };
currentMeetingTimes = Object.keys(currentMeetingTimes).sort(function(a, b) {
  // sort based on the value in the monthNames object
  return monthNames[a[0]] - monthNames[b[0]];
});
console.log('currentMeetingTimes:', currentMeetingTimes)

A: You was on a correct way. You need to convert month to some numeric value and sort its.
Object.keys(currentMeetingTimes).sort( (a,b) => new Date(`${a} 1, 2020 12:00:00`).getMonth() - new Date(`${b} 1, 2020 12:00:00`).getMonth())

By the way:
Object.keys(currentMeetingTimes).sort( (a,b) => console.log(a[0])) // you need to use a
S
J
A
A
J
O

A:

const currentMeetingTimes = {
    May: 2464,
    September: 2265,
    June: 1656,
    April: 1595,
    August: 2111,
    July: 2005,
    October: 649,
}

function orderedByMonth(objNotSorted) {

    const objSortedMonths = {}

    const monthNames = [
        "January",
        "February",
        "March",
        "April",
        "May",
        "June",
        "July",
        "August",
        "September",
        "October",
        "November",
        "December",
    ];

    for (const month of monthNames) {
        if (objNotSorted.hasOwnProperty(month)) {
            objSortedMonths[month] = objNotSorted[month]
        }
    }

    return objSortedMonths

}

console.log(orderedByMonth(currentMeetingTimes))

A: Here is how you order an object in a certain order (map object order), using key as relation and value as the order in the list, things to remember and take into consideration most javascript iteration functions already order your list primarily by number secondarily by alphabetic order(read more), best approach is to use map which takes insertion order into consideration, more in depth explanation can be read here.

const monthNames = {
    "January": 1,
    "February": 2,
    "March": 3,
    "April": 4,
    "May": 5,
    "June": 6,
    "July": 7,
    "August": 8,
    "September": 9,
    "October": 10,
    "November": 11,
    "December": 12
};
const currentMeetingTimes = {
    May: 2464,
    September: 2265,
    June: 1656,
    April: 1595,
    August: 2111,
    July: 2005,
    October: 649
}
let ordered = {};
Object.keys(currentMeetingTimes).sort((a, b) => {
    return monthNames[a] - monthNames[b]
}).forEach(function(key) {
    ordered[key] = currentMeetingTimes[key];
});
//remeber to "loop" a object in correct order
//map is the most certain way other typ of loopes
//may brake the order
Object.entries(ordered).map((row) =>
    console.log({
       row
    })
)


text:
Q: working with system tray i create a setup file for my window based project. it is working fine. my requirement is when i minimize the window it should come in system tray not in task bar. help me thank u

A: This depends on which language you have written your program in. You would need to create a class or use a built in function to minimize it to the system tray. More information would be helpful.

A: *

*To get started, open an existing C# Windows form (or create a new one).

*Open the Visual Studio Toolbox.

*Drag a NotifyIcon control onto the form. The control will named notifyIcon1 by default and placed below the form because it has no visual representation on the form itself.

*Set the NotifyIcon control's Text property to the name you want to appear when the user pauses the mouse over the application's icon. For example, this value could be "KillerApp 1.0".

*Set the control's Icon property to the icon that you want to appear in the System Tray.
  Tip: If you have a BMP file that you want to convert to an icon file, I highly recommend the QTam Bitmap to Icon 3.5 application.

*Add an event handler for the form's Resize event that will hide the application when it's minimized. That way, it won't appear on the task bar.
private void Form1_Resize(object sender, System.EventArgs e)
  {
     if (FormWindowState.Minimized == WindowState)
        Hide();
  }

*Add an event handler for the NotifyIcon.DoubleClick event and code it as follows so that the application will be restored when the icon is double-clicked.
private void notifyIcon1_DoubleClick(object sender,
                                       System.EventArgs e)
  {
      Show();
      WindowState = FormWindowState.Normal;
  }


text:
Q: Sort an array in ascending order - React js I'm trying to sort my array. I want to have the lowest "time" element in first, and the biggest "time" element in last.
[
  {
    "Payload": {
      "humidity": 32,
      "time": 1610877284,
    },
    "time": "1610877284",
    "PositionInRow ": "{raw}"
  },
  {
    "Payload": {
      "humidity": 33,
      "time": 1610876854,
    },
    "time": "1610876854",
    "PositionInRow ": "{raw}"
  },
  {
    "Payload": {
      "humidity": 31,
      "time": 1610877588,
    },
    "time": "1610877588",
    "PositionInRow ": "{raw}"
  },
  {
    "Payload": {
      "humidity": 36,
      "time": 1610877462,
    },
    "time": "1610877462",
    "PositionInRow ": "{raw}"
  }
]

I wanted to use "array.sort((a, b) => a - b)" but it's not possible with this type of array. Anyone have any idea of a function that can sort my array in ascending order ("time") ?

A: You can simply modify the function like this:
array.sort((a, b) => a.time - b.time)


text:
Q: Count sum of the given html object's text using Angular 1.x.x Tring to count sum of all the tds which has ng-model. But It works as a string as shown in the code below.

    Products
    Price

    Product 1
    120

    Product 2
    120

    Product 3
    120

{{ one + two + three }}

A: You should not use div for an input , you should use input element. Also if you are binding only in HTML multiply the value by 1 instead of just adding as expression which will result as a string.
DEMO

  <input type="text" ng-model="one">
  <input type="text" ng-model="two">
  <input type="text" ng-model="three">
  <input type="text" ng-model="four">

{{one  * 1 + two  * 1 + three  * 1 + four  * 1}}

A: You can use ng-bind
and ng-init

Demo Fiddle 1
or  initialization in controller:
$scope.one = 120;
$scope.two = 120;
$scope.three = 120;

HTML

    Products
    Price

    Product 1

    Product 2

    Product 3

Result: 360

Demo Fiddle 2


text:
Q: generating table rows for objects with children Im trying to display a bunch of objects in table format. If the object has a child, i'd like it displayed in the next row before continuing down the array to the next object.
In my example below I successfully render a table showing all top level or parent objects:
const renderCategories = (categories) => {
            let myCategories = [];
            for(let category of categories){
                myCategories.push(

                        <input type="checkbox"></input>
                        {category.name}

                );
            }

            return myCategories;
    }

    return(

              <input type="checkbox"></input>
              Name

            {renderCategories(category.categories)}

    )
};

In my original version i wasn't using a table but instead using lists and so achieved what i was looking for by doing something like:
const renderCategories = (categories) => {
                let myCategories = [];
                for(let category of categories){
                    myCategories.push(

                          {category.name}
                          {category.children.length > 0 ?
                            {
renderCategories(category.children)}
) : null}

                    );
                }

                return myCategories;
        }

This solution obviously wont work for my new use case as I cant render table rows inside table rows.  This is driving me crazy as no alternative seems to work.  I could achieve my desired design using divs instead of a table. However I want to use a table, or at least know how to do it by using a table.
Anyone able to point me in the right direction? thanks

A: Use Array.flatMap() and array spread to return a flattened array of
 elements.
Note: I've also added the indentation using level and empty  elements. You remove the Array.from() line, and the level if not needed.

const renderCategories = (categories, level = 0) =>
  categories.flatMap(({ name, children }) => {
    const cat = (

        <input type="checkbox"></input>
        {Array.from({ length: level }, (_, i) => 	)}
        {name}

    );

    return children.length ?
      [cat, ...renderCategories(children, level + 1)]
      :
      cat;
  });

const Demo = ({ categories }) => (

          <input type="checkbox"></input>
          Name

        {renderCategories(categories)}

);

const categories = [{ name: 'A', children: [{ name: 'A1', children: [] }, { name: 'A2', children: [] }] }, { name: 'B', children: [{ name: 'B1', children: [{ name: 'B1-1', children: [] }, { name: 'B1-2', children: [] }] }, { name: 'B2', children: [] }] }]

ReactDOM.render(
  <Demo categories={categories} />,
  root
)
th, td {
  border: 1px solid black;
}


text:
Q: VueJS button click executes only second click I have "Sign in with facebook" button in my webpage. everything working as expected but the problem is the action is triggered in second time of click.
i cans ee error in console in first click.
HTML Code :

                    <button type="button"  v-on:click="logInWithFacebook" class="btn-facebook">Facebook</button>

JS code :


text:
Q: exec-maven-plugin want to pass maven.dependency.classpath as a variable in my EXEC Goal I want to define property or want to use maven.plugin.classpath and maven.dependency.classpath in my build.xml.

How can i do it ?

Sample code is as below...

<property> </property> is not working and not able to read the values from my build.xml so please explain me how can i do it ?

            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>exec-maven-plugin</artifactId>
                <version>1.2</version>
                <executions>
                    <execution>
                        <id>install</id>
                        <phase>install</phase>
                        <goals>
                            <goal>exec</goal>
                        </goals>
                    </execution>
                </executions>
                <configuration>
                    <property name="plugin_classpath" refid="maven.plugin.classpath" />
                    <property name="maven_dependency_classpath" refid="maven.dependency.classpath" />
                    <executable>antscript.bat</executable> <!-- ant -f build.xml build -->
                </configuration>
            </plugin>

Hi Sean Patrick Floyd,

Yes i tried using maven-antrun-plugin but i am not able to setup JDK 1.4.2 version in it. I am trying to specify all possible way to apply JDK version 1.4.2 but it's still taking tools.jar or JDK version, Which maven.bat file is using (jdk 1.5)

I was using following code in MAVEN-ANTRUN-PLUGIN as below code.

<plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-antrun-plugin</artifactId>
                <version>1.6</version>

                <executions>
                    <execution>
                        <id>install</id>
                        <phase>install</phase>
                        <goals>
                            <goal>run</goal>
                        </goals>
                        <configuration>
                            <source>${java-version}</source>
                            <target>${java-version}</target>
                            <compilerVersion>${java-version}</compilerVersion>
                            <executable>${java.1.4.2.home}/bin/javac</executable>
                             <target>

                                <property name="plugin_classpath" refid="maven.plugin.classpath" />
                                <property name="maven_dependency_classpath" refid="maven.dependency.classpath" />
                                <ant antfile="ant_build.xml" />
                             </target>
                      </configuration>
                    </execution>
                </executions>
                <dependencies>
                    <dependency>
                        <groupId>sun.jdk</groupId>
                        <artifactId>tools</artifactId>
                        <version>1.4.2</version>
                        <scope>system</scope>
                        <systemPath>${java.1.4.2.home}/lib/tools.jar</systemPath>
                    </dependency>
                    <dependency>
                        <groupId>com.sun</groupId>
                        <artifactId>rt</artifactId>
                        <version>${java-version}</version>
                        <scope>system</scope>
                        <systemPath>${java.1.4.2.home}/jre/lib/rt.jar</systemPath>
                    </dependency>
                </dependencies>
            </plugin>

That's why i choose exec GOAL where my SYSTEM JAVA_HOME is 1.4.2 and it's able to execute it if i have all dependencies which i needed.

Please help me out.

Thanks.

A: maven.plugin.classpath etc. are variables defined in the maven-antrun-plugin only. The exec plugin doesn't know about these values. Also, it wouldn't be possible to do it like that in the first place, as you are calling an external .bat file and hence starting a new process.
If I were you I'd use the antrun plugin. See the usage page for details.

Update: ok, now I see your problem. No, you can't use a different JDK, since antrun works within the same vm. So either you need to switch the JDK maven uses, or you do in fact need to use the exec-maven-plugin. In the latter case, you will have to use
dependency:build-classpath -DoutputFile=someFile.txt
and on the ant side, read the contents of someFile.txt as a property and create a classpath from it. Or you can use the %classpath variable placeholder in your command line args.

A: Yes correct answer which i found is to Use MAVEN version which supports JDK 1.4.2. So i have to use apache-maven-2.0.11 which supports JDK 1.4.2
Thanks all for your answers.


text:
Q: Why does the Spark DataFrame conversion to RDD require a full re-mapping? From the Spark source code:
/**
   * Represents the content of the Dataset as an `RDD` of `T`.
   *
   * @group basic
   * @since 1.6.0
   */
  lazy val rdd: RDD[T] = {
    val objectType = exprEnc.deserializer.dataType
    rddQueryExecution.toRdd.mapPartitions { rows =>
      rows.map(_.get(0, objectType).asInstanceOf[T])
    }
  }

https://github.com/apache/spark/blob/master/sql/core/src/main/scala/org/apache/spark/sql/Dataset.scala#L2972
The mapPartitions can take as long as the time to compute the RDD in the first place..   So this makes operations such as
df.rdd.getNumPartitions

very expensive.  Given that a  DataFrame is DataSet[Row] and a DataSet is composed of RDD's why is a re-mapping required? Any insights appreciated.

A: TL;DR That's because the internal RDD is not RDD[Row].

Given that a DataFrame is DataSet[Row] and a DataSet is composed of RDD's

That's a huge oversimplification. First of all DataSet[T]  doesn't mean that you interact with container of T. It means that if you use collection-like API (often referred as strongly typed), internal representation will be decoded into T.
The internal representation is a binary format used internally by Tungsten.This representation is internal and subject of changes and far too low level to be used in practice.
An intermediate representation, which exposes this data is the InternalRow - rddQueryExecution.toRDD is in fact RDD[InternalRow]. This representation (there are different implementation) still exposes the internal types, is consider "weakly" private, as all objects in o.a.s.sql.catalyst (the access is not explicitly restricted, but API is not documented), and rather tricky to interact with.
This where decoding comes into play and why you need full "re-mapping" - to convert internal, often unsafe, objects into external types intended for public usage.
Finally, to reiterate my previous statement - the code in question won't be executed when getNumPartitions is called.


text:
Q: Flex URLRequest and .NET authorization can I make role based authorization when sending requests to an ASP.NET MVC backend system. I am calling action methods and expecting JSON results, however, some action methods are decorated with the [Authorize] attribute, others require some role privileges to be present. I certainly hope that passing authorization data with every request is possible

A: Unless the methods are designed to accept login information as parameters, you would typically have to login to the system by posting a form to the "login" action -- typically /account/login -- and from then on send the authorization cookie that you receive back with each new request to validate who you are.  There are a lot of ways to configure the backend, though what I've described is the typical way.  Fortunately, URLRequest has a way to specify that you want the HTTP stack to manage cookies for you, so this should be reasonably seamless from your end.  NOTE: I've never used FLEX, I'm just going by the documentation.


text:
Q: Looking for a paper by Vinberg I have been reading about the Schinzel-Zassenhauss conjecture, and have been looking for the following reference:
Vinberg E.: On some number-theoretic conjectures of V. Arnold, Japanese J. Math., vol 2 (2007)
Unfortunately, despite extensive search, I haven't found the above paper I would really appreciate if someone could provide the paper or a link to the same. I would also like to ask if there is a website where I could find the articles of the Japanese Journal of Mathematics.


text:
Q: Is there any method to join/concatenate all DataFrame created? i have a range of datetime generate as below and i want to store the datetime as a list in a cell.
example as below:
df = pd.DataFrame({'date1': ['2020-11-17 13:35:18', '2020-11-17 00:00:45','2020-11-17 00:18:18','2020-11-17 22:45:19'],
                   'date2': ['2020-11-17 13:36:50', '2020-11-17 00:01:53', '2020-11-17 00:19:27','2020-11-17 22:46:40']})

print(df)

OUTPUT:
                 date1                date2
0  2020-11-17 13:35:18  2020-11-17 13:36:50
1  2020-11-17 00:00:45  2020-11-17 00:01:53
2  2020-11-17 00:18:18  2020-11-17 00:19:27
3  2020-11-17 22:45:19  2020-11-17 22:46:40

i created the list of datetime range and i would like to add as the third column, but i stuck concatenating the list into a new dataframe
result i get:
for i in range(len(df)):
    listrange =pd.date_range(start=df['date1'][i], end=df['date2'][i], freq='S')
    a = listrange.append([listrange])
    dd=pd.DataFrame([[a]])
    print(dd)
    aa = pd.concat([df,dd[0]], axis=1, sort=False)
    print(aa)

OUTPUT:
                                                   0
0  DatetimeIndex(['2020-11-17 13:35:18', '2020-11...
                                                   0
0  DatetimeIndex(['2020-11-17 00:00:45', '2020-11...
                                                   0
0  DatetimeIndex(['2020-11-17 00:18:18', '2020-11...
                                                   0
0  DatetimeIndex(['2020-11-17 22:45:19', '2020-11...

                 date1  ...                                                  0
0  2020-11-17 13:35:18  ...  DatetimeIndex(['2020-11-17 13:35:18', '2020-11...
1  2020-11-17 00:00:45  ...                                                NaN
2  2020-11-17 00:18:18  ...                                                NaN
3  2020-11-17 22:45:19  ...                                                NaN

[4 rows x 3 columns]
                 date1  ...                                                  0
0  2020-11-17 13:35:18  ...  DatetimeIndex(['2020-11-17 00:00:45', '2020-11...
1  2020-11-17 00:00:45  ...                                                NaN
2  2020-11-17 00:18:18  ...                                                NaN
3  2020-11-17 22:45:19  ...                                                NaN

[4 rows x 3 columns]
                 date1  ...                                                  0
0  2020-11-17 13:35:18  ...  DatetimeIndex(['2020-11-17 00:18:18', '2020-11...
1  2020-11-17 00:00:45  ...                                                NaN
2  2020-11-17 00:18:18  ...                                                NaN
3  2020-11-17 22:45:19  ...                                                NaN

[4 rows x 3 columns]
                 date1  ...                                                  0
0  2020-11-17 13:35:18  ...  DatetimeIndex(['2020-11-17 22:45:19', '2020-11...
1  2020-11-17 00:00:45  ...                                                NaN
2  2020-11-17 00:18:18  ...                                                NaN
3  2020-11-17 22:45:19  ...                                                NaN

[4 rows x 3 columns]

EXPECTED RESULT:
                                             0
0  DatetimeIndex(['2020-11-17 13:35:18', '2020-11...
1  DatetimeIndex(['2020-11-17 00:00:45', '2020-11...
2  DatetimeIndex(['2020-11-17 00:18:18', '2020-11...
3  DatetimeIndex(['2020-11-17 22:45:19', '2020-11...

then END of RESULT:
                 date1                date2                 **range**
0  2020-11-17 13:35:18  2020-11-17 13:36:50      ['2020-11-17 13:35:18', '2020-11...,'2020-11-17 13:36:50']
1  2020-11-17 00:00:45  2020-11-17 00:01:53      ['2020-11-17 00:00:45', '2020-11...,'2020-11-17 00:01:53']
2  2020-11-17 00:18:18  2020-11-17 00:19:27      ['2020-11-17 00:18:18', '2020-11...,'2020-11-17 00:19:27']
3  2020-11-17 22:45:19  2020-11-17 22:46:40      ['2020-11-17 22:45:19', '2020-11...,'2020-11-17 22:46:40']

A: Concat after making all data range.
listrange = []
for i in range(len(df)):
    daterange = pd.date_range(start=df['date1'][i], end=df['date2'][i], freq='S')
    listrange.append([daterange])

rangecol = pd.DataFrame(listrange)
print(rangecol)
res = pd.concat([df, rangecol], axis=1, sort=False)
print(res)


text:
Q: Excel VBA - Password prompt after Form Show and Import Data I have this macro that is password protected and shows a form. Recently I added code to import data from excel and every time I close it asks me for a password - I can cancel through it but I'd like to make it go away, I see no plausible reason why it would come.
I've separated out the few lines that causes this problem
Sub a()

UserForm1.Show
strConnString = "Provider=Microsoft.Jet.OLEDB.4.0" & _
    ";Data Source=" & "C:\Book1.xls" & _
    ";Extended Properties='Excel 8.0; IMEX=1'" & _
    ";Persist Security Info=False"
Set objRSGlobal = CreateObject("ADODB.Recordset")
objRSGlobal.Open "select * from [Sheet1$]", strConnString
objRSGlobal.Close
Set objRSGlobal = Nothing
End Sub

This goes into Module1. I have a blank form called UserForm1. I lock the code (for viewing as well) using a password and save everything in Book1.xls.
Now I open the file, do an Alt+F8 to run the macro, close the form and then close the file the password prompt comes up. I can't understand why it comes up and how to make it go away.
Thanks in advance!!
Note - for the record, this also happens if I just show the form and do an Import Data via the UI (Data > Import External Data > Import Data)

*

*Update - it looks like its happening only when I import from the same file I have open.

A: This looks like the problem described in Microsoft Knowledge Base Article KB280454
http://support.microsoft.com/kb/280454
I encountered this problem working with .NET and COM interop.  The article advises ensuring COM references are released.  I was unable to do this successfully in my case.  I tried delegating commands from Excel to a non-VBA-password protected workbook which reduced the occurrence and finally set up a process to kill my app (with Xtreme Prejudice, using a second process).  Neither of these seem appropriate in the case of this question but a similar kludge may be required.

A: http://www.officekb.com/Uwe/Forum.aspx/excel-prog/40862/VBA-project-does-not-close-when-workbook-is-closed
looks like a google desktop issue.

A: I had the same issue, and it is related to the Excel/Jet queries from open Excel Workbooks (including the current workbook). The following Microsoft kb article describes the problem.
The issue seems to be fixed in Excel 2010, although that did not help me (as my clients are still using Excel 2007). One way to do it is to save the data into another workbook, query it there and then copy the result back in to the original workbook, but that is a bit cumbersome.


text:
Q: partitioning Windows 8 drive I have 3 partitions - Sys reserve, C, and D. When I try to create another partition it creates a logical drive not a primary drive and doesn't ask which one I want.
I need a primary with Fat32 format. How do I get it. I haven't had this issue with W7.
thx

A: Try using diskpart from the command prompt.
Here's some basic instruction, you may want to read up on using Diskpart before you start, as this may not be the exact procedure you want to use (depending on what you want in the end).

*

*Right-click the Command Prompt shortcut and click Run as administrator
(Start > All Programs > Accessories > Command Prompt).

*Type DISKPART at the Prompt and press Enter.

*Type LIST DISK at the Diskpart prompt and press Enter

*

*Note the disk number for your new Unallocated space (Disk 0=1st hard disk, Disk 1=2nd, etc.).

*Type SELECT DISK X (where x is the number you just noted)

*Type CREATE PARTITION PRIMARY

*

*All the Unallocated space will be used for the new Primary.

*Type EXIT to exit Diskpart.

*Type EXIT to exit Command Prompt.


text:
Q: query with a reference condition I have a query inside a trigger and one of the conditions is that a reference field (lookup) is not null.
My query is:
List<Contract> contratti=[Select Id,Opportunitl__c from Contract
        where Id IN: Trigger.new AND Opportunitl__c !=null ];

where Opportunitl__c is the reference field, but it's not working. The list "contratti" contains Contracts with an empty Opportunitl__c. What is wrong in this query?

A: Actually, the best way to do that is to not use a query at all. Just loop through the trigger.new and retrieve the Contracts you need.
List<Contract> contratti = new List<Contract>();
for(Contract contratto : Trigger.new){
    if(contratto.Opportunitl__c != null) contratti.add(contratto);
}

If, form some reason, you still need the query. You can't compare with null. Change it to
List<Contract> contratti=[Select Id,Opportunitl__c from Contract
    where Id IN: Trigger.new AND Opportunitl__c != ''];

A: Try this query it may help to you.
List<Contract> contratti = [Select Id,Opportunitl__c from Contract where Id IN :Trigger.newMap.keySet() AND Opportunitl__c != NULL];

Incase if failure this query you can try in this method
Set<Id> conIds = Trigger.newMap.keySet();
List<Contract> contratti = [Select Id,Opportunitl__c from Contract where Id IN :conIds AND Opportunitl__c != NULL];


text:
Q: How to show a row in excel if there is a X
i am busy learning excel but i need to show the passed students with a formula. everyone with a "X" at "exam passed" need to show up under "who passed?" with all the grades and names. all the students without a "X" behind their name don't need to show up under "Who Passed?"
I tried a if statement but i am not getting the results i want

A: FILTER Function: "filters" a range of data based on supplied criteria(X). The result is an array(B2:E7) of matching values(X) from the original range(G2:G7).
=FILTER(B2:E7,G2:G7="X")


text:
Q: show and hide column with Ifelse in summary General I am summary like below
enter image description here
now i am trying to make my column show and hide , i want total_var = FALSE the summary should hide second column and if total_var = TRUE then it should show Total(second column) the summary will always have total column in second row.
i have tried ifelse but its not working
any solution....??
tt <- mtcars %>%
  tab_cols(total(), am %nest% vs) %>%
  tab_stat_cpct() %>%
  tab_pivot()

tt <- as.data.frame(tt)
total_var = FALSE
total_col <- ifelse(total_var== TRUE,1,0)
ifelse(total_col==1,tab1[,-2],tab1)

A: this worked now, i have used
total_col <- ifelse(total_var== TRUE,1,0)
if(total_col==0){tab2 = tab2[,!grepl("^#Tot",names(tab2))]}

now it worked for me , and able to hide and show Total column


text:
Q: How is Verilog's macro_text split into tokens? From my reading of IEEE 1800-2017, it seems that lexing is context-dependent, notably due to numbers. Consider the following examples.
// A number followed by an identifier -- delayed invocation of task `f`
# 1f;

// A number followed by a null statement.
#'h 1f;

Whether f is part of the preceding numeric token depends on whether the numeric token is preceded by 'h.
However, when preprocessing, the context is not always clear. What should the following snippet print?
module m;
    initial begin
        `define Y(f) 1f
        $display('h `Y(c));
    end
endmodule

Should 1f inside the macro_text be treated as two tokens and f be substituted for c (with 'h1c getting printed), or should 1f be treated as a single token, making the macro parameter unused (and the $display argument 'h1f)?

A: Not really an answer to your question, but it seems that the tools don't agree either. If you try it on https://www.edaplayground.com, different tools give different results.
You might already know that it's possible to force the f to be replaced. The following works the same across tools:
module m;
    initial begin
      `define Y(f) 1``f``
      $display("%x", 'h `Y(c));
    end
endmodule

The extra backticks force the preprocessor to interpret f as the macro argument and to fuse it to 1. (I took  the liberty of also adding a format specifier for the display to make the printed text easier to read.)


text:
Q: Remove force when objects collide in corona I m getting one issue in my game. I am Colliding two objects one of bullet type and another is of dynamic type. When my bullet type object collide with dynamic type object then it add force to other object(don't know whether it is force or not) due which other objects are getting disturb.
I check below line in postcollision
print( "Collision force: " .. event.force)

but I'm getting a nil value.

A: It depends on how you set up your post collision function. Here is an example that works for me.
local function collisionFunction( self, event )
     print( "Collision force: " .. event.force)
end

object.postCollision = collisionFunction
object:addEventListener('postCollision', object)

This should print out the force of the collision between the 2 objects.


text:
Q: How to know when a newly pushed screen is fully transitioned on Flutter? Problem: Let's say there are only 2 screens. When a second screen is pushed on the first one, animation of transition jitters and is not smooth. The reason is that second screen has a very costly widgets. I am trying to wait till a transition animation finishes completely and then render costly widgets. Currently, I am just delaying using
await Future.delayed(const Duration(milliseconds: 200));

What I am trying to achieve
 class SecondScreenState extends State<SecondScreen> {
  @override
  void initState() {
    super.initState();

    initialize();
  }

  initialize() async {
    await waitTillTransitionFinishes;

    loadCostlyWidgets;
  }
}

I am navigating like below
Navigator.push(context, MaterialPageRoute(
    builder: (context) => SecondScreen()
  )
)

A: Have you tried
  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
    WidgetsBinding.instance.addPostFrameCallback(
      (_) {
        loadCostlyWidgets;
      },
    );
  }

A: You can use ModalRoute.of(context)?.animation to obtain the current page's  animation and listen for completion, as follows:
class SecondScreenState extends State<SecondScreen> {
  Animation<double>? get transitionIn => ModalRoute.of(context)?.animation;
  bool isWidgetVisible = false;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      transitionIn?.addStatusListener(_handleTransitionCompletion);
    });
  }

  void _handleTransitionCompletion(AnimationStatus status) {
    if (status == AnimationStatus.completed) {
      transitionIn?.removeStatusListener(_handleTransitionCompletion);
      setState(() {
        isWidgetVisible = true;
      });
    }
  }

A full example can be found here:
https://dartpad.dev/?id=57e57e674293dd72bca1340e9e8ebac6
Good luck!


text:
Q: How to get img src for image clicked on I am attempting to get the img src for the specific image being clicked on. I am using the this function in my attempt, so I am unsure what I am doing wrong.
Does anyone see the issue?
HTML:

//Project Container Zoom
 $('#projectGallery').on('click', '.projectCont', function (event) {
  event.stopPropagation();
  $('#zoomPop').fadeIn(350);
  $('body').css('overflow', 'hidden');
  var currentImg = $(this).attr('src');
  console.log(currentImg);
 });
#zoomPop {
 width: 100%;
 height: 100%;
 color: #FFF;
 position: fixed;
 z-index: 999999;
 margin: 0;
 padding: 0;
 top: 0;
 right: 0;
 bottom: 0;
 overflow-y: scroll;
 display: none;
}
#zoomPop {
 background: rgba(0,0,0,.7);
}
#zoomInner {
 position: relative;
 padding: 60px 0;
 margin: 0 auto;
 width: 90%;
}

A:

//Project Container Zoom
 $('#projectGallery').on('click', '.projectCont img', function (event) {
  event.stopPropagation();
  $('#zoomPop').fadeIn(350);
  $('body').css('overflow', 'hidden');
  var currentImg = $(this).attr('src');
  console.log(currentImg);
$('#zoomInner img').attr('src', currentImg);
 });
#zoomPop {
 width: 100%;
 height: 100%;
 color: #FFF;
 position: fixed;
 z-index: 999999;
 margin: 0;
 padding: 0;
 top: 0;
 right: 0;
 bottom: 0;
 overflow-y: scroll;
 display: none;
}
#zoomPop {
 background: rgba(0,0,0,.7);
}
#zoomInner {
 position: relative;
 padding: 60px 0;
 margin: 0 auto;
 width: 90%;
}

A: your this refer to DOM Node

Use a
console.log($(this).find('img').attr('src'));

or change selector for event handler to
$('#projectGallery').on('click', '.projectCont img', function (event) {


text: Q: Как сделать триггер на неправильное значение textbox, и чтобы кнопка стала неактивной? WPF Есть приложение с textbox (вводится цена от 0 до 100 тысяч), значение которого привязано к значению slider. Если значение текстбокса не содержится у слайдера (ошибка привязки) - текстбокс становится красным. Но как сделать так, чтобы, например,одна кнопка при таком раскладе стала неактивной? Советовать регулярные выражения не нужно