text:
Q: In Javascript, my onEvent isn't being called, while other onEvents are I'm currently creating a blackjack game. In my game, when the user clicks "Stay", the program is suppose to find who is closer to 21, the user or the house. When I click stay, nothing occurs in my program. Any help will be appreciated. Thanks for reading.
onEvent("stayButton","clicked", function()   {

 if (userTotal == 21) {
      setText("userArea","Player total is: " + userTotal +" Player wins!");
 }
  houseTotal();

  while (houseTotal < 17)  {
    appendItem( houseHand,deck.pop() );
    houseHandTotal();
  }

  if (houseTotal > 21) {
   setText("houseArea","House busts, User wins");
   var userWins = betAmount * 1.2;
   TotalMoney = TotalMoney + userWins;
  }

  setText("houseArea",houseHand + "house total is: " + houseTotal);

  if ( 21 - userTotal < 21-houseTotal && userHandValue != "bust" && houseHandValue != "bust")
  {
    setText("userArea","Player total is: " + userTotal +" Player wins!");
  }

  else if (21 - userTotal > 21-houseTotal && userHandValue != "bust" && houseHandValue != "bust")
  {
    setText("userArea","Player total is: " + userTotal +" Player loses!");
  }

});

A: Assuming onEvent is a wrapper for addEventListener, then the proper event name is click, not clicked.
Other minor clean up points:

*

*Also, use === and !== for equality comparisons instead of == and != to avoid type conversion related nuances.

*Lastly, mostly stylistic, JS code tends to prefer single quotes for strings '.

*Not JS specific, but try using a logical approach to new lines in your code to make it readable.

onEvent('stayButton', 'click', () => {
  if (userTotal === 21)
    setText('userArea', 'Player total is: ' + userTotal + ' Player wins!');

  houseTotal();
  while (houseTotal < 17) {
    appendItem(houseHand, deck.pop());
    houseHandTotal();
  }

  if (houseTotal > 21) {
    setText('houseArea', 'House busts, User wins');
    let userWins = betAmount * 1.2;
    TotalMoney = TotalMoney + userWins;
  }

  setText('houseArea', houseHand + 'house total is: ' + houseTotal);

  if (21 - userTotal < 21 - houseTotal && userHandValue !== 'bust' && houseHandValue !== 'bust')
    setText('userArea', 'Player total is: ' + userTotal + ' Player wins!');
  else if (21 - userTotal > 21 - houseTotal && userHandValue !== 'bust' && houseHandValue !== 'bust')
    setText('userArea', 'Player total is: ' + userTotal + ' Player loses!');
});


text:
Q: Creating a function in Python for creating buckets from pandas dataframe values based on multiple conditions I asked this question and it helped me, but now my task is more complex.
My dataframe has ~100 columns and values with 14 scales.
{'Diseasetype': {0: 'Oncology',
 1: 'Oncology',
 2: 'Oncology',
 3: 'Nononcology',
 4: 'Nononcology',
 5: 'Nononcology'},
'Procedures1': {0: 100, 1: 300, 2: 500, 3: 200, 4: 400, 5: 1000},
'Procedures2': {0: 1, 1: 3, 2: 5, 3: 2, 4: 4, 5: 10},
'Procedures100': {0: 1000, 1: 3000, 2: 5000, 3: 2000, 4: 4000, 5: 10000}}

I want to convert each value in each column of the dataframe into a bucket value.
My current solution is:
def encoding(col, labels):
    return np.select([col<200, col.between(200,500), col.between(500,1000), col>1000], labels, 0)

onc_labels = [1,2,3,4]
nonc_labels = [11,22,33,44]
msk = df['Therapy_area'] == 'Oncology'

df[cols] = pd.concat((df.loc[msk, cols].apply(encoding, args=(onc_labels,)), df.loc[msk, cols].apply(encoding, args=(nonc_labels,)))).reset_index(drop=True)

It works well, if all columns of the dataframe has the same scale, but they do not. Remember, I have 14 different scales.
I would like to update the code above (or get another solution), which would allow me to bucket data. I cannot use the same range of values for bucketing everything.
My logic is the following:
If Disease == Oncology and Procedures1 on this scale, convert values to these buckets (1, 2, 3)
If Disease == Oncology and Procedures2 on this scale, convert values to these buckets (1, 2, 3)
If Disease != Oncology and Procedures77 on this scale, convert values to these buckets (4, 5, 6)
Example of a scale and buckets:
Procedures1 for Oncology: < 200 = 1, 200-400 = 2, >400 = 3
Procedures2 for Oncology: < 2 = 1, 2-4 = 2, >4 = 3
Procedures3 for Oncology: < 2000 = 1, 2000-4000 = 2, >4000 = 3
Procedures1 for nonOncology: < 200 = 4, 200-400 = 5, >400 = 6
Procedures2 for nonOncology: < 2 = 4, 2-4 = 5, >4 = 6
Procedures3 for nonOncology: < 2000 = 4, 2000-4000 = 5, >4000 = 6
Expected output (happy to provide more info!)
Diseasetype Procedures1 Procedures2 Procedures100
Oncology        1             1           1
Oncology        2             2           2
Oncology        3             3           3
Nononcology     4             4           4
Nononcology     5             5           5
Nononcology     6             6           6

Link with rules:

A: I used an helper file with all scales (source at the end of answer):

Use melt to flatten your dataframe then filter out your rows with query and finally use pivot to reshape your dataframe. You can execute each line independently to show the transformations:
scales = pd.read_csv('scales.csv').fillna({'Start': -np.inf, 'End': np.inf})
out = (
  df.melt('Diseasetype', var_name='Procedure', ignore_index=False).reset_index()
    .merge(scales, on=['Diseasetype', 'Procedure'], how='left')
    .query("value.between(Start, End)")
    .pivot_table('Label', ['index', 'Diseasetype'], 'Procedure').astype(int)
    .droplevel(0).rename_axis(columns=None).reset_index()
)

Output:
>>> df
   Diseasetype  Procedures1  Procedures100  Procedures2
0     Oncology            1              1            1
1     Oncology            2              2            2
2     Oncology            3              3            3
3  Nononcology            4              4            4
4  Nononcology            5              5            5
5  Nononcology            6              6            6

Content of scales.csv:
Diseasetype,Procedure,Start,End,Label
Oncology,Procedures1,,200,1
Oncology,Procedures1,200,400,2
Oncology,Procedures1,400,,3
Oncology,Procedures2,,2,1
Oncology,Procedures2,2,4,2
Oncology,Procedures2,4,,3
Oncology,Procedures100,,2000,1
Oncology,Procedures100,2000,4000,2
Oncology,Procedures100,4000,,3
Nononcology,Procedures1,,200,4
Nononcology,Procedures1,200,400,5
Nononcology,Procedures1,400,,6
Nononcology,Procedures2,,2,4
Nononcology,Procedures2,2,4,5
Nononcology,Procedures2,4,,6
Nononcology,Procedures100,,2000,4
Nononcology,Procedures100,2000,4000,5
Nononcology,Procedures100,4000,,6

redpajama_set_name: RedPajamaStackExchange


text:
Q: Stop Postback if Validation Error I have the following text box control ;
   <asp:TextBox ID="txtAmount" runat="server" AutoPostBack="true" Width="85px" class="validate[ERExpenseTypeDaterequired,custom[float]]"
                                OnTextChanged="txtAmount_TextChanged"   ></asp:TextBox>

Here, if there any value change in the text box , txtAmount_TextChanged will be called because AutoPostBack="true" is there in the control.
So if we put a non numeric value in the textbox, validation error will fire from the attribute Class using Jquery, but this error which pops up as a red box from the textbox wont stays for more than 3 seconds, it vanishes when the page posts back within 3 seconds, This post back is happening just because there is a AutopostBack="true".
I cannot do Autopostback="false" because, I need to do some calculation based on this text box value change on the spot.
If I do Autopostback="false", page will not post back and error message stays for ever, but I cannot do any calculations on "txtAmount_TextChanged" event as this event will never be called on textchcange if Autopostback="false".
So, what I do to prevent this postback, if there is any validation error in this textbox?

A: function txtAmount_TextChanged(){
    //do validations here, Eg: validate if txtAmount is valid amount and "> 0"
   return false; //if somethings's wrong, else true

}

A: You'll need to add a client-side event handler, and return false from it when you don't want a PostBack to happen.
<asp:TextBox onkeydown="return doMyCheck()" ID="txtAmount" runat="server"
  AutoPostBack="true" Width="85px" class="validate[ERExpenseTypeDaterequired,custom[float]]"
  OnTextChanged="txtAmount_TextChanged"></asp:TextBox>

JavaScript:
function doMyCheck() {
  if (// call your jQuery validity check)
    return false;
}

A: Use Input event to check the added text in Textbox using jquery
jQuery('#txtAmount').live('input', function()
   {
     // do your Validation
     // If Valid return True
     // If Invalid Return False
   }
)

A: you can use jquery change function
$('#txtbox').change(function() { if(validationfail){return false;} );

you can use keychange event also
 $('#txtbox').keyup(function() {
       if(validationfail){return false;}
    });


text:
Q: How do I calculate Manhattan distance with PostGIS? I am using the ST_Distance function to calculate the distance between two geometries (a train station and a building) Since I know that all buildings and all train stations are in Chicago, which has an excellent/complete street grid, I would like to use Manhattan (or taxicab) distance.
The generic formula for this is the difference in X plus the difference in Y, so Abs(X1-X2)+Abs(Y1-Y2).
What PostgreSQL query would make this work?

A: I am answering my own question with a proposed query.
select *, ABS(x_permit-x_station)+ABS(y_permit-y_station) as manhattan FROM (SELECT
longname AS NAME,
lines AS metadata,
T .slug,
ST_Distance (
    T .geom,
    ST_Transform (P .geometry, 3435)
) AS distance,
ST_X(ST_Transform(p.geometry, 3435)) as x_permit,
ST_Y(ST_Transform(p.geometry, 3435)) as y_permit,
ST_X(t.geom) as x_station,
ST_Y(t.geom) as y_station
FROM
permits P,
stations_cta T
WHERE
P .permit_ = '100533644'
ORDER BY
distance
LIMIT 2) as foo

This results in the following with some columns snipped out:
Kedzie-Ravenswood   Brown Line  3738.52830193659    3796.29623843171
Addison-O'Hare  Blue Line   4105.37381385087    5790.20002649655

The first numbered column is the distance (in feet, because I'm using EPSG 3435) calculated by the ST_Distance PostGIS function, and the second numbered column is the result of the Manhattan distance formula.
I spot-checked the second result, getting the walking distance from Google Maps between the Addison Blue Line CTA station and the building at 3226 W Belle Plaine Ave (noted as '100533644' in the query). Google Maps outputted a 1.1 miles walking route while the Postgres result of 5,790 feet = 1.09 miles. The difference is acceptable for my purposes.

A: I think I also found a slightly more elegant solution that uses trigonometry and the built in ST_Azimuth function and encapsulated it into a nice function:
CREATE OR REPLACE FUNCTION JZ_TaxiCab(p1 geometry, p2 geometry)
RETURNS REAL AS $$
DECLARE
    az REAL;
    h REAL;
BEGIN
    az := ST_Azimuth(p1, p2);
    /* Cast to geography to get result in meters */
    h := ST_Distance(p1::geography, p2::geography);
    /*   Note: we have to take abs() because the values returned by
         can be positive or negative. We really don't necessarily care
         about the reference point since it's going to be a right triangle.
    */
    RETURN h * abs(sin(az)) + h * abs(cos(az));
END;
$$  LANGUAGE plpgsql


text:
Q: Sublime Text & Source Tree cannot see FileDiff in files generated using xml.File and fsObject in Excel VBA We are looking at certain .yml files that store translation of a Rails application. For example, the structure of en.yml is as follows:
en:
  blog:
    left_navigation:
      list_topic: "Blog topics blah blah"
    articles:
      show:
        by_author: "By %{author}"
  number:
    currency:
      format:
        separator: "."
        delimiter: ","
        format: "%u%n"
  admin:
    blog:
      topics:
        form:
          topic_name: "Topic name"
          topic_parent: "Parent topic"
          save: "Save"
          cancel: "Cancel"

As part of our team's translation procedure, we have translators translate changes in Excel, then reexport the new .yml file via macros. The relevant code is:
...
FilePathAndName = ExportFolder & ExportLang & ".yml"
...
Set xmlFile = fsObject.createtextfile(FilePathAndName, True, True)
maxline = TargetRange.Rows.Count
i = 1
For Each mCell In TargetRange
    line = mCell.Value
    xmlFile.write line & IIf(i = TargetRange.Rows.Count, vbNullString, vbCrLf)
    i = i + 1
Next mCell
xmlFile.Close
...

However, SublimeText cannot see FileDiff when looking at both files together under "Open Folder" interface. Similar, when loaded to Source Tree it says that the 2 files are not identical, but it fails to show the file difference.
We need this file difference to verify that the translations were done with correct syntax. Could somebody help us?

A: Thanks for your ideas @Odatnurd and @barrowc
The issue comes from the encoding of the second (destination file). Apparently it needed to be UTF-8. So I just resaved this file in Sublime Text with Encoding = UTF-8 and FileDiff worked again.

So a final question is, how do I make xml.File and fsObject in Excel VBA save the file in UTF-8 format?


text:
Q: Custom department-like structure in NetSuite There is a need to create a custom structure in NetSuite. The structure must be as closer as possible to existing Department record type. All standard classifications are occupied, we need more classifications.
I created a custom record type with two fields: name and parent. Parent points to the record of the same type. The question is how to create a nicely formatted name like:
"Parent_of_the_parent : the_parent : child". We need to specify all parent names in record name. What is the best way to achieve this with NetSuite customization capabilities?

A: I like the previous solution by Suite Resources if there is only 3 levels to the classifications.
If you absolutely NEED many levels to your classifications (like departments or class), you can create a custom record (with inline editing disabled) and use a script to update all of the sub-classifications that change if you edit a classification.
For example, if you create a custom record with an ID = 'customrecord_classification' and you have fields (custrecord_classificationname [type=FreeFormText], custrecord_classificationparent [type=ListRecord] referring to the new custom record type, and custrecord_classificationfullname [type=FreeFormText]), then you can use/modify the following script I wrote for you below.  I tested it and it works great, but if you want to use it some error handling, logging, etc. should be added.
function beforeSubmit(type) {
// Make sure you turn off inline editing on the custom record type so we don't have to handle xedit events

// Get the context the record was changed and only run when the change was made in the UI
var context = nlapiGetContext();
if (context.getExecutionContext() == 'userinterface') {
    // If creating a new classification record
    if (type == 'create' ) {
        // Get the current record fields: internal ID, custrecord_classificationname, custrecord_classificationparent
        var classificationID = nlapiGetRecordId();
        var classificationName = nlapiGetFieldValue('custrecord_classificationname');
        var parentID = nlapiGetFieldValue('custrecord_classificationparent');
        // Check if the classification has a parent specified
        var hasParent = parentID.length == 0 ? false : true;
        var classificationFullName;

        // If the classification has a parent specified lookup the parent's full name and append the new classification name to it
        if (hasParent == true) {
            var parentFullName = nlapiLookupField('customrecord_classification', parentID, 'custrecord_classificationfullname');
            classificationFullName = parentFullName + ' : ' + classificationName;
        }
        // If the classification does not have a parent then the full name is equal to the name
        else {
            classificationFullName = classificationName;
        }
        // set the classification full name on the current record
        nlapiSetFieldValue('custrecord_classificationfullname', classificationFullName);
    }
    // If editing an existing classification record
    else  if (type = 'edit') {
        var classificationID = nlapiGetRecordId();
        // get the recored before the record was edited to grab the old value for the full classification name
        var previousClassificationRecord = nlapiGetOldRecord();
        var oldClassificationFullName = previousClassificationRecord.getFieldValue('custrecord_classificationfullname');
        var classificationName = nlapiGetFieldValue('custrecord_classificationname');
        var parentID = nlapiGetFieldValue('custrecord_classificationparent');
        var hasParent = parentID.length == 0 ? false : true;
        var classificationFullName;
        if (hasParent == true) {
            var parentFullName = nlapiLookupField('customrecord_classification', parentID, 'custrecord_classificationfullname');
            classificationFullName = parentFullName + ' : ' + classificationName;
        }
        else {
            classificationFullName = classificationName;
        }
        nlapiSetFieldValue('custrecord_classificationfullname', classificationFullName);

        var filters = new Array();
        var columns = new Array();
        // Filter for a saved search for all classifications that have a full classification name beginning with the old classification name
        filters[0] = new nlobjSearchFilter( 'custrecord_classificationfullname', null, 'startswith', oldClassificationFullName );
        // Make sure the current record is not one of the records returned
        filters[1] = new nlobjSearchFilter( 'internalid', null, 'noneof', classificationID );
        columns[0] = new nlobjSearchColumn( 'custrecord_classificationfullname' );
        var affectedClassifications = nlapiSearchRecord( 'customrecord_classification', null, filters, columns );
        // loop through all of the classifications that need to be updated
        for ( var i = 0; affectedClassifications != null && i < affectedClassifications.length; i++ ) {
            var subClassificationToFix = affectedClassifications[i];
            var subClassificationToFixID = subClassificationToFix.getId();
            // load the sub-classification record to fix, correct it's value then re-submit it
            var subClassificationToFixRecord = nlapiLoadRecord('customrecord_classification', subClassificationToFixID);
            var subClassificationToFixOldFullName = subClassificationToFixRecord.getFieldValue('custrecord_classificationfullname');
            var subClassificationToFixNewFullName = subClassificationToFixOldFullName.replace(oldClassificationFullName, classificationFullName);
            subClassificationToFixRecord.setFieldValue('custrecord_classificationfullname', subClassificationToFixNewFullName);
            var id = nlapiSubmitRecord(subClassificationToFixRecord, false);
        }
    }
}
}

A: You'd probably need a name (full name with parent), parent, and name (no hierarchy).
You could then fill out the Name (no hierarchy) value (Ex. Socks), specify the parent (Ex. Clothing).
You could then populate the full name field by loading the parent record and concatenating the name (no hierarchy) value.
I'm not sure if that makes sense or not, but if you notice in Netsuite they use that structure also with the name and name (no hierarchy) that you can see if you create an item saved search as an example and you should see that both of those are available on the results.

A: It's only 3 levels deep? Or more?
If 3, create a field on the parent that references the grandparent (store value is unchecked, use the Sourcing and Filtering tab).
On the child, you can do the same thing - reference the parent and reference to the grandparent.


text:
Q: How do I add child items dynamically to an expandable listview.? For example, I have an edit text and a button. When the button is pressed the text is added to the first group in my expandable listview and each following item is added underneath it. Thank you. (If you need the code I have so far please request.)

A: first one you should create your own custom adapter.
once create a class like this.
public class ExpandableListParentClass{

    private Object parent;
    private ArrayList<Object> parentChildren;

    public ExpandableListParentClass() {
    }
    public ExpandableListParentClass(Object parent, ArrayList<Object> parentChildren) {
        this.parent = parent;
        this.parentChildren = parentChildren;
    }

    public Object getParent() {
        return parent;
    }

    public void setParent(Object parent) {
        this.parent = parent;
    }

    public ArrayList<Object> getParentChildren() {
        return parentChildren;
    }

    public void setParentChildren(ArrayList<Object> parentChildren) {
        this.parentChildren = parentChildren;
    }
}

and create your adapter
public class ExpandableListAdapter extends BaseExpandableListAdapter implements Filterable{

    private LayoutInflater inflater;
    private ArrayList<ExpandableListParentClass<Object>> mParent;
    private View view;

    public ArrayList<Object> getMParent() {
        return mParent;
    }

    public ExpandableListAdapter(Context context,
         ArrayList<ExpandableListParentClass<Object>> parentList ) {
        this.mParent = parentList;
        this.inflater = LayoutInflater.from(context);

    }

    // counts the number of group/parent items so the list knows how many
    // times calls getGroupView() method
    public int getGroupCount() {
        return mParent.size();
    }

    // counts the number of children items so the list knows how many times
    // calls getChildView() method
    public int getChildrenCount(int parentPosition) {
        int size =0;
        if(mParent.get(parentPosition).getParentChildren() != null){
        size = mParent.get(parentPosition).getParentChildren().size();
        }
        return size;
    }

    // gets the title of each parent/group
    public Object getGroup(int i) {
        return mParent.get(i).getParent();
    }

    // gets the name of each item
    public Object getChild(int parentPosition, int childPosition) {
        return mParent.get(parentPosition).getParentChildren().get(childPosition);
    }

    public long getGroupId(int parentPosition) {
        return parentPosition;
    }

    public long getChildId(int i, int childPosition) {
        return childPosition;
    }

    public boolean hasStableIds() {
        return true;
    }

    // in this method you must set the text to see the parent/group on the list

    public View getGroupView(int parentPosition, boolean b, View view, ViewGroup viewGroup) {
        if (view == null) {
            view = inflater.inflate(R.layout.layout_listview, viewGroup, false);
        }

        return view;

    }

    // in this method you must set the text to see the children on the list

    public View getChildView(int parentPosition, int childPosition, boolean b, View view, ViewGroup viewGroup) {
        if (view == null) {
        view = inflater.inflate(R.layout.layout_listview, viewGroup, false);
        }

        // return the entire view
        return view;
    }

    public boolean isChildSelectable(int i, int i1) {
        return true;
    }

    }

 now fill to list

      List<ExpandableListParentClass> arrayParents = new ArrayList<ExpandableListParentClass>();
      ExpandableListParentClass item = new ExpandableListParentClass();
      item.setParent(yourParentItem);
      item.setParentChildren( yourChildList);

after that when you need to add child
ExpandableListView myExpList= (ExpandableListView) this.view.findViewById(R.id.yourExpListView);

ExpandableListAdapter adapter =
        (ExpandableListAdapter) myExpList.getExpandableListAdapter();

( (ExpandableListParentClass)adapter.getMParent().get(0) ).getParentChildren().add(object);
//(change to get(0) which you parent want to get )
adapter.notifyDataSetChanged();
adapter.notifyDataSetInvalidated();


text:
Q: How do I rename a (work)sheet in a Google Sheets spreadsheet using the API in Python? I have been trying/looking to solve this problem for a long while.
I have read the documentation for gspread and I cannot find that there is a way to rename a worksheet.
Any of you know how to? I would massively appreciate it!
There is indeed worksheet.title which gives the name of the worksheet, but I cannot find a way to rename the actual sheet.
Thank you in advance!

A: Although the title says using the API, the question details OP wanted to use gspread API (instead of using direct calls to Google Spreadsheets API).
I am surprised that there is no answer to this yet. Perhaps gspread had not a method for this when the question was posted, but now it is as simple as using update_title method:
import gspread

# authenticate:
gc = gspread.service_account()
# choose a gspread method to open your spreadsheet and your worksheet:
wsh = gc.open_by_key(spreadsheetId).worksheet("old_WorkSheetName")
# update your worksheet name:
wsh.update_title("new_WorksheetName")

That's it.

A: Your answer can be solved via a HTTP request from Python.
Link is here
You need to send some sort of metadata for the worksheet via HTTP.
For example, get the ID of the worksheet using Python, and send the following info:
<entry>
  <id>
    https://spreadsheets.google.com/feeds/worksheets/key/private/full/worksheetId
  </id>
  <updated>2007-07-30T18:51:30.666Z</updated>
  <category scheme="http://schemas.google.com/spreadsheets/2006"
    term="http://schemas.google.com/spreadsheets/2006#worksheet"/>
  <title type="text">Income</title>
  <content type="text">Expenses</content>
  <link rel="http://schemas.google.com/spreadsheets/2006#listfeed"
    type="application/atom+xml" href="https://spreadsheets.google.com/feeds/list/key/worksheetId/private/full"/>
  <link rel="http://schemas.google.com/spreadsheets/2006#cellsfeed"
    type="application/atom+xml" href="https://spreadsheets.google.com/feeds/cells/key/worksheetId/private/full"/>
  <link rel="self" type="application/atom+xml"
    href="https://spreadsheets.google.com/feeds/worksheets/key/private/full/worksheetId"/>
  <link rel="edit" type="application/atom+xml"
    href="https://spreadsheets.google.com/feeds/worksheets/key/private/full/worksheetId/version"/>
  <gs:rowCount>45</gs:rowCount>
  <gs:colCount>15</gs:colCount>
</entry>

The website has a Java and .NET solution as well. (This is for the legacy version 3)
For the newer version, you can use a batch update via a POST http request from Python as well.
link is here
The data for the request is
{
  "requests": [{
      "updateSpreadsheetProperties": {
          "properties": {"title": "My New Title"},
          "fields": "title"
        }
    }]
}

to be sent via POST to https://sheets.googleapis.com/v4/spreadsheets/spreadsheetId:batchUpdate
In both requests, replace the spreadsheetId in the URL with the ID of the Google Sheet you are editing.
Notice the change from v3 to v4 in the URLs.
If you are using a version 3 application and want to migrate, the link to that is here
EDIT
A commentor noted that the second request does not change name of a worksheet. The link I added shows the way to change intricate properties of a worksheet, I will be updating my answer soon.

A: This is an extraction of a library which I've coded personally:
def _batch(self, requests):
    body = {
        'requests': requests
    }
    return self._service.spreadsheets().batchUpdate(spreadsheetId=self.spreadsheetId, body=body).execute()

def renameSheet(self, sheetId, newName):
    return self._batch({
        "updateSheetProperties": {
            "properties": {
                "sheetId": sheetId,
                "title": newName,
            },
            "fields": "title",
        }
    })

I think that with a little effort, you can implement it into your code and obtain what you want.
In order to make the batchUpdate call, you will need the spreadsheetId as well as the initialized service as explained in the Python QUickstart - Google Sheet API

A: You could achieve the same with the gspread port for api v4: pygsheets (author here).
The corresponding code using pygsheets would be:
import pygsheets

gc = pygsheets.authorize()

# open spreadsheet and then worksheet
sh = gc.open('my new spreadsheet')
wks = sh.sheet1
wks.title = 'new title'

A: If you are using Node, here's what worked for me:
import {google} from 'googleapis';

const auth = new google.auth.OAuth2(...)

const sheetsService = google.sheets({version: 'v4', auth})

const requests = [
 {
  updateSheetProperties: {
   properties: {
    sheetId: 'id-of-the-sheet-that-you-want-to-rename',
    title: 'new-title',
   },
   fields: 'title'
   }
  }
];

sheetsService.spreadsheets.batchUpdate({
 spreadsheetId: 'some-spreasheet-id',
 requestBody: {
  requests,
 },
});

A: This can also be implemented with Google API methods only.
Here is a json-free solution.
sheetsService = getSheetsService();
// create a SheetProperty object and put there all your parameters (new title, sheet id, something else)
SheetProperties title = new SheetProperties().setSheetId(0).setTitle("Main");
// make a request with this properties
UpdateSheetPropertiesRequest rename = new UpdateSheetPropertiesRequest().setProperties(title);
// set fields you want to update
rename.setFields("title");
// as requestBody.setRequests gets a list, you need to compose an list from your request
List<Request> requests = new ArrayList<>();
// convert to Request
Request request = new Request().setUpdateSheetProperties(rename);
requests.add(request);
BatchUpdateSpreadsheetRequest requestBody = new BatchUpdateSpreadsheetRequest();
requestBody.setRequests(requests);
// now you can execute batchUpdate with your sheetsService and SHEET_ID
sheetsService.spreadsheets().batchUpdate(SHEET_ID, requestBody).execute();

Here you can find more info on sheetProperties

A: For those whose solving this renaming using NodeJS. Just use the batchRequest API. Indicate in the sheetID the sheet id youre editing and the title field the new title. Then indicate "title" in the fields.

A: In PHP
    public function updateSheetTitle(string $fileId, string $title, ?int $sheetId = NULL): void
    {
        if (!$sheetId) {
            // rename first sheet
            $file = $this->get($fileId);
            if (!$file->getSheets()) {
                throw new NoSheetsException();
            }
            $sheetId = $file->getSheets()[0]->getProperties()->getSheetId();
        }
        $titleProp = new Google_Service_Sheets_SheetProperties();
        $titleProp->setSheetId($sheetId);
        $titleProp->setTitle($title);

        $renameReq = new Google_Service_Sheets_UpdateSheetPropertiesRequest();
        $renameReq->setProperties($titleProp);
        $renameReq->setFields('title');

        $request = new Google_Service_Sheets_Request();
        $request->setUpdateSheetProperties($renameReq);

        $batchUpdateRequest = new Google_Service_Sheets_BatchUpdateSpreadsheetRequest();
        $batchUpdateRequest->setRequests([$request]);

        $this->spreadsheets->batchUpdate($fileId, $batchUpdateRequest);
    }


text:
Q: Kinect v2 Alignment of Infrared Sensor & RGB Image always slightly off I'm using the official Kinect SDK 2.0 and Emgu CV in order to recognize the colors of a Rubik's Cube.

At first I use Canny Edge Extraction on the Infrared Camera since it handles different lightning conditions better than the RGB Camera and is much better to detect contours.
Then I use this code to convert the coordinates of the infrared sensor to the ones of the RGB camera.
As you can see the in the picture they are still off from what I am looking for. Since I already use the official KinectSensor.CoordinateMapper.MapDepthFrameToColorSpace I don't know how else I can improve the situation.
using (var colorFrame = reference.ColorFrameReference.AcquireFrame())
using (var irFrame = reference.InfraredFrameReference.AcquireFrame())
{
    if (colorFrame == null || irFrame == null)
        return;

    // initialize depth frame data
    FrameDescription depthDesc = irFrame.FrameDescription;

    if (_depthData == null)
    {
        uint depthSize = depthDesc.LengthInPixels;
        _depthData = new ushort[depthSize];
        _colorSpacePoints = new ColorSpacePoint[depthSize];

         // fill Array with max value so all pixels can be mapped
         for (int i = 0; i < _depthData.Length; i++)
         {
             _depthData[i] = UInt16.MaxValue;
         }
         // didn't work so well with the actual depth-data
         //depthFrame.CopyFrameDataToArray(_depthData);

        _sensor.CoordinateMapper.MapDepthFrameToColorSpace(_depthData, _colorSpacePoints);
    }
}

This is a helper-function I created in order to convert Point-Arrays in Infrared-Space to Color-Space
public static System.Drawing.Point[] DepthPointsToColorSpace(System.Drawing.Point[] depthPoints, ColorSpacePoint[] colorSpace){
        for (int i = 0; i < depthPoints.Length; i++)
        {
            // 512 is the width of the depth/infrared image
            int index = 512 * depthPoints[i].Y + depthPoints[i].X;

            depthPoints[i].X = (int)Math.Floor(colorSpace[index].X + 0.5);
            depthPoints[i].Y = (int)Math.Floor(colorSpace[index].Y + 0.5);
        }
        return depthPoints;
    }

A: We can solve this problem by transforming infrared image coordinates to color image coordinates with 2 quadrilateral mapping.
A quadrilateral Q(x1,y1,x2,y2,x3,y3,x4,y4) in an infrared image, similarly,
it's mapping quadrilateral Q'(x1',y1',x2',y2',x3',y3',x4',y4') in the  corresponding color image.
We can write the above mapping in form of equation as follows:
Q'= Q*A
where, A is a 3 X 3 matrix with coefficients a11, a12, a13, a21,.., a33;
The formula to obtain the coefficients are listed as follows:
x1=173; y1=98; x2=387; y2=93; x3=395; y3=262; x4=172; y4=264;
x1p=787; y1p=235;  x2p=1407; y2p=215; x3p=1435; y3p=705;  x4p=795; y4p=715;
tx=(x1p-x2p+x3p-x4p)*(y4p-y3p)-(y1p-y2p+y3p-y4p)*(x4p-x3p);
ty=(x2p-x3p)*(y4p-y3p)-(x4p-x3p)*(y2p-y3p);
a31=tx/ty;
tx=(y1p-y2p+y3p-y4p)*(x2p-x3p)-(x1p-x2p+x3p-x4p)*(y2p-y3p);
ty=(x2p-x3p)*(y4p-y3p)-(x4p-x3p)*(y2p-y3p);
a32=tx/ty;
a11=x2p-x1p+a31*x2p;
a12=x4p-x1p+a32*x4p;
a13=x1p;
a21=y2p-y1p+a31*y2p;
a22=y4p-y1p+a32*y4p;
a23=y1p;
a33=1.0;

A: Its because its not the same camera the camera that retrieves the depth data and the one that retrieves color data.
So you should apply a correction factor to displace the depth data.
Its a factor that is almost constant but its related to the distance.
I've got no code for you, but its something you can calculate yourself.


text:
Q: How can I use one machine to access keychains stored on extracted disk of different machine? I have two similar but not identical MacBook Pros (a 2012 13" i5 and a ~2011 15" i7).  The 15" died today with a video problem that has affected machines of that generation (possibly a solder problem; this is the second time the same thing has happened to this machine).
Anyway, I pulled the SSD out of the 15" before sending it in for service, and I have it connected to the 13" through a USB/SATA adapter.  The data is intact, and I can access everything that was on the 15" machine.
However, I have some passwords in the 15" login keychain that I would like to view somehow on the 13".  I can access the files that probably have the keychain data, but I don't know how to open those files using Keychain Access on the 13" system.  The passwords were automatically unlocked when I logged in on the 15". I don't know the details of that process.
Is it possible to open the 15" keychains somehow, given root access on the 13" and knowledge of the login password for the 15" system (whose disk is now sitting on my desk, connected to the 13")?
Other options I've considered:

*

*Put 15" disk in main drive bay of 13" and try to boot it.

*Make a new Parallels VM and attach it to the 15" disk as a physical drive.

I'm a bit nervous about those, because the machines are different, and I don't want the 13" to screw up the 15" drive.  (I do have a write-protect switch on my USB/SATA adapter, but I had to connect the 15" disk in writeable mode so that the journal could replay.  However, the filesystems were/are all intact, so I don't think any damage was done.)

A: You can just copy your old keychain to your new keychain:

*

*Open Keychain Access from the Other folder in Launchpad.

*Choose Add Keychain from the File menu.

*Go to your drive > Users > Username > Library > Keychains (/Volumes/_DRIVE_NAME_/Users/USERNAME/Library/Keychains/).

*Select the file named: login.keychain

Now you have your old keychain in your new one.


text:
Q: MySQL pivot select 2 SUMs I have two sum functions being done in the same table with the following query:
select sum(a), sum(b) from table

resulting in the following output:
SUM a    SUM b
1312     2121

I want the output to show the labels in the left column and results in the right column i.e.:
SUM a    1312
SUM b    2121

Thanks in advance

A: you can use union
select 'SUM a' my_text, col_sum_a
from my_table
union
select  'SUM b', col_sum_b
from my_table


text:
Q: inverse laplace transform - with symbolic variables Transform: $$ F(s) = \frac{2s^2 + (a-6b)s + a^2 - 4ab}{(s^2-a^2)(s-2b)} $$
My steps:
 $$ F(s) = \frac{2s^2 + (a-6b)s + a^2 - 4ab}{(s+a)(s-a)(s-2b)} $$
 $$ = \frac{A}{s+a}  + \frac{B}{s-a} + \frac{C}{s-2b} + K $$
 $$ K = 0$$
$$A = F(s) * (s+a) $$ at s = -a
 $$ A = \frac{2a^2 + (a-6b)(-a) +a^2 - 4ab}{4ab+2a^2} $$
$$ A = \frac{a+b}{2b+a}$$
I problems like this (that I've seen)  at the step above the fraction would reduce into just a number. In this case, it doesn't and its surprising because I've never seen it happened before. Is there something I am doing wrong here?

A: The routine way is to use the way we get in partial fractions and you correctly noted that. If we set:
$$ \frac{2s^2 + (a-6b)s + a^2 - 4ab}{(s^2-a^2)(s-2b)}=F= \frac{A}{s+a}  + \frac{B}{s-a} + \frac{C}{s-2b}
$$ then by doing  boring :-) handy calculations we can find $A,B$ and $C$. We have then:
$$\frac{-Asa+2Aab+As^2-2Asb+Bsa-2Bab+Bs^2-2Bsb+Cs^2-Ca^2}{(-s+2b)(-s^2+a^2)}$$ Now if we put $s=-a$ in the numerators, we get $A=\frac{a+b}{a+2b}$ and this is what you already got. With the similar approach $s=+a$ for $B$ and $s=2b$ for $C$, we get:
$$B=\frac{2a-5b}{a-2b},~~C=\frac{4b^2+2ab-a^2}{a^2-4b^2}$$


text:
Q: Having multiple IFrames in a single page I have an application which takes in users' HTML from an editor like CKEditor and display them back to the user in a list.
To be safe, as in to avoid breaking the container page's html structure by mal-formed html input, i want to render each user's html input in an iframe (iframe will render from a URL).
The container page will just have a list of frames each with users html. They will be sized to a height of 100px or so to accommodate multiple inputs in a list.
My question is:
1.) how good of an idea is it to render potentially hundreds of iFrames in a single page ? Will the memory usage blow-up the end users browser ?
2.) Is there a safer and easier way to render user's html ? I want to put as few restrictions as possible on user's input.
[I will of course sanitize all the input on the server before sending it back to client.]

A: The iFrame is exactly what you are looking for.
Why would you render 100+ iFrames? As I understood, you want to paste the content of a users "page" to your page - so just make it one site per "user Site" ...
If you want to display all iFrames on one site, it would be a potential huge ass Website but as everying is static, it should'nt be a problem.


text:
Q: Putty Automation using TOSCA I am using TOSCA for automating putty. I want to enter commands using TOSCA and want to verify search results too. If there is anyone who has worked on it, please help. Thanks in advance.

A: Tricentis Tosca provides an on-demand Putty Engine as part of the Tosca Classic Engines. You can reach out to support.tricentis.com to know more about this engine.

A: Tosca provides an inbuilt standard modules to run a Program use that and in arguments add the server name username, password and use t-box window operation using Regex for the title if you have multiple serves for putty. Regex should be for Tittle.

A: The "Putty Engine" exists but It's not the greatest. We automated a program that utilized putty and primary used SendKeys commands and Image Verifications
https://documentation.tricentis.com/tosca/1210/en/content/tbox/special_characters.htm
https://documentation.tricentis.com/en/1110/content/tbox/optical_intelligence_generic.htm


text:
Q: Why is preprocessor condition giving me this output     #include<stdio.h>
    #define Y 10
    int main()
    {
    #if X && Y || Z
    printf ("A\n");
    #else
    printf("B\n");
    #endif
    }

Here else is satisfied B is printed but if I use
#if !X && Y || Z

If is satisfied and A is printed
My question is, If X and Z isn't defined, how's pre-processor solving the statement?

A: Unresolved symbols in a preprocessor conditional are treated as zeros.  Hence when neither X nor Z is defined, both are treated as zero.
See C11 §6.10.1 Conditional inclusion ¶4:

After all replacements due to macro expansion and the defined unary operator have been performed, all remaining identifiers (including those lexically identical to keywords) are replaced with the pp-number 0, and then each preprocessing token is converted into a token.

A preprocessing number (or pp-number) is more general than a number in the main language.


text:
Q: When I click a method in eclipse with Command (ctrl) it opens xcode In eclipse for mac when you press command and then click on a method or variable it will take you to were it is located. HOWEVER suddenly instead of doing that it started opening XCODE, because it was treating every click as opening the .java file.
I thought that maybe it was key bindings so I went into eclipse and reset all key bindings, so now it jumps to the correct part of the eclipse document... then it opens XCODE.
Any suggestions?

A: Make sure your *.java files in eclipse "open with" eclipse not XCODE.


text:
Q: Each row has the same random number being inserted I'm looking to insert random numbers into each column in a database.
The issue that is occuring is that each column for some reason has the same random generated value being passed inside.
$sql = "SELECT * FROM players";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
  // output data of each row
  $targScore = 3;
  while($row = $result->fetch_assoc()) {

    $target = 3; // The target number the sequence is adding up to
    $n = 4; // Max numbers within sequence

    while ($n) {
        if (1 < $n--) {
            $addend = rand(0, $target - ($n - 1));
            $target -= $addend;
            $num[] = $addend;
        } else {
            $num[] = $target;
        }
    }

    /* Rows to update */
    /* Output looks like:
        [0] = 1
        [1] = 2
        [0] = 0
        [0] = 1
    */
    $changeScore = "UPDATE players SET doja='$num[0]' WHERE score='$targScore'";
    $conn->query($changeScore);

    $changeScore = "UPDATE players SET 7acres='$num[1]' WHERE score='$targScore'";
    $conn->query($changeScore);

    $changeScore = "UPDATE players SET tweed='$num[2]' WHERE score='$targScore'";
    $conn->query($changeScore);

    $changeScore = "UPDATE players SET bickel='$num[3]' WHERE score='$targScore'";
    $conn->query($changeScore);
  }
}

The data looks like: https://imgur.com/a/nhhZDVo
What I need is that each loop, it will run the randomizer again but change the numbers its inserting so that each row will have different numbers.

A: You need to first get a list of all the rows that meet the score condition. Then you have to update them one by one, so you can set different random values in each.
$select_stmt = $conn->prepare("SELECT id FROM players WHERE score = ?");
$select_stmt->bind_param("i", $targScore);
$select_stmt->execute();
$res = $select_stmt->get_result();
$update_stmt = $conn->prepare("UPDATE players SET doja = ?, 7acres = ?, tweed = ?, bickel = ? WHERE id = ?");
$update_stmt->bind_param("iiiii", $doja, $acres, $tweed, $bickel, $id);

$target = 3;

while ($row = $res->fetch_assoc()) {
    $n = 4;
    $num = [];
    while ($n) {
        if (1 < $n--) {
            $addend = rand(0, $target - ($n - 1));
            $target -= $addend;
            $num[] = $addend;
        } else {
            $num[] = $target;
        }
    }
    [$doja, $acres, $tweed, $bickel] = $num;
    $id = $row['id'];
    $update_stmt->execute();
}

There's also no need to use four UPDATE statements to update 4 columns in the same rows.

A: MySQL has a rand() function https://dev.mysql.com/doc/refman/5.7/en/mathematical-functions.html#function_rand
(Note the warning that it's not perfectly random / security secure, but nor is PHPs rand()).
If you do not need to know what the values are, you can simply do UPDATE myCol=FLOOR(RAND() * 200) WHERE myConditionalField=MyCondition
This will allocate a random number from 0 to 199; examples in the MySQL manual (linked above) as to how to set a range, e.g. FLOOR(7 + (RAND() * 5)) gives an integer from 7 to 11.


text:
Q: Is it possible to vertically center text in its bounding box? My text is not vertically centered and my designers are pointing it out.
However, I am using the proper CSS to achieve vertical centering, that is not the issue.
The problem lies in the font itself. The glyphs are not centered in the actual text. Selecting the text reveals its bounding box, and from here I can see an uneven amount of space below the text.

Line-height does not appear to fix this issue. The bounding box is still off, even with a line-height of 0. I can add padding to the top of my elements to attempt to fix this problem, but that's not going to be scalable across the many elements that use this font.

It appears that the uneven space is because of descenders. This makes sense, but unfortunately it doesn't get me any closer to figuring out how to truly vertically center this text.

The font in question is SouvenirStd-Medium, but I have noticed this with many other web fonts. It is consistently off no matter which element is used... h1's, paragraph tags, etc.
Although it probably wont be useful, here is an example my styles for headlines:
font-family: SouvenirStd-Medium;
font-size: 5rem;
font-weight: 400;
font-style: normal;
line-height: 1.3;
letter-spacing: 0;

And an example of how I am centering my text in a wrapping  tag.
div {
   display: flex;
   height:100px;
   align-items: baseline;
}

A: Line height won't help the issue, as it adds or subtracts equal amount of space to the top and bottom of a single text line, based on the top and bottom spacing defined within the font itself (see line-height description at w3c for more information). This means that you need to find a different font in order to get what you want without going out of your way.
padding-top or padding-bottom work great if you use em as the unit, which is relative to the total height of the letter (including the above and below space). That will allow you to shift text by the same relative amount accross the whole webpage, independant of the font-size (and you can use line-height from there to manage distance between individual lines):
.font-timesnewroman {
  font-family: 'Times New Roman', serif;
  padding-top: 0.1em;
}

Adapted from a hack I found in this blog post, here's a possible solution if the above doesn't work for you (yet also a bit narrow in application):

div {
  height: 100px;
  margin-top: 40px;
  border: thin dotted gray;
  text-align: center;
}
.text {
  font-size: 100px;
  line-height: 0px;
  background-color: #9BBCE3;
}
.text::after {
  content:'';
  display: inline-block;
  height: 80%; /* adjust this to shift the text */
}

  Test

This has the following features and constraints:

*

*works for elements the above solution doesn't, for example because the elements you're trying to style already have a padding

*allows you to adjust the baseline with percentage or em values (so they do scale with font-size)

*halfway implementable with the after-selector, however requires a span (or other inline-rendered) element around the text to be positioned

*only works for non-wrapping lines


text:
Q: How to avoid passing around an IOC Container I have some legacy code that is creating instances of classes.
I have managed to wire up an IOC container to scan assemblies and create instances of them. However, I have spotted that in a configuation class specific classes may be created numerous times.
The logic basically loops over an array of class types and if it matches the one a user selected it calls CreateInstance.
This is fine but the only way I can think to provide that functionality is to pass the IOC Container around and call Resolve which will provide a new instance of the class.
I know this is seriously frowned upon but I can't think how to make it work.

A: Create an abstract factory which provides a layer of abstraction between the IOC container and the code requiring the new instances, this will avoid the code being littered with container dependent calls.
For example, when using the 'Unity Application Block', Func<T> can be used as a factory. This Func<T> then hides the container implementation which is actually container.Resolve<T>().
Update
Here is an example:
public class TestClass
{
    readonly Func<Foo> _fooFactory;

    public TestClass(Func<Foo> fooFactory)
    {
        _fooFactory = fooFactory;
    }

    public void LoadFoo()
    {
        var foo = _fooFactory(); // This hides the call container.Resolve<Foo>()
        // Do something with foo
    }
}


text:
Q: How to set Wallpaper automatically everyday in android I am developing an application that shows the different photos from server and user can set select photos as wallpaper of its device i used given code to set wallpaper it working but i want to wallpaper set automatically every day. I used this code.
Java
 private void setAsWallpaper()
    {
        Picasso.get().load(imageUrl).into(new Target()
        {
            @Override
            public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from)
            {
                progressBar.bringToFront();
                progressBar.setVisibility(View.VISIBLE);

                WallpaperManager wallpaperManager = WallpaperManager.getInstance(SetWallPaperFullScreenActivity.this);
                try
                {
                    wallpaperManager.setBitmap(bitmap);

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

                Toast.makeText(SetWallPaperFullScreenActivity.this, "Wallpaper set successfully.", Toast.LENGTH_SHORT).show();
                progressBar.setVisibility(View.INVISIBLE);
            }

            @Override
            public void onBitmapFailed(Exception e, Drawable errorDrawable)
            {
                Log.d("TAG", "Failed: ");

            }

            @Override
            public void onPrepareLoad(Drawable placeHolderDrawable)
            {
                Log.d("TAG", "Prepare Load: ");

            }

        });

    }

A: 1) first you need to Schedule job which  called every 24 hour. reference link
2) now use below method to set wallpaper
 public void setWallpaper {
          WallpaperManager myWallpaperManager =
                      WallpaperManager.getInstance(getApplicationContext());
        try {
            myWallpaperManager.setResource(R.drawable.wallpaper);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
     }

A: Try this out,
Create a sticky service as shown below then i have created a TimerTask(Scheduler) which will run after every 24hrs there you can add your code for setting wallpaper. Don't forget to register the service in Manifest. Start this service from any activity.
You can refer the sticky service from here to know more
private Timer timer;
private TimerTask timerTask;

@Override
public IBinder onBind(Intent intent) {
    return null;
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    startTimer();
    return START_STICKY;
}

public void startTimer() {
    timer = new Timer();
    initializeTimerTask();
    //schedule the timer, after the first **5000ms** the TimerTask will run in every **24hrs**
    timer.schedule(timerTask, 5000, 86400000);
}

public void initializeTimerTask() {
    timerTask = new TimerTask() {
        public void run() {
            //ToDo set wallapaper here
        }
    };
}

@Override
public void onDestroy() {
    super.onDestroy();
    if (timer != null) {
        timer.cancel();
        timer = null;
    }
}


text:
Q: When should we use console class? I was reading about Console class, and in the very first line, it was written

New to Java 6 and when we are running Java SE 6 from command line, then we are typically using console class object

So, which means we are implicitly using console class through the command line ??
Then, I started looking for more detail about Console class and I found Input from console class in java and Console link. So, concluded some points

*

*Console class are only usable outside the IDE using System.console().readLine();

*Console class reads a password or passphrase from the console with echoing disabled using readPassword()

Although, we had Scanner class and BufferedReader class to read the input from console and that was added earlier than Java 5. So, only due to security reason Console class was added in Java 6 ? or are there any other advantage(s) to use this class.
Could anyone share more details about Console class ?

A: The Console class reads directly from the process console (usually /dev/console in Unix systems). The console differs from System.in in that it cannot be redirected when a command is launched. It is also used to read passwords because reading from the console you can control whether or not you echo the chars being typed.
To clarify more on this class, read about console and standard input in Unix systems (this is typically a Unix thing and I'm not really sure how it maps to Windows systems).
Finally, Scanner can read from any input: a file, an stream, or the console itself so it's different from Console.

A: The Console class tries to implement a platform independent way to handle with console input. All OS has a console in any way, but they are quiet diferent in implementation. So Console class gives you a Java platfrom independent runtime class to access things like password input, etc.

A:
Whether a virtual machine has a console is dependent upon the
  underlying platform and also upon the manner in which the virtual
  machine is invoked. If the virtual machine is started from an
  interactive command line without redirecting the standard input and
  output streams then its console will exist and will typically be
  connected to the keyboard and display from which the virtual machine
  was launched. If the virtual machine is started automatically, for
  example by a background job scheduler, then it will typically not have
  a console.

How To Get Input From Console Class In Java?


text:
Q: firefox font bug on middlemouse click I input some font on site:
@font-face {
    font-family: 'willamette_sfregular';
    src: url('wills.eot');
    src: url('wills.eot?#iefix') format('embedded-opentype'),
         url('wills.woff') format('woff'),
         url('wills.ttf') format('truetype'),
         url('wills.svg#willamette_sfregular') format('svg');
    font-weight: normal;
    font-style: normal;
}

In browsers IE9,10,Chrome,Safari,Opera it works perfectly and also Firefox supports it but with some little problem. If you trying to open new link just with left mouse click it all good, the font is using well but if you trying to open new link using mouse3 button the font dissapear changing it to default font, it happens only in Firefox browser (clean, without any adds)
Here link to example - http://www.mediafire.com/download/k7sc10h47qdadmm/fonts.rar
When you open sub.html with mouse3 button font changes to default but when you click to index.html with mouse3 font returned. I understand like that - it works on firefox only if font stay at the same directory as html file is but when you use sub.html which has link to css file <link rel="stylesheet" href="../stylesheet.css" type="text/css" charset="utf-8" /> it changes font to default when mouse3 click it. Can't imagine how to fix it

i'll try to make some code on jsFiddle but to see the problem you should do next: create any folder, then put index.html file and near stylesheet.css file which has code like this - http://jsfiddle.net/YtHAd/ . Then create new folder where you put index.html and styleshee.css , name folder "1" and put on that folder sub.html which has code like this - http://jsfiddle.net/YtHAd/1/ . the font you can get here - http://www.mediafire.com/download/1ok85zsrs41kgim/WILLS.TTF. Take the font and convert it here - http://www.fontsquirrel.com/tools/webfont-generator and grab generated filed that has extensions .eot .svg .ttf .woff to you'r main directory where index.html is and check this u'll see the problem on firefox

the all files should look like this:
folder/index.html
folder/stylesheet.css
folder/wills.eot
folder/wills.svg
folder/wills.ttf
folder/wills.woff
folder/1/sub.html


text:
Q: Splitting a string from a potential splitter It's relatively a common requirement to split a string from a potential splitter:
$name = 'John'; // or can be 'John Smith'

I use
list($firstName, $lastName) = explode(' ', $name) + [1 => null];

or
@list($firstName, $lastName) = explode(' ', $name);

I wonder if you guys use a more concise or more legible method for this?

A: Oh, I found it!
list($firstName, $lastName) = explode(' ', $name.' ');

The simple trick is appending the glue string to the end of the main string. Tadda!
This make accessing to the second part of the string really easy:
$domain = explode('@', $filter->email . '@')[1]; // for an invalid input the domain will be ''.

A: Use array_pop to get last_name and all in first_name. Your code not works for name which have three words. Example below also works for three words in name like Niklesh Kumar Raut
Uncomment one $name and comment two to check
//$name = "Niklesh";
//$name = "Niklesh Raut";
$name = "Niklesh Kumar Raut";
$name_arr = explode(" ",$name);
$last_name = array_pop($name_arr);
$first_name = implode(" ",$name_arr);
echo "First Name : $first_name\n";//Niklesh Kumar
echo "Last Name : $last_name";//Raut

Live demo : https://eval.in/871971

A: you can use regex to check if the string contains space in between, and then explode using the space to get the first and last string.
$name = 'john smith';
$first_name = $name;
$last_name = '';
if(preg_match('/\s/',$name)) {
  list($first_name, $last_name) = explode(' ', $name);
}

echo "Hello ".$first_name."  ".$last_name;


text:
Q: sqlite insert statement BAD MOJO I have a simple problem which probably has a simple solution, but the solution alludes me...
so I have a simple table i.e. phone that has 4 columns, and I want to add one new column. Since SQLite doesn't modify tables I have to drop and create.
phone_old
_id integer primary key autoincrement,
name text not null,
value text
phone
_id integer primary key autoincrement,
name text not null,
itemState text not null,
value text
so I do the following :
1. I rename the old table,
2. I create the new one with the extra field (in my case it's itemState) and
3. I select and insert everything defining a default value for itemstate.
1 ALTER TABLE Phone RENAME TO Phone_OLD;

2 CREATE table Phone(
_id integer primary key autoincrement,
name text not null,
itemState text not null,
value text );

3) INSERT INTO Phone SELECT * , 'Synced' as itemState from Phone_OLD where Phone_OLD. ;

what happends as a result is that the item state (synced) is added as the last field and not in column 3 which is the itemState.
so the column names do not correspond to the row values, meaning the itemstate is added at the end (as the last column in the row and not as position 3 as it's supposed to )
Just putting the itemstate at the end would solve the problem, but since my table creation statements are generated I would have to rewrite a whole bunch of code to do so, and to be hones it pisses me off that this set of queries returns crap..
any ideas?

A: Sqlite does support appending columns
 ALTER TABLE Phone ADD COLUMN [itemState] text not null default ''


text:
Q: Перестали записываться трансляции с youtube Добрый день.
Ранее получал ссылку следующим способом:
youtube-dl -f bestvideo -g URL

И записывал например 20 секунд:
ffmpeg -i NEW_URL -c copy -bsf:a aac_adtstoasc -t 00:00:20 OUTPUT_FILE

Сейчас не работает, ошибки не сыпятся.
Пример трансляции которую пытаюсь записать.
На сервере ничего не менялось.
Есть у кого опыт записи кусков видео с Youtube, поделитесь опытом?


text:
Q: Which following sentence is the clearest? 1.- Any one cup of drink is limited not to be over than xx.- (currency)
2.- Any one cup of drink is limited to be less than xx.- (currency)
3.- Any one cup of drink is limited to xx.- (currency)
4.-The price of any one cup of drink is limited not to be over than xx.- (currency)
5.-The price of any one cup of drink is limited to be less than xx.- (currency)
6.-The price of any one cup of drink is limited to xx .- (currency)
7.-The price of any one cup of drink is not to be over than xx .- (currency)
[If not, what should it be? - I mean a client will not be given any drink which the price are over than the rate we limited. For example, £10 for one cup, they can not order any drink which the price is over than £10.]
Thank you in advance.

A: If you are promoting your coffee shop and want to give out some freebees, of course you do not want to give away the store. So, your offer needs limits balanced with friendliness.
You can use the following wording for simplicity:
First Prize - One month of drink-a-day, as follows: One free drink (£10 or less) every day for 30 days from the first day you choose.
Second Prize - One week of drink-a-day as follows: One free drink (£10 or less) every day for 7 days from the first day you choose.
Third Prize - Two free drinks (£10 or less)
Any wording that is overly formal is wording that chases your customers away with the feeling that your gift is no gift. Your challenge is to have reasonable limits on your offer without sounding like the offer has more limits than it has in value.


text:
Q: .Net Core 3 Asking for Namespace that already exists Hoping someone can help, ive just updated some nuget packages (from .net core preview to 3) ran a build and now get an error saying:
The type name 'SqlConnection' could not be found in the namespace. This type has been forwarded to assembly Consider adding a reference to that assembly.

As you can see from the image below i have got the names in there. but i believe the grey means that it doesnt think its using it? and im getting the error.
Any ideas on how to fix the issue?
Thanks


text:
Q: Cors enabled in Spring Boot with Angular, still cors errors I have cors enabled for all origins and headers but I still get an cors error when I call a get method from my angular app to spring boot.
Cors error from console:
Access to XMLHttpRequest at 'http://localhost:8080/api/users/test@ronny.nl' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

My controller (I call the getbyemail):
@CrossOrigin(origins = "*", allowedHeaders = "*")
@RestController
@RequestMapping(value = "/api/users", produces = MediaType.APPLICATION_JSON_VALUE)
public class UserController {

    private final UserService userService;

    @Autowired
    public UserController(final UserService userService) {
        this.userService = userService;
    }

    @GetMapping
    public List<UserDTO> getAllUsers() {
        return userService.findAll();
    }

    @GetMapping("/{id}")
    public UserDTO getUser(@PathVariable final Long id) {
        return userService.get(id);
    }

    @CrossOrigin(origins = "*", allowedHeaders = "*")
    @GetMapping("/{email}")
    public UserDTO getUserByMail(@PathVariable String email) {
        return userService.getByEmail(email);
    }

    @PostMapping
    @ResponseStatus(HttpStatus.CREATED)
    public Long createUser(@RequestBody @Valid final UserDTO userDTO) {
        return userService.create(userDTO);
    }

    @PutMapping("/{id}")
    public void updateUser(@PathVariable final Long id, @RequestBody @Valid final UserDTO userDTO) {
        userService.update(id, userDTO);
    }

    @DeleteMapping("/{id}")
    @ResponseStatus(HttpStatus.NO_CONTENT)
    public void deleteUser(@PathVariable final Long id) {
        userService.delete(id);
    }

}

Where I call the get from my angular app:
onSubmit(): void {
    this.submitted = true;
    this.wrongInput = false;
    this.loginService.getLogin<User>(this.loginForm.value.email).subscribe((response) => {
      this.tempUser = response;
      console.log(this.tempUser);
      if (this.loginForm.value.email === this.tempUser.email && this.loginForm.value.password === this.tempUser.password) {
        this.localStorageService.save(this.tempUser);
        this.router.navigate(['/home']);
        console.log(true);
      }
      else {
        this.wrongInput = true;
      }
    });
  }

I also tried to add an DevCorsConfiguration:
package com.team13.triviaquiz.triviaquizserver.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
@Profile("development")
public class DevCorsConfiguration implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/api/**").allowedMethods("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS");
    }
}

And added the profile in my application.properties:
application.properties
spring.profiles.active=development
#enabling h2 console
spring.h2.console.enabled=true
#fixed URL for H2 (necessary from Spring 2.3.0)
spring.datasource.url=jdbc:h2:mem:triviaquizserver
#turn statistics on
spring.jpa.properties.hibernate.generate_statistics = true
logging.level.org.hibernate.stat=debug
#show all queries
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true
logging.level.org.hibernate.type=trace

But still no luck...

A: The reason behind this issue has been clearly mentioned in the answer, briefly CorsRegistry#allowCredentials(true) cannot be used with the default value of CorsRegistry#allowedOrigins() (By default all origins are allowed if you haven't set this property unless any of CorsRegistry#allowedOriginPatterns() is set)

*

*Elucidating the issue with the most typical Spring boot corsMappings:

    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**").allowedMethods("*").allowCredentials(true);
            }
        };
    }

In the above example allowCredentials is set to true, at the same time allowedOrigins is not configured which means by default all origins are allowed (The allowedOrigins value will be *).

*

*To resolve this issue you have to explicitly set the allowedOrigins or allowedOriginPatterns.
In the following code snippet, the allowedOriginPatterns is used and the value is set to -> "https://*.domain.com". This wildcard pattern matches any host from domain.com and url patterns like https:microservice.division.domain.com
    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**").allowedMethods("*").allowedOriginPatterns("https://*.domain.com");
            }
        };
    }

Complete code snippet link

A: Changing corsConfiguration.setAllowedOrigins("*")
to corsConfiguration.setAllowedOriginPatterns("*") did the trick for me!
so basically setAllowedOrigins to setAllowedOriginPatterns

A: This could be due to a change in Spring libraries, thus affecting Spring Boot 2.4.0.
Look here https://github.com/spring-projects/spring-framework/issues/26111 and to its related ticket https://github.com/spring-projects/spring-framework/pull/26108
EDIT
Here the original message from the 1st link:

#25016 introduced the ability to configure allowedOriginPatterns in addition to just allowedOrigins. It lets you define more flexible
patterns while the latter is literally the value to return in the
Access-Control-Allow-Origin header and for that "*" is not allowed in
combination with allowCredentials=true. The change introduced
equivalent allowedOriginPatterns methods in the WebMvc and the WebFlux
config, but not in the SockJS config and the AbstractSocketJsService.
I'll add those for 5.3.2. You'll then need to switch to
allowedOriginPatterns instead of allowedOrigins but that gives you an
option to define more precisely the allowed domain patterns. In the
mean time, you might be able to work around by listing specific
domains if that's feasible.

A: try the following on your Controller
@CrossOrigin(origins = "*", allowCredentials = "true", allowedHeaders = "*", exposedHeaders = "If-Match")

A: The cors error came from Handling ambiguous handler errors for my two get methods.
I got two get methods in my controller one took an integer the other a String. So it couldn't really figure out to parse a string or int (I think) I've changed bot paths of the get methods to:
 @GetMapping("/id/{id}")
    public UserDTO getUser(@PathVariable final Long id) {
        return userService.get(id);
    }

    @GetMapping("/email/{email}")
    public UserDTO getUserByMail(@PathVariable String email) {
        return userService.getByEmail(email);
    }

This fixed the cors error aswell with @CrossOrigin(origins = "*", allowedHeaders = "*")
in the controller.

A: My Scenario when I got the error is:
I've added the Spring Boot Security Dependency in my Spring Boot Server Application.
Similar to your trail, I've added the CrossOrigin() Annotation to resolve the issue. But the issue didn't get solved.
I solved the issue by added the basic authentication to my header options of the request.
Please refer to the post to know about adding basic authentication to the header:
Angular 6 HTTP Get request with HTTP-Basic authentication
import { HttpHeaders } from '@angular/common/http';

const httpOptions = {
headers: new HttpHeaders({
'Content-Type':  'application/json',
'Authorization': 'Basic ' + btoa('username:password')
})
};

Replace username and password with your username and password.
By default username in Spring boot is 'user' and password will be generated on the console where the spring boot application is started.
NOTE: You also have to add the CrossOrigin Annotation to your RequestMapping as well.
Since You are using Basic Authentication, You should add WebSecurityConfiguration to allow Security Configuration as below:
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().anyRequest().authenticated().and().httpBasic();
        http.cors();
    }
}

References:

*

*https://www.baeldung.com/spring-security-cors-preflight

*https://www.baeldung.com/spring-security-basic-authentication
Hope the solution have helped you.
Thanks
Chandu

A: You should create a classs with name "", the code is the following
package com.api.juego.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    private final long MAX_AGE_SECS = 3600;

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
        .allowedOrigins("*")
        .allowedMethods("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS")
        .allowedHeaders("*")
        .allowCredentials(false)
        .maxAge(MAX_AGE_SECS);
    }
}

For security reason the methos allowed are GET, POST, PUT, PATCH, DELETE and OPTIONS.

A: Recently I faced same issue and tried all possible ways but it didn't work out. I am using spring 2.6.7 and I added below code to resolve the same.
In Spring boot main class you can add below code
@Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**").allowedOrigins("*").allowedMethods("*");
            }
        };
    }

you can see I have added addMapping("/**").allowedOrigins("*").allowedMethods("*");
Happy Coding !!


text:
Q: MySQL select query and PHP convert as nested JSON object I am try to retrieve unique object with nested object property and value, is there a possible way to retrieve as json object key and their child property and value
SELECT id,name,year FROM `v_exam_schedule` ORDER BY year ASC;

+----+----------+----------+
| id | name     | year     |
+----+----------+----------+
|  3 | MID TERM | 2021     |
|  4 | Fina Exam| 2021     |
|  1 | Monthly  | 2022     |
+----+----------+----------+
3 rows in set (0.001 sec)

php code for json encoding result of array

$arr = array();
$q = $db->query("SELECT id,name,year FROM `v_exam_schedule` ORDER BY year ASC");

while ($rs = $q->fetch_assoc()) {
    $arr[] = array(
               $rs['year'] => array(
                    "id" => $rs['id'],
                    "name" => $rs['name']
               )
       );
}
exit(json_encode($arr));

Result php code
[
    {
        "2022": {
            "id": "1",
            "name": "Monthly"
        }
    },
    {
        "2021": {
            "id": "3",
            "name": "MID TERM"
        }
    },
    {
        "2021": {
            "id": "4",
            "name": "FINAL EXAM"
        }
    }
]

I want to retrieve with unique object key for year like this below

[
    {
        "2022": {
            "id": "1",
            "name": "Monthly"
        }
    },
    {
        "2021": [
                  {
                      "id": "4",
                      "name": "FINAL EXAM"
                  },
                  {
                     "id": "3",
                     "name": "MID TERM"
                  }
               ]
    }
]

A: Just change your code a bit:
$arr = [];//define array
while ($rs = $q->fetch_assoc()) {
   //Do year base assignments
    $arr[$rs['year']][] = array(
               $rs['year'] => array(
                    "id" => $rs['id'],
                    "name" => $rs['name']
               )
       );
}

exit(json_encode(($arr)));


text:
Q: If $\lim_{x \rightarrow 0}\frac{f(x)}{x^2} = 5$, then what is $\lim_{x \rightarrow 0}f(x)$? I know the answer to the above question, but I have a question on some of the reasoning.
The way I know how to solve it is $$\lim_{x \rightarrow 0}f(x) = \lim_{x \rightarrow 0}\left(f(x)\cdot \frac{x^2}{x^2}\right) = \lim_{x \rightarrow 0}\left(\frac{f(x)}{x^2}\cdot x^2\right) = \left(\lim_{x \rightarrow 0}\frac{f(x)}{x^2}\right)\left(\lim_{x \rightarrow 0}x^2\right) = 5\cdot0 = 0.$$
I saw another solution elsewhere that gets the right answer, but I am unsure if the steps are actually correct.
\begin{align*}
&\lim_{x \rightarrow 0}\frac{f(x)}{x^2} = 5 \\
\Longrightarrow &\frac{\lim_{x \rightarrow 0}f(x)}{\lim_{x \rightarrow 0}x^2} = 5 \\
\Longrightarrow &\lim_{x \rightarrow 0}f(x) = 5\cdot \lim_{x \rightarrow 0}x^2\\ \Longrightarrow &\lim_{x \rightarrow 0}f(x) = 5\cdot 0 = 0.
\end{align*}
My issue is with that first step. I know that $\lim_{x \rightarrow a} \frac{f(x)}{g(x)} = \frac{\lim_{x \rightarrow a}f(x)}{\lim_{x \rightarrow a}g(x)}$, but only when $\lim_{x \rightarrow a}g(x) \neq 0$. Since $\lim_{x \rightarrow 0}x^2 = 0$, wouldn't this invalidate the above work? However, it still got the same answer, so my real question is why did it work and when will it work in general?
EDIT: Does anyone have a nice example for when the logic in the second method doesn't work?

A: $$\frac{\lim_{x \rightarrow 0}f(x)}{\lim_{x \rightarrow 0}x^2} = 5$$ doesn't work, the LHS is not defined.

But for the limit of $\dfrac{f(x)}{x^2}$ to exist, $\lim_{x\to0}f(x)$ must be zero, which is also the limit of $x^2$.

A: If $\lim\limits_{x\to0}\dfrac{f(x)}{x^2}=5$, then for every $n\in\Bbb N$ there is some $x\neq 0$ such that
$$5-\frac1n<\frac{f(x)}{x^2}<5+\frac1n$$
and hence
$$5x^2-\frac{x^2}n<f(x)<5x^2+\frac{x^2}n$$
If $x\to 0$ we get $f(x)\to 0$.

A: You can not do this since the denominator on the right is $0$.
$$\lim_{x \rightarrow 0}\frac{f(x)}{x^2} =
\frac{\lim_{x \rightarrow 0}f(x)}{\lim_{x \rightarrow 0}x^2}$$
But first aproach is perfect.


text:
Q: Validate 5 Combo Boxes is Not choose Same Value I need to ask how to validate Each combo box is not select same value
ex :
Filter by :

*

*[Combobox] [TextBox] And

*[Combobox] [TextBox] And

*[Combobox] [TextBox] And

*[Combobox] [TextBox] And

*[Combobox] [TextBox]

We have five combobox And value for each Combobox is

*

*Name

*Job

*Age

*City

*Place

What I want to Achieve is If Combobox 1 and 3 Choose Name its Said that "Can't choose 2 Filter type"


text:
Q: anaconda numpy, theano and pymc3 installation on windows 10 64bit As a beginner, I tried to install pymc3 on my surface pro 4/win 10 64bit, searched several information on the web and struggled with several problems. Now I want to share my experience and ask some questions.
First, I chose winpython 3.5.2.3Qt5 with python 3.5. However I faced collapse errors when I run the pymc3 start example Linear Regression model enter link description here:sometimes is "kernel died", sometimes is "ImportError: DLL load failed:initialization routine failed". To solve the problem I searched blogs/articles and found other people recommend anaconda with python 2.7 enter link description here. Also someone said theano 0.8.2 is just only support python 3.4, not 3.5. I guess there are some compatible issues to result in the collapse.
So at last I install anaconda 4.2 64bit with python 2.7.
Questions 1: Since from anaconda 2.5 MKL is free and auto installed, I tested the links between numpy and MKL according to some blogs.
1)
numpy.__config__.show()
lapack_opt_info:
    libraries = ['mkl_core_dll', 'mkl_intel_lp64_dll', 'mkl_intel_thread_dll']
    library_dirs = ['C:/Users/sejab/Anaconda2\\Library\\lib']
    define_macros = [('SCIPY_MKL_H', None), ('HAVE_CBLAS', None)]
    include_dirs = ['C:/Users/sejab/Anaconda2\\Library\\include']
blas_opt_info:
    libraries = ['mkl_core_dll', 'mkl_intel_lp64_dll', 'mkl_intel_thread_dll']
    library_dirs = ['C:/Users/sejab/Anaconda2\\Library\\lib']
    define_macros = [('SCIPY_MKL_H', None), ('HAVE_CBLAS', None)]
    include_dirs = ['C:/Users/sejab/Anaconda2\\Library\\include']
openblas_lapack_info:
  NOT AVAILABLE
lapack_mkl_info:
    libraries = ['mkl_core_dll', 'mkl_intel_lp64_dll', 'mkl_intel_thread_dll']
    library_dirs = ['C:/Users/sejab/Anaconda2\\Library\\lib']
    define_macros = [('SCIPY_MKL_H', None), ('HAVE_CBLAS', None)]
    include_dirs = ['C:/Users/sejab/Anaconda2\\Library\\include']
blas_mkl_info:
    libraries = ['mkl_core_dll', 'mkl_intel_lp64_dll', 'mkl_intel_thread_dll']
    library_dirs = ['C:/Users/sejab/Anaconda2\\Library\\lib']
    define_macros = [('SCIPY_MKL_H', None), ('HAVE_CBLAS', None)]
    include_dirs = ['C:/Users/sejab/Anaconda2\\Library\\include']

but there is no mkl_intel_lp64 files in the anaconda folder. Does it not matter?
2)id(numpy.dot) == id(numpy.core.multiarray.dot) >> True
someone said if they are linked, numpy should use numpy.core._dotblas. Does it means numpy dot also use the multiarray rather than MKL blas in the environment?
In a word, is numpy automatically link with MKL in anaconda?
Second, Theano is a special package as it need c/c++ and cuda compile configuration. Because my laptop doesn't have Nvidia GPU, I only need to concern c/c++ compile environment. Official theano installation guide and many articles/blogs suggest that first use conda install mingw libpython
and then git. However, I foundconda install theanohave already included mingw64 (may be TDM-GCC 64?) component and libpython. So I just run the command to install theano and thought it enough. Then I put the path of g++ to system path
(in my environment, it is

"C:\Users\sejab\Anaconda2\Library\mingw-w64\bin",  "C:\Users\sejab\Anaconda2\Library\mingw-w64\x86_64-w64-mingw32\bin"
  and corresponding "include" path).

To verify the installation, use the test program
import numpy as np
import time
import theano
A = np.random.rand(1000,10000).astype(theano.config.floatX)
B = np.random.rand(10000,1000).astype(theano.config.floatX)
np_start = time.time()
AB = A.dot(B)
np_end = time.time()
X,Y = theano.tensor.matrices('XY')
mf = theano.function([X,Y],X.dot(Y))
t_start = time.time()
tAB = mf(A,B)
t_end = time.time()
print("NP time: %f[s], theano time: %f[s] (times should be close when run on CPU!)" %(np_end-np_start, t_end-t_start))
print("Result difference: %f" % (np.abs(AB-tAB).max(), ))

It's OK. Result difference: 0.000000.
Third, I follow the instruction on the official manual installation guide and other blogs,
1) downloaded precompiled OpenBLAS-v0.2.19-Win64-int32.zip and extract into c:\, put its bin and include path into system path;
2) Create a .theanorc.txt in the root

C:\Users\sejab

and write into
[global]
device = cpu
floatX = float64

[blas]
ldflags = -LC:/OpenBLAS-v0.2.19-Win64-int32/bin -lopenblas

to config the oopenblas with theano. Run the test above again,
NP time: 0.431000[s], theano time: 0.307000[s] (times should be close when run on CPU!)
Result difference: 0.000000.
If floatX = float32, the Result difference is not 0.
Question 2: is there another way to verify the link between theano and openblas? The test CPU time is change even fix the value of Matrix A, B.
Question 3: in the test, is theano automatically use multicore? If not, how to config it?
Finally, I used conda install -c conda-forge pymc3 to install pymc3. It showed no problem to solve the same Linear Regression model in pymc3 official tutorial.
It's a little long, but I hope it can help others.


text:
Q: How to save my generated QR code image? I am in process of learning.I wanted to try an qrcode generator project.The project works fine.I have two small doubts.Can someone suggest me anything,It would be very helpful.Thank you guys.
1.How can I save my generated QR code image ?
2.How to set a limit for data entry ? (i mean to set a limit for the value to be entered in the code)
<!DOCTYPE html>

     <title>QRCode generator </title>
     <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
     <meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=no" />

     <input id="text" type="string" value={"foo":"35"};  style="width:80%" />


text:
Q: Nested model properties value null I have below class which contains nested model property
public class TestClass
    {
        public string DropdownControlHtml { get; set; }

        public TestClass1 TestClass1 { get; set; } = new();
    }

From controller i am returning object of testClass class like below
return View(testClass);

But when I submit form I am getting all the property of testClass as null.My button type is Button and using ajax call to post form data.

A: You need to make sure the name of properties of TestClass1 is right.For example:
TestClass1 :
 public class TestClass1 {
        public string Id { get; set; }
    }

view:
<form id="frmCustAppSelection" method="post">
    <select name="DropdownControlHtml">
        <option value="1">1</option>
        <option value="2">2</option>
        <option value="3">3</option>

    </select>
    <input name="TestClass1[Id]" />
    <input type="button" onclick="postdata()" value="test">
</form>
<script>
        function postdata() {
            $.ajax({
                url: "GetTestClass",
                type: 'post',
                data:$("#frmCustAppSelection").serialize(),
                success: function (response) {
                }
                });
        }
</script>

Action:
public IActionResult GetTestClass(TestClass testClass)
        {
            return View(testClass);
        }


text:
Q: How to get a row that one column's value in this row has appear more than 100 times in this table I have a courseinfo table in MySql,
it has four columns
id INT(10), cno INT(10), sno INT(10), cname VARCHAR(10)

I want to have the cname's value where the corresponding cno appears more than 100 times in this table.
Example:

1,10,12, math
2,8, 13, science
3,8, 9, science
4,8, 10, science,

So what I want is to find the cname if cno appear more than 100 times.
BTW, the cno always correspond to cname.
Does the function COUNT() help?
Thanks!

A: Try
SELECT cname
  FROM table_name
 GROUP BY cname
HAVING COUNT(cname) > 100

or
SELECT cno, cname
  FROM table_name
 GROUP BY cno, cname
HAVING COUNT(cno) > 100

or just
SELECT cname
  FROM table_name
 GROUP BY cno
HAVING COUNT(cno) > 100

A: Need a 'group' function on the column we are not grouping by
Untested code:
SELECT cno, max(cname) as cname,
FROM courseinfo
GROUP BY cno
HAVING count(cno) > 100


text:
Q: Is there any way to see why my v7.6 Elasticsearch mapping isn't working and defaulting to the base mapping? I'm upgrading my Elasticsearch project from v6.6 to v7.6.2. I use Elasticsearch.NET and NEST in order to create my index including mappings, settings, and to ingest my data into Elasticsearch from my SQL db.
Everything works well in v6.6, but when I upgraded to v7.6.2, it no longer accepts my custom mappings and settings. I'm referring to things like my nested objects, my custom analyzers, etc. The data does get ingested, but it defaults to the, well, default mapping (where mostly everything is a keyword or simple data type).
This type of behavior normally happens when there's something syntactically wrong in your mappings or in your POCO. This isn't my case, I don't think.
Is there some breaking change in v7.x that I may have missed? I've been through the documentation fairly extensively.
To give an example of what my mapping should look like, here's an excerpt (from my v6.6 cluster).
...notice things like the 'products' object is of type: nested...
[{"searchdata":{"_all":{"enabled":false},"properties":{"groupid":{"type":"text","fields":{"keyword":{"type":"keyword","ignore_above":256}}},"products":{"type":"nested","properties":{"adddate":{"type":"date"},"additionaltitles":{"type":"text"},"additionaltitleslist":{"type":"text","fields":{"keyword":{"type":"keyword","ignore_above":256}}},"adult":{"type":"integer"},"artists":{"properties":{"id":{"type":"text","fields":{"keyword":{"type":"keyword","ignore_above":256}}},"name":{"type":"text","norms":false,"fields":{"ci":{"type":"text","norms":false,"analyzer":"caseInsensitive"},"nc":{"type":"text","norms":false,"analyzer":"titleNoCharAnalyzer"},"raw":

and here's what it shows as the default version in v7.6.2...
...notice things like the 'products' object not nested, and lots of 'keyword' types, no custom analyzers, etc. ...
    [{"_doc":{"properties":{"groupid":{"type":"text","fields":{"keyword":{"type":"keyword","ignore_above":256}}},"products":{"properties":{"adult":{"type":"long"},"artists":{"properties":{"id":{"type":"text","fields":{"keyword":{"type":"keyword","ignore_above":256}}},"name":{"type":"text","fields":{"keyword":{"type":"keyword","ignore_above":256}}},"nameidsplit":{"type":"text","fields":{"keyword":{"type":"keyword","ignore_above":256}}},"nameremarticle":{"type":"text","fields":{"keyword":{"type":"keyword","ignore_above":256}}}}},"catalognum":{"type":"text","fields":{"keyword":{"type":"keyword","ignore_above":256}}},"costprice":{"type":"float"},"cover":{"type":"text","fields":{"keyword":{"type":"keyword","ignore_above":256}}},"credits":{"properties":{"id":{"type":"text","fields":{"keyword":{"type":"keyword","ignore_above":256}}},"name":{"type":"text","fields":{"keyword":{"type":"keyword","ignore_above":256}}},"nameidsplit":{"type":"text","fields":{"keyword":{"type":"keyword","ignore_above":256}}},"nameremarticle":{"type":"text","fields":

As you may be able to notice, the v6.6 version is much more detailed and contains my nested objects, etc. But my v7.6.2 version contains the basic, default structure.
Something must be going wrong here but I don't know what.
Is there some debug logging level that I can enable that will tell me why it's "failing"?
UPDATE
So I'm putting a slightly abbreviated version of how I'm mapping my objects and settings here. Hopefully this helps to understand this issue.
var indexCreate = client.Indices.Create(indexName, nc => nc
.Settings(st => st
    .RefreshInterval(60) //slowing the refresh interval so we can get a running count
    .NumberOfReplicas(0) //must be set to refresh after created
    .NumberOfShards(numOfShards)
    .Analysis(a => a
        .Analyzers(an => an
            .UserDefined("fullTermCaseInsensitive", FullTermCaseInsensitive)
            .UserDefined("fullTerm", FullTerm)
            .UserDefined("caseInsensitive", CaseInsensitive)
        )
        .TokenFilters(tf => tf
            .UserDefined("syn", Syn)
            .UserDefined("myStopFilter", MyStopFilter)
            .UserDefined("wordDelimiter", WordDelimiter)
        )
    )
)
.Map<Store24>(m => m
    .Dynamic(false)

    .AutoMap()
    .Properties(props =>
    {
        SetPutMappingStore24(props); //see function below
        return props;
    })
));

       private static void SetPutMappingStore24(PropertiesDescriptor<Store24> pm)
       {
            pm.Nested<Product>(x => x
                .AutoMap()
                .Name(nm => nm.Products)
                .Properties(pr => pr
                    .Nested<StorePriceSplit>(sp => sp
                        .Name("storeprice").AutoMap()
                    )
                .Properties(props =>
                    {
                        SetPutMappingDescriptorTiWo(props, "tracks");
                        SetPutMappingDescriptorTiWo(props, "title");
                    }
                )
           );

       //...... more fluent mappings here
       }

    [ElasticsearchType(IdProperty = "Groupid")]
    public class Store24
    {
        /// <summary>
        /// Identifiers
        /// </summary>
        [Key]
        [Keyword]
        public string Groupid { get; set; }

        [JsonIgnore]
        public string Upc { get; set; }

        [JsonIgnore]
        public string Titleremarticle { get; set; }

        [Nested]
        [PropertyName("products")]
        public IEnumerable<Product> Products { get; set; }

    //... more properties here
    }

    [ElasticsearchType(RelationName = "product")]
    public class Product
    {
        [Key]
        [Text(Analyzer = "fullTermCaseInsensitive")]
        public string Upc { get; set; }

        [Text(Analyzer = "fullTermCaseInsensitive", Fielddata = true)]
        public string Titleremarticle { get; set; }

    //...more properties here
    }

I use two objects, one called Store24 which maps from the data returned from SQL and one called Product which creates the Elasticsearch mapping.

A: I figured out my own issue. It seems the creating of the index was throwing an error but I wasn't seeing it. It was being 'hidden' by the response to the Indices.Create() returned object. (the var indexCreate object in my sample above). Once I poked at it, the following error was being thrown: "Token filter [wordDelimiter] cannot be used to parse synonyms".
This was an issue in my settings -  I guess a breaking change for 7.x that I didn't see. A rather complex issue actually.


text:
Q: Xamarin Forms: Azure AD B2C using MSAL: Set Client Id through code I am trying to use MSAL for Azure AD B2C authentication in Xamarin forms.
I have followed this tutorial:
Tutorial
But this asks to set the client id in Intent Filter. What if i am building a product and it needs to be distributed to more then one customer through public store?
Is there any way we can set the client ID programmatically?
Please help.
Thank you.

A: You should not set client ID programmatically.
If you want your customer from different tenants to use your B2C project, you just need to configure your Azure AD app as multi-tenant.
Just like the document you shared mentions:

Select Accounts in any organizational directory or any identity
  provider.

And then you could Set up sign-in for multi-tenant Azure Active Directory using custom policies in Azure Active Directory B2C. Then customer will be able to log into your project with their own credentials.
In fact, you don't even need to configure sign-in for multi-tenant Azure Active Directory using custom policies. Customers could sign up to your B2C tenant to use your product. This is exactly how B2C works.

A: The client id used in the IntentFilter on that particular tutorial is for the DataScheme which needs to be unique, so AAD knows where to redirect after the authentication screen. You could use a different value if you want. It is common to use the reverse-DNS for that field (as for the app package).
In other words, clientId is not mandatory for that field.


text:
Q: Proving that the sequence $a_0=1, a_{n+1}=\cos(a_n)$ converges Consider the following recursively defined sequence:
$$a_0 = 1, a_{n+1}=\cos\left(a_n\right)$$
Having a look with Wolfram Alpha, it's fairly clear that this sequence converges to something in the neighborhood of $0.74$ or so.
However, I have no clue how to actually prove that this sequence is convergent. I've thought about proving that it is a Cauchy sequence - that is, for any given $\varepsilon>0$, there exists an $N\in\mathbb{N}$ such that $|a_n-a_m|<\varepsilon$ for any $n,m>N$.
However, I have no clue how to approach to repeated application of the cosine function, especially since you don't know how many iterations of the cosine function there are between $n$ and $m$.
Looking at the Wolfram Alpha plot of the first 30 terms in the sequence also gave me the idea to separate the whole thing into two subsequences $a_{2n}$ and $a_{2n+1}$ and then prove that they are increasing and decreasing while being bounded, but again I had no idea how to proceed to due to the repeated iteration of the cosine function.
I'd also be interested in a closed form of the limit if there is one, but I'd guess that none exists.

A: By induction, it is easy to prove that
$\forall n\geq 0 \;\; 0\leq a_n \leq 1$.
let $f:x\mapsto \cos(x)$.
$f$ is decreasing from $[0,1]$ to $[0,1]$.
thus $(a_{2n})$ and $(a_{2n+1})$ are monotonic. on the other hand, by MVT,
$$|a_{ 2n+1 }-a_{2n}|=|a_{2n}-a_{2n-1}||\sin(\xi)|\leq \sin(1)|a_{2n}-a_{2n-1}|$$
This is just a Hint, you can finish it.

A: Draw a graph of $y=x$ and $y= \cos x$. Any possible limit has $y=\cos y$ so the points of intersection of the curves are possible limts. Then start bpouncing from one curve to the other: given a $\cos a_n$ go horizontally to hit the linear graph, then vertically to hit the $\cos$ graph  and so on.  If this does not make immediate sense look up pictures of how Newton Raphson convereges (or not) for squre roots.


text:
Q: Update Aptana to 3.3.0.201212131616-13122012161933 has hidden all my connections? I´ve updated Aptana Studio 3 to version 3.3.0.201212131616-13122012161933 and no longer have success to my connections.
Where can I find them and recover?
I'm using Aptana as standalone, not as eclipse plugin.

A: Ok, a new problem results.
I´ve manually retyped all my Connections, so that I did my works yesterday.
But today I started Aptana Studio and all my Connections are gone again!
They are choosable again in the Connection Manager, but after another restart, they are gone again.
Is there a property which I have to enable or disable to keep aptana the connections right to the projects?
thanks
EDIT
I´ve demonstrated my problem by images, because it´s easier to understand as my bad english.
First
I deinstalled Aptana and reinstalled it.
I began to create a new Project and for example three connections for it.
Second
I tested the Connections of functionality and all three are ok!
Then I closed Aptana Studio and resarted it.
No Connection is linked to the Project!
You can see step 1 and 2 here
Third
If I click the "+"-Symbol for a new Connection linked to the project, I can choose the manually added connections from the dropdown list and link it to the project.
See it on last screen here
My conjecture
There must be something to disable or enable to keep the connections linked to the project.
But I don´t know what is my mistake. I handle the studio like in version 3.2.
Is there something changed in 3.3 what I don´t see?
Thanks for help

A: Today, appcelerator has published an update wich is able to fix the problem.
So you can fix it by starting Aptana Studio and run updates. After installation, all connections should be linked to their project as assigned by you!


text:
Q: I want to know rigorous proof of lim x→0 sin(x)/x=1 we gets (sinx)'=cosx from lim x→0 sin(x)/x=1
Geometric proof of it is based on the fact that the area of sector of unit circle with central angle x is x/2
However, when we calculate the area of unit circle, we use the integral of trigonometrical function which derive from (sinx)'=cosx.
That is an circulation logic!
Also, area formula of polar coordination also derives from area of sector, so we can't use it to proof lim x→0 sin(x)/x=1
I tried many other methods, but I can't find any process.
I want to know rigorous proof of lim x→0 sin(x)/x=1 not using the differential and integral of trigonometrical function.
Thank you.