text:
Q: How to reduce size of icons on Ubuntu (GNOME) desktop? How do I reduce the size of icons on my Ubuntu (GNOME) desktop? All the icons are too big since I am using a 12.1" laptop so it looks horrible.

A: two solutions i know of -

*

*right click the icon, select Stretch Icon...

*Open a terminal
type nautilus (this open a file browser)
Edit -> Preferences -> Icon View Defaults and select the size you like

A: Going below 48px requires changing the Nautilus source code and recompiling. (Yes, they hard-coded icons sizes.)
**** INSTRUCTIONS FOR NAUTILUS 3.20.4 ON UBUNTU-GNOME 17.04 ****
1. Install the following dependencies:
libgd-dev autotools-dev libexif-dev libexempi-dev libselinux1-dev libtracker-sparql-1.0-dev libext-dev libxml2-dev libgnome-desktop-3-dev
Each one installs a bunch of other stuff, so hopefully I've given you the correct parent package name. I apologize for not recalling with 100% accuracy exactly what I installed, but this looks fairly correct to me immediately after my install. (Notify me if I'm inaccurate anywhere.)
2. Download from the Nautilus snapshots website (https://download.gnome.org/sources/nautilus/) the version of Nautilus that you are currently using. To find that out, run "nautilus --version" from the terminal. After downloading the archive, unzip it to whatever directory you want to work from.
3. From within the unzipped package, open the file "nautilus-icon-info.h". Within the first several lines you will see various sizes designated for the particular scroll-setting options. For instance, within the file for version 3.20.4 the icon sizes start on line 36. Change each of those levels to whatever you want to use so that you can make the icons much smaller (or larger).
4. After editing and saving the file, it's time to configure, compile, and install. Run the following commands from the terminal from within the base directory of the version of nautilus that you have downloaded and unzipped. Make sure that you are within the base of the folder structure of the nautilus directories!
./configure
make
sudo make install
This can be run altogether with the command "./configure && make && make install".
If the ./configure command fails it's because you are missing some other dependencies. I apologize if my list of dependencies above was incomplete. Google (or whatever search engine you want) to find what package it is that you need. You can use Synaptic to search for what you need if you're unsure even after Googling.
Once installed, I suggest a reboot just to make sure that every single thing is reloaded properly. You can now tweak your icon sizes as you wish.
Have fun!


text:
Q: VOIP dialer in iOS I want to create an iOS application which acts as a VOIP dialer.
I need to know does apple allow VOIP Dialing in iOS.? IF yes then what libraries should I use  and how?

A: Apple has allowed multiple VoIP apps in the app store. One option for building an app like this would be Twilio Client which has an iOS SDK currently in beta.
(I work at Twilio)

A: Of course apple allow the voip application on Apple Store. there are hundreds of app on apple store like bria(counter path), vippi , Adore SIP client..............
Please follow the Below URL:
http://code.google.com/p/siphon/ that is using pjsip integration.

A: I want to create an iOS application which acts as a VOIP dialer. I need to know does apple allow VOIP Dialing in iOS.? IF yes then what libraries should I use and how?
Hello Dear,
yes, apple allows VOIP Dialing in iOS with swift and C both. as I was making R&D for same then I found the best way to implement VoIP in IOS and android both is PJSip. you can see here. and there are many of open source using this for that see. and for IOS specially see it.
Enjoy your code time:)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Not found because of proxy error: Error: certificate has expired when trying to do an axios Post I am getting Not found because of proxy error: Error: certificate has expired when trying to do an axios Post.
I am using the below code to get the Axios post request:
axios.post('https://35.163.140.105:9999/osm/admin/v1/tokens', postData, axiosConfig)
.then(function(response) {
  console.log('Authenticated');
}).catch(function(error) {
  console.log('Error on Authentication');
});


text:
Q: iptables: Auto-add log-prefix to all DROP targets In iptables i would to add logging to every place where DROP is called.
However since I could encounter different tables in a production environment, I would just like to extend all rules that contain the DROP target, I don't want to go through the tedious process of rewriting every rule manually. Hence, I wonder - Is there a way to just change or add a log-prefix in a number of matching rules in order to add a custom string, say "DROPPED" ...? This way, if I add a similar entry in the PREROUTING table I can detect all the packets in a range of ports where PREROUTING is not followed by DROPPED, which would indicate a packet passthrough, which is ultimately what I would like to detect.
Either this way, or if there is another better way...

A: Here is one of the best options.
iptables -N myDrop
iptables -A myDrop -j LOG --log-prefix "dropping " --log-level 7 --log-tcp-sequence --log-tcp-options --log-ip-options
iptables -A myDrop -j DROP

Now instead of doing a -j DROP do -j myDrop and it will be logged.
You can setup ulogd and log to a number of other destinations including a database.
iptables -A myDrop -j NFLOG --nflog-prefix  banned_hosts --nflog-group 1


text:
Q: Issue with escape char in mySql import I have a small issue importing a csv file into mysql.
I am using csv file with loaddata as import.
The escape char that the supplier of the csv file have chosen to use is : ¤
What ever I try to enter when importing the csv file ends up with this error:
LOAD DATA LOCAL INFILE 'C:\\xampp\\tmp\\php1E14.tmp' INTO TABLE `TableName` FIELDS TERMINATED BY ';' ENCLOSED BY '"' ESCAPED BY '\\¤' LINES TERMINATED BY '\r\n'

MySQL returned: Documentation
#1083 - Field separator argument is not what is expected; check the manual

Any ideas on how to fix this issue, and please not just have the supplier using another escape char.

A: Why are you prefixing your escape character with a literal backslash?  Indeed, as documented under LOAD DATA INFILE Syntax:

If not empty, the FIELDS [OPTIONALLY] ENCLOSED BY and FIELDS ESCAPED BY values must be a single character.

Therefore:
LOAD DATA LOCAL INFILE 'C:\\xampp\\tmp\\php1E14.tmp'
    INTO TABLE `TableName`
    FIELDS
        TERMINATED BY ';'
        ENCLOSED BY '"'
        ESCAPED BY '¤'
    LINES
        TERMINATED BY '\r\n'


text:
Q: Alias Queue in Cluster with queue type "cluster" In cluster environment I have deleted a remote queue say "REMOTEtoTNSERVER". But i could see the same queue exists as type "cluster" with several instance. How can i delete them? I checked on repository the queue manager entry for that remote queue is no longer exists.
Please suggest your answers.
Thanks,
Vignesh

A: Assume QMgrs A, B, C, and REPOS1 and REPOS2 in the cluster.  If you are working on A and delete REMOTEtoTNSERVER and still see it as a cluster queue, then it is defined somewhere else in the cluster, probably on B and C.
If you go to the repository QMgrs, they too will show the queues that are on B & C and advertised to the cluster.  The only way to get rid of these is to sign onto the B & C QMgrs and delete the queues or remove them from the cluster.
To determine which QMgrs in the cluster host the clustered instances of these queues, use the DIS QCLUSTER() command from the A QMgr or either of the repositories.  This will tell you which QMgrs host an instance of a clustered queue so that you can go there and delete them.


text:
Q: How isolate between two times in pandas data frame and then modify just those values in a larger pandas dataframe? I have a large pandas dataframe. I want to select a subset (time range) of the dataframe and modify it by multiplying it by -1. I was trying something like this but it didn't work. Any suggestions?
g[g.between_time('22:55:00', '22:59:35')] =  g[g.between_time('22:55:00', '22:59:35')] * -1

A: Use update:
g.update(g[g.between_time('22:55:00', '22:59:35')] * -1)


text:
Q: How can I view what percentage of my hard drive bandwidth is currently being used? Can anyone recommend a disk access utility, preferably free, that will allow me to see what percentage of my hard drive access bandwidth is being used?
Windows Task Manager shows CPU usage.  That was fine, back in the day, when the CPU was the bottleneck, but these days it's typically the hard drive that slows everything down.

A: You can use Process Hacker to show you this information.  Process Hacker is an extension of the popular Process Explorer program, albeit a lot more powerful.  In the default view, there is a column titled I/O Total Rate, and it shows what each processes' disk transfer rate is (if it's performing any I/O reads or writes).  This provides the transfer rate in either B/s, kB/s, or MB/s.
To see your total HDD bandwidth, you need to get a hard drive benchmark utility (like HdTach).  From that, you can determine what percent of full bandwidth is being used by simply dividing the Process Hacker's I/O rate by your HDD's read or write rate (depending on what the application is doing).

A: I've since learned that the Resource Monitor utility included with Windows 7 has a pretty good hard drive usage feature.


text:
Q: Converting RGB images into lossless video with avconv / ffmpeg I am trying to convert a series of PNG24 images containing a screen animation to a lossless video, so that every pixel is reproduced exactly as it was in the original. But avconv (and ffmpeg) both produce the same, unsatisfying results, which seem to stem from a colospace conversion going wrong.
This is the version of avconv I am using:
avconv version 0.8.6-4:0.8.6-0ubuntu0.12.04.1, Copyright (c) 2000-2013 the Libav developers
  built on Apr  2 2013 17:02:36 with gcc 4.6.3

Each of the images is 1280×800 pixels in size. They do not contain any photographic motives, but specially dithered patterns.
I used the qtrle codec because apparently this is a lossless codec that works very much like animated GIFs or animated PNGs. However, during the conversion to video there seems to happen a color space conversion ("filter") that is messing with the pixels.
This is the avconv output:
$ avconv -f image2 -r 30 -i frames.png/wth-%08d.png -vcodec qtrle -pix_fmt rgb24 -t 15 qtrle-30fps-rgb.mov
avconv version 0.8.6-4:0.8.6-0ubuntu0.12.04.1, Copyright (c) 2000-2013 the Libav developers
  built on Apr  2 2013 17:02:36 with gcc 4.6.3
Input #0, image2, from 'frames.png/wth-%08d.png':
  Duration: 00:11:17.96, start: 0.000000, bitrate: N/A
    Stream #0.0: Video: png, bgra, 1280x800, 30 fps, 30 tbr, 30 tbn, 30 tbc
File 'qtrle-30fps-rgb.mov' already exists. Overwrite ? [y/N] y
[buffer @ 0x740a00] w:1280 h:800 pixfmt:bgra
[avsink @ 0x742ac0] auto-inserting filter 'auto-inserted scaler 0' between the filter 'src' and the filter 'out'
[scale @ 0x743680] w:1280 h:800 fmt:bgra -> w:1280 h:800 fmt:rgb24 flags:0x4
Output #0, mov, to 'qtrle-30fps-rgb.mov':
  Metadata:
    encoder         : Lavf53.21.1
    Stream #0.0: Video: qtrle, rgb24, 1280x800, q=2-31, 200 kb/s, 30 tbn, 30 tbc
Stream mapping:
  Stream #0:0 -> #0:0 (png -> qtrle)
Press ctrl-c to stop encoding
frame=  450 fps= 22 q=0.0 Lsize=  126056kB time=15.00 bitrate=68843.4kbits/s
video:126052kB audio:0kB global headers:0kB muxing overhead 0.003441%

This is an original PNG image file:

This is a screenshot of the video being replayed:

Please note that you need to see these images in their original 1280×800 resolution to notice the differences.
Here is a side-by-side comparison, with the left picture being the original and the right one the outcome after video encoding:

Is there any way I can produce a truly lossless, pixel-perfect video file from a series of PNGs?

A: With the help of a ffmpeg contributor it was found out that both ffmpeg and libav create flawless lossless Quicktime files. The problem seems to be the graphic card driver displaying the videos wrongly (since GStream based players and VLC both display it wrongly, however VLC is exporting perfect PNGs of video frames). If you want to check if a video is really containing the frames pixel by pixel, try using
$ ffmpeg -i input.png -vcodec qtrle out.mov

$ ffmpeg -i input.png -f framecrc -
$ ffmpeg -i out.mov -f framecrc -

This will output frame data checksums.
For a visual comparison, convert the lossless video back to single frames and compare those.

A: I posted a longish answer on:
How to create an uncompressed AVI from a series of 1000's of PNG images using FFMPEG
vcodec libx264rgb with -preset ultrafast -qp 0, or utvideo.


text:
Q: Authentication Failed issue on sending sms using Way2Sms + Java Tried to send sms from Java application by creating three Java Class given below 1. Credentials 2. URLConnector 3. Way2Sms and running Way2Sms Class, but getting authentication failed! because of responseCode is 404 or 408 in Way2Sms java login method...any help to resolve this would be appreciated....
**Way2Sms.java**
package way2sms;
/* Code from this site
 *
 * http://jtechbits.blogspot.in/2011/06/sending-sms-through-way2sms-in-java.html
 *
 * */

import java.net.HttpURLConnection;
import java.util.Calendar;

public class Way2Sms
{
    private static int responseCode = -1;
    private static String userCredentials;
    private static String cookie;
    private static String token;
    private static String site;
    private static String actionStr;
    private static String random1;
    private static String random2;
    private static String random3;
    private static Credentials credentials = new Credentials();

    public static void main(String[] args)
    {
        login("mynumber", "mypassword");
        sendSMS("9663384741", "Hello");
        System.out.println("Message has been sent successfully!");
    }

    private static void setProxy(String host, int port)
    {
        URLConnector.setProxy(host, port);
    }

    private static void login(String uid, String pwd)
    {
        getSite();
        preHome();
        String location = null;
        credentials.set("username", uid);
        credentials.append("password", pwd);
        credentials.append("userLogin", "no");
        credentials.append("button", "Login");
        userCredentials = credentials.getUserCredentials();
        URLConnector.connect("http://" + site + "/w2sauth.action", false, "POST", cookie, userCredentials);
        **responseCode = URLConnector.getResponseCode();**
        if(responseCode != HttpURLConnection.HTTP_MOVED_TEMP && responseCode != HttpURLConnection.HTTP_OK)
        {
            exit("authentication failed!");
        }
        else
        {
            location = URLConnector.getLocation();
            URLConnector.disconnect();
            URLConnector.connect(location, false, "GET", cookie, null);
            responseCode = URLConnector.getResponseCode();
            if(responseCode != HttpURLConnection.HTTP_MOVED_TEMP && responseCode != HttpURLConnection.HTTP_OK)
            {
                exit("redirection failed!");
                URLConnector.disconnect();
            }
        }
    }

    private static void sendSMS(String receiversMobNo, String msg)
    {
        getActionString();
        credentials.reset();
        credentials.set("t_15_k_5", random1);
        credentials.append("i_m", "sn2sms");
        credentials.append("m_15_b", random2);
        if(actionStr != null)
            credentials.append("kriya", actionStr);
        else
        {
            exit("Action string missing!");
            credentials.append(random3, "");
            credentials.append(random1, token);
            credentials.append("catnamedis", "Birthday");
            credentials.append("chkall", "on");
            credentials.append("diffNo", Calendar.getInstance().getTime().toString().split(" ")[3]);
            credentials.append(random2, receiversMobNo);
            credentials.append("txtLen", "" + (140 - msg.length()));
            credentials.append("textArea", msg);
            userCredentials = credentials.getUserCredentials();
            URLConnector.connect("http://" + site + "/jsp/w2ssms.action", false, "POST", cookie + "; 12489smssending34908=67547valdsvsikerexzc435457", userCredentials);
            responseCode = URLConnector.getResponseCode();

            if(responseCode != HttpURLConnection.HTTP_MOVED_TEMP && responseCode != HttpURLConnection.HTTP_OK)
                exit("sendSMS failed!");
            URLConnector.disconnect();
        }
    }

    private static void sendSMS(String[] receiversMobNos, String msg)
    {
        int noOfReceivers = receiversMobNos.length;
        for(int i = 0; i < noOfReceivers; i++)
            sendSMS(receiversMobNos[i], msg);
    }

    private static void getSite()
    {
        URLConnector.connect("http://www.way2sms.com/", false, "GET", null, null);
        responseCode = URLConnector.getResponseCode();
        if(responseCode != HttpURLConnection.HTTP_MOVED_TEMP && responseCode != HttpURLConnection.HTTP_OK)
            exit("getSite failed!");
        else
        {
            site = URLConnector.getLocation();
            if(site != null)
                site = site.substring(7, site.length() - 1);
        }
        URLConnector.disconnect();
    }

    private static void preHome()
    {
        URLConnector.connect("http://" + site + "/content/prehome.jsp", false, "GET", null, null);
        responseCode = URLConnector.getResponseCode();
        if(responseCode != HttpURLConnection.HTTP_MOVED_TEMP && responseCode != HttpURLConnection.HTTP_OK)
            exit("preHome failed");
        else
        {
            cookie = URLConnector.getCookie();
            token = cookie.substring(cookie.indexOf("~") + 1);
        }
        URLConnector.disconnect();
    }

    private static void getActionString()
    {
        URLConnector.connect("http://" + site + "/jsp/SingleSMS.jsp?Token=" + token, false, "GET", cookie, null);
        responseCode = URLConnector.getResponseCode();
        if(responseCode == HttpURLConnection.HTTP_MOVED_TEMP || responseCode == HttpURLConnection.HTTP_OK)
        {
            String str = URLConnector.getResponse();
            String aStr = "id='kriya' value='";
            int index = str.indexOf(aStr);
            if(index > 0)
            {
                index = index + aStr.length();
                StringBuffer actionStringChars = new StringBuffer();
                char ch = str.charAt(index);
                while(ch != '\'')
                {
                    actionStringChars.append(ch);
                    ch = str.charAt(++index);
                }
                actionStr = actionStringChars.toString();
                getRandom1(str);
                getRandom2(str);
                getRandom3(str);
            }
        }
        else
        {
            exit("getActionString failed!");
            URLConnector.disconnect();
        }
    }

    private static void getRandom1(String str)
    {
        String aStr = "id='t_15_k_5'";

        int index = str.indexOf(aStr);
        if(index > 0)
        {
            index = index + aStr.length();

            StringBuffer random1Chars = new StringBuffer();
            char ch = str.charAt(index);

            if(ch == '>')
            {
                ch = str.charAt(++index);
                while(ch != '<')
                {
                    random1Chars.append(ch);
                    ch = str.charAt(++index);
                }
            }
            else
            {
                index += 8;
                ch = str.charAt(index);
                while(ch != '\'')
                {
                    random1Chars.append(ch);
                    ch = str.charAt(++index);
                }
            }
            random1 = random1Chars.toString();
        }
    }

    private static void getRandom2(String str)
    {
        String aStr = "id='m_15_b'";

        int index = str.indexOf(aStr);
        if(index > 0)
        {
            index = index + aStr.length();
            StringBuffer random2Chars = new StringBuffer();
            char ch = str.charAt(index);
            if(ch == '>')
            {
                ch = str.charAt(++index);

                while(ch != '<')
                {
                    random2Chars.append(ch);
                    ch = str.charAt(++index);
                }
            }
            else
            {
                index += 8;
                ch = str.charAt(index);
                while(ch != '\'')
                {
                    random2Chars.append(ch);
                    ch = str.charAt(++index);
                }
            }
            random2 = random2Chars.toString();
        }
    }

    private static void getRandom3(String str)
    {
        String aStr = "dnipb";

        int index = str.lastIndexOf(aStr);
        if(index > 0)
        {
            index -= 40;

            StringBuffer random3Chars = new StringBuffer();
            char ch = str.charAt(index);

            while(ch != '\"')
            {
                random3Chars.append(ch);
                ch = str.charAt(--index);
            }
            random3 = random3Chars.reverse().toString();
        }
    }

    private static void exit(String errorMsg)
    {
        System.err.println(errorMsg);
        System.exit(1);
    }
}

**URLConnector.java**

package way2sms;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ByteArrayOutputStream;
import java.net.HttpURLConnection;
import java.net.Proxy;
import java.net.URL;

public class URLConnector {
private static HttpURLConnection connection;
private static Proxy proxy;

public static void setProxy(String host, int port) {
proxy = new Proxy(Proxy.Type.HTTP, java.net.InetSocketAddress.createUnresolved(host, port));
}

public static void connect(String urlPath, boolean redirect, String method, String cookie, String credentials)
{
    try
    {
        URL url = new URL(urlPath);
        if(null != proxy)
            connection = (HttpURLConnection) url.openConnection(proxy);
        else
        {
            connection = (HttpURLConnection) url.openConnection();
            connection.setInstanceFollowRedirects(redirect);
            if(cookie != null)
                connection.setRequestProperty("Cookie", cookie);
            if(method != null && method.equalsIgnoreCase("POST"))
            {
                connection.setRequestMethod(method);
                connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            }
            connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:10.0.4) Gecko/20100101 Firefox/10.0.4");
            connection.setUseCaches (false);
            connection.setDoInput(true);
            connection.setDoOutput(true);
            if(credentials != null)
            {
                DataOutputStream wr = new DataOutputStream (connection.getOutputStream ());
                wr.writeBytes (credentials);
                wr.flush ();
                wr.close ();
            }
        }

    }
    catch(Exception exception)
    {
        System.out.println("Connection error");
    }
}

    public static String getCookie()
    {
        String cookie = null;
        if(connection != null)
        {
            String headerName=null;
            for (int i = 1; (headerName = connection.getHeaderFieldKey(i)) != null; i++)
            {
                if (headerName.equals("Set-Cookie"))
                {
                    cookie = connection.getHeaderField(i).split(";")[0];
                    break;
                }
            }
        }
        return cookie;
    }

    public static String getLocation()
    {
        String location = null;
        if(connection != null)
        {
            String headerName=null;
            for (int i = 1; (headerName = connection.getHeaderFieldKey(i)) != null; i++)
            {
                if (headerName.equals("Location"))
                {
                    location = connection.getHeaderField(i).split(";")[0];
                    break;
                }
            }
        }
        return location;
    }

    public static int getResponseCode()
    {
        int responseCode = -1;
        if(connection != null)
        {
            try
            {
                responseCode = connection.getResponseCode();
            }
            catch(Exception exception)
            {
                System.err.println("Response code error");
            }
        }
        return responseCode;
    }

    public static String getResponse()
    {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        if(connection != null)
        {
            try
            {
                InputStream is = connection.getInputStream();
                int next = is.read();
                while (next > -1)
                {
                    bos.write(next);
                    next = is.read();
                }
                bos.flush();
            }
            catch(Exception exception)
            {
                System.err.println("Response error");
            }
        }
        return new String(bos.toByteArray());
    }
    public static String getErrorMessage()
    {
        StringBuilder errorMessage = new StringBuilder();
        if(connection != null)
        {
            try
            {
                InputStream es = connection.getErrorStream();
                BufferedReader rd = new BufferedReader(new InputStreamReader(es));
                String line;
                while((line = rd.readLine()) != null)
                {
                    errorMessage.append(line);
                    errorMessage.append("\r\n");
                }
                rd.close();
            }
            catch(Exception exception)
            {
                System.err.println("Error in getting error message");
            }
          }
          return errorMessage.toString();
    }
    public static void disconnect()
    {
        if(connection != null)
            connection.disconnect();
    }
}
**Credentials.java**

package way2sms;

import java.net.URLEncoder;
import java.util.ArrayList;

public class Credentials
{
    private ArrayList< String > list = new ArrayList< String >();
    public void set(String name, String value) {
    StringBuilder buffer = new StringBuilder();
    buffer.append(name);
    buffer.append("=");
    buffer.append(getUTF8String(value));
    add(buffer.toString());
}
    public void append(String name, String value)
    {
        StringBuilder buffer = new StringBuilder();
        buffer.append("&");
        buffer.append(name);
        buffer.append("=");
        buffer.append(getUTF8String(value));
        add(buffer.toString());
    }

    private void add(String item)
    {
        list.add(item);
    }

    private String getUTF8String(String value)
    {
        String encodedValue = null;
        try
        {
            encodedValue = URLEncoder.encode(value, "UTF-8");
        }
        catch(Exception exception)
        {
            System.err.println("Encoding error! Please try agian...");
            System.exit(1);
        }
        return encodedValue;
    }
    public boolean isEmpty()
    {
        return list.isEmpty();
    }
    public void reset()
    {
        list.clear();
    }
    public String getUserCredentials()
    {
        StringBuilder buffer = new StringBuilder();
        int size = list.size();
        for(int i = 0; i < size; i++)
        {
            buffer.append(list.get(i));
        }
        return buffer.toString();
    }
}

A: This is due to human verification code that is Captcha. Now you can't login with previous api to send sms. You need to contact with your service provider.


text:
Q: Ruby Selenium 3.0 - how to click on 'rel Attribute'? How can I click on the login button ?
Login

Below the code in the screenshot:

I can do it by xpath, but I wonder if there is other ways ?
Any help would be appreciated,
Thanks!

A:
I can do it by xpath, but I wonder if there is other ways ?

I would suggest you, try using cssSelector which would be much faster than xpath to locate an element as :-
driver.find_element(:css, "div#anonymous > a[rel='IDS_login']").click

You can also locate this element using link_text as :-
driver.find_element(:link_text, "Login").click


text:
Q: Trouble on shutdowning my laptop I have a laptop Compaq Presario R4000 and because of the end of support to Windows XP -installed previously on it- I decided finally to install Ubuntu 12.04 LTS. Now I have only this OS on my laptop, but it doesn't shutdown. It closes every apps and goes to the screen with the name of UBUNTU and the little spots below, and continues like this for all the time. I have to push the on/off button for a 5 seconds and shutdown my laptop like this. I tried to change grub, and to change modules, and to try to shutdown from the terminal but it doesn't run.
¿May someone help me, please? Thank you and best regards.

A: From Terminal you can use the poweroff command to perform a soft shutdown, rather than the more destructive hard shutdown you've used by holding down the power button.  Close all of your programs and windows, then run this from Terminal:

sudo poweroff now

You'll need to enter your password, and should see the machine softly shutdown.


text:
Q: Pandas subset of DataFrame with fixed number of value per class I have a pandas DataFrame df that contains a column ID and a column Type. Here is an example :
print(df)

>>
+---------+---------+
|       ID|     Type|
+---------+---------+
|      AAA|        A|
|      BBB|        B|
|      CCC|        B|
|      DDD|        A|
|      EEE|        B|
|      FFF|        A|
|      GGG|        B|
+---------+---------+

From that DataFrame, I want to extract a sub DataFrame with X distinct values for each Type.
Here is with the previous example (The order does not matter):
X = 2
new_df = do_something(df, X)
print(new_df)

>>
+---------+---------+
|       ID|     Type|
+---------+---------+
|      AAA|        A|
|      DDD|        A|
|      BBB|        B|
|      CCC|        B|
+---------+---------+

Is there a simple way to do that ?

A: Use pandas.DataFrame.groupby.head:
import pandas as pd

df.groupby('Type').head(2)

Output:
    ID Type
0  AAA    A
1  BBB    B
2  CCC    B
3  DDD    A


text:
Q: unicodedata.unidata_version prints wrong unicode version? >>> import sys
>>> sys.version_info
sys.version_info(major=2, minor=7, micro=2, releaselevel='final', serial=0)

>>> import unicodedata
>>> unicodedata.unidata_version
'5.2.0'

Which means my Python version should have Unicode 5.2.0.
But When I go to the list of newly added unicode chars in version 5.2.0 and print such char, it is not recognised:
>>> print u"\u0803"
ࠃ

Chars from 5.1.0 are recognised however:
>>> print u"\u03CF"
Ϗ

So should I always count one version below the one is actually outputted by unicodedata.unidata_version or am I misunderstanding something?

A: You are confusing what your terminal can print with what Python knows about unicode characters.
Your terminal font doesn't recognize those code points. Python can handle them just fine:
>>> import unicodedata
>>> unicodedata.category(u'\u0803')
'Lo'
>>> unicodedata.name(u'\u0803')
'SAMARITAN LETTER DALAT'
>>> unicodedata.category(u'\u03CF')
'Lu'
>>> unicodedata.name(u'\u03CF')
'GREEK CAPITAL KAI SYMBOL'

Ironically enough, the font used by my browser doesn't define an image for either codepoint. Your post shows two placeholder characters for me:


text:
Q: Best option to detect if url is hit from page rather than copy paste in browser I need to count number of hits of a url being hit from a page but for that I need to detect if url is being hit from page or simply copy pasted.
Can anyone suggest me what to choose among methods:
    1. Using $_SERVER['HTTP_REFERER']
    2. Using sessions
    3. IP matching

A: $_SERVER['HTTP_REFERER'] seems to be the natural choice, however, the php docs at http://php.net/manual/en/reserved.variables.server.php have some intersting stuff to say:

'HTTP_REFERER' The address of the page (if any) which referred the
  user agent to the current page. This is set by the user agent. Not all
  user agents will set this, and some provide the ability to modify
  HTTP_REFERER as a feature. In short, it cannot really be trusted.

A more reliable method would be to encode some data dynamically into the URL when it is clicked on the page, like the current UTC datetime.  Then server side check if the received timestamp is within 1 or 2 seconds of the current time.  If there is a copy and paste, either there will not be a timestamp, or the timestamp will be wrong.
It is possible that the client will have the wrong time, but unlikely nowadays.  To be extra extra sure, you would need to send a timestamp from the server and use this as a base for generating your datetime.

Following comments:
agree, timestamps can be subject to network fluctuations.  How about encoding some data in a once-time-only cookie (ie expires immediately) with Javascript (which the server can verify).  You can't copy and paste a cookie!


text:
Q: How to fix firefox connection untrusted Firefox gives me connection untrusted for SSL https, and why is that, Chrome shows https in green so, chrome OK, firefox not, why ?

A: when i install ff 16.0.2, i seem to have same prob with you(untrusted connection especially firefox addon)..For me, it basically cause by my nod32 antivirus, i try go to setting>protocol filtering>ssl>certificates>untick "add the root certificate to known browser''(make sure ff really close)..then tick it again and click OK..done

A: Please check this:
https://developer.mozilla.org/En/Displaying_web_content_in_an_extension_without_security_issues

A: I thing you can bypass the warning:
You can tell Firefox to bypass these certificate warnings. You should only bypass the warning if you're sure that the site is legitimate. Legitimate public sites will not ask you to do this. An invalid certificate can be an indication of a web page that will defraud you or steal your identity.
1.On the warning page, click Or you can add an exception....
2.Click Add Exception.... The Add Security Exception dialog will appear.
3.Click Get Certificate.
4.Read the text describing the problems with this site.
5.Click Confirm Security Exception if you want to trust the site.

http://support.mozilla.com/en-US/kb/Secure%20Connection%20Failed
http://support.mozilla.com/en-US/kb/Firefox%20cannot%20connect%20securely%20because%20the%20site%20uses%20an%20older%20insecure%20version%20of%20the%20SSL%20protocol
If any of these TS won't work, then try to update to FF V7. Don't forget to file a bug in bugzilla with all the necessary information.

A: However if you wish to access sites without accepting the certificate each time, use the add-on skip-cert-error "https://addons.mozilla.org/en-US/firefox/addon/skip-cert-error"

A: I had this weird issue "Your connection is not secure" whereas Chrome works like a charm.
Actually, it is because i let the corporate pac script to manage the proxy setup ticking the option "use system proxy settings". Actually, Firefox don't like it !
When i switch back to the manual proxy settings, all get back to work.
Of course, you need to known proxy params.
Go & surf ...

A: Change your Date to current date :D
I had same issue


text:
Q: SwiftUI crashing with EXC_BREAKPOINT (SIGTRAP) for one user and I can't replicate it in simulator I taught myself to code this year and finally started sharing my app with some friends through TestFlight. One friend of mine can't tap anything in the app without it crashing, but I can't seem to replicate the issue in simulator. Here's the crash log:
Incident Identifier: 9C5CBC92-D799-4EF7-A0BD-B3D38BDFCD6A
Beta Identifier:     14981E01-C6E4-4340-A6C2-2C7730C5F39F
Hardware Model:      iPhone9,3
Process:             Skool [849]
Path:                /private/var/containers/Bundle/Application/CD824E3B-BB88-47D1-912E-55156C40187E/Skool.app/Skool
Identifier:          com.kevinolmats.Skool
Version:             2777 (0.2.2)
AppStoreTools:       11E503a
AppVariant:          1:iPhone9,3:13
Beta:                YES
Code Type:           ARM-64 (Native)
Role:                Foreground
Parent Process:      launchd [1]
Coalition:           com.kevinolmats.Skool [677]

Date/Time:           2020-05-09 10:19:43.2873 -0600
Launch Time:         2020-05-09 10:19:41.3463 -0600
OS Version:          iPhone OS 13.4.1 (17E262)
Release Type:        User
Baseband Version:    4.02.02
Report Version:      104

Exception Type:  EXC_BREAKPOINT (SIGTRAP)
Exception Codes: 0x0000000000000001, 0x00000001becb85e0
Termination Signal: Trace/BPT trap: 5
Termination Reason: Namespace SIGNAL, Code 0x5
Terminating Process: exc handler [849]
Triggered by Thread:  0

Thread 0 name:
Thread 0 Crashed:
0   libswiftCore.dylib              0x00000001becb85e0 _assertionFailure(_:_:file:line:flags:) + 796 (AssertCommon.swift:132)
1   libswiftCore.dylib              0x00000001becb85e0 _assertionFailure(_:_:file:line:flags:) + 796 (AssertCommon.swift:132)
2   SwiftUI                         0x00000001e9394268 EnvironmentObject.error() + 216 (EnvironmentObject.swift:55)
3   Skool                           0x0000000104223228 CourseAssignmentsListView.body.getter + 2116 (CourseAssignmentsListView.swift:0)
4   SwiftUI                         0x00000001e8ef4a40 DynamicPropertyBody.update(context:) + 1788 (CustomView.swift:110)
5   SwiftUI                         0x00000001e8ef5040 protocol witness for static UntypedAttribute._update(_:graph:attribute:) in conformance DynamicPr... + 36 (<compiler-generated>:0)
6   AttributeGraph                  0x00000001dd21e998 partial apply + 28 (<compiler-generated>:0)
7   AttributeGraph                  0x00000001dd2079fc AG::Graph::UpdateStack::update() + 440 (ag-closure.h:104)
8   AttributeGraph                  0x00000001dd207eb4 AG::Graph::update_attribute(unsigned int, bool) + 372 (ag-graph-update.cc:399)
9   AttributeGraph                  0x00000001dd20b044 AG::Graph::value_ref(AG::attribute_t, AGTypeID, bool*) + 116 (ag-graph.cc:762)
10  AttributeGraph                  0x00000001dd218310 AGGraphGetValue + 48 (AGGraph.mm:304)
11  SwiftUI                         0x00000001e8ff59a0 ViewGraph.accessibilityNodes() + 108 (<compiler-generated>:0)
12  SwiftUI                         0x00000001e93adf08 specialized _UIHostingView.enableAccessibility() + 116
13  SwiftUI                         0x00000001e93a4aac specialized _UIHostingView.init(rootView:) + 2116 (UIHostingView.swift:1278)
14  SwiftUI                         0x00000001e93b3dc8 specialized UIHostingController.init(rootView:) + 56 (UIHostingView.swift:0)
15  SwiftUI                         0x00000001e933df74 specialized DestinationHostingController.__allocating_init(rootView:) + 56 (<compiler-generated>:0)
16  SwiftUI                         0x00000001e933dd2c NavigationBridge_PhoneTV.push(_:onto:animated:) + 76 (NavigationBridge_PhoneTV.swift:84)
17  SwiftUI                         0x00000001e8f83438 UIKitNavigationBridge.updatePresentedContent(_:animated:) + 204 (UIKitNavigationBridge.swift:168)
18  SwiftUI                         0x00000001e8f83844 UIKitNavigationBridge.preferencesDidChange(_:) + 372 (UIKitNavigationBridge.swift:203)
19  SwiftUI                         0x00000001e933d560 NavigationBridge_PhoneTV.preferencesDidChange(_:) + 44 (NavigationBridge_PhoneTV.swift:21)
20  SwiftUI                         0x00000001e8f26078 _UIHostingView.preferencesDidChange() + 476 (_UIHostingView.swift:199)
21  SwiftUI                         0x00000001e8ff3d74 ViewGraph.updateOutputs(at:) + 180 (ViewGraph.swift:652)
22  SwiftUI                         0x00000001e92928b4 closure #1 in closure #1 in ViewRendererHost.render(interval:updateDisplayList:) + 816 (ViewRendererHost.swift:157)
23  SwiftUI                         0x00000001e9291d54 closure #1 in ViewRendererHost.render(interval:updateDisplayList:) + 524 (ViewRendererHost.swift:145)
24  SwiftUI                         0x00000001e9288c5c ViewRendererHost.render(interval:updateDisplayList:) + 316 (ViewRendererHost.swift:132)
25  SwiftUI                         0x00000001e93aee50 _UIHostingView.displayLinkTimer(timestamp:) + 160 (UIHostingView.swift:1391)
26  SwiftUI                         0x00000001e8f26344 DisplayLink.displayLinkTimer(_:) + 88 (_UIHostingView.swift:270)
27  SwiftUI                         0x00000001e8f2639c @objc DisplayLink.displayLinkTimer(_:) + 40 (<compiler-generated>:0)
28  QuartzCore                      0x00000001b81c0368 CA::Display::DisplayLink::dispatch_items(unsigned long long, unsigned long long, unsigned long long) + 516 (CADisplay.mm:2528)
29  IOKit                           0x00000001b2751628 IODispatchCalloutFromCFMessage + 480 (IOKitLib.c:1239)
30  CoreFoundation                  0x00000001b1762bc0 __CFMachPortPerform + 172 (CFMachPort.c:533)
31  CoreFoundation                  0x00000001b178c200 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__ + 56 (CFRunLoop.c:1937)
32  CoreFoundation                  0x00000001b178b90c __CFRunLoopDoSource1 + 444 (CFRunLoop.c:2075)
33  CoreFoundation                  0x00000001b17866c0 __CFRunLoopRun + 1888 (CFRunLoop.c:3098)
34  CoreFoundation                  0x00000001b1785c34 CFRunLoopRunSpecific + 424 (CFRunLoop.c:3192)
35  GraphicsServices                0x00000001bb8cf38c GSEventRunModal + 160 (GSEvent.c:2246)
36  UIKitCore                       0x00000001b58b822c UIApplicationMain + 1932 (UIApplication.m:4820)
37  Skool                           0x000000010417275c main + 68 (OverdueDashboardSubview.swift:13)
38  libdyld.dylib                   0x00000001b160d800 start + 4

Thread 1:
0   libsystem_pthread.dylib         0x00000001b1527738 start_wqthread + 0

Thread 2:
0   libsystem_pthread.dylib         0x00000001b1527738 start_wqthread + 0

Thread 3:
0   libsystem_pthread.dylib         0x00000001b1527738 start_wqthread + 0

Thread 4:
0   libsystem_pthread.dylib         0x00000001b1527738 start_wqthread + 0

Thread 5:
0   libsystem_pthread.dylib         0x00000001b1527738 start_wqthread + 0

Thread 6 name:
Thread 6:
0   libsystem_kernel.dylib          0x00000001b15e1198 mach_msg_trap + 8
1   libsystem_kernel.dylib          0x00000001b15e060c mach_msg + 72 (mach_msg.c:103)
2   CoreFoundation                  0x00000001b178b3b4 __CFRunLoopServiceMachPort + 148 (CFRunLoop.c:2575)
3   CoreFoundation                  0x00000001b17863e8 __CFRunLoopRun + 1160 (CFRunLoop.c:2931)
4   CoreFoundation                  0x00000001b1785c34 CFRunLoopRunSpecific + 424 (CFRunLoop.c:3192)
5   Foundation                      0x00000001b1ac8bcc -[NSRunLoop(NSRunLoop) runMode:beforeDate:] + 228 (NSRunLoop.m:374)
6   Foundation                      0x00000001b1ac8aac -[NSRunLoop(NSRunLoop) runUntilDate:] + 88 (NSRunLoop.m:421)
7   UIKitCore                       0x00000001b595a160 -[UIEventFetcher threadMain] + 152 (UIEventFetcher.m:736)
8   Foundation                      0x00000001b1bf79d0 __NSThread__start__ + 848 (NSThread.m:724)
9   libsystem_pthread.dylib         0x00000001b1523d98 _pthread_start + 156 (pthread.c:896)
10  libsystem_pthread.dylib         0x00000001b152774c thread_start + 8

Thread 7:
0   libsystem_pthread.dylib         0x00000001b1527738 start_wqthread + 0

Thread 8:
0   libsystem_pthread.dylib         0x00000001b1527738 start_wqthread + 0

Thread 9:
0   libsystem_pthread.dylib         0x00000001b1527738 start_wqthread + 0

Thread 0 crashed with ARM Thread State (64-bit):
    x0: 0x0000000105d669e0   x1: 0x00000001bef56ef8   x2: 0x0000000000000407   x3: 0x000000000000001e
    x4: 0x0000000105d71c00   x5: 0x0000000000000013   x6: 0x0000000000000000   x7: 0x00000000000003f8
    x8: 0x0000000105d669e8   x9: 0x0000000200000002  x10: 0xfffffffe00000000  x11: 0x0000000000000000
   x12: 0x0000000000000002  x13: 0x0000000000003fff  x14: 0x000000004ca45cf5  x15: 0x000000000000f0be
   x16: 0x00000001b1512ffc  x17: 0x0000000001000002  x18: 0x0000000000000000  x19: 0x0000000105d669e0
   x20: 0x0000000000000000  x21: 0x0000000000000000  x22: 0x0000000000000000  x23: 0x00000001e94156a0
   x24: 0x0000000105d669e0  x25: 0xf000000000000095  x26: 0x000000000000000b  x27: 0x0000000000000002
   x28: 0x00000001042c7c58   fp: 0x000000016bc906a0   lr: 0x00000001becb85e0
    sp: 0x000000016bc90620   pc: 0x00000001becb85e0 cpsr: 0x60000000
   esr: 0xf2000001  Address size fault

I'm particularly concerned with this line:
37  Skool                           0x000000010417275c main + 68 (OverdueDashboardSubview.swift:13)

In the code, that line is:
@FetchRequest(entity: Assignment.entity(), sortDescriptors: [NSSortDescriptor(keyPath: \Assignment.dueDate, ascending: true), NSSortDescriptor(keyPath: \Assignment.name, ascending: true)]) var assignments: FetchedResults<Assignment>

but this works perfectly fine for me and everyone else I've sent the beta to. Is there something I'm missing in the crash log? Like I said I'm pretty new to coding and even newer when it comes to reading logs like this. Any ideas would be much appreciated!
Edit: Here is the code for CourseAssignmentListView as requested:
struct CourseAssignmentsListView: View {
    @FetchRequest(entity: Assignment.entity(),
                  sortDescriptors: [NSSortDescriptor(keyPath: \Assignment.course?.name, ascending: true),
                                    NSSortDescriptor(keyPath: \Assignment.isDue, ascending: false),
                                    NSSortDescriptor(keyPath: \Assignment.dueDate, ascending: true),
                                    NSSortDescriptor(keyPath: \Assignment.name, ascending: true)]) var assignments: FetchedResults<Assignment>

    @EnvironmentObject var accentColor: AccentColorManager
    @Environment(\.managedObjectContext) var context

    @State var course: Course?
    @State private var newAssignment: Assignment? = nil
    @State var newAssignmentViewIsPresented = false

    var body: some View {

        Group {
            if self.assignments.filter({ $0.course?.name == self.course?.name }).isEmpty {
                Text("No Assignments")
                    .foregroundColor(.secondary)
                    .font(.largeTitle)
            } else {
                List(assignments.filter { $0.course?.name == self.course?.name }, id: \.self) { assignment in
                    AssignmentRow(assignment: assignment).environment(\.managedObjectContext, self.context)
                }
            }
        }
        .navigationBarTitle(Text("\(course?.wrappedName ?? "")").foregroundColor(course?.color ?? Color.primary))
        .navigationBarItems(
            trailing: Button(
                action: {
                    self.newAssignment = Assignment(context: self.context)
                    self.newAssignmentViewIsPresented = true
            }
            ) {
                Image(systemName: "plus")
                    .accessibility(label: Text("New Assignment"))
                    .font(.title)

        })
            .accentColor(self.accentColor.color)
            .onAppear {
                self.accentColor.color = self.course?.color ?? .green
        }
        .sheet(isPresented: $newAssignmentViewIsPresented, content: {
            AssignmentEditorView(assignment: self.newAssignment!, defaultCourse: self.course).environment(\.managedObjectContext, self.context)
        })

    }
}

A: I was seeing an almost-identical crash. It seems there is still a bug with SwiftUI where @EnvironmentObject variables aren't accessible in child views.
Do you launch your CourseAssignmentsListView from a NavigationLink (in a NavigationView or List) or in a modal sheet? If so, try injecting your AccentColorManager directly in using the .environmentObject modifier - something like this:
// In the parent view
@EnvironmentObject var accentColor: AccentColorManager

// Wherever you are loading the view from... demonstrating using `NavigationLink`
NavigationLink(CourseAssignmentsListView().environmentObject(self.accentColor))

In my case, we have just had both people with crashes report that this approach works.


text:
Q: How to compare two rows in pandas/ python if they overlap I have data frame like below
     product        model   ci_low      ci_upp

        A             X    0.041667    48.0

        A             Y    0.000000    21.0

I want to check if ci_low and ci_upp overlap by product and return something like
 product       CI Band X        CI Band Y         Overlap

       A      [0.041667-48.0]   [0.00000 - 21.0]    Yes

Note: I have function to check if range overlap, if it return 0 then they dont overlap
    def getOverlap(a, b):
          return max(0, min(a[1], b[1]) - max(a[0], b[0]))

A: First we need pivot and create the range index then use the overlap to find the intersection
df['Ci band']=pd.IntervalIndex.from_arrays(df.ci_low,df.ci_upp,closed='both')
s=df.pivot('product','model','Ci band').add_prefix('CI Band')
s['Overlap']=s.apply(lambda x : x['CI BandX'].overlaps(x['CI BandY']),axis=1)
s
Out[55]:
model            CI BandX     CI BandY  Overlap
product
A        [0.041667, 48.0]  [0.0, 21.0]     True


text:
Q: Cygwin chmod failing with path, working after cd Windows 7, 64-bit, Genuine Intel. NTFS. SSD, fwiw.
C:\SVN\zFPE610>uname -r
1.7.35(0.287/5/3)
If I do a chmod with a path, it says it worked, but doesn't. If I cd into the directory first, it works. Bulleted lines are my comments (I had 'em as asterisks, the site editor is making them into bullets):

*

*OK, i'm in C:\SVN\zFPE610:

C:\SVN\zFPE610>cat ZFP-BUILD-2015-03-27-001\Updated\VSHPCRT1
cat: ZFP-BUILD-2015-03-27-001\Updated\VSHPCRT1: Permission denied

*

*Let's chmod:

C:\SVN\zFPE610>chmod -v 777 C:/SVN/zFPE610/ZFP-BUILD-2015-03-27-001/Updated/*
mode of 'C:/SVN/zFPE610/ZFP-BUILD-2015-03-27-001/Updated/VSHPCRT1' changed from 0644 (rw-r--r--) to 0777 (rwxrwxrwx)

*

*Nope:

C:\SVN\zFPE610>cat ZFP-BUILD-2015-03-27-001\Updated\VSHPCRT1
cat: ZFP-BUILD-2015-03-27-001\Updated\VSHPCRT1: Permission denied

*

*Let's look:

C:\SVN\zFPE610>ls -l ZFP-BUILD-2015-03-27-001/Updated/*
----rwx---+ 1 phsiii None 6800 Mar 27 15:24 ZFP-BUILD-2015-03-27-001/Updated/VSHPCRT1

*

*That sneaky chmod lied!

*Let's go to the directory:
C:\SVN\zFPE610>cd C:/SVN/zFPE610/ZFP-BUILD-2015-03-27-001/Updated/

*

*Nope, as expected:

C:\SVN\zFPE610\ZFP-BUILD-2015-03-27-001\Updated>cat VSHPCRT1
cat: VSHPCRT1: Permission denied

*

*Now let's chmod again from there:

C:\SVN\zFPE610\ZFP-BUILD-2015-03-27-001\Updated>chmod 777 *

*

*Hey, it worked!

C:\SVN\zFPE610\ZFP-BUILD-2015-03-27-001\Updated>cat VSHPCRT1
¦Q¦@@X¦¦^G¦¦b¦¦¦¦¦¦¦¦¦¦a¦¦a¦¦¦¦K¦¦@@@Ö¦¦¦¦¦¦¦@¦¦¦¦`¦¦¦¦¦¦¦¦¦¦¦¦¦¦@@¦8@@¦8@@
X¦??X¦ ¦¦?¦ ?!A0?¦.Q¦  ¦?¦?¦dA?¦?? ? ¦¦¦¦¦¦¦¦¦¦¦¦¦@  ¦@@ 8@@ ??¦I Q¦? P¦¦¦¦
This happens whether I use a Windows- or UNIX-style path. I've tried using /cygwin/c/... as the path and that doesn't work either. Lots of searching finds tons of chmod problems but all seem related to not using NTFS or other things. And chmod does work when I'm in the directory, which is even weirder.
Before I got down to chmod, I had made sure I had full Windows permissions on the directory, too. The only thing that seems odd there is that I have "special" permissions as well; when I click Advanced, it agrees there are special permissions, but when I drill down in the dialogs, I don't see anything except regular (full) permissions.
Ideas?


text:
Q: Enumerate Python class properties (not functions) How do I enumerate functions of a Python class marked with @property?
class MyClass:
    @property
    def my_property():
        pass

Something like this, but there is no lambda filter for inspect.isproperty:
properties = inspect.getmembers(obj, inspect.isproperty)

Apparently, these are known as managed attributes.

A: This will do it:
inspect.getmembers(obj.__class__, lambda x: isinstance(x, property))
Here's how it works exactly (using IPython):
In [29]: class Foo(object):
   ....:     @property
   ....:     def foo(self): return 42
   ....:

In [30]: obj = Foo()

In [31]: inspect.getmembers(obj.__class__, lambda prop: isinstance(prop, property))
Out[31]: [('foo', <property at 0x106aec6d8>)]

This works because property is a normal (new-style) class really; by marking something with @property, you're just making an instance of property. This also means that instances of properties (on a class) can be type-compared against property using isinstance.


text:
Q: JQuery tabs disordering when add Run code follow and click in last tab of first rows tab.
http://jsfiddle.net/pKcJp/

<button id="addspan">Add tabs</button>

See that have an disordering tabs.
This problem not occurs if Jquery version is changed to 1.7.2 and jquery-ui to 1.8.18(changed in menu)
Any Idea?

A: This is because the jQuery UI CSS adds it's own class to the active tab and inserts a margin-bottom rule. Add your own to override it.
.ui-tabs .ui-tabs-nav li.ui-tabs-active {
    margin-bottom:0;
}

jsFiddle example


text:
Q: Wordpress Docker NGINX Reverse I'm having issue setting up reverse proxy on my Wordpress docker. I have an Nginx docker container running separately. Using unRAID as the OS. I have other services running under domain.com so I'm trying to run WP in a subdir.
This is the block i'm using in my nginx conf file
#Wordpress Docker
location ^~ /blog {
    proxy_pass http://10.0.0.18:91/;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Proto $scheme;
    proxy_redirect http://10.0.0.18:91/ https://$host/;
    proxy_cookie_domain http://10.0.0.18:91/ $host;
    include /config/nginx/php.conf;
}

When going to domain.com/blog looks like it tries to load but without CSS and only text, for example:

Any help would be greatly appreciated.
Thank you


text:
Q: Running script at shutdown and reboot to prevent Chromium session loss I'm running Ubuntu 18.04.1 and I'm trying to create a script that shuts down Chromium properly before shutting down the system so that it doesn't give me "restore session" popup after booting. I figured I'll use killall to this and came up with
/home/shutdownscript.sh:
#!/bin/bash
killall -HUP "chromium-browser --enable-pinch"

that seems to do the trick.
However, now I have a problem with actually running this script at shutdown or reboot.
First thing I tried was  putting it in /etc/init.d as shutdownscript with chmod a+x and then symlinking it to rc0.d and rc6.d as K99shutdownscript and later K01ashutdownscript. However, that didn't work for me.
I thought maybe I should just create a new systemd service, so I created shutdownscriptnew.service in /etc/systemd/system with contents like this:
#!/bin/bash
### BEGIN INIT INFO
# Provides:          shutdownscript
# Required-Start:
# Required-Stop:
# Default-Start:
# Default-Stop:      0 1 6
# Short-Description: Start daemon at boot time
# Description:       Enable service provided by daemon.
### END INIT INFO

[Unit]
Description=Saves Chromium session
Before=shutdown.target reboot.target halt.target

[Service]
Type=oneshot
RemainAfterExit=true
ExecStop=/home/istir/shutdownscript.sh

[Install]
WantedBy=multi-user.target

Then I ran systemctl start shutdownscriptnew.service and systemctl enable shutdownscriptnew.service but it still didn't work as intended.
However, when I run systemctl stop shutdownscriptnew.service it actually does what it should do and closes chromium properly so that after I open it again it doesn't want to restore pages.
Ubuntu 18.04.1 LTS
GNOME Shell 3.28.2
Chromium installed from Ubuntu's software application (chromium-browser)
Shutting down from GNOME taskbar.
I also tried just installing Google Chrome from google.com/chrome/ but it still wanted to restore pages after reboot.
I specifically want to be able to run script like this and not fix chromium because I have similar issue with Spotify - it doesn't save my last song when I shut down my PC and I'm hoping to do something similar to it.
I guess the problem is with shutdownscriptnew.service but I searched and searched and can't find anything that works for me.
Thanks for help!

A: The issue is your script is running later than it should.
By the time the script runs, the display manager has already died and taken Chromium with it.
You need to have your script run at logout vice shutdown.
Edit: On GDM3, you can try /etc/gdm3/PostSession/Default


text:
Q: How select first N items in Java TreeMap? Given this map
SortedMap<Integer, String> myMap = new TreeMap<Integer, String>();

Instead of a for loop is there a utility function to copy first N items to a destination map?

A: Maybe, but not as part of the standard Java API. And: the utility would use a loop inside.
So you'll need a loop, but you can create your own "utility" by doing it all in a static method in a utility class:
public static SortedMap<K,V> putFirstEntries(int max, SortedMap<K,V> source) {
  int count = 0;
  TreeMap<K,V> target = new TreeMap<K,V>();
  for (Map.Entry<K,V> entry:source.entrySet()) {
     if (count >= max) break;

     target.put(entry.getKey(), entry.getValue());
     count++;
  }
  return target;
}

The complexity is still O(n) (I doubt, that one can achieve O(1)) but you use it like a tool without "seeing" the loop:
SortedMap<Integer, String> firstFive = Util.putFirstEntries(5, sourceMap);

A: There's SortedMap.headMap() however you'd have to pass a key for the element to go up to. You could iterate N elements over Map.keySet() to find it, e.g.:
Integer toKey = null;
int i = 0;
for (Integer key : myMap.keySet()) {
    if (i++ == N) {
        toKey = key;
        break;
    }
}

// be careful that toKey isn't null because N is < 0 or >= myMap.size()
SortedMap<Integer, String> copyMap = myMap.headMap(toKey);

A: Using the power of Java 8+:
TreeMap<Integer, String> myNewMap = myMap.entrySet().stream()
    .limit(3)
    .collect(TreeMap::new, (m, e) -> m.put(e.getKey(), e.getValue()), Map::putAll);

A: You can also use an ordored iterator to get the first x records, orderer by descending id for instance :
Iterator<Integer> iterator = myMap.descendingKeySet().iterator();

A: You can use the putAll(Map t) function to copy the items from the map to specified map.But it copies all the items. You cannot copy fixed number of items.
http://download.oracle.com/javase/1.4.2/docs/api/java/util/Map.html#putAll%28java.util.Map%29


text:
Q: Heat balance in layer coupled via BC I am trying to solve the heat balance in a 3 layer system in Mathematica 12.0.0. Each layer has different thermal properties. The layers are coupled via the boundary conditions (Neumann type) to ensure that heat flux is preserved over the interfaces with the central layer (layer 2).
The system is schematically depicted here:

I came up with the following approach:
(*definition of parameters*)
km = 0.128; rhom = 975; Cpm = 1948;
ka = 0.024; rhoa = 1.292; Cpa = 1003;
kf = 0.33; rhof = 940; Cpf = 2100;
h = 5;

thickness = 0.18;
L1 = N[-thickness/2];
L2 = N[thickness/2];
Tair = 120;

timemax=2;

(*heat equation*)
heateqf1 =
  rhof*Cpf*D[uf1[x, t], {t, 1}] - (10^6*kf)*D[uf1[x, t], {x, 2}] ==
   NeumannValue[h*(u[x,t]- uf1[x, t]), x == L1]; (*miss the -infinity bc*)

heateqm =
  rhom*Cpm*D[u[x, t], {t, 1}] - (10^6*km)*D[u[x, t], {x, 2}] ==
   NeumannValue[h*(uf1[x, t] - u[x, t]), x == L1] +
    NeumannValue[h*(u[x, t] - uf2[x, t]), x == L2];

heateqf2 =
  rhof*Cpf*D[uf2[x, t], {t, 1}] - (10^6*kf)*D[uf2[x, t], {x, 2}] ==
   NeumannValue[h*(u[x, t] - uf2[x, t]), x == L2] ;  (*miss the +infinity bc*)

icf1 = uf1[x, 0] == T0;
icm = u[x, 0] == T0;
icf2 = uf2[x, 0] == T0;

bc1 = uf1[-10*thickness, t] == Tair;
bc2 = uf2[10*thickness, t] == Tair;

(*solution finding*)
sol1 = NDSolveValue[{{heateqf1, heateqm, heateqf2}, {icf1, icm, icf2,
     bc1, bc2}}, {uf1, u, uf2}, {t, 0, timemax}, {x, L1 - Lf,
    L2 + Lf},
   Method -> {"MethodOfLines", "TemporalVariable" -> t,
     "SpatialDiscretization" -> {"FiniteElement",
       "MeshOptions" -> {"MaxCellMeasure" -> {"Length" -> 0.001}}}}];

Besides, I am not sure that bc1 and bc2 are good definitions for the boundary conditions, I do not make it to the result.

A: As I commented in your previous question 240844, currently, Mathematica does not support internal NeumannValues. It does, however, allow you to create region-dependent material properties.
When you have multiple regions, it is often conducive to construct a mesh manually with each material region marked. Here is an example workflow.
User supplied parameters
(*Import required FEM package*)
Needs["NDSolve`FEM`"];
(*OP defined parameters*)
km = 0.128; rhom = 975; Cpm = 1948;
ka = 0.024; rhoa = 1.292; Cpa = 1003;
kf = 0.33; rhof = 940; Cpf = 2100;
h = 5;
thickness = 0.18;
L1 = N[-thickness/2];
L2 = N[thickness/2];
Lf = 8/1000;
Tair = 120;
Length1 = 0.1;
time1 = 60*Length1/4;
(*T0 was not supplied*)
T0 = 0;
(*Create property arrays*)
λ = {kf, km, ka};
ρ = {rhof, rhom, rhoa};
cp = {Cpf, Cpm, Cpa};

Construct ElementMesh
The mesh is constructed following my previous answer to a multiple material problem here 223034.
(*Create mesh with region markers*)
g = {Lf, thickness, Lf} // N;(*thicknesse*)
gw = {0}~Join~Accumulate[g] + (L1 - Lf);
bmesh = ToBoundaryMesh["Coordinates" -> Partition[gw, 1],
  "BoundaryElements" -> {PointElement[{{1}, {2}, {3}, {4}}]}]; nrEle \
= 10; pt = Partition[gw, 2, 1];
regmarkers =
  Transpose[{Partition[(Mean /@ pt), 1], {1, 2, 3},
    Abs[Subtract @@@ pt]/nrEle}];
mesh = ToElementMesh[bmesh, "RegionMarker" -> regmarkers];

Create region dependent physical properties
(*Create region dependent physical properties*)
rhocp = Evaluate[Piecewise[{{ρ[[1]] cp[[1]], ElementMarker == 1},
     {ρ[[2]] cp[[2]], ElementMarker == 2},
     {ρ[[3]] cp[[3]], ElementMarker == 3}}]];
k = Evaluate[Piecewise[{{λ[[1]], ElementMarker == 1},
     {λ[[2]], ElementMarker == 2},
     {λ[[3]], ElementMarker == 3}}]];

Set up PDE system
We will use the HeatTransferPDEComponent and HeatTransferValue to set up the heat transfer PDE.
(*Set up PDE*)
vars = {Θ[t, x], t, {x}};
pars = <|"MassDensity" -> 1, "SpecificHeatCapacity" -> rhocp,
   "ThermalConductivity" -> {k}|>;
pars["BC1"] = <|"HeatTransferCoefficient" -> h,
   "AmbientTemperature" -> Tair|>;
Γleft =
  HeatTransferValue[x == gw[[1]], vars, pars, "BC1"];
Γright =
  HeatTransferValue[x == gw[[-1]], vars, pars, "BC1"];
ics = Θ[0, x] == T0;
eqn = HeatTransferPDEComponent[vars,
    pars] == Γleft + Γright;

For those who do not have version 12.2, here is the input form of eqn:
Inactive[Div][{{-k}} . Inactive[Grad][Θ[t, x], {x}], {x}] +
  rhocp*Derivative[1, 0][Θ][t, x] ==
 NeumannValue[h*(Tair - Θ[t, x]), x == gw[[-1]]] +
  NeumannValue[h*(Tair - Θ[t, x]), x == gw[[1]]]

Solve and plot the PDE system
Tfun = NDSolveValue[{eqn, ics}, Θ, {t, 0,
    500000}, {x} ∈ mesh];
Plot3D[Tfun[t, x], {t, 0, 100000}, {x, First@gw, Last@gw},
 ColorFunction -> "ThermometerColors", PlotRange -> All,
 MeshFunctions -> {#3 &}, Mesh -> 24]

A: This is an extended comment. You can have internal NeumannValues - but you will have to generate a mesh that actually has an internal boundary:
Needs["NDSolve`FEM`"]
bmesh = ToBoundaryMesh[
   "Coordinates" -> {{0, 0}, {1, 0}, {2, 0}, {2, 1}, {1, 1}, {0, 1}},
   "BoundaryElements" -> {LineElement[{{1, 2}, {2, 3}, {3, 4}, {4,
        5}, {5, 6}, {6, 1}}], LineElement[{{2, 5}}]}];
mesh = ToElementMesh[bmesh];
mesh["Wireframe"]

if = NDSolveValue[{Laplacian[u[x, y], {x, y}] ==
     1 + NeumannValue[u[x, y], {x == 1}]},
   u, {x, y} \[Element] mesh];
Plot3D[if[x, y], {x, y} \[Element] mesh]

Update:
1D example:
bmesh = ToBoundaryMesh["Coordinates" -> {{0}, {1}, {2}},
   "BoundaryElements" -> {PointElement[{{1}, {2}, {3}}]}];
mesh = ToElementMesh[bmesh];
eqn = {Laplacian[u[x], {x}] == 1 + NeumannValue[10, {x == 1}],
   DirichletCondition[u[x] == 0, x == 0 || x == 2]};
if = NDSolveValue[eqn, u, {x} \[Element] mesh];
Plot[if[x], {x} \[Element] mesh]

I still think Tim Laska's answer is what you want.


text:
Q: Java packing a module with a automatic module into a JAR I'm playing around with modules but there is something that I cannot perform so far is fact is quite simple but is not working.
I have a module named Student with only 1 package which exports and requires a class in a non-modular jar is something like this.

The relevant code here is that Administracion class requires a class in a non-modular jar the code is like this.
public class Administracion extends classpath.ClassPathClass{

In this example I am considering that I don't have the sources only the binaries in a Jar file in fact the jar is located on the root of next to src but in out directory
Like this:

I can compile all the module code with this command
C:\Ocp11>javac -d out --module-source-path src -p out --module Student

Great, the binaries are located in the out directory and now it looks like this:

I can run it with this command:
C:\Ocp11>java -p out --module Student/university.upel.Administracion

And runs like a charm but the step I could not perform I package it.
I would like to ignore the module root folder I mean the Student is this possible for be able to run the main class easier.
I would like to have a structure in the jar like this.

I have tried this:
C:\Ocp11>jar --create --file App.jar -e university.upel.Administracion -C out/Student .

This is creating the JAR and if I unzip it I see what I wanted.
The Jar file ClassPath.jar
The module-info.class for creating this as a module
The Main-Class: university.upel.Administracion

Package structure:

In fact if I see the module-info.class using Javap I see this
C:\Ocp11>javap App/module-info.class
Compiled from "module-info.java"
module Student {
  requires java.base;
  requires ClassPath;
  exports university.upel;
}

At this time I'm thinking well seems to work. The run:
C:\Ocp11>java -p App.jar -m Student
Error occurred during initialization of boot layer
java.lang.module.FindException: Module ClassPath not found, required by Student

It is saying that the module ClassPath the automatic module is not present even when the ClassPath.jar is inside the jar I think this is not possible right? I'm stuck at this moment.
I just thought that in this way the Student would be a module with a automatic module inside and that would locate the automatic module on each run.
I am sure I'm wrong or I am taking the wrong approach.
If I change the command a little bit locates the Jar and runs without a issue.
C:\Ocp11>java -p App.jar;out/ClassPath.jar -m Student
OUTPUT

So can I not put the JAR inside the JAR and run it? Is a kind annoying the carrying the 2 jars file even when only this jar uses the Automatic module.


text:
Q: How to filter a Pandas DataFrame using multiple conditions? i have a data frame object as below
    Issue Type       Status  Reporter  Issue id
0   Eng Activity       Closed  snalanag     98908
1   Eng Activity  In Progress  snalanag     98452
2   Eng Activity       Closed  snalanag     98425
3     Dev-Defect       Closed  snalanag     97244
4     Dev-Defect       Closed  snalanag     96716
5   Eng Activity       Closed  snalanag     96698
6     Dev-Defect       Closed  snalanag     96696

Now i want to filter data based on multiple conditions.
Condition will be in dictionary.
Example:{'Issue Type': 'Dev-Defect', 'Status': 'Closed', 'Reporter': 'snalanag'}
Based on the condition, i have to filter the data frame by forming the query dynamically. Please note that i need to filter the data by applying AND condition .
That means i have to apply the filter for the given data frame with "Issue Type = Dev-Defect","Status = Closed","Reporter = snalanag" at once.
Something like this but it should be generated dynamically based on the condition dictionary.
print (df[(df["Issue key"] == 'BUG-22212') & (df["Issue id"] == 97244) & (df["Status"] == 'Closed')])

A: You can use .loc with numpy.logical_and in it to accommodate multiple logical expressions. Since numpy.logical_and can have only 2 expressions, reduce function can be used to make it work with multiple expressions. An explanation: Numpy logical_or for more than two arguments.
For your case we can use something like:
df.loc[np.logical_and.reduce((df["Issue Type"]=="Dev-Defect", df["Status"]=="Closed", df["Reporter"]=="snalanag"))]

Hope this helps!
EDIT
Since you are using a dictionary for conditions, following may help:
conditions = {'Issue Type': 'Dev-Defect', 'Status': 'Closed', 'Reporter': 'snalanag'}
df.loc[np.logical_and.reduce(list(map(lambda x: df[x]==conditions[x], conditions.keys())))]

A: You might be able to get away with something like this:
cond_dict = {'Issue Type': 'Dev-Defect', 'Status': 'Closed', 'Reporter': 'snalanag'}

final_mask = np.ones(len(orig_df)).astype(bool)

for this_cond in cond_dict:
    cond_dict = (final_mask ) & (orig_df[this_cond] == cond_dict[this_cond])

filtered_df = orig_df[final_mask]


text:
Q: Weblogic read metadata file I have a Java application running on a Weblogic server.
The weblogic server has a number of Metadata Repositories
The Repository I am interested in has a number of Patitions.
I want to find some API's I can call to:

*

*List all the Metadata Repositories on the server

*List all the Partitions in a particular Repository

*Read the contents of a particular file in the Partition

Can anyone point me at the right spot in documentation.

A: I have hacked my way through getting what I want.
To achieve this I had to:

*

*get JNDI context for WL Server

*lookup an MBeanServer

*(Commented out) use MBean interface to list MDS Repos and Partitions

*get a MDSAppRuntime

*invoke startExport and save the streamID

*invoke doExport passing in the name of the file I want

*invoke get saving the byte array returned

*invoke endExport

*The byte array is actually a zip file so I need to extract the contents of the file I wanted

It seems a lot or work to read a file but that is the only way that I have found that works.
My code is below, note step 3 is commented out as you don't need the weblogic password to just read the MDS file.
Hope this saves someone time in the future
package ic.ac.uk.icdev.rjmtest.wladminserversensor.wsdlgen;

import ic.ac.uk.icdev.rjmtest.wladminserversensor.wsdlgentypes.RequestSOAEndpointsMessageType;
import ic.ac.uk.icdev.rjmtest.wladminserversensor.wsdlgentypes.ResponseSOAEndpointsMessageType;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;

import java.util.Hashtable;

import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

import javax.jms.Destination;

import javax.jws.WebService;

import javax.management.MBeanServer;

import javax.management.ObjectName;

import javax.management.RuntimeMBeanException;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

import javax.xml.ws.BindingType;
import javax.xml.ws.soap.SOAPBinding;

@WebService(serviceName = "mainService", targetNamespace = "urn:WLAdminServerSensor", portName = "mainPort", endpointInterface = "ic.ac.uk.icdev.rjmtest.wladminserversensor.wsdlgen.Main_pt", wsdlLocation = "/WEB-INF/wsdl/service.wsdl")
@BindingType(SOAPBinding.SOAP12HTTP_BINDING)
public class Main_ptImpl {
    public Main_ptImpl() {
    }

    private byte[] exportMetadataFile(MBeanServer p_server) throws Exception {
        //Reading from SOA1
        ObjectName mdsSOA1Bean = new ObjectName("oracle.mds.lcm:Location=WLS_SOA1,name=MDSAppRuntime,type=MDSAppRuntime,Application=soa-infra");

        //String streamID = UUID.randomUUID().toString();
        String streamID = (String) p_server.invoke(mdsSOA1Bean, "startExport",null,null);

        String[] docs = new String[1];
        docs[0] = "/apps/AIAMetaData/dvm/XXIC_DVM_SOAEndpoints.dvm";

        Object[] x = new Object[9];
        String[] y = new String[9];
        int c=0;
        x[c] = streamID;            y[c] = String.class.getName();  c++;
        x[c] = docs;            y[c] = String[].class.getName();  c++;
        x[c] = new String[0];            y[c] = String[].class.getName();  c++; //restrict custs to
        x[c] = false;            y[c] = boolean.class.getName();  c++;
        x[c] = false;            y[c] = boolean.class.getName();  c++;
        x[c] = false;            y[c] = boolean.class.getName();  c++;
        x[c] = false;            y[c] = boolean.class.getName();  c++;
        x[c] = "";            y[c] = String.class.getName();  c++;
        x[c] = "";            y[c] = String.class.getName();  c++;
        javax.management.openmbean.TabularData ret = (javax.management.openmbean.TabularData) p_server.invoke(mdsSOA1Bean, "doExport",x,y);

        Object[] x0 = new Object[2];
        String[] y0 = new String[2];
        c=0;
        x0[c] = streamID;            y0[c] = String.class.getName();  c++;
        x0[c] = 4096;            y0[c] = int.class.getName();  c++;
        byte[] fil = (byte[]) p_server.invoke(mdsSOA1Bean, "get",x0,y0);

        Object[] x2 = new Object[1];
        x2[0] = streamID;
        String[] y2 = new String[1];
        y2[0] = String.class.getName();
        p_server.invoke(mdsSOA1Bean, "endExport",x2,y2);

        //We get a zip file with the MDS file contained inside it. We must extract it out
        ZipInputStream zin = new ZipInputStream(new ByteArrayInputStream(fil));
        ZipEntry ze = null;
        ByteArrayOutputStream bos = new ByteArrayOutputStream(fil.length);
        while ((ze = zin.getNextEntry()) != null) {
            if (true) {
                byte[] buffer = new byte[8192];
                int len;
                while ((len = zin.read(buffer)) != -1) {
                    bos.write(buffer, 0, len);
                }
                bos.close();
                break;
            }
        }
        return bos.toByteArray();

    }

    private ResponseSOAEndpointsMessageType run(RequestSOAEndpointsMessageType requestSOAEndpointsInputPart) throws Exception {

        Hashtable env = new Hashtable();
        //Username and password only required for enurmrating parittipons
        //env.put(Context.SECURITY_PRINCIPAL, "weblogic");
        //env.put(Context.SECURITY_CREDENTIALS, "password");
        env.put(Context.INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactory");

        Context jndiContext = null;

        try {
            jndiContext = new InitialContext(env);
        } catch (NamingException e) {
            throw new Exception("Creating initial context NamingException:" + e.toString());
        }

        Destination passedDest = null;

        //MBeanServer server = (MBeanServer)jndiContext.lookup("java:comp/env/jmx/runtime");
        MBeanServer server = (MBeanServer)jndiContext.lookup("java:comp/env/jmx/domainRuntime");

    /*
     *  Code to enurmrate MDS repos and partitions - not needed to read actual file
        ObjectName service = new ObjectName(
"com.bea:Name=DomainRuntimeService,Type=weblogic.management.mbeanservers.domainruntime.DomainRuntimeServiceMBean"
        );

        ObjectName mdsBean = new ObjectName("oracle.mds.lcm:name=MDSDomainRuntime,type=MDSDomainRuntime");

        String[] repositories = (String[]) server.invoke(mdsBean, "listRepositories",null,null);

        ObjectName rep = null;
        for (int c=0;c<repositories.length;c++) {
            ObjectName cur = new ObjectName(repositories[c]);
            if (cur.getKeyProperty("Name").equals("mds-owsm")) {
                rep = new ObjectName(repositories[c]);
            };
        }
        if (rep==null) throw new Exception("No mds-owsm repository found");

        Object[] x = new Object[1];
        x[0] = new String(rep.getKeyProperty("Name"));
        String[] y = new String[1];
        y[0] = String.class.getName();
        String[] partitions = (String[]) server.invoke(mdsBean, "listPartitions",x,y);

        String part = null;
        for (int c=0;c<partitions.length;c++) {
            if (partitions[c].equals("soa-infra")) {
                part = partitions[c];
            };
        }
        if (part==null) throw new Exception("Could not find partition soa-infra in mds");
        */

        byte[] fil = exportMetadataFile(server);
        String s = new String(fil,"UTF-8");

        ResponseSOAEndpointsMessageType ret = new ResponseSOAEndpointsMessageType();
        ret.setOutput(s);
        return ret;

    }

    public ResponseSOAEndpointsMessageType querySOAEndpoints(RequestSOAEndpointsMessageType requestSOAEndpointsInputPart) {
        ResponseSOAEndpointsMessageType ret = new ResponseSOAEndpointsMessageType();
        try {
            return run(requestSOAEndpointsInputPart);
        } catch (RuntimeMBeanException e) {
            String st = "";
            for (int c=0;c<e.getStackTrace().length;c++) {
                st += "\n" + e.getStackTrace()[c].toString();
            }

            if (e.getTargetException()==null) {
                st += "\n\nTARG EXCEPTION IS NULL";
            } else {
                st += "\n\nTARG EXCEPTION: " + e.getTargetException().getMessage();
                for (int c=0;c<e.getTargetException().getStackTrace().length;c++) {
                    st += "\n" + e.getTargetException().getStackTrace()[c].toString();
                }
            }

            ret.setOutput("RuntimeMBeanException: " + e.getMessage() + "\n" + e.getLocalizedMessage() + "\n" + st);
            return ret;
        } catch (Exception e) {
            String st = "";
            for (int c=0;c<e.getStackTrace().length;c++) {
                st += "\n" + e.getStackTrace()[c].toString();
            }

            ret.setOutput("Exception: " + e.getMessage() + "\n" + e.getLocalizedMessage() + "\n" + st);
            return ret;
        }
    }
}


text:
Q: ¿Se están recibiendo y calculando correctamente los parámetros en este proyecto? La clase procedimientos tiene como proceso este método:
public void LeerVotosCandidato1(String d1, String d2, String d3, String    d4, String d5)
{
    int D1, D2, D3, D4, D5;

    D1 = Integer.parseInt(d1);
    D2 = Integer.parseInt(d2);
    D3 = Integer.parseInt(d3);
    D4 = Integer.parseInt(d4);
    D5 = Integer.parseInt(d5);

    TVC1 = (D1 + D2 + D3 + D4 + D5);
}

Y este método recibe mediante el evento del botón del formulario así:
    Clase_FrmVotos Objeto = new Clase_FrmVotos();
    Objeto.LeerVotosCandidato1(lblC1D1.getText(), lblC1D2.getText(), lblC1D3.getText(), lblC1D4.getText(), lblC1D5.getText());
    btnVotarC1.setEnabled(false);
    }

Posteriormente esto se realiza con 5 Metodos LeerVotosCandidatos bajo la misma estrctura.
Adjuntaré imagen para mejor entendimiento

Ahora bien, posteriormente a recibir y calcular los datos e estos 4 métodos, se determinan los porcentajes de participación de la siguiente forma:
    public void CalcularPorcentajes()
{
    double TotalVotantes;

    TotalVotantes = (TVC1 + TVC2 + TVC3 + TVC4);

    PC1 = ((TVC1 * 100) / TotalVotantes);
    PC2 = ((TVC2 * 100) / TotalVotantes);
    PC3 = ((TVC3 * 100) / TotalVotantes);
    PC4 = ((TVC4 * 100) / TotalVotantes);
}

Y luego de esto se determina si hay o no ganador electoral bajo este método:
    public void DeterminarGanador()
{
    double Vector[] = new double[4];
       Vector[0] = PC1;
       Vector[1] = PC2;
       Vector[2] = PC3;
       Vector[3] = PC4;

    if (PC1 > 50 | PC2 > 50 | PC3 > 50 | PC4>50)
    {
       for (int i = 4; i<0; i = i -1)
       {
           if (Vector[i] > 50)
           {
               Ganador = "Candidato: " + Vector[i];
           }
       }
    }
    else
    {
        int L = 0;
        double A;
        for (int i = 4; i<0; i = i -1)
        {
            if (Vector[i]<Vector[L])
            {
                A = Vector[i];
                Vector[i] = Vector[L];
                Vector[L] = A;
                L = L + 1;
            }

        }
        SegundaVuelta1 = "Candidato: " + Vector[1];
        SegundaVuelta2 = "Candidato: " + Vector[2];
    }
}

Una vez realizado todos los cálculos vienen los métodos de impresiones:
   public String RetornarPC1()
{
    String PorC1;
    PorC1 = String.valueOf(PC1);
    return PorC1;
}

public String RetornarPC2()
{
    String PorC2;
    PorC2 = String.valueOf(PC2);
    return PorC2;
}

public String RetornarPC3()
{
    String PorC3;
    PorC3 = String.valueOf(PC3);
    return PorC3;
}

public String RetornarPC4()
{
    String PorC4;
    PorC4 = String.valueOf(PC4);
    return PorC4;
}

public String ObtenerGanador()
{
    return Ganador;
}

public String ObetenerSegundaVuelta1()
{
    return SegundaVuelta1;
}

public String ObtenerSegundaVuelta2()
{
    return SegundaVuelta2;
}

El problema es el siguiente: Si se ingresan los datos de la siguiente forma o la que sea (ya se ha intentado), siempre muestra el mismo resultado, y anteriormente todas las respuestas daban cero.

Además de que la tabla no imprime la fabulación de los votos.
Si sobra el interés y hace falta información: Ajunto link de descarga del proyecto:
introducir la descripción del enlace aquí

A: Para calcular los totales por candidato has esto:
   public int leerVotosCandidato(String d1, String d2, String d3, String d4, String d5)
   {
        int resultado = Integer.parseInt(d1) + Integer.parseInt(d2) + Integer.parseInt(d3)
        + Integer.parseInt(d4) + Integer.parseInt(d5);
        return resultado;
   }

Ahora, para cada candidato, lo único que tienes que hace es pasarle sus respectivos valores:
TC1 =  leerVotosCandidatos(lblC1D1.getText(), lblC1D2.getText(), lblC1D3.getText(),
           lblC1D4.getText(), lblC1D5.getText());
TC2 =  leerVotosCandidatos(lblC2D1.getText(), lblC2D2.getText(), lblC2D3.getText(),
               lblC2D4.getText(), lblC2D5.getText());
TC3 =  leerVotosCandidatos(lblC3D1.getText(), lblC3D2.getText(), lblC3D3.getText(),
               lblC3D4.getText(), lblC3D5.getText());
TC4 =  leerVotosCandidatos(lblC4D1.getText(), lblC4D2.getText(), lblC4D3.getText(),
               lblC4D4.getText(), lblC4D5.getText());

Porque de la forma que estás encarando tu metodo void LeerVotosCandidato1, tendráis que tener un método para cada candidato, en cambio de la forma que te planteo, utilizas un solo método para los 4 y solo varía los parámetros pasados para cada candidato.


text:
Q: Problem with parsing eslint for async function I have problem with my ESLint parser. I use Sage project from Roots.io
I've been searching the internet all day. I use Webpack and my terminal print:
Module build failed:
19 :     redirect_uri: redirectUri,
20 : });
21 :
22 :
23 : async function getAsyncAuth() {
           ^
Unexpected token (23:6)

You may use special comments to disable some warnings.
Use // eslint-disable-next-line to ignore the next line.
Use /* eslint-disable */ to ignore all warnings in a file.

These comments like eslint-disable still not work!
My .eslintrc.js
  'ecmaVersion': 2017,
  'sourceType': 'module',

I changed ecmaVersion from '2016' to '2017', '2018' or 'latest' but still not working.
In package.json I have in devDependencies:
"eslint": "~4.19.1",
"eslint-loader": "^4.0.2",
"eslint-plugin-import": "^2.14.0",

My script where I use async/await.
    import axios from 'axios';
    import oauth from 'axios-oauth-client';

    var clientId = '';
    var clientSecret = '';
    var redirectUri = '';

    const getAuthorizationCode = oauth.client(axios.create(), {
        url: 'https://api.getbase.com/oauth2/authorize',
        response_type: 'code',
        client_id: clientId,
        client_secret: clientSecret,
        redirect_uri: redirectUri,
    });

    async function getAsyncAuth() {
        const auth = await getAuthorizationCode();
        console.log(auth);
        return auth;
    }

    getAsyncAuth();

What it's wrong? Do you know solution?


text:
Q: How to rotate the background image in css? I have a custom radiobutton image. I am trying to rotate the background image alone when some one chooses the option. But it rotates the the whole div.
here is my partially working jsFiddle
ul.pt-answers > li > label > input:checked +img {
    background: url(http://www.opinionpoll.in/files/images/vote_symbol.png);
    background-repeat: no-repeat;
    background-position:center center;
    background-size:30px 30px;
    -webkit-animation:spin 0.5s ease 1 both;
    -moz-animation:spin 0.5s ease 1 both;
    animation:spin 0.5s ease 1 both;
    border:none;

}

@-moz-keyframes spin { 100% { -moz-transform: rotate(30deg); } }
@-webkit-keyframes spin { 100% { -webkit-transform: rotate(30deg); } }
@keyframes spin { 100% { -webkit-transform: rotate(360deg); transform:rotate(30deg); } }

A: I suggest you use the <div> element tag instead of <img> so you can create a pseudo ::before element in it. You can specify the css select to create the pseudo ::before element, assign the background properties and apply the spin, viola!
You can see what I mean in your updated fiddle here.
Get additional information here.
edit: spelling


text:
Q: Max Ent enviromental layers for archaeology First, I have to put you in context.  I got trouble with some of my raster layers, I'm trying to apply max ent in archaeology. What I want to do is to predict the areas where are a higher probability to be an archeological site. It's the same logic with Species Distribution Models but instead of a particular species it will be with archaeological sites.
So I got my site, x coord and y coord. These are my presence points (archaeological sites) with Northing and Easting (x,y). Until here I got no problems, the thing comes when i try to use my raster layers converted in ASCII format.
To be specific, I'm not working with the 19 bioclimatic variables from WorldClim, I'm using layers I made from the DEM with GrassGIS and ARCGIS such as Topographic position index, distance from water, Topographic wetness index, slopes, aspect) but when i try to run the program it sends me an error telling me that the geography of the rasters don't match, i googled the issue and the answer was that the ASCII values of the rasters didn't have the same numbers of cols, row, xllcorner and yllcorner. I searched for the 19 variables from WorldClim and they all have the same ncols, rcols, xllcorner, yllcorner.
How do I transform this raster layers and homogenize them to have the same numbers because my rasters numbers in this ASCII matrix are way too different?


text:
Q: OnSleep and OnResume not called In my UWP and Windows Phone 8.1 projects only OnStart is called. When I exit the app via the back button or home button, OnSleep is not called. If I open the app OnResume is not called.
It looks like the app never goes in the Deactivated state.
I tried it with Android and it is working fine. Why are these methods not called in both Windows projects?

A: This was a known bug in Xamarin.Forms 2.0: OnStart / OnResume are not called on WP8.1 which according to bugzilla was fixed in 2.1.0-pre1 version. If this is still not working for you, you should reopen the issue and attach your project which reproduces the issue.
As a workaround you can try using application lifecycle event in windows phone project: App lifecycle but this is obviously platform specific solution.


text:
Q: Proofs by contradiction can be used also for theorems that are not implications right? I'm reading "Mathematical proofs a transition to advanced mathematics" and in chapter 5 proofs by contradiction are introduced. The introduction though is a little confusing, because it says
"We now introduce a method that can be used to establish the truth of $R$ (which is a proposition) regardless of whether $R$ is expressed in terms of an implication".
but then it explains how to do these kind of proofs like this:
"If $R$ is the quantified statement $\forall x\in S, P(x)\rightarrow Q(x)$, then a proof by contradiction of this statement consists of verifying the implication $¬(\forall x\in S, P(x)\rightarrow Q(x))\rightarrow P∧¬P$"
I don't understand, can this kind of proof technique be used for proving other kind of propositions (theorems)?
An example the book gives is: "Prove that there is no smallest positive real number." and then proceed with a the proof by contradiction. The result to be proved, in predicate logic, would be translated as $¬\exists x \forall y(x<y)$ assuming the domain of $x$ and $y$ is the set of positive real numbers.
So from the example i would say that this proof technique can be used more generally, is this correct?

A: Remember that implications can be written as disjunctions, $p \implies q \equiv - p \vee q$. So being able to apply it for implications means that you can apply it for disjunctions, which means that you can apply it for conjunctions too (because if you have to prove $p \wedge q$ is true, you can prove $-p \vee -q$ is false).


text:
Q: C# Autofac New Instance I have a class "DependencyResolver" where I return instances of objects by hand. There I used "Activator.CreateInstance".
I wanted to change it so it uses autofac.
My function "Get" works fine:
      public T Get<T>()
        {
            return _container.Resolve<T>();
        }

But I also have a function "CreateNew" where I need a new instance:
      public T CreateNew<T>()
        {
            return _container.Resolve<T>();
        }

The Problem is that I always get the same instance.
My Registration looks like this:
            var builder = new ContainerBuilder();
            foreach (var dllFileName in DependencyMapping.GetAllDllFilenames())
            {
                builder
                    .RegisterAssemblyTypes(Assembly.LoadFile(Path.Combine(GetPathFromInstalledSys(), dllFileName)))
                    .AsImplementedInterfaces()
                    .SingleInstance();
            }
            _container = builder.Build();

So there is a place where I can control the behaviour: "SingleInstance" or "InstancePerDependency". But I dont know whether the user needs a new instance or not. Is there any way to change the behavior when "CreateNew" is called?

A: Lifetime scope (single instance, instance per dependency) is controlled at registration time, not resolve time. There's no way to change it. This is the case with all DI containers, not just Autofac. Part of the point of it is that the consumer shouldn't have to know what scope they want - they just ask for a thing and get it.
Consumers also generally shouldn't deal with disposal - things get disposed by the container.
Note what you have here is service location (client asks the container for a thing), not dependency injection (client takes dependencies in constructor and doesn't know about the container). While service location is sometimes required, generally try to avoid it if you can; it's not really much better than just calling new in your code.


text:
Q: agGrid autoHeightCalculator holds rendering While using agGridReact faced issue with autoHeightCalculator. After the data has been fetched this script takes over 10 sec. before rendering 3000 rows of data. Is there some option to switch it off or any idea how to reduce this time interval?

A: Check ag-grid property "autoHeight", autoHeightCalculator() running if it's true.


text:
Q: Integrate equations of motion when force depends on position I'm fairly new to Mathematica. I'm trying to test my C++ implementation of a fourth order Runge Kutta method for Newton's equations of motion. I want to test my integrator when the applied force is dependant on the position. I tried to implement Newton's equations of motion in Mathematica as below:
iMass = 4
iVel0 = {1.0, 1.0, 1.0}
iTime = 1.0
iMagn = Dot[iPos, iPos]^0.5
iForce = ((12.3/iMagn) - 1.2)*Normalize[iPos]
  (* Applied force is 12.3 / distance from 0 0 1.2 minus 1.2 and pointing towards 0,0,0 *)
iAccel = iForce/iMass
iVel = iVel0 + Integrate[iAccel, time]
iPos = {0.0, 10000, 0.0} + Integrate[iVel, time]}]

Mathematica ran for a couple of hours until I aborted the calculation.
How can I get Mathematica to integrate Newton's equations of motion when the applied force is a function of position?

A: iMass = 4;
iVel0 = {1.0, 1.0, 1.0};
iTime = 1.0;
iMagn = Dot[iPos[time], iPos[time]]^0.5;
iForce = ((12.3/iMagn) - 1.2)*Normalize[iPos[time]];
iAccel = iForce/iMass;
iPos0 = {0.0, 10000, 0.0};

sol =
  NDSolve[
   {iPos''[time] == iAccel, iPos'[iTime] == iVel0, iPos[iTime] == iPos0},
   iPos, {time, iTime, 10}]
ParametricPlot3D[Evaluate[iPos[time] /. sol], {time, iTime, 10}, PlotRange -> All]


text:
Q: Assign new column of a dataframe to values matching other dataframe I have two data frames:
geodata<-read.csv(text='postalcode;latitude;longitude
7000;47.8415;16.5041
7000;47.8921;16.4011
7000;47.9400;16.5032
7071;47.8012;16.671
2443;47.9156;16.5179', sep=';', header=TRUE)

addresses<-read.csv(text='postalcode;address
2400;Lorem ipsum
7000;Dolor sit amet
2443;Consetetur sadipscing elitr
7000;Sed diam nonumy', sep=';', header=TRUE)

What I would need is two additional columns in the addresses dataframe with the corresponding (first match when multiple postalcodes rows exist) geodata$latitude and geodata$longitude values.
How to join (merge) data frames (inner, outer, left, right)? shows nearly what I'm looking for except that I don't want duplicated lines in the merged dataframe.
I tried something like
# code not working... #
addresses$latitude<-geodata[addresses$postalcode==geodata$postalcode]

which I know is really ugly :-(

A: NO NEED to use extra packages here . Simply merge:
merge(geodata,addresses,all.x=TRUE)

#   postalcode latitude longitude                     address
# 1       2443  47.9156   16.5179 Consetetur sadipscing elitr
# 2       7000  47.8415   16.5041              Dolor sit amet
# 3       7000  47.8415   16.5041             Sed diam nonumy
# 4       7071  47.8012   16.6710                        <NA>

EDIT:
to add geodata to address we should invert the order here :
merge(addresses,geodata,all.x=TRUE)
  postalcode                     address latitude longitude
1       2400                 Lorem ipsum       NA        NA
2       2443 Consetetur sadipscing elitr  47.9156   16.5179
3       7000              Dolor sit amet  47.8415   16.5041
4       7000             Sed diam nonumy  47.8415   16.5041

A: Perhaps with a left_join from dplyr:
library(dplyr)
left_join(addresses,geodata, fill=NA)
#Joining by: "postalcode"
#  postalcode                     address latitude longitude
#1       2400                 Lorem ipsum       NA        NA
#2       7000              Dolor sit amet  47.8415   16.5041
#3       2443 Consetetur sadipscing elitr  47.9156   16.5179
#4       7000             Sed diam nonumy  47.8415   16.5041

Edit, if there is more than one result per postal code, you could try subsetting geodata:
#left_join(addresses, subset(geodata, !duplicated(postalcode)), fill=NA)
#Joining by: "postalcode"
#  postalcode                     address latitude longitude
#1       2400                 Lorem ipsum       NA        NA
#2       7000              Dolor sit amet  47.8415   16.5041
#3       2443 Consetetur sadipscing elitr  47.9156   16.5179
#4       7000             Sed diam nonumy  47.8415   16.5041

A: You could join them (in plyr)
library(plyr)
addresses <- join(addresses,geodata)


text:
Q: Как с помощью функции и цикла изменять один и тот же список? Происходит зацикливание, не знаю как записать по-другому
  def show_magicians(list):
        """Выводит список фокусников"""
        print(magicians)

def make_great(list2):
    while magicians:
        current_magician = "Great "+magicians.pop()
        magicians.append(current_magician)
        print(magicians)
magicians = ['alice','jame','kevin']
make_great(magicians)

A: У вас зацикливание так как вы идете по списку пока он не кончится и добавляете в него элементы. Получается бесконечный цикл
Вот пример решения вашей задачи
def show_magicians(magicians):
    for mag in magicians:
           print(mag)

def make_great(magicians):
    for i in range(len(magicians)):
        magicians[i] = "Great "+magicians[i]
    return magicians

magicians = ['alice','jame','kevin']
magicians=make_great(magicians)

show_magicians(magicians)


text:
Q: Limit number of running jobs in Oracle Scheduler without decreasing job_queue_processes value Is there any way to limit number of IMMEDIATE/ONCE type jobs that can run simultanously.
Scenario: Parameter job_queue_processes is set to 10.
There's one recurring job (Name: TEST_JOB) configured which runs after every 1 seconds interval and performs a critical application processing task.
Application also has some batches which can be executed on request basis and these batches also use DBMS_SCHEDULER jobs for faster processing. These jobs are created automatically by the batch with AUTO_DROP=TRUE configuration and are to be executed only once. The number of jobs created by batch can range between 50 to 100 and these jobs are created under DEFAULT_CLASS.
Problem is, when a batch is executed, since the whole job_queue_processes slots/jobs are consumed by the jobs submitted by batch (as number of submitted jobs is higher than job_queue_processes value), the important recurring TEST_JOB has to wait for a running job to finish.
Is there any way to configure DBMS_SCHEDULER to use only 9 (out of 10) slots/jobs for one time execution jobs and keep 1 slot/job always available for recurring TEST_JOB.
Thanks for the help.

A: I'm not aware of a way to reserve a job process like this. That said, you have a couple of options:
Make the critical job always run
Instead of ending the job when the critical task completes, loop round to run it again:
begin
  loop important_task; end loop;
end;

This means the job never stops, so no other process can consume all the available job slots.
I'd add some kind of option to break out of the loop (e.g. check a row in a table and exit if this is STOPPED) so you can disable it for upgrades, etc. and you may want a short sleep between runs, but the principle remains the same.
Prioritize the critical job
The scheduler has powerful job prioritization capabilities; you may be able to use this to ensure the critical job is able to execute by limiting the resources available to the other batch jobs.