text:
Q: Compare values from two List in Java I have a problem with getting the value from a list. For example, I create an ArrayList from a ResultSet. I want to compare the values of this ResultSet to another ResultSet. My approach is to convert the ResultSets to ArrayLists and then compare them.I already used String.append() but failed to obtain the string.
How to get the value from from the ArrayList?
Can a simple solution be provided?
my code:
main class:
String my_query = "SELECT * FROM test.test_application";

Connection connection = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
Boolean result = false;

DatabaseConnection cc = new DatabaseConnection();
connection = cc.connect();

if (connection != null) {
    pstmt = connection.prepareStatement(my_query);
    rs = pstmt.executeQuery();

    TestingModel tm = new TestingModel();
    Gson gs = new Gson();
    ArrayList<TestingModel> list = new ArrayList<TestingModel>();

    while(rs.next()) {
        tm.setClientID(rs.getInt(1));
        tm.setClientName(rs.getString(2));
        tm.setClientAddress(rs.getString(3));
        tm.setClientTelpNumber(rs.getString(4));
        tm.setClientEmail(rs.getString(5));
        list.add(tm);
    }
    System.out.println(gs.toJson(list));

    StringBuilder string = new StringBuilder();

    for (int i = 0; i < list.size(); i++) {
        System.out.println(string.append(list.get(i).toString()));
    }
}

model:
public class TestingModel {

    private int clientID;
    private String clientName;
    private String clientAddress;
    private String clientTelpNumber;
    private String clientEmail;
    // setter and getter
}

A: What you can do is to override the equals(Object obj) method in your TestingModel class. There,you can use the String.equals(String s) or String.equalsIgnoreCase(String s) depending on your need and also check for equality of other data members.
In you main class, simply iterate through the 'Lists that you have obtained from the ResultSets and call the equals method.
References:

*

*String comparison

*Comparing ArrayLists of same type of objects


text:
Q: How to fix a Gutenburg block error - A component is changing an uncontrolled input of type url to be controlled I am getting this error when I add a value to the buttonUrl input.
A component is changing an uncontrolled input of type url to be controlled. Input elements should not switch from uncontrolled to controlled (or vice versa). Decide between using a controlled or uncontrolled input element for the lifetime of the component.
this is the code for my block.
Also what do i need to change to get a span inside of my h3 subhead.
I have been going around for ages with this. Cheers
 ( function ( blocks, editor, i18n, element, components, _ ) {
    const __ = i18n.__;
    const el = element.createElement;
    const RichText = editor.RichText;
    const MediaUpload = editor.MediaUpload;
    const InspectorControls = editor.InspectorControls;
    const PanelBody = components.PanelBody;
    const TextControl = components.TextControl;
    const SelectControl = components.SelectControl;

    blocks.registerBlockType('unify/about-block', {
        title: __('Unify About Block', 'unify'),
        icon: 'align-left',
        category: 'layout',
        attributes: {
            title: {
                type: 'array',
                source: 'children',
                selector: 'h2',
            },
            subhead: {
                type: 'array',
                source: 'children',
                selector: 'h3',
            },
            content: {
                type: 'string'
            },
            mediaID: {
                type: 'number',
                default: 0
            },
            mediaURL: {
                type: 'string',
                source: 'attribute',
                selector: 'img',
                attribute: 'src',
            },
            buttonText: {
                type: 'string',
                default: ''
            },
            buttonUrl: {
                type: 'url',
                default: ''
            },
            blockColor: {
                type: 'string',
                default: 'brand-dark-blue'
            },
        },
        edit: function ( props ) {
            const attributes = props.attributes;
            const onSelectImage = function ( media ) {
                return props.setAttributes({
                    mediaURL: media.url,
                    mediaID: media.id,
                });
            };
            return el(
                'div',
                {
                    className: props.className
                },
                el(
                    'div',
                    { className: 'column block-content' },
                    el(
                        RichText,
                        {
                            tagName: 'h2',
                            inline: true,
                            placeholder: __('Title', 'unify'),
                            value: attributes.title,
                            onChange: function ( value ) {
                                props.setAttributes({ title : value });
                            },
                        }
                    ),
                    el(
                        RichText,
                        {
                            tagName: 'h3',
                            inline: true,
                            placeholder: __('Subhead', 'unify'),
                            value: attributes.subhead,
                            onChange: function ( value ) {
                                props.setAttributes({ subhead : value });
                            },
                        }
                    ),
                    el(
                        RichText,
                        {
                            tagName: 'p',
                            placeholder: i18n.__('Content', 'unify'),
                            value: attributes.content,
                            onChange: function ( value ) {
                                props.setAttributes({ content : value });
                            }
                        }
                    ),
                    el(
                        'a',
                        {
                            className: 'components-button button button-large is-primary',
                            href: attributes.buttonURL
                        },
                        attributes.buttonText
                    )
                ),
                el(
                    'div',
                    {
                        className: 'column block-image'
                    },
                    el(
                        MediaUpload,
                        {
                            onSelect: onSelectImage, allowedTypes: 'image', value: attributes.mediaID,
                            render: function ( obj ) {
                                return el(
                                    components.Button,
                                    {
                                        className: attributes.mediaID ? 'image-button' : 'button button-large', onClick: obj.open
                                    },
                                    ! attributes.mediaID ? __('Upload Image', 'unify') : el('img', { src: attributes.mediaURL })
                                );
                            },
                        }
                    )
                ),
                el(
                    InspectorControls,
                    {
                        key: 'inspector'
                    },
                    el(
                        PanelBody,
                        { title: i18n.__('Button Link'), className: 'block-button-link', initialOpen: true },
                        el(
                            TextControl,
                            {
                                type: 'url',
                                label: i18n.__('Enter the destination URL for the button'),
                                value: props.attributes.buttonURL,
                                onChange: function ( newButtonURL ) {
                                    console.log(newButtonURL);
                                    props.setAttributes({ buttonURL: newButtonURL });
                                }
                            }
                        ),
                        el(
                            TextControl,
                            {
                                type: 'text',
                                label: i18n.__('Button Text', 'unify'),
                                value: attributes.buttonText,
                                onChange: function (newButtonText) {
                                    props.setAttributes({ buttonText: newButtonText })
                                }
                            }
                        )
                    ),
                    el(
                        PanelBody,
                        { title: i18n.__('Color Settings'), className: 'block-color', initialOpen: false },
                        el(
                            SelectControl,
                            {
                                type: 'string',
                                label: i18n.__('Choose the highlight color for the block'),
                                value: attributes.blockColor ? attributes.blockColor : '',
                                options: [{
                                    label: 'Dark Blue',
                                    value: 'brand-dark-blue'
                                },{
                                    label: 'Light Blue',
                                    value: 'brand-blue'
                                },{
                                    label: 'Green',
                                    value: 'brand-green'
                                },{
                                    label: 'Purple',
                                    value: 'brand-purple'
                                }],
                                onChange: function ( value ) {
                                    props.setAttributes({ blockColor : value });
                                },
                            }
                        ),
                    ),
                )
            )
        },
        save: function ( props ) {
            const attributes = props.attributes;
            return el(
                'section',
                {
                    className: 'about-block-section ' + attributes.blockColor
                },
                el(
                    'div',
                    {
                        className: 'grid-container'
                    },
                    el(
                        'div',
                        {
                            className: 'grid-x grid-padding-x align-center-middle'
                        },
                        el(
                            'div',
                            {
                                className: 'cell small-12 medium-6 large-6 small-order-2 medium-order-1 about-block-image-outer'
                            },
                            el(
                                'div',
                                {
                                    className: 'about-block-image square-aspect-ratio'
                                },
                                attributes.mediaURL ? el(
                                    'img',
                                    {
                                        src: attributes.mediaURL
                                    }
                                ) : ''
                            ),
                        ),
                        el(
                            'div',
                            {
                                className: 'cell small-12 medium-6 large-5 large-offset-1 small-order-2 medium-order-1 about-block-content-outer'
                            },
                            attributes.title ? el(
                                RichText.Content,
                                {
                                    tagName: 'h2',
                                    className: 'about-block-content-title',
                                    value: attributes.title,
                                }
                            ) : '',
                            attributes.subhead ? el(
                                RichText.Content,
                                {
                                    tagName: 'h3',
                                    className: 'about-block-content-subhead',
                                    value: attributes.subhead,
                                }
                            ) : '',
                            attributes.content ? el(
                                RichText.Content,
                                {
                                    tagName: 'p',
                                    className: 'about-block-content-body',
                                    value: attributes.content
                                }
                            ) : '',
                            attributes.buttonURL && attributes.buttonText ? el(
                                'a',
                                {
                                    href: attributes.buttonURL,
                                    className: 'button about-block-content-button'
                                },
                                attributes.buttonText,
                                el(
                                    'i',
                                    { className: 'fas fa-arrow-right'}
                                )
                            ) : ''
                        )
                    )
                )
            )
        },
    });
} )(
    window.wp.blocks,
    window.wp.blockEditor,
    window.wp.i18n,
    window.wp.element,
    window.wp.components,
    window._
);

A: This is likely long after you've resolved this but I believe it'll help someone else. That issue is usually down to a component's value being set as undefined initially. See A component is changing an uncontrolled input of type text to be controlled error in ReactJS
From your error message:

A component is changing an uncontrolled input of type url to be controlled. Input elements should not switch from uncontrolled to controlled (or vice versa). Decide between using a controlled or uncontrolled input element for the lifetime of the component.

You have one component of type URL - TextControl and the value being passed to it is value: props.attributes.buttonURL
So based on that, I believe buttonURL is undefined at some point, which results in that error. To address that, set a default value for buttonURL in the edit.
edit: function ( props ) {
            const attributes = props.attributes;
            const buttonURL = props.attributes && props.attributes.buttonURL ?? props.attributes.buttonURL : '' // Decide on an appropriate default
            const onSelectImage = function ( media ) {
                return props.setAttributes({
                    mediaURL: media.url,
                    mediaID: media.id,
                });
            };

Then use it in the TextControl component - value: props.attributes.buttonURL becomes value: buttonURL

redpajama_set_name: RedPajamaStackExchange


text:
Q: Get User SID From Logon ID (Windows XP and Up) I have a Windows service that needs to access registry hives under HKEY_USERS when users log on, either locally or via Terminal Server. I'm using a WMI query on win32_logonsession to receive events when users log on, and one of the properties I get from that query is a LogonId. To figure out which registry hive I need to access, now, I need the users's SID, which is used as a registry key name beneath HKEY_USERS.
In most cases, I can get this by doing a RelatedObjectQuery like so (in C#):
RelatedObjectQuery relatedQuery = new RelatedObjectQuery( "associators of {Win32_LogonSession.LogonId='" + logonID + "'} WHERE AssocClass=Win32_LoggedOnUser Role=Dependent" );

where "logonID" is the logon session ID from the session query. Running the RelatedObjectQuery will generally give me a SID property that contains exactly what I need.
There are two issues I have with this. First and most importantly, the RelatedObjectQuery will not return any results for a domain user that logs in with cached credentials, disconnected from the domain. Second, I'm not pleased with the performance of this RelatedObjectQuery --- it can take up to several seconds to execute.
Here's a quick and dirty command line program I threw together to experiment with the queries. Rather than setting up to receive events, this just enumerates the users on the local machine:
using System;
using System.Collections.Generic;
using System.Text;
using System.Management;

namespace EnumUsersTest
{
    class Program
    {
        static void Main( string[] args )
        {
            ManagementScope scope = new ManagementScope( "\\\\.\\root\\cimv2" );

            string queryString = "select * from win32_logonsession";                          // for all sessions
            //string queryString = "select * from win32_logonsession where logontype = 2";     // for local interactive sessions only

            ManagementObjectSearcher sessionQuery = new ManagementObjectSearcher( scope, new SelectQuery( queryString ) );
            ManagementObjectCollection logonSessions = sessionQuery.Get();
            foreach ( ManagementObject logonSession in logonSessions )
            {
                string logonID = logonSession["LogonId"].ToString();
                Console.WriteLine( "=== {0}, type {1} ===", logonID, logonSession["LogonType"].ToString() );
                RelatedObjectQuery relatedQuery = new RelatedObjectQuery( "associators of {Win32_LogonSession.LogonId='" + logonID + "'} WHERE AssocClass=Win32_LoggedOnUser Role=Dependent" );
                ManagementObjectSearcher userQuery = new ManagementObjectSearcher( scope, relatedQuery );
                ManagementObjectCollection users = userQuery.Get();
                foreach ( ManagementObject user in users )
                {
                    PrintProperties( user.Properties );
                }
            }

            Console.WriteLine( "\nDone! Press a key to exit..." );
            Console.ReadKey( true );
        }

        private static void PrintProperty( PropertyData pd )
        {
            string value = "null";
            string valueType = "n/a";
            if ( pd.Value != null )
            {
                value = pd.Value.ToString();
                valueType = pd.Value.GetType().ToString();
            }

            Console.WriteLine( "  \"{0}\" = ({1}) \"{2}\"", pd.Name, valueType, value );
        }

        private static void PrintProperties( PropertyDataCollection properties )
        {
            foreach ( PropertyData pd in properties )
            {
                PrintProperty( pd );
            }
        }
    }
}

So... is there way to quickly and reliably obtain the user SID given the information I retrieve from WMI, or should I be looking at using something like SENS instead?

A: I asked a very similar question a while back and got this answer: how to get a SID from a windows username.
I was planning on using SystemEvents to detect when a user logs on to windows, then looping through the logged on users list at that point to detect all the logged on users. (Here's my question, about all this including references for detecting logons and current users.)
If you decide on an approach please post an update - I'd be interested to hear what you find works well.

A: Another simple way:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion \ProfileList

A: Another working answer (code in VB.Net)
Public Function GetSIDfromAccName(ByVal strAccName As String) As String
        Debug.WriteLine("***WMI-GetSIDfromAccName***")
        Dim strSID As String = ""
        Try
            Dim wmiClass As System.Management.SelectQuery = New System.Management.SelectQuery(("Select * from Win32_UserAccount where Name='" _
              + (strAccName + "'")))
            Dim wmiSearcher As System.Management.ManagementObjectSearcher = New System.Management.ManagementObjectSearcher(wmiClass)
            For Each val As System.Management.ManagementBaseObject In wmiSearcher.Get
                strSID = val("SID").ToString
            Next
        Catch e As Exception
            Debug.WriteLine(e.ToString)
        End Try
        Return strSID
    End Function

A: Powershell is easier.
Function GetSIDfromAcctName()
{
$myacct = Get-WmiObject Win32_UserAccount -filter "Name = '$env:USERNAME "
write-host Name: $myacct.name
Write-Host SID : $myacct.sid
}


text:
Q: Ubuntu has wrong resolution and won't let me change it Ubuntu 15.04 x64 gives me 800x600 when my screen can output 1600x900. I went into my display settings and there was only one option. Anything I can do to fix it?
    lspci -k | grep -EA2 'VGA|3D'
Outputs
VGA compatible controller: Advanced Micro Devices, Inc. [AMD/ATI] Kabini

[Radeon HD 8240 / R3 Series]
Subsystem: Acer Incorporated [ALI] Device 083a
Kernal driver in use: fglrx_pci
Sorry for formatting issues

A: Run
sudo apt-get install mesa-utils

in terminal.This should hep you to change to correct resolution.
In case your drivers are not upto date , try installing proprietary drivers from the Software and Updates section of ubuntu.


text:
Q: How to use UIImage to show picture at the same time let the black part of pic hidden I just have processed picture with thresholding with Swift 4.2, and OpenCV. However, I want to use the result UIImage as foreground to overlay the other background image. At the same time, I want to crop the black part of the foreground, and leave only the white part visible. How can I deal with this problem?

A: I just got it!
I modify the Mat before I transform it to UIImage. The basic method is naive. I only determine the value of the 4th dimension of Mat, which represents the opacity. (You can ignore the inversion. That's used for keeping the part I want to left)
    int size[3] = { resultGrayMat.rows, resultGrayMat.cols, 4 };
    cv::Mat resultRGBAMat(3, size, CV_32F, cv::Scalar(0));
    cv::cvtColor(resultGrayMat, resultRGBAMat, cv::COLOR_GRAY2RGBA);
    for (int i = 0; i < size[0]; i++) {
        for (int j = 0; j < size[1]; j++) {
            resultRGBAMat.at<cv::Vec4b>(i,j)[0] = 255 -  resultRGBAMat.at<cv::Vec4b>(i,j)[0];
            resultRGBAMat.at<cv::Vec4b>(i,j)[1] = 255 -  resultRGBAMat.at<cv::Vec4b>(i,j)[1];
            resultRGBAMat.at<cv::Vec4b>(i,j)[2] = 255 -  resultRGBAMat.at<cv::Vec4b>(i,j)[2];
            resultRGBAMat.at<cv::Vec4b>(i,j)[3] =(resultRGBAMat.at<cv::Vec4b>(i,j)[0]==255)? 255:0;
        }
    }


text:
Q: Need a mix of Delayed and Map I have an application without a save button; saving happens automatically in the background. As the user works with the app, tasks are created and put into a queue for execution. Some of them are delayed, for example, when you start typing, I wait 200ms before I update the corresponding value in the database.
To make this more simple to use code wise, I'd like to be able to add a task to the queue with a delay and a "key". If there is already a task with the same "key", then my second task should be ignored (because the same operation is already queued).
Does something like that already exist?

A: I think you should look into TreeMap class. Use the constructor which let you pass a Comparator. This way you can let the Map sort on Delayed (since this class implements Comparable interface). Before adding a "Task" to the map, check if the key already exists using containsKey method.

A: This is how I understood the question and would take the challenge:
A task wrapper wraps a task or command and adds the additional values, the delay for the task and the identifier. I understood, that two tasks may have the same 'key', so we can't just take the tasks hashvalue.
public TaskWrapper<T> {
   private T task;
   private long delayInMillis;
   private long key;

   public TaskWrapper(T task, long delayInMillis, long key) {
     this.task = task;
     this.delayInMillis = delayInMillis;
     this.key = key;
   }

   // getter, setters, and so on

   public boolean equals(Object o) {
      if (o == null || !(o instanceof TaskWrapper)) return false;
      return key == ((TaskWrapper) o).key;
   }
}

A queue decorator adds the 'set' like behaviour. A queue doesn't have 'contains' method, so I take an additional Set to record the objects that are actually enqued. All methods that change the queue will be implemented to keep the consistency between the internal queue and the set. This quick draft is not thread safe and shows just the add method.
public SetQueue<TaskWrapper> implements Queue<T> {
  private Queue<TaskWrapper> queue;
  private Set<TaskWrapper> set = new HashSet<TaskWrapper>();

  public SetQueue(Queue<TaskWrapper> queue) {
    this.queue = queue;
  }

  // just to demonstrate the idea
  public boolean add(TaskWrapper<?> task) {
     if (set.contains(task)
        return false;
     boolean result = queue.add(task);
     if (result)
        set.add(task);
     return result;
  }

(may be full of bugs, I don't have an IDE at hand. It's just a draft)

A: One of the elegant solution that came into my mind: use a thread pool executer that has a priority blocking queue as working queue.


text:
Q: Making a Linked List in Java I am adding elements in a Linked List via scanning the elements one by one using a for loop, but at the end there is a 0 coming while printing the list. The last node is pointing to null but still the list is having one element that is 0. I am providing my source code below and then inputs
import java.util.Scanner;
import static java.lang.System.out;
class Node{
    int data;
    Node next;
    Node(){
       this.next=null;
          }
    Node(int data){
        this.data=data;
        this.next=null;
          }
}
public class MyClass{
    public static void main(String args[]) {
        Node head=new Node();
        Node temp=head;
        Scanner sc = new Scanner(System.in);
        int size=sc.nextInt();
        for(int i=1;i<=size;i++){
            temp.data=sc.nextInt();
            temp.next=new Node();
            temp=temp.next;
        }
        temp=null;
        while(head!=null){
            out.print(head.data+" ");
            head=head.next;
        }
    }
  }

Inputs:
5 1 2 3 4 5

A: The next pointer in the last node of a linked list should be null to denote that it is the last node.
In your case, you are keeping it 'not null'. In your for loop, just don't instantiate the next pointer if it is the last element you are reading.
    for(int i=1;i<=size;i++){
        temp.data=sc.nextInt();
        if(i != size) {
           temp.next=new Node();
           temp=temp.next;
        }
    }

A: You're creating the head-node outside of the loop and a new node within it.
You therefore get 1 extra node.
You might try the following:
public static void main(String args[]) {
    Node head=null;
    Node last=null;
    Scanner sc = new Scanner(System.in);
    int size=sc.nextInt();
    for(int i=1;i<=size;i++){
        if (head == null){
            head = new Node();
            last = head;
        } else {
            last.next = new Node();
            last = last.next();
        }
        last.data=sc.nextInt();
    }
    while(head!=null){
        out.print(head.data+" ");
        head=head.next;
    }
}

A: The problem is that even though you are setting temp=null after you exit your loop, you still have one extra unassigned node.
The simplest fix is to remove the '=' sign in your for loop so that you exit the loop after your last node and then assign your final value, like this:
    for(int i=1;i<size;i++){
        temp.data=sc.nextInt();
        temp.next=new Node();
        temp=temp.next;
    }
    temp.data=sc.nextInt();


text:
Q: SharePoint site workflow I have a question, I have created a SharePoint workflow using designer and I need to run the workflow at the first of each month and it should check all the records created on that month. How can I achieve this?
Someone said I can achieve this using site workflow, however I cant find where I can say run at the first of each month?
Kind Regards

A: For SharePoint designer workflow, using 2013 workflow will be an option like this blog. You will need to construct a loop inside and there will not be an normal way to stop it.
If you are using SharePoint Online, it may be better to use Flow for recurring events


text:
Q: Is there an iPhone-like Keychain in Android? I'm looking for something like the Keychain on the iPhone, but for Android development. Something that gives me the capability to save small key-value pairs that are persistent and unchanged even if the user reinstalls the application.
Is there something like that? Can I use the standard preferences that way?
I would like to achieve a behavior similar to the way it works with games on a PC - writing the save files to another folder so that after deletion and reinstallation the save files are not lost.

Edit:
The bounty ran out without somebody mentioning the accountManager. I just stumbled over it. Would that be a method to achieve the behaviour described by me?

A: You you use storage on the SD card like Michael Cramer stated ( Let the user know you are storing data :-) ). The data on the SD card is not deleted when the app is removed.
You could on the other hand use a server which stores all the details which can be downloaded as and when required and instead of using a user name use the IMEI of the phone which is unique. That way even if the user reinstalls the OS he will still be able to refetch the settings.
for getting the IMEI you may refer : How to get the device's IMEI/ESN programmatically in android?

A: You have the real thing here:

By integrating Smart Lock for Passwords into your Android app, you can
  automatically sign users in to your app using the credentials they
  have saved. Users can save both username-password credentials and
  federated identity provider credentials.
Integrate Smart Lock for Passwords into your app by using the
  Credentials API to retrieve saved credentials on sign-in. Use
  successfully retrieved credentials to sign the user in, or use the
  Credentials API to rapidly on-board new users by partially completing
  your app's sign in or sign up form. Prompt users after sign-in or
  sign-up to store their credentials for future automatic
  authentication.

https://developers.google.com/identity/smartlock-passwords/android/

A: Since Android & iPhone-like phones will normally run with a data plan, I would suggest that you save your key-value pairs into a centralized server. When the app goes through the uninstall, followed by an install process, just resync it with your server.

A: Yes. Preferences are persistant and will survive a normal application upgrade.


text:
Q: Chrome 'Aw, snap' error only on mobilel I am a newbie and am developing and hosting a website for the first time. I have a rails app, running on a Centos system with Phusion passenger and nginx server. The website url is http://www.shutuplegs.in . The website is loading fine on computers, however on chrome on mobile phones am getting the 'Aw, snap' error. What might be wrong and where should I start debugging this?
My repository : https://github.com/dsmegha/shut_up_legs
Edit : I still am stuck with this weird problem and have no idea how to get this working. I have filed a bug with chrome, but that might take a lot of time to fix.


text:
Q: mysql in list only validates first id in list. maybe a blob issue I work with a system that used comma separated values as a one-2-many relation. It is stored in as a blob.
I try to use the MySQL IN (LIST), but only ends up with the rows where the uid is first in the list or only one in the list.
mytable
uid categories
1   24,25,26
2   25
3   22,23,25
4   25,27

run sql:
SELECT * FROM mytable WHERE 25 IN (categories)

Result:
uid categories
2   25
4   25,27

Missing (should have been selected but are not)
uid categories
1   24,25,26
3   22,23,25

Any idea why a string has to start with 25 and not just contain 25? I guess it is a string issue rather than an IN (LIST) issue
UPDATE - based on answers below:
When using th IN (LIST) on a blob, the blob is converted to an int and commas and "digits" are lost.
In stead use FIND_IN_SET(needle, haystack) that will work also on a blob containing comma separated values.

A: I think you are looking for FIND_IN_SET
 SELECT * FROM mytable WHERE FIND_IN_SET(25,category)

A: This should give you your asnwer:
SELECT * FROM mytable WHERE CONCAT(',', categories, ',') LIKE '%,25,%'

But it would make more sense to create a connecting table, with each comma separated value as a new row.

A: What's happening is that MySQL is converting the blob to an integer (not a list of integers) for comparison. So '24,25,26' becomes the value 24. You can confirm this by running the query
SELECT CAST(categories AS signed) FROM mytable

This is not how IN (nor the blob data type) is meant to be used. Is there a reason you're not using another table for this?

A: Yes, it's astring issue. Your 'list' is just a string to mysql, meaning nothing.
You would have to use RegEx.
But you might think about normalizing your tables instead.


text:
Q: Combination Problem: Solving for $n$ such that $C(n, 2) = 10$ Solve for n ,
$C(n, 2) = 10$
What I have done so far:
$\frac{n!}{2!(n-2)!} = 10$
$\frac{n!}{2!(n-2)(n-1)n!} =10$
$\frac{1}{2n^2 - 6n-4} = 10$
$ 1 = 20n^2-6n-40$
I think I did something wrong along the way

A: $C(n,2)=\frac{n!}{(n-2)!2!}=\frac{n(n-1)(n-2)!}{(n-2)!2!}=\frac{n^2-n}2$, so you need to solve $n^2-n=20$.


text:
Q: How do I query a Drupal Shortcut (8.x/9.x) by its URL or Menu Path? We're rolling out an update to an in-house Drupal installation profile, and one of the menu paths that is used frequently is getting changed. Most of our installations reference that menu path in a shortcut (via the "Shortcut" module in core). In an update hook, we'd like to be able to query for those shortcuts and update them.
It feels like this should be straightforward, but for some reason we're finding it difficult to query for shortcuts by their url. We can query them by title, but that seems fragile (since the title could be different between installations, might be different by localization, etc.).
We tried the following, but this lead to the error message 'link' not found:
// This does NOT work.
$shortcuts_needing_update =
  \Drupal::entityTypeManager()
    ->getStorage('shortcut')
    ->loadByProperties([
      'link' => [
        'internal:/admin/timeline-management',
      ],
    ]);

// This works, but is fragile.
$shortcuts_needing_update =
  \Drupal::entityTypeManager()
    ->getStorage('shortcut')
    ->loadByProperties([
      'title' => 'My shortcut',
    ]);

Based on the code in \Drupal\shortcut\Entity\Shortcut::baseFieldDefinitions() and \Drupal\shortcut\Controller\ShortcutSetController::addShortcutLinkInline() it's obvious that Shortcut entities have a property called link that can be set like an array containing a uri key, yet it does not seem possible to query by this property even though it's a base field.

A: Looking at the database, it appears that Drupal stores the URL in a database column called link__uri:

TL;DR That means that this works:
$shortcuts_needing_update =
  \Drupal::entityTypeManager()
    ->getStorage('shortcut')
    ->loadByProperties([
      'link__uri' => 'internal:/admin/old/path',
    ]
  );

Read on if you want to know the subtle reason why this is the case.
Drupal's database layer uses pluggable "table mapping" objects to tell it how to map an entity (like a Shortcut) to one or more database tables and database table columns. The logic for generating a column name for a field looks like this in the default table mapping (\Drupal\Core\Entity\Sql\DefaultTableMapping):

As shown above, if a field indicates it allows "shared" table storage, and the field has multiple properties (uri, title, etc.), then the mapping flattens the field into distinct columns for each property, prefixed by the field name. So, a Shortcut entity with link => ['uri' => 'xyz']] becomes the column link__uri with a value of xyz in the database.
You don't see this often with entities like nodes, which is why this seems strange here. I'm usually accustomed to seeing a separate database table for things like link fields. That's because nodes and other content entities don't usually allow shared table storage for their fields.
How does the mapping determine if a field should use shared table storage? That logic looks like this:

So, the default table mapping will use shared table storage for a field only under specific circumstances:

*

*The field can't have a custom storage handler (checks out here since shortcuts don't provide their own storage logic).

*The field has to be a base field (shortcuts are nothing without a link, so that field is defined as a base field as mentioned in the OP).

*The field has to be single-valued (checks out -- shortcuts have only one link).

*The field must not have been deleted (checks out; again, what is a shortcut without a link field?).

This specific set of circumstances aren't often satisfied by nodes or other content entities, which is why it's a bit surprising here.
We can confirm this by using Devel PHP to ask the table mapping for shortcuts directly, with code like the following:
$shortcut_table_mapping =
  \Drupal::entityTypeManager()
    ->getStorage('shortcut')
    ->getTableMapping();

$efm = \Drupal::service('entity_field.manager');
$storage_definitions = $efm->getFieldStorageDefinitions('shortcut');

$link_storage_definition = $storage_definitions['link'];

$has_dedicated_storage = $shortcut_table_mapping->requiresDedicatedTableStorage($link_storage_definition);
$link_column = $shortcut_table_mapping->getFieldColumnName($link_storage_definition, 'url');

dpm($has_dedicated_storage, 'has_dedicated_storage(link)');
dpm($link_column, 'link_column');

This results in the following:


text:
Q: How to retrieve the depth of nested dictionaries in nested dictionaries in Python? I'm not sure if I'm just having a brainblock here or if this is actually supposed to be a challenge, but I am having trouble figuring out how to check the depth of nested dictionaries if the keys are not known.
Here is an example of what I am trying to do (in the most simple/efficient way):
Optimally, there would be some way for me to determine the maximum depth of this dict, without knowing the keys and values -
nested_dict = {
  'nest1': {
    'nest2': {
       'nest3': 'val'
    },
    'unknown_key', 'val',
    'unknown_key': 'val'
  }
}

Please let me know if this makes sense.

A: Check if its a dict, if so, iterate over the values and recursively call the function get the max of the value.
PS : Dict was a syntax error, fixed it
def max_depth(d):
    if isinstance(d, dict):
        return 1 + max((max_depth(value) for value in d.values()), default=0)
    return 0

nested_dict = {'nest1': {'nest2': {'nest3': 'val'}, 'unknown_key': 'val', 'unknown_key': 'val'}}

print(max_depth(nested_dict))

Output
3


text:
Q: How to hide port number in a url I have run an application on a cloud server..i am accessing the url https://xx.xx.xx.xx:5004/double/request with a public Ip. Can it be possible to access the url https://xx.xx.xx.xx/double/request(Without port number)

A: Default port for HTTPS is 443. So you can just change your port to 443 and will be able to use https://xx.xx.xx.xx/double/request
More infos about port number : See this Question.

A: What about using of services that short url: e.g. tiny.ly?

A: No, it's not possible to access the "https" url of "5004" port number without "5004".
So, to access the "https" url of your application without port number, you need to change "5004" port number of the "https" url of your application to "443" port number because "443" port number is default to "https".
In addition, "80" port number is default to "http".


text:
Q: Restore MySQL from files (without dump) Is it possible to duplicate a MySQL database from their files? [I know mysqldump would be the best method to duplicate a db, but that's not possible as all we have is the backed up files from the mysql folder].
We have the ibdata1 file, the ib_log* files, and the full directories for the three db's we want to restore from the backed up files (folders seem to contain all needed frm and par files). Obviously already tried just to copy all the files into /var/lib/mysql and though it appeared the structure was intact attempts to access the data were unsuccessful.
i.e. show databases will show the db's, use dbname works, and show tables properly displays the tables, but when trying to access the data from [any] table (via query) it says ERROR 1146 (42S02): Table 'dbname.dbtable' doesn't exist - despite mysql having happily showed us the table does exist when we did show tables.
Should also point out the service was stopped prior to copying files and all files chown'ed to have mysql as owner and then the service restarted prior to attempting to access the data.

A: To answer your question indirectly, there is some information here regarding setting up replication using a raw file copy. So I guess the answer is possibly yes, but it may depend.
http://dev.mysql.com/doc/refman/5.0/en/replication-howto-rawdata.html
Not wishing to add to your current pain, but were you relying on a backup that you have never tried / don't know how to restore?


text:
Q: How to configure Pandas to read .dat file Can't seem to load this file with pd.read_csv or pd.read_table:
http://cdsarc.u-strasbg.fr/ftp/cats/J/A+A/594/A27/psz2.dat

I've tried:
psz2_2017 = pd.read_csv('http://cdsarc.u-strasbg.fr/ftp/cats/J/A+A/594/A27/psz2.dat', sep=';', header=None)

Also tried pd.read_table with/wo sep='\t' (same result) and sep='\s+' (gets Error tokenizing data).
Results in:
0
0   1 PSZ2 G000.04+45.13 0.0405432 45.135175...
1   2 PSZ2 G000.13+78.04 0.1380577 78.042113...
2   3 PSZ2 G000.40-41.86 0.4029953 -41.860792...

Any suggestions?
The first line looks like this:
1 PSZ2 G000.04+45.13   0.0405432  45.1351750 229.1905120  -1.0172220  4.107310  6.75319 2 111 0     1 0 0.938825   5.481591  1.899500  20 RXC J1516.5-0056           0.119800  3.962411 0.393290 0.370242 J1516.5-0056 RMJ151653.9-010506.3

A: How about using pd.read_fwf()?
psz2_2017 =pd.read_fwf('http://cdsarc.u-strasbg.fr/ftp/cats/J/A+A/594/A27/psz2.dat',header=None)

A: Your data has irregular columns, and pandas is trying to figure out the correct number by reading the first few lines and making the wrong inference.
This works:
psz2_2017 = pd.read_csv('http://cdsarc.u-strasbg.fr/ftp/cats/J/A+A/594/A27/psz2.dat',header = None, delim_whitespace=True, error_bad_lines=False )

The key argument here is error_bad_lines=False


text:
Q: SQL Server 2017 Connections working in ASP.NET C# Web projects, but not in Windows projects, in Visual Studio 2019 Using the basic SqlConnection code below, I have discovered that, at my workstation, I am unable to connect to our Sql Server 2017 deployment via ASP.NET C# code in any given type of Windows-based project, such as Winforms (.NET Framework or Core) or Console apps. However, this code will run without incident in any Web-based project, such as Web Forms or MVC, either using .NET Framework or Core.
    protected void testConnection()
    {
        string con = "Server=MySqlServer;database=MyDatabase;Integrated Security=true";

        using (SqlConnection cnn = new SqlConnection(con))
        {
            cnn.Open();

            cnn.Close();
        }
    }

In a web project, this code runs. In a Windows project, I get this error:

System.Data.SqlClient.SqlException: 'A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)'

In investigating this problem, I have tried the following:

*

*Explicitly declaring the domain on which my SQL server is found (eg. MySqlServer.domain.com). No good.

*Explicitly declaring the SQL Server port number, according to the example shown on connectionstrings.com (eg. MySqlServer, 1433). We do use the standard port number, for the record. No good.

*Changing the protection level of the test method (protected/private/public). No good.

*Connecting to the SQL Server in PowerShell. This connection worked.

*Pinging in the SQL Server in a command prompt. The server responded in 1ms consistently.

*I have asked other users on this network to test this code in a Winforms project on their workstations. No one is able to reproduce my issue.

*Consulted my sysadmin. He is so far not able to find any reason why I should be having this issue.

The only difference I have noticed in all of this is that, when I declare the port number, the Inner Exception returned with the error reads "Win32Exception: A non-recoverable error occurred during a database lookup". Otherwise, it simply reads "Access is Denied."
All of this tells me that the issue is obviously something peculiar to my workstation, but I have no idea what, apart from some firewall or other local security setting that the sysadmin neglected to check. Has anyone encountered this problem?
My VS 2019 installation is only one revision out of date as of this writing, 16.8.3 as opposed to 16.8.4. I am able to connect to and run TSQL code on any database I care to via SSMS. We connect using Windows Authentication. According to the results of "select @@version", our version of SQL Server is 2017, 14.0.3356.20 (x64).
Any insight is appreciated.

A: We fixed it by forcing Named Pipes to be enabled in SQL Server, as opposed to using the default setting.


text:
Q: Print Zero Even Odd problem of leetcode shows error Time Limit Exceeded I tried the following code for leetcode problem of Print Zero Even Odd problem.
It is showing me Time Limit Exceeded error while testing for simplest input.
Can anybody give some suggestions?
https://leetcode.com/problems/print-zero-even-odd
class ZeroEvenOdd {

    private int n;

    public ZeroEvenOdd(int n) {
        this.n = n;
    }

    // printNumber.accept(x) outputs "x", where x is an integer.
    boolean z = true;
    public void zero(IntConsumer printNumber) throws InterruptedException {
        for(int i = 1; i <= n; i++) {
            if(z) {
                printNumber.accept(0);
            }
            z = false;
            odd = !odd;
            try { notifyAll(); } catch(Exception e){}
            do { try { wait(); } catch(Exception e){ } } while(!z);
        }
    }
    boolean odd = false;
    public void even(IntConsumer printNumber) throws InterruptedException {
        for(int i = 1; i <= n; i++) {
            do { try { wait(); } catch(Exception e){ } } while(z || odd);
            if(!odd && !z && i%2 == 0) {
                printNumber.accept(i);
            }
            z = true;
            try { notifyAll(); } catch(Exception e){}
        }
    }

    public void odd(IntConsumer printNumber) throws InterruptedException {
        for(int i = 1; i <= n; i++) {
            do { try { wait(); } catch(Exception e){ } } while(z || !odd);
            if(odd && !z && i%2 == 1) {
                printNumber.accept(i);
            }
            z = true;
            try { notifyAll(); } catch(Exception e){}
        }
    }
   }

A: Try using synchronized: the code will looks more simple
class ZeroEvenOdd {
    private int n;

    public ZeroEvenOdd(int n) {
        this.n = n;
    }

    private enum STATUS{
        ZERO, ODD, EVEN;
    }

    private STATUS status = STATUS.ZERO;
    private int x = 0;
    private Object lock = new Object();

    // printNumber.accept(x) outputs "x", where x is an integer.
    public void zero(IntConsumer printNumber) throws InterruptedException {
        while(x<=n){
            switch(status){
                case ZERO:
                    synchronized(lock){
                        if(x < n){
                            printNumber.accept(0);
                        }
                        if(x%2==0){
                            status = STATUS.ODD;
                        }else{
                            status = STATUS.EVEN;
                        }
                        x++;
                    }
                    break;
            }
        }
    }

    public void even(IntConsumer printNumber) throws InterruptedException {
        while(x<=n){
            switch(status){
                case EVEN:
                    if (x<=n){
                        printNumber.accept(x);
                    }
                    status = STATUS.ZERO;
                break;
            }
        }
    }

    public void odd(IntConsumer printNumber) throws InterruptedException {

        while(x<=n){
            switch(status){
                case ODD:
                    synchronized(lock){
                        if(x <= n){
                            printNumber.accept(x);
                        }
                        status = STATUS.ZERO;
                    }
                    break;
            }
        }
    }
}

For a complete reference of synchronized, visit this


text:
Q: How to prove monotonicity of this sequence In probability, we often need to deal with dyadic rational numbers and floor functions.
Fix a  positive real number,
Define a sequence $a_n = \min(n, 2^{-n} \lfloor 2^nx\rfloor)$ , how to prove this sequence increasingly converge to $x$?
in the $\min$ expression, $n$ is of course increasing.
I am trying to compute quotient of the floor function part between
$a_{n+1}$ and $a_n$. Then $ a_{n+1}/a_n = \frac{\lfloor 2^{n+1} x\rfloor}{2\lfloor 2^n x\rfloor}$. How to proceed? Is my idea most efficient one?
This is a sequence used in Rosenthal's probability book. He used this to construct a sequence of simple functions converging to a positive random variable.
What's the general strategy for treating this kind of numerical question?

A: You want to prove that $\frac{\lfloor 2^{n+1}x\rfloor}{2\lfloor 2^n x\rfloor} \geq 1$. for all $n$ and a fixed $x$. Let $u = 2^n x$, then the statement is equivalent to $\lfloor 2a\rfloor \geq 2\lfloor a\rfloor$. We divide this into two cases depending on $\{a\} = a - \lfloor a\rfloor$:

*

*If $0 \leq \{a\} < \frac{1}{2}$, then $\lfloor 2a \rfloor = \lfloor 2(\lfloor a\rfloor + \{a\})\rfloor = 2\lfloor a\rfloor + \lfloor\underbrace{2\{a\}}_{< 1}\rfloor = 2\lfloor a\rfloor$.

*If $\frac{1}{2} \leq \{a\} < 1$, then the underlined expression is between $1$ and $2$, and hence $\lfloor 2a\rfloor = 2\lfloor a\rfloor + 1$.
We see that in both cases, the statement holds.
Hope this helps!
Here is a picture, the red segments being $y = \lfloor 2x\rfloor$ and blue segments being $y = 2\lfloor x\rfloor$.

A: The expression $b_n(x) \equiv 2^{-n} \lfloor 2^nx\rfloor$ is just the approximation to $x$ using $n$ binary digits in the fractional part of the approximation, so it increases with $n$ for fixed $x$.
So $\min(n,b_n(x))$ caps $b_n$ at $n$, which produces an increasing sequence since $b_n(x)$ is increasing. In fact, once $n > \lceil x \rceil$, it must be true that $\min (n, b_n(x)) = b_n(x)$.


text:
Q: How to commit after removing a directory from GIT Several posts talk about removing a file or directory from GIT - but they don't go as far as explaining how to PUSH those changes into the main repository.
For example, this works just fine to remove the directory but when I try to PUSH this change to the main Git repo, I am denied:
! [rejected]        master -> master (non-fast forward)
error: failed to push some refs to '/repo/project.git'
To prevent you from losing history, non-fast-forward updates were rejected
Merge the remote changes before pushing again.  See the 'non-fast forward'
section of 'git push --help' for details.

What is the last step to actually push this to the main repo and actually remove that directory?

A: When you remove something so aggressively, you rewrite history. Therefore, the upstream repository is rejecting your change because it would result in a loss of history. In this case, you will need to use
git push --force

A: Nick Lewis' answer is sufficient, but I just want to add some emphasis, more than will fit in a comment. Here's a quote from the git filter-branch man page:

WARNING! The rewritten history will have different object names for all the objects and will not converge with the original branch. You will not be able to easily push and distribute the rewritten branch on top of the original branch. Please do not use this command if you do not know the full implications, and avoid using it anyway, if a simple single commit would suffice to fix your problem. (See the "RECOVERING FROM UPSTREAM REBASE" section in git-rebase(1)  for further information about rewriting published history.)

Italics emphasis added - that's pretty important. Filter-branch really does rewrite history, it'll screw up anyone who's cloned/pulled from your repo, and it's scary. You should really know all that before you give it a go. Most people here are pretty good about providing that reminder whenever they recommend filter-branch or rebase; I think it's appropriate to have a pretty strong repetition of it here, on a question where the answer is push --force in order to completely rewrite the history in your public repo. That's a scary operation.


text:
Q: How to avoid frequently needing to re-grant permission in Hue? My organization has a cluster/environment with the following:
Component   Version
Hue             2.5.1-695
HDP             2.1.2
Hadoop          2.4.0
Pig             0.12.1
Hive-Hcatalog   0.13.0
Oozie           4.0.0
Ambari          1.5.1
HBase           0.98.0
Knox            0.4.0
Storm           0.9.1
Falcon          0.5.0

data from Hive is queried by R programmers in the R language via ODBC (specially, RODBC).
Prior to an upgrade several months ago, the programmers simply entered their connection/authentication strings in their scripts and wrote queries within the R scripts to be run programmatically over ODBC.
However, since the upgrade, anytime a table is refreshed/recreated, it's necessary for the users to (re-) grant themselves permission to select via a query in Hue, such as:
grant select on table my_table to user kmitnick

Then queries over ODBC work as expected until the next time the table is refreshed.
This has caused a great number of automated/scheduled scripts to "break". Note that the exact same query can be run by the same within Hue and no grant select statement is needed.
Could someone help me understand the cause and/or find a work-around to avoid the need for these grant select statements.


text:
Q: PHP: how would I use this simple class? I was looking around for more "correct" login/logout portions of code, and found this one:
http://snipplr.com/view/1079/auth/
I got two questions though that stop me from using it.
1: How would I instantiate the class, and use it in my script?(I know PHP but am just befuddled for some reason)
2: there's the following lines:
global $db;
$db->query("sql here...");

How on earth does that make a database object? I think maybe I should create an object like $db = mysql_connect(...) outside the script, and global is calling it from outside the class?
If I know how to call this class, others will seem like a breeze, this is really helpful to me!

A: That code is dangerous, you should not use it in it's current state.

*

*It blindly trusts $_COOKIE and creates SQL queries using string concatenation, without properly escaping input.  Malicious users can easily perform SQL injection on any application using that class.

*The presence of the var keyword, the presence of a constructor using the same name as the class and the lack of access control keywords in front of the methods tells me that the code was written for PHP4, not PHP5.  It will still run, though

Both of these are fixable problems.  First, let's address your questions.

*

*The code written by @Delan Azabani is a good example of how to use the class.

*The code is confusing.  At first, it looks like the code is using a real database object instead of the old, low-level functions provided by the mysql extension.  But then it goes and calls functions from the mysql extension!  It's probably someone's custom-written wrapper.  The code isn't actually creating a database object, it's simply referencing the value of $db in the global scope, as you suspect.

You've mentioned that you're using the mysql extension.  I urge you to reconsider and use PDO or mysqli instead.  Not only will this class work with either (though with some changes to mitigate the glaring security hole), but your own code will be better off using the more modern, safer techniques used in PDO and mysqli.
Let's fix the login method, using PDO.
public function login($username, $password) {
    global $db;
    $sth = $db->prepare("SELECT user_id FROM users WHERE username = ? AND password = ?");
    $sth->execute(array($username, $password));
    if($sth->rowCount() == 1) {
        $this->user_id = $sth->fetchColumn();
        ...

Let's go over what changed.  First, we added query placeholders, those are the question marks.  The prepare method returns a statement handle, which you're already probably familiar with.  Next, we tell the prepared statement to run itself using the execute method, passing an array of variables.  The variables will be automatically escaped for you and then inserted into the query in place of the placeholders.
After the query has run, we use rowCount to pull back the number of matching rows.  We want exactly one.  Because we're pulling back the first column of the first row, we then use fetchColumn to grab just that bit of data.
The rest of the login method is just fine.
The check method needs similar fixing up.
public function check($username, $password) {
    global $db;
    $sth = $db->prepare("SELECT user_id, password FROM users WHERE username = ?");
    $sth->execute(array($username));
    if($sth->rowCount() == 1) {
        list($db_user_id, $db_password) = $sth->fetch(PDO::FETCH_NUM);
        if(md5($db_password . $this->salt) == $password) {
            $this->user_id = $db_user_id;
            ...

Once again, we prepare a query with placeholders, then execute with the actual variables.  Again we want only one row, but this time we want everything in the row.  We'll use PDO::FETCH_NUM to tell fetch that we want a numerically indexed array, then we'll take the two resulting entries in the array and stuff them in $db_user_id and $db_password, using them where the old code called mysql_result.  PDO doesn't let you pick and choose different columns from the same row using fetchColumn.
If you wanted to use the mysqli extension instead, there's a bit more work to be done.  I hope I've convinced you to use PDO instead, though!
The rest of the class is, eh, adequate.  Make sure to adjust the $domain class variable at the top to match your actual domain name, it's used in the cookies.

A: global $db just allows the global database pointer $db to be accessed from inside the class method. You need to create the database by running mysql_connect and mysql_select_db. The entire class is in class Auth, so instantiate an Auth object before doing anything else (well, after connecting to the database, of course).
You can then call the methods inside your Auth object. For example, if a login form submits to login-post.php, you can have this code inside:

$m = new Auth();
if ($m -> login($_POST['u'], $_POST['p'])) {
    header('Location: /');
    exit;
} else {
    header('Location: login?wrong=1');
    exit;
}

A: Looks like the code you posted is just assuming you have a variable defined in your global scope called $db that looks like a wrapper class to the native PHP MySQL resource. So yes, you should create $db outside in the global scope (i.e. not inside a class), but it's expecting a custom class.
I did a little searching, and it looks like he's using THIS class: http://snipplr.com/view/27966/class-db/
It asks you to create an ini file called "crunksauce.ini" (I kid you not) in the same directory as the executing script, and contains configuration variables. The config file should like this:
database = <your database name>
host = <your db host>
user = <your db user>
pass = <your db password>

After creating the config file, you can create the db object like this:
$db = new Db();


text:
Q: how to use set define off in liquibase sql format I have an HTML file to be stored in the database. I am using Liquibase for this but in HTML I have lot of   instances.
The problem is that SQL does not allow & to run without set define off option.
I got to know the below solutions from the net:

*

*I have read that I can use cdata, but here I am inserting HTML in Liquibase SQL format and not the XML format, so I think it is not of use.

*As there are lot of   in the file, I cannot use ASCII characters for each to avoid &.

Error from Liquibase execution:
SEVERE 6/7/17 11:30 AM:liquibase: Error executing SQL set define off
java.sql.SQLException: ORA-00922: missing or invalid option

    at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:112)

What can I do to fix this?

A: The set define off that Liquibase is complaining about is not SQL, it is a SQL*Plus client command:

SET DEF[INE] {& | c | ON | OFF}
Sets the character used to prefix substitution variables to c.
ON or OFF controls whether SQL*Plus will scan commands for substitution variables and replace them with their values. ON changes the value of c back to the default '&', not the most recently used character. The setting of DEFINE to OFF overrides the setting of the SCAN variable.

It is used by SQL Developer and SQLcl as well. All of those clients use it to control the behaviour of substitution variables.
Liquibase clearly doesn't recognise that client command, so it should be removed from your script.

A: As & in &(ampersand)nbsp; is considered as substitution variable in sql and liquibase ignores set define off statement , so I used ascii characters to use & in sql query defined in liquibase as below:
&(ampersand)nbsp;  changed to ' || '&' || 'nbsp' || CHR(59) || ' and query worked


text:
Q: Apply transform of your own function in Pandas dataframe I have pandas dataframe on which I need to some data manipulation, the following code provide me the average of column "Variable" group by "Key":
df.groupby('key').Variable.transform("mean")

The advantage of using "transform" is that it return back the result with the same index which is pretty useful.
Now, I want to have my customize function and use it within "transform" instead of "mean" more over my function need two or more column something like:
lambda (Variable, Variable1, Variable2): (Variable + Variable1)/Variable2

(actual function of mine is more complicated than this example) and each row of my dataframe has Variable,Variable1 and Variable2.
I am wondering if I can define and use such a customized function within "transform" to be able to rerun the result back with same index?
Thanks,
Amir

A: Don't call transform against Variable, call it on the grouper and then call your variables against the dataframe the function receives as argument:
df.groupby('key').transform(lambda x: (x.Variable + x.Variable1)/x.Variable2)

A: Why didn't you use simple
df.Variable + df.Variable1 / df.Variable2
There is no need to groupby. In case for example you want to divide by df.groupby('key').Variable2.transform("mean") you can still do it with transform as following:
df.Variable + df.Variable1 / df.groupby('key').Variable2.transform("mean")


text:
Q: Failing test for predict k nearest Neighbors function?
Apparently the function predict itself works well and the whole model gets 75% success. But when I tried to do a test case for the function to check if it will return the correct outcome (1), I get the error outcomes = np.append(outcomes, y_train[n]) IndexError: index 160 is out of bounds for axis 0 with size 3. Any suggestions to what could be the bug?

A: This is impossible to debug based on your screenshot alone. Please provide a minimal working example in the future.
In this particular case, I assume that y_train[n] tries to access y_train[160], but your y_train only has three elements [1, 1, 0]. So I assume that get_neighbors does not return the type of data that you expect.
It appears that you are using PyCharm. Try to execute the very same code with the built-in debugger (a bug next to the run icon), wait for the Exception to appear (it will pause the code at that point), and check the content of your neighbors variable in the debugger menu. It should give you more hints.


text:
Q: Why is my AJAX call in jQuery not working? What am I trying to achieve:

*

*After form is being filled-out and submit button being clicked, I want to be able to submit form and do an AJAX call - payment.php file (I did integration of PayPal, I am sending following values via mail firstname, surname, email, phone, number, date of birth, CV, photo, etc...) and I am also trying to store it into the database.

Where am I failing at?
This is multiple-step form, the problem is occuring when I get to the last step of filling-out form and by clicking "Submit" button nothing happens - my AJAX call is not working...

My jQuery code:
$(document).ready(function(){

var current_fs, next_fs, previous_fs; //fieldsets
var opacity;
var current = 1;
var steps = $("fieldset").length;

setProgressBar(current);

$(".next").click(function(){

    current_fs = $(this).parent();
    next_fs = $(this).parent().next();

    //Add Class Active
    $("#progressbar li").eq($("fieldset").index(next_fs)).addClass("active");

    //show the next fieldset
    next_fs.show();
    //hide the current fieldset with style
    current_fs.animate({opacity: 0}, {
        step: function(now) {
            // for making fielset appear animation
            opacity = 1 - now;

            current_fs.css({
                'display': 'none',
                'position': 'relative'
            });
            next_fs.css({'opacity': opacity});
        },
        duration: 500
    });
    setProgressBar(++current);
});

$(".previous").click(function(){

    current_fs = $(this).parent();
    previous_fs = $(this).parent().prev();

    //Remove class active
    $("#progressbar li").eq($("fieldset").index(current_fs)).removeClass("active");

    //show the previous fieldset
    previous_fs.show();

    //hide the current fieldset with style
    current_fs.animate({opacity: 0}, {
        step: function(now) {
            // for making fielset appear animation
            opacity = 1 - now;

            current_fs.css({
                'display': 'none',
                'position': 'relative'
            });
            previous_fs.css({'opacity': opacity});
        },
        duration: 500
    });
    setProgressBar(--current);
});

function setProgressBar(curStep){
    var percent = parseFloat(100 / steps) * curStep;
    percent = percent.toFixed();
    $(".progress-bar")
      .css("width",percent+"%")
}

$(".submit").click(function(){
    var request;
        //moj kod
        event.preventDefault();

    // Abort any pending request
    if (request) {
        request.abort();
    }
    // setup some local variables
    var $form = $("#msform");

    // Let's select and cache all the fields
    var $inputs = $form.find("input, select, button, textarea");

    // Serialize the data in the form
    var serializedData = $form.serialize();

    // Let's disable the inputs for the duration of the Ajax request.
    // Note: we disable elements AFTER the form data has been serialized.
    // Disabled form elements will not be serialized.
    $inputs.prop("disabled", true);

    // Fire off the request to /form.php
    request = $.ajax({
        url: "payment.php",
        type: "post",
        data: serializedData
    });

    // Callback handler that will be called on success
    request.done(function (response, textStatus, jqXHR){
        // Log a message to the console
        console.log("Request uspješno poslat!");
    });

    // Callback handler that will be called on failure
    request.fail(function (jqXHR, textStatus, errorThrown){
        // Log the error to the console
        console.log(JSON.stringify(errorThrown));
        console.error(
            "Desio se sljedeci error: "+
            textStatus, errorThrown
        );

    });

    // Callback handler that will be called regardless
    // if the request failed or succeeded
    request.always(function () {
        // Reenable the inputs
        $inputs.prop("disabled", false);
    });

        //moj kod ->end
    return false;
    })

    });

This is jQuery code (obviously) - and here I am handling the form and its data (at least it's what I intended to do with it)
This is form inside of HTML:
 <form class="paypal" action="payment.php" method="post" name="Form" id="msform">
                    <?php
                            $paket = $_GET['paket'];
                            if($paket == "standard")
                            {
                                ?>
                                <input type="hidden" name="standard" value="standard">
                                <input type="hidden" name="item_number" value="1">
                                <?php
                            }
                            else if($paket == "bewerbungscheck")
                            {
                                ?> <input type="hidden" name="bewerbungscheck" value="bewerbungscheck">
                                <input type="hidden" name="item_number" value="2">
                                <?php
                            }
                            else if($paket == "premium")
                            {
                                ?> <input type="hidden" name="premium" value="premium">
                                <input type="hidden" name="item_number" value="3">
                                <?php
                            }
                            else if($paket == "lowbudget")
                            {
                                ?>
                                <input type="hidden" name="lowbudget" value="lowbudget">
                                <input type="hidden" name="item_number" value="4">
                                <?php
                            }
                            else{
                                echo "There's no package with this name, please go back and choose again, wisely!";
                                ?>
                                <button class="btn">
                                Go Back
                                </button>
                                <?php
                                exit();
                            }
                            ?>

Personal Info

Appointment

Documents

Finish

                        <fieldset>

Personal Information:

Step 1 - 4

                                <input type="hidden" name="cmd" value="_xclick" />
                                <input type="hidden" name="no_note" value="1" />
                                <input type="hidden" name="lc" value="DE" />
                                <input type="hidden" name="bn" value="PP-BuyNowBF:btn_buynow_LG.gif:NonHostedGuest" />
                                <input type="hidden" id="first_name" name="first_name" value="Customer's First Name" />
                                <input type="hidden" id="last_name" name="last_name" value="Customer's Last Name" />
                                <input type="hidden" id="payer_email" name="payer_email" value="customer@example.com" />

                                Email: *
                                <input id="email" type="email" name="email" placeholder="example@meinegutebewerbung.de" />
                                Name: *
                                <input id="fn" type="text" name="uname" placeholder="Name" />
                                Surname: *
                                <input id="sur" type="text" name="usur" placeholder="Surname" />
                                Expertised in: *
                                <input type="text" name="expert" placeholder="ex.:Bachelor in Computer science" />
                                Phone number: *
                                <input type="tel" name="phone" placeholder="+000000000000000" />
                                Birth Date: *
                                <input type="date" name="date" placeholder="Date" />

                            <input type="button" name="next" onclick="populate()" class="next action-button"
                                value="Next" />
                        </fieldset>
                        <fieldset>

Appointment details:

Step 2 - 4

                                Select appointment date: *
                                <input id="date_picker" type="date" name="date-res" />
                                Which time span is the most fitting for you: *

                                <select name="suitabletime " id="suitable">
                                    <option value="09-14">09:00 - 14:00</option>
                                    <option value="14-20">14:00 - 20:00</option>
                                </select>

                            <input type="button" name="next" class="next action-button" value="Next" />
                            <input type="button" name="previous" class="previous action-button-previous"
                                value="Previous" />
                        </fieldset>
                        <fieldset>

Upload documents:

Step 3 - 4

                                Upload Your Photo:
                                <input type="file" name="pic" accept="image/*">
                                Upload CV (must be PDF):
                                <input type="file" name="pic" accept=".pdf">

                            <input type="button" name="next" class="next action-button" value="Submit" />
                            <input type="button" name="previous" class="previous action-button-previous"
                                value="Previous" />
                        </fieldset>
                        <fieldset>

Finish:

Step 4 - 4

SUCCESS !

You Have Successfully Signed Up

                        </fieldset>
                    </form>

How did I came to conclusion that this is not working?

*

*I have actually inserted console.log() so I can get some output after the code is executed, but I am not getting anything. The second thing is that I also setted up PHP to do echo and again I am not getting anything.

A: As @kikon already stated inside of the comments, the problem was that I did not put the class="submit" as a attribute to the <button>, therefore element with the class of submit didn't exist, so the jQuery couldn't trigger the code inside of the function for AJAX.


text:
Q: css order property adding ghost spacing on top with flex - trying to imitate float right I am essentially trying to imitate float: right with images in a row and I am getting a mysterious space above the parent item when I do it. I am using flexbox in the elements and I tried to achieve the float: right type functionality by using the order: 2 property. Here is a screenshot:
A live sample of the app can here: removed link, because in development, forgive the long load times. Just click "play"

A: Since there are two app-team components inside app-game component make app-game as a flex container so app-team components will be flex items.
.app-game-class {
    display: flex;
    /* align-items: center; */
    justify-content: center;
}


text:
Q: Filling complex areas of a ListPlot I have a ListPlot with vertical and horizontal lines. I would like to color the resulting rectangles by something like "Fill with Green if less than both line 1 & line 3". However, I can't figure out how to make this logic work with Filling.
Two examples of non-working code below:
The first displays a strange band of green underneath line 1.
 ListPlot[{
  (*Horizontal line 1*){{0, 5}, {35, 5}},
  (*Horizontal line 2*){{0, 10}, {35, 10}},
  (*Vertical line 3*){{5, 0}, {5, 35}},
  (*Vertical line 4*){{10, 0}, {10, 35}}},
 Joined -> True,
 Filling -> {1 -> 3}, FillingStyle -> LightGreen]

The second displays no filling at all.
 ListPlot[{
  (*Horizontal line 1*){{0, 5}, {35, 5}},
  (*Horizontal line 2*){{0, 10}, {35, 10}},
  (*Vertical line 3*){{5, 0}, {5, 35}},
  (*Vertical line 4*){{10, 0}, {10, 35}}},
 Joined -> True,
 Filling -> {1 -> {3}}, FillingStyle -> LightGreen]

Eventually the locations of the lines will be controlled via Manipulate. Thanks for any advice!

A: This is very closely related to this question. Here is a version of kglr's answer adapted to your problem:
ListPlot[{
  (*Horizontal line 1*){{0, 5}, {35, 5}},
  (*Horizontal line 2*){{0, 10}, {35, 10}},
  (*Vertical line 3*){{5, 0}, {5, 35}},
  (*Vertical line 4*){{10, 0}, {10, 35}},
  (*Horizontal line 5*){{0, 0}, {5, 0}}
  },
 Joined -> True,
 Filling -> {1 -> {5}},
 FillingStyle -> LightGreen,
 PlotStyle -> {Automatic, Automatic, Automatic, Automatic, None}
 ]

As you can see, the key is to create a shorter line that goes between $x=0$ and $x=5$ where 5 is the position of the vertical line. Then you can fill between the chosen full length horizontal line and this shorter other horizontal line to get what you want, since you cannot use vertical lines with the Filling option.
For full flexibility, I would consider using Graphics instead:
Graphics[{
  LightGreen, Rectangle[{0, 0}, {5, 5}],
  Gray,
  InfiniteLine[{0, 5}, {1, 0}],
  InfiniteLine[{0, 10}, {1, 0}],
  InfiniteLine[{5, 0}, {0, 1}],
  InfiniteLine[{10, 0}, {0, 1}]
  },
 Axes -> True,
 PlotRange -> {{0, 35}, {0, 35}}
 ]

AspectRatio -> 1/GoldenRatio, which may or may not be wanted, is used here to match the output of ListPlot.
You might also consider adding the Rectangle to the ListPlot using the Prolog or Epilog option (probably Prolog so that the rectangle goes under the lines).


text:
Q: Calling relying party over HTTPS and token encryption I have an issue with the Windows Azure ACS and I can't quite determine if it's supposed to be that way, or if there's an error in my code.
I have a number of relying parties configured in the ACS and all of them are configured with HTTPS. Every service is configured in such a way that Token Encryption is required. For this, I've uploaded a certificate created using MakeCert.exe.
When the client communicates with the relying party, I add the public part of the certificate as the service certificate and I add the subject name as a DnsIdentity:
var identity = EndpointIdentity.CreateDnsIdentity( GetClientCertificateSubjectName() );
var serviceEndpointAddress = new EndpointAddress( new Uri( _serviceAddress ), identity );

// Creation of channel factory

if( channelFactory.Credentials != null ) {
  channelFactory.Credentials.ServiceCertificate.DefaultCertificate = GetClientCertificate();
  channelFactory.Credentials.ClientCertificate.Certificate = GetServiceIdentityCertificate();
}

Here's the thing: when I call the relying party over HTTPS, then I can skip the creation of the EndpointIdentity and then the relying party will give me a correct answer. I can also skip setting the ServiceCertificate.DefaultCertificate property or set a totally random certificate, and the relying party will still give me a correct answer.
When calling over HTTP, doing any of the above will result in the ACS erroring out with messages indicating that I haven't used the correct certificates. In short: when calling over HTTP, I can only communicate with the correct client certificate. I expected that this was the case for HTTPS as well.
I can imagine that the ChannelFactory<T> or the ACS is smart enough to detect that HTTPS is used and that the configured encryption is skipped, in favour of SSL encryption. Sadly, I can't find any documentation that supports this idea.
My question is: Is it normal to ignore the EndpointIdentity and certificates when calling a relying party over HTTPS? Or do I need additional configuration to make this work?
Thanks in advance!

A: The amount of information I gave turned out to be insufficient to properly answer the question. It turned out that it was all in the bindings we were creating. It creates a binding with the following piece of code:
public static Binding CreateServiceBinding( string acsCertificateEndpoint, string bindingNameSpace, bool useSsl ) {
  var binding = new IssuedTokenWSTrustBinding( CreateAcsCertificateBinding(), new EndpointAddress( acsCertificateEndpoint ) );

  if( useSsl ) {
    binding.SecurityMode = SecurityMode.TransportWithMessageCredential;
  }

  if( !string.IsNullOrWhiteSpace( bindingNameSpace ) ) {
    binding.Namespace = bindingNameSpace;
  }

  return binding;
}

public static CertificateWSTrustBinding CreateAcsCertificateBinding() {
  return new CertificateWSTrustBinding( SecurityMode.TransportWithMessageCredential );
}

That results in the following:

*

*If it is http communication, it goes through MutualCertificate authentication mode flow and it is applied on the message layer only. That is why client is mandated to present a client certificate. This binding element creates an asymmetric security binding element that is configured to require certificate-based client authentication as well as certificate-based server authentication.

*If it is https communication, it goes through the CertificateOverTransport authentication mode flow and it is applied on transport layer only. That's why even though client certificate is not presented, it works. This binding element expects the transport to provide server authentication as well as message protection (for example, HTTPS).

For more information on the security modes, check out the following links:
https://msdn.microsoft.com/en-us/library/ms733098%28v=vs.110%29.aspx
https://msdn.microsoft.com/en-us/library/ms731074%28v=vs.110%29.aspx
Hope this helps someone!


text:
Q: Migrating git svn commits with moved and relocated commits We are trying to migrate our main source repository from svn to git
My first try was to simply do an git svn clone. After cloning was done I find that the first commit is in november 2012. I know for a fact that the code is a couple of years old
Examining the svn repo it looks like the first commit to the main directory took place in november 2012, while several files inside the repo have been committed years before that. So how can files inside a directory be committed before the parent directory..
I asked around as I'm new in the company, and no one knows for sure, but this repo has experienced a couple of svn relocate and svn move in an unusal way, for example they developed into a branch then moved that branch as a directory inside trunk, or developed into a branch, then renamed that branch as trunk and so on.
I picked one of those old commits that happened before november 2012 and can be queried using git log and tried
svn up -r 599 http://myrepo/trunk

and received the error:
svn: E195012: Unable to find repository location for 'http://myrepo/trunk' in revision 559

This error is reproducible for all committs before november 2012, i.e. those that can be queried using svn log, but cannot be checked out
The good news is that I'm able to do something like:
svn diff -r 599 http://myrepo/trunk

My next approach is to run through all commits using svn diff, create patches and applies them to git using the original author, date, etc...
Any better ideas how to extract such corrupted commits?
I do not have physical access to the repo, and I can't use svnadmin
Edit 1:
It turned out I was not querying the root directory, but one level down the tree, that's why I was getting such errors.
Anyways I did an svnrdump and succeeded in dumping the whole repository (> 32K commits), also the repo contained corrupted commits which I had to skip.
Further it has been imported locally. This helped me further understand what has happened
Basicaly, the repo used to have a very chaotic structure, something like
svn
   |_Project1
         |_subproject1
               |_branches
                      |_branch1
                      |_branch2
               |_trunk
               |_tags
                      |_tagv1
   |_Non-JavaProject
         |_subproject
   |_Project2
          |_AnotherSubproject
               |_SubSubproject
          |_Subproject2
               |_branches
               |_tags
          |_Subproject3
               |_trunk
          |_Subproject4
               |_Subsubproject
                       |_branches
                       |_tags
                       |_trunk

What happened afterwards, is that using a mixture of svn mv and copy, the structure was refined a bit
svn
    |_mainProject
         |_trunk
         |_branches
         |_tags
So now we have paths like
mainProject/trunk/_Project1
mainProject/trunk/_Project1/subproject1
mainProject/trunk/Project2/AnotherSubproject/SubSubproject

and the same goes for branches/tags
In other words, I need to to define in .git/config in the fetch and other headers a method so that different directories from mainProject will follow different (multiple) old paths
Is this possible?

A: In SVN branches, including trunks are essentially just directories in a repository. One way you can figure out where your files were before r599 is by running log on the root of SVN repo in verbose mode. I.e. svn log -v http://myrepo/@599 It will show you all commits and the paths they touched  before r599 in that repository, including commits to branches, renames, etc. One of those will be the commit that moved directories around. This will help you where the files were before that commit and you could checkout previous revision from its old location.


text:
Q: telnet automation script fails sometimes I am running the following simple telnet script which just logs into a machine and exits.
The same script works fine (goes through 1000 iterations) from one Linux server but fails (consistently) from another Linux server (fails after say 200 attempts).
In failure case, the number of iterations it takes to fail varies but failure is persistent.
#!/usr/bin/perl
use Net::Telnet;

my $loop = 0;
my $dumpfile = "dump.log";
my $inputfile = "input.log";

for ($loop =1; $loop <=1000; $loop++) {
        print "===============Loop: $loop =====================\n";
        $telnet = new Net::Telnet ( Timeout=>20, Errmode=>'die');
        print "$telnet\n";
        $telnet->open('sys-007');
        $telnet->dump_log($dumpfile);
        $telnet->input_log($inputfile);
        $telnet->waitfor('/login: $/i');
        $telnet->print('root');
        $telnet->waitfor('/Password:$/i');
        $telnet->print('007');
        sleep 2;
        $telnet->print('exit');
        print "=================================================\n";
}

Script exits with:
pattern match read eof at ./telnettest.pl line 15 (i.e, waitfor('/login: $/i'); Line)

I tried the following to see what is going wrong:

*

*In the client machine: (sys-007)
tcpdump -nvvv -w test.txt host <Server IP>

strings test.txt has:
Successful attempt Log:
sys-007 (ttyp0)
^Fl$4
^!^Fl$
login:
^Fl$4
^Fl$4
root
^(^Fl*
root
bP"u
^Fl*4
bP5u
^.^Fl*
Password:
^Fl*4
^Fl*4
007
^7^Fl6
^Fl64
^9^Fl6
Terminal type? [xterm]
^Fl64
^Fl64
exit
^Fl<4
^Fl<
exit
^Fl<

Failed Attempt:
sys-007 (ttyp0)
*^hn
+^hn

No login: prompt!

*

*In server machine: (Linux Server)
[telnet@server]~% netstat --inet -a | grep telnet | grep sys-007

There are no TIME_WAIT or CLOSE_WAIT sockets.

Please tell me what should I look for to find out what is going wrong.

A: Are you able to login normally after this? I'm guessing this other server is cutting you off because you've made too many connections.

A: What I suspect is that the telnet program is waiting for the prompt. I usually use the below format to define the prompt, so that the script usually is able to find the prompt from the below given options.
test  = new Net::Telnet (Timeout => 3000 , Prompt => '/[%#\$>?:] $/' );
$test->open($IPAddress1);
$test->login($Login,$Password1);
my @input=$test->cmd("uname -a\n");
print "Connected to : @input";
@input=$cmd->cmd("pwd\n");

Please let us know if you still face the problem.


text:
Q: Grub does not load after bios update I use Ubuntu dual boot with Windows. I recently updated my BIOS from the Acer official website for increased performance, but after updating the BIOS, I am not able to boot Ubuntu. Earlier I used the Windows Boot Manager screen to boot to Ubuntu which appeared after I pressed F12 on my laptop. The boot screen does not show the option for Ubuntu.

A: This happens because on updating BIOS, its preferences and settings changes to default i.e. mode gets set to Legacy mode instead of UEFI mode, also the order of UEFI is reset to put windows first and ubuntu later so just switching mode won't work, you will also have to change order.
Follow these steps(f1 or f2 keys may differ on different laptops)
1. Restart System and enter BIOS (using f2 key or other)
2. Change the mode from Legacy to UEFI
3. Change the order of UEFI to put Ubuntu on top, atop Windows. This will ensure that grub menu is loaded on startup.

A: The following worked for me:
1) Enter BIOS.
2) Change startup priority so Ubuntu goes first (on top).
This is a similar solution to that from arnav. But I had no need to change other UEFI settings, only the boot priority.

A: Boot into Live Ubuntu flash drive. R. click desktop and Open Terminal.
Enter commands:
sudo add-apt-repository ppa:yannubuntu/boot-repair then
sudo apt-get update then
sudo apt-get install boot-repair
Once installed, run command: boot-repair and follow the instructions and wait for program to complete. You should get a message whether boot-repair was successful.
If so, restart your computer, go into BIOS and check that Ubuntu exists as an HDD option, and ensure it's first boot option. Then save BIOS settings and restart computer.

A: I have encountered a similar problem. This worked for me.

*

*Log-in to Windows using your Administrative account.
Right click on windows icon and select command prompt(admin).
Run this from the command prompt:
bcdedit /set {bootmgr} path \EFI\ubuntu\grubx64.efi
This will make Grub the default boot manager. Then in the Grub menu, you will find both Windows and Ubuntu.

*If in the Grub menu you could not find Windows bootloader then, select the advanced option (which is just below Ubuntu) in Grub menu. Then select Ubuntu(Recovery Mode). There you will find update grub. Select it and press enter. It will fix the problem and then in Grub menu there will be Windows boot loader.
http://myviewsonfoss.blogspot.in/2018/05/how-to-fix-grub.html


text:
Q: Using the Temperature Sensor TC1047A with MCU In the manual in order to convert the A/D conversion result of an HCS12 MCU to the corresponding temperature, we need to do the
following:

*

*Divide the conversion result by 6.2

*Subtract 40 from the quotient

Is there a particular reason for this, or this is a way that temperature sensor is made?
Thanks

A: Your sensor has an input range of -40°C to +125°C producing a voltage range of 0.1V - 1.75V
There is a scaling circuit which scales and offsets this voltage to 0V @ -40°C to 5V @ 125°C
- that is a 165°C range of temperature over a 5V range in voltage
The A2D produce a reading of 0 for a 0V input and 1023 for 5V input - that is a range of 1024
so 1024 / 165 = 6.206
and a 40°C offset
To convert bits to °C you take the A2D reading divide by 6.206 and subtract 40.


text:
Q: Is it easy to recover an encryption password from a compiled encryption script only? Can a encryption password <password> in compiled script script.x  be easily recovered?
The source version of script.x would be for instance
# cat script
openssl enc -des3 -in myfile -out myfile.des -k <password>

and the compiled version script.x is obtained with
# shc -f script

Can I recover <password> if I only have script.x without long lasting bruteforcing?

A: Personally, I do not know - my opinion is that it is easy.
I would not try to reverse engineer script by using brute force to 'decrypt' the compiled script - instead would try to discover  by using an audit of commands that are executed by "sh", "bash" and just examine the command arguments.
Worst case: /usr/bin/ps would/could show the password and/or /proc/*/"something" - do not know /proc well enough to specify the file containing the command arguments

A: Yes, it's pretty easy, even if you don't know anything about the compiled format. You just run the script in a debugger and catch when it uses the password for something. As a general principle, it's impossible to hide a password that's being used on someone else's machine. If they can run software that uses the password then they can see the password.
In this case, even that is overkill: since the password is passed to the openssl command, all you need is to put a wrapper for openssl that logs its arguments, or to observe the openssl process while it's running.
In addition, it's likely that the password can be recovered from the encrypted file, by simple brute force, which will not be as long as it should be. openssl enc is horribly bad at generating an encryption key from a password: this should be slow (see Possible to show Metasploitable (Linux) password in plain text?, How to securely hash passwords?) but openssl enc makes it fast, and worse, you're not even using it correctly: you're using it without a salt. See How to gradually encrypt the tshark output file along the capture? for what to do instead.
A word of warning: from your recent questions, you appear to be well over your head when it comes to security. I strongly recommend that you stick to simple things and keep your system's defaults as much as possible. Your attempts to use tools that you don't understand to make unnecessary improvements tend to make things worse.


text:
Q: How do I test an error on reading from a request body? I'm writing unit tests for http Handlers in golang. When looking at code coverage reports of this I am running into the following issue: When reading the request body from a request, ioutil.ReadAll might return an error that I need to handle. Yet, when I write unit tests for my handler I do not know  how to send a request to my handler in a way that it will trigger such an error (premature end of content seems not to generate such an error but will generate an error on unmarshaling the body). This is what I am trying to do:
package demo

import (
    "bytes"
    "io/ioutil"
    "net/http"
    "net/http/httptest"
    "testing"
)

func HandlePostRequest(w http.ResponseWriter, r *http.Request) {
    body, bytesErr := ioutil.ReadAll(r.Body)
    if bytesErr != nil {
        // intricate logic goes here, how can i test it?
        http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
        return
    }
    defer r.Body.Close()
    // continue...
}

func TestHandlePostRequest(t *testing.T) {
    ts := httptest.NewServer(http.HandlerFunc(HandlePostRequest))
    data, _ := ioutil.ReadFile("testdata/fixture.json")
    res, err := http.Post(ts.URL, "application/json", bytes.NewReader(data))
    // continue...
}

How can I write a test case for HandlePostRequest that also covers the case of bytesErr not being nil?

A: You may create and use an http.Request forged by you, which deliberately returns an error when reading its body. You don't necessarily need a whole new request, a faulty body is enough (which is an io.ReadCloser).
Simplest achieved by using the httptest.NewRequest() function where you can pass an io.Reader value which will be used (wrapped to be an io.ReadCloser) as the request body.
Here's an example io.Reader which deliberately returns an error when attempting to read from it:
type errReader int

func (errReader) Read(p []byte) (n int, err error) {
    return 0, errors.New("test error")
}

Example that will cover your error case:
func HandlePostRequest(w http.ResponseWriter, r *http.Request) {
    defer r.Body.Close()
    body, err := ioutil.ReadAll(r.Body)
    if err != nil {
        fmt.Printf("Error reading the body: %v\n", err)
        return
    }
    fmt.Printf("No error, body: %s\n", body)
}

func main() {
    testRequest := httptest.NewRequest(http.MethodPost, "/something", errReader(0))
    HandlePostRequest(nil, testRequest)
}

Output (try it on the Go Playground):
Error reading the body: test error

See related question if you would need to simulate error reading from a response body (not from a request body): How to force error on reading response body


text:
Q: Visual Studio 2017 C++ компиляция win32 под 64бит С проблемой не раз сталкивался,но решения не находил.
Выходит такая ошибка:

Пробывал вручную решения очищать билды,не помогло.

UPD:
Искал решение моей ошибки почти два дня. Побаловался с настройками и все заработало.


text:
Q: Интеграция PL/SQL Developer с системой контроля версий. Как? Добрый день! Для работы используем PL/SQL Developer. Хочется наладить взаимодействие с какой либо системой контроля версий. Может быть плагины какие то или еще что-то.
Кто сталкивался с подобными проблемами, как решали?
Поделитесь опытом или идеями.

A: Лучшим вариантом для реализации данной задачи, думаю, будет Subversion.
Во-первых, можно развернуть SVN-сервер на собственных ресурсах или же пользоваться облачным. Тут в зависимости от ваших требований и бюджета.
Во-вторых, имеются весьма достойные и многофункциональные клиенты – TortioseSVN и SmartSVN (pro). Я пользуюсь последним несколько лет и весьма доволен. TortoiseSVN бесплатный, за пользование SmartSVN придется заплатить. Если решитесь, посодействую в приобретении лицензий со скидкой.

Дабы не нарушать правил сообщества, сразу оговорюсь, что не имею
  никаких коммерческих отношений со SmartSVN и не получаю никаких выгод.
  Просто это замечательное решение, которое, на мой взгляд стоит
  популяризировать и которое уж точно отвечает на заданный вопрос.

Интеграция в IDE, по моему мнению, совершенно необязательна и не делает решение автоматически хорошим. TortoiseSVN интегрирован с проводником Windows, в то время как SmartSVN - кросс-платформенный и весьма удобен в отслеживать изменений "на лету" и логичных, понятных коммитов.