text:
Q: How to render datetime.datetime with timezone to the HTML template in Django? views.py
def myVideo(request, id):
    myVideo = MyVideo.objects.filter(id=id)
    serializerClassVideo = MyVideoSerializer(myVideo,many=True)
    print(type(myVideo[0].upload_time))
    print(myVideo[0].upload_time)
    myDate = datetime.now()
    print(type(myDate))
    print(myDate)

    return render(request, 'video.html', {
        'myDate': myDate,
        'videos': serializerClassVideo.data,
        }
    )

in the console, output like this:
<class 'datetime.datetime'>
2018-05-30 19:52:20+00:00     # video.upload_time
<class 'datetime.datetime'>
2018-08-05 13:47:57.653627    # datetime.now()

video.html
{{ myDate|date:"Y-m-d" }}
{{ v.upload_time|date:"Y-m-d" }}

On the html page, the first line above shows: 2018-08-05 which is great, and the second one, that I need, shows nothing.
I thought the issue should be related to the timezone in the "upload_time" field. What should I do if I don't want to change this field (which means I want to keep the timezone of "upload_time")?

A: you are passing the serialized data to your view, instead pass the objects list. Try this
 return render(request, 'video.html', {
        'myDate': myDate,
        'videos': myVideo,
        }

A: Did you debugged the view.py?
what's serializerClassVideo.data 's type?
Before you assure that "data" is what you want,you should not pass the "data ".
Try replacing
serializerClassVideo.data

with
myVideo


text:
Q: How to use boost.xpressive without entire boost? I'm trying to use regular expression in VC 2008, however I can not use boost library (or at least the entire boost library).
I've seen the files in boost.xpressive are using files in other boost directories.
As a curiosity, this tutorial from boost.xpressive provided a way to download xpressive.zip from a link, which is no longer available.
I'm assuming the xpressive.zip contains the minimum dependencies of xpressive.
Where can I get the "minimum portable boost.xpressive"?

A: In my boost root I executed
./b2 tools/bcp
mkdir /tmp/XPRESSIVE
bcp --boost=$PWD xpressive /tmp/XPRESSIVE/

This resulted in a work tree of 29M (compared to ~542M of boost 1_60_0).
It includes about 25% of all boost headers.
It does include the library part of Boost Regex. You're probably going to have to include that (I don't know whether it's optional if you only use static regular expressions)

redpajama_set_name: RedPajamaStackExchange


text:
Q: What is the time complexity of HashMap.containsValue() in java? I was given a problem to solve in O(n) time complexity :
"Given a list of numbers and number x. Find if there any 2 numbers in the list that add up to x?"
And this is my solution :
public class SumMatchResult {

  public static void main(String[] args){
    int[] numberList = {6,1,8,7,4,6};
    int requiredSum = 8;
    boolean isSumPresent = checkSumPresentHash(numberList,requiredSum);
    if(isSumPresent) {
      System.out.println("Numbers exist");
    }else {
      System.out.println("Numbers donot exist");
    }
  }

  private static boolean checkSumPresentHash(int[] numberList, int requiredSum) {
    Map<Integer, Integer> m = new HashMap<Integer,Integer>();
    int count = 0;
    for(int i=0;i<numberList.length;i++){
      m.put(i, numberList[i]);
    }
    for(int i=0;i<numberList.length;i++){
      if(m.containsValue(requiredSum - numberList[i])){
        count++;
      }
    }
    if(count>1){
        return true;
    }
    return false;
  }

}

I am using HashMap.containsValue() instead of using a HashSet.contains() which surely has a complexity of O(1) because, I have to account for the scenario where my input might contain identical values. For example, in the above case, I can have a set of input values {3,6,4,4,7} to be matched for the sum 8, which should return true.
My above solution's time complexity depends on the complexity of HashMap.containsValue() method. Please shed some light on the time complexity of containsValue() method and suggest me if there is any better solution for the above problem in terms of time complexity. Thank you.

A: HashMap.containsValue complexity is O(n). But n is not exactly the map size but rather hash table size because containsValue goes thru all table elements if even map size = 0.
Suppose we created an empty map with initial capacity = 1024. containsValue will have to go thru 1024 elements hash table array:
public boolean containsValue(Object value) {
    if (value == null)
        return containsNullValue();

    Entry[] tab = table;
    for (int i = 0; i < tab.length ; i++)
        for (Entry e = tab[i] ; e != null ; e = e.next)
            if (value.equals(e.value))
                return true;
    return false;
}

A: To answer the question in the title - as mentioned by others, containsValue is O(n), because without the key it doesn't know where it is and the algorithm has to go over all the values stored in the map.
To answer the question in the body of your question - on how to solve it - just consider whether you really need a general map which can count how many instances have you seen of each number. I mean, the only time you'd care if there's more than one appearance of a number is when it's x/2, right? That smells like a corner case to me. Just add a test that checks for that corner case - something like embedding if (numberList[i] == requiredSum/2) half++ during your set-construction loop, and then if (requiredSum % 2 == 0 && half == 2) return true after it (see other variation below).
Then you can just iterate over the set and for each item check whether requiredSum-item also appears in the set.
To summarize (with early exits when possible):
Set<Integer> seen = new HashSet<Integer>();
boolean halfSeen = false;
for (int num : numberList) {
    if (num == requiredSum/2 && requiredSum % 2 == 0) {
        if (halfSeen) return true;
        halfSeen = true;
    } else {
        seen.add(num);
    }
}
for (int num : seen) {
    if (seen.contains(requiredSum - num)) return true;
}
return false;

A: The HashMap essentially is a key-value store, which can access it's keys with a complexity of O(1). Checking a value, however, there's nothing the HashMap can do but check all values and see if they're equal to the one you're searching. Therefore, the complexity is O(n) with n being the number of elements in the HashMap.
On a different note: You are looking up primitive values (int) in a collection of its boxed type (Integer). This means each time you are invoking a method on the HashMap, Java needs to box you primitive values: http://docs.oracle.com/javase/1.5.0/docs/guide/language/autoboxing.html

A: There is no index that is tagged to any value in HashMap, so, to find a value using containsValue(), you have to go through all the values of the HashMap.
Be mindful that the complexity O(n) here is the number of values in the HashMap and not the keys/size with which we usually denote its complexity.


text:
Q: Should the data from API be saved to the database or just call API everytime when data is needed for a website Please assume I have no experience in developing the structure of websites.
I am currently working on a website that displays data fetched from an API. (I use Django and python for the web app)
I want to display the current Covid-19 data and analyze the trend in graphs and charts.
I am able to grab the data from the API, but question is for a site like that needs an update on the numbers on a daily basis, what is the best practice for retrieving data. Should I be saving the api data to my database for easier access or should I just call the API everytime when the web page is visited (which is already a necessity due to the day to day update) and process data? (Performance wise or easily of processing data.)
I would appreciate if anyone would share their experience.


text:
Q: Adding XValues to a series line graph I am having trouble adding X Values to my Series line graph.
I have my code like this
Set Xacross = Range(Cells(2, 1), Cells(TimeNumber, 1))

Worksheets("Graph").Activate

    With ActiveChart.SeriesCollection.XValues
        .Name = "Time"
        .Values = Xacross
    End With

But whenever I run the code I always get Error 438
I have also tried using  code like
ActiveChart.SeriesCollection.XValues = Range(Cells(2,1),Cells(TimeNumber,1))
As well as
Xacross = Range(Cells(2,1),Cells(TimeNumber,1)
ActiveChart.SeriesCollection.XValues = Xacross

Can you offer any solutions or locations of solutions.
Thanks

A: You either...
- have to specify the SeriesCollection you are editing
SeriesCollection(index).XValues

- or have to add a new seriescollection
SeriesCollection.Add source:=Xacross

And about locations of solutions: generally try typing the problematic object (seriescollection) into google like this:
seriescollection vba
On MSDN's page you can find a lot of examples.
(Sorry for no formatting, typing from my cell)

A: A series has a .Name, .XValues, and (Y) .Values. Your code mixes this up.
Change this:
With ActiveChart.SeriesCollection.XValues
    .Name = "Time"
    .Values = Xacross
End With

to this:
With ActiveChart.SeriesCollection
    .Name = "Time"
    .XValues = Xacross
    ' and perhaps you need to specify .Values = something?
End With


text:
Q: Get element wise average of multiple arrays I have a numpy.ndarray that is made up of other arrays all of the same length. For example:
array_1 = [[3,5,6.2],
           [2,4.1,10],
           [3,3.5,4]]

How can I get averages element wise. So as to return a single array where each element is the average of the respective elements across all the sub arrays in array_1? So it would return:
averaged_array = [2.66, 4.2, 6.733]

A: to obtain the average for each list in the matrix:
averaged_array = np.array(array_1).mean(axis=1)

to obtain the average for each column:
averaged_array = np.array(array_1).mean(axis=0)


text:
Q: Contains method not working Can you please tell me why in below code contains not working:
String str=
        "/XYZ1/Test3-NV28"+
        "/678/13855497776650XB"+
        "/123/";

if ("XYZ".contains(str))

        System.out.println("yes");
else
    System.out.println("no");
    }

RP

A: You are using the Yoda style condition in a wrong way. You  have to use it as
if (str.contains("XYZ")) {

}

For furthur clarification
 String x= "test";
    if (x.contains("est")) {  //true
        System.out.println("true");
    }
 if(x.contains("set")){  //false
     System.out.println("false");
 }

A: change this if ("XYZ".contains(str)) to if (str.contains("XYZ"))
you are searching if XYZ is present in String str or not
From the oracle docs
Returns true if and only if this string contains the specified sequence of char values.

A: Change
if ("XYZ".contains(str))

To
if (str.contains("XYZ"))

A: Should be
str.contains("XYZ")

because str contains "XYZ" but not the XYZ contains str
contains method name itself says the meaning of the method...

A: change this
if ("XYZ".contains(str))

to
if (str.contains("XYZ"))

because str contains "XYZ". whereas "XYZ" does not contains str
Here is Java Doc link

A: If we have two strings and we want to compare them using contains method, the string that is contained must be the subset of original String.
i.e
 String originalString="Africa is a continent";
    System.oout.println(originalString.contains("Africa"))
     ///true, will be printed because Africa is in
                                 ///the originalString
       }
   System.out.println("Africa".contains(OriginalString))// it will print false

    }


text:
Q: How to support authorization token in WKWebView? I have native iOS app and one of the flows of the app should be done with WebView. From native part of the app, user can navigate to WebView part. And, somehow, web page should identify user. I have authorization token stored in the app and of course I can pass that token in the headers of the WKWebView. And other stuff will be handle in the web (routing and etc). But is it a good and secure way of doing this? How can I easily integrate WebView in the app caring about token?

A: There are a few options here:

*

*Using headers seems problematic according to this thread but hopefully you can get it to work. It feels like this will have reliability problems if the token ever expires in the web view, so you'll need to manage that.

*Simple option: open a system browser - either Safari or a Safari View Controller. The user may have to sign in again though, which your stakeholders may not like.

*More complex option: use the Javascript API to pass the token from the mobile UI to the web UI. This will give you full control, and the web app can call back the mobile app to refresh its token. It can be the best usability option if used sparingly. It requires tricky foundational work in both the web and mobile UIs though.
SECURITY
Passing the token from the Mobile UI to the Web UI is natural if both are part of the same logical application and access the same level of data. In this case option 1 or 3 would work.
If the apps have very different security levels (eg the web app is now getting a much higher privilege token than it usually gets), then I would not pass the token and would use option 2 instead.
FURTHER DETAILS
I wrote a quite detailed blog post on considerations a while back, and there is also a code sample you can run:

*

*Blog Post

*Mobile Bridge Code in Web UI

*Javascript Bridge Code in Mobile UI


text:
Q: sm.current does not switch screen and gives me attribute error : 'str' object has no attribute 'current' I am new to Kivy, and i was trying to build the login screen where i am getting an error as below. Can someone pls help to understand what is going wrong & what needs to done ?
AttributeError: 'str' object has no attribute 'current'
My Kivy file looks like the below
ScreenManager:
    Welcome:
    SelectionOption:

<Welcome>:
    id: welcome
    name: 'welcome'
    manager: 'sm'
    emailInput: emailInput
    passwordInput: passwordInput
    MDScreen :
        md_bg_color : [102/255,153/255,153/255,1]
        MDCard :
            size_hint : None, None
            size : 300, 450
            pos_hint : {"center_x":.5,"center_y":.5}
            padding : 20
            spacing : 30
            orientation : "vertical"

            MDLabel :
                text : 'Manager'
                font_style : 'Overline'
                font_size : 30
                halign : "center"
                size_hint_y : None
                height : self.texture_size[1]
                padding_y : 10

            MDTextFieldRound :
                id: emailInput
                hint_text : "Email address"
                icon_right : "account"
                size_hint_x : None
                width : 220
                font_size : 15
                pos_hint : {"center_x":.5}
                color_active : [0.2,0.2,0.1,1]
                TextInput:
                    multiline: False

            MDTextFieldRound :
                id: passwordInput
                hint_text : "password"
                icon_right : "eye-off"
                size_hint_x : None
                width : 220
                font_size : 15
                pos_hint : {"center_x":.5}
                color_active : [0.2,0.2,0.1,1]
                password : True
                TextInput:
                    multiline: False

            MDRoundFlatButton :
                text : 'Login'
                pos_hint : {'center_x':0.5, 'center_y':0.5}
                font_size : 20
                text_color: 0, 0, 0, 0
                on_release:
                    root.validatelogin()

            MDRoundFlatButton :
                text: 'NEW USER'
                pos_hint: {'center_x':.5, 'center_y':0.4}
                font_size: 20
                text_color: 0, 0, 0, 0
                on_press:
                    root.signup()

            Widget :
                size_hint_y : None
                height : 30

<SelectionOption>:
    name : 'selection'
    MDLabel:
        text : 'Selection Option'
        font_style : 'Overline'
    MDRoundFlatButton :
        text: 'Login'
        pos_hint : {'center_x':0.5, 'center_y':0.5}
        font_size : 20
        text_color: 0, 0, 0, 0

And my python code looks like below.
from kivymd.app import MDApp
from kivy.lang.builder import Builder
from kivy.uix.screenmanager import Screen, ScreenManager
from kivy.core.window import Window
from kivy.properties import ObjectProperty

Window.size = (350, 580)

class Welcome(Screen):
    emailInput = ObjectProperty(None)
    passwordInput = ObjectProperty(None)

    def validatelogin(self):
        if self.emailInput.text == "123" and self.passwordInput.text == "123":
            print("????", self.manager)
            self.manager.current = 'selection'

class SelectionOption(Screen):
    pass

class windowManager(ScreenManager):
    pass

class Console(MDApp):

    def build(self):
        return Builder.load_file('../Files/ScreenManager.kv')

if __name__ == '__main__':
    Console().run()

A: manager: 'sm'

I don't know what this is for, but it codes for exactly the error that you see.
Probably just delete this line.


text:
Q: CodeIgniter pass data from model to controller to view I'm having trouble passing data from the controller to the view using Codeigniter
My model:
public function get_post($post_id) {
  $sql = "SELECT * FROM cities WHERE id = ? AND active ='y' LIMIT 1";
  $query = $this->db->query($sql, $post_id);
  return $query->result();
}

My controller:
public function city($post_id) {
  $this->load->model('post_model');
  $data = $this->post_model->get_post($post_id);
  $this->load->view('post_view', $data);
}

My view:

<?php echo $title; ?>

<img src="<?php echo base_url(); ?>uploads/max_<?php echo $photo_name; ?>" alt="Post Photo">

<?php echo $city; ?>, <?php echo $state; ?>,
[<?php echo strtoupper($gender); ?>] <?php echo date("D M j g:i a", strtotime($post_date)); ?>

When I do a print_r in the controller on $data I get:
Array ( [0] => stdClass Object ( [id] => 2 [title] => Sample Title [city] => San Francisco [state] => California [gender] => F [photo_name] => 1404181142680616849.jpg [post_date] => 2014-07-01 03:21:41 [active] => y ) )

A: Change return $query->result(); in your model to return $query->row(); as right now you're getting an array wrapping the actual data you want


text:
Q: Mode of LogNormal distribution? I have data that turn out to be describable by a lognormal distribution. However, I feel like the peak value (mode) of the lognormal distribution would be more representative of the data points. Is there an analytical expression for this, and what kind of dispersion measure would be most suitable to report along with it?

A: Mode of lognormal distribution has closed-form solution:
$$\exp(\mu-\sigma^2)$$
As about dispersion, assuming that you are interested in variability around the mode, if I were you I'd simply use bootstrap to compute intervals over it. You could also use mean absolute deviation around the mode. However if you are interested in general measure of variability, why not simply use standard deviation?


text:
Q: How to connect to FTPS server with reuse sessions? I am using the Apache Commons FTP library in my android application.
I am trying to connect to my FTPS server from my application (using Android Studio) and then upload some files.
However when I want to reuse sessions by overiding the method _prepareDataSocket_ from FTPSClient, I always have the same error about :java.lang.NoSuchFieldException: sessionHostPortCache.
I have tried with the code from the others posts : How to connect to FTPS server with data connection using same TLS session?
or Transfer files from android with FTPS to the server
Do you know why I have this error ?
I'm using Android studio with jdk 1.8.
I appreciate any help, thanks.
Main code :
String server = "ftp.[HIDDEN]";
int port = 21;
String user = "[HIDDEN]";
String pass = "[HIDDEN]";

System.setProperty("jdk.tls.useExtendedMasterSecret", "false");
SSLSessionReuseFTPSClient ftpClient = new SSLSessionReuseFTPSClient("SSL");
ftpClient.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out), true));

ftpClient.connect(server, port);
System.out.println("Connected to " + server + " on " + port);

ftpClient.login(user, pass);

ftpClient.execPBSZ(0);
ftpClient.execPROT("P");
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
ftpClient.enterLocalPassiveMode();

// transfer files
InputStream input;
input = new FileInputStream(local);
ftpClient.storeFile(remote, input);
input.close();

ftpClient.noop(); // check that control connection is working OK
ftpClient.logout();

SSLSessionReuseFTPSClient :
public class SSLSessionReuseFTPSClient extends FTPSClient {

    public SSLSessionReuseFTPSClient(String protocol) {
        super(protocol);
    }

    // adapted from: https://trac.cyberduck.io/changeset/10760
    @Override
    protected void _prepareDataSocket_(final Socket socket) throws IOException {
        if (socket instanceof SSLSocket) {
            // Control socket is SSL
            final SSLSession session = ((SSLSocket) _socket_).getSession();
            if (session.isValid()) {
                final SSLSessionContext context = session.getSessionContext();
                try {
                    final Field sessionHostPortCache = context.getClass().getDeclaredField("sessionHostPortCache");
                    sessionHostPortCache.setAccessible(true);
                    final Object cache = sessionHostPortCache.get(context);
                    final Method method = cache.getClass().getDeclaredMethod("put", Object.class, Object.class);
                    method.setAccessible(true);
                    method.invoke(cache, String
                            .format("%s:%s", socket.getInetAddress().getHostName(), String.valueOf(socket.getPort()))
                            .toLowerCase(Locale.ROOT), session);
                    method.invoke(cache, String
                            .format("%s:%s", socket.getInetAddress().getHostAddress(), String.valueOf(socket.getPort()))
                            .toLowerCase(Locale.ROOT), session);
                } catch (NoSuchFieldException e) {
                    throw new IOException(e);
                } catch (Exception e) {
                    throw new IOException(e);
                }
            } else {
                throw new IOException("Invalid SSL Session");
            }
        }
    }
}

Logcat :
220---------- Welcome to Pure-FTPd [privsep] [TLS] ----------
07-22 09:53:59.516 9529-9561/com.example.test I/System.out: 220-You are user number 1 of 50 allowed.
07-22 09:53:59.516 9529-9561/com.example.test I/System.out: 220-Local time is now 11:54. Server port: 21.
07-22 09:53:59.516 9529-9561/com.example.test I/System.out: 220-This is a private system - No anonymous login
07-22 09:53:59.516 9529-9561/com.example.test I/System.out: 220-IPv6 connections are also welcome on this server.
07-22 09:53:59.516 9529-9561/com.example.test I/System.out: 220 You will be disconnected after 15 minutes of inactivity.
07-22 09:53:59.519 9529-9561/com.example.test I/System.out: AUTH TLS
07-22 09:53:59.533 9529-9561/com.example.test I/System.out: 234 AUTH TLS OK.
07-22 09:53:59.561 9529-9550/com.example.test D/EGL_emulation: eglMakeCurrent: 0xadc34d60: ver 2 0 (tinfo 0xadc394d0)
07-22 09:53:59.589 9529-9550/com.example.test D/EGL_emulation: eglMakeCurrent: 0xadc34d60: ver 2 0 (tinfo 0xadc394d0)
07-22 09:53:59.593 9529-9561/com.example.test I/System.out: Connected to ftp.[HIDDEN] on 21
07-22 09:53:59.597 9529-9561/com.example.test I/System.out: USER *******
07-22 09:53:59.609 9529-9561/com.example.test I/System.out: 331 User [HIDDEN] OK. Password required
07-22 09:53:59.610 9529-9561/com.example.test I/System.out: PASS *******
07-22 09:53:59.613 9529-9550/com.example.test D/EGL_emulation: eglMakeCurrent: 0xadc34d60: ver 2 0 (tinfo 0xadc394d0)
07-22 09:53:59.695 9529-9550/com.example.test D/EGL_emulation: eglMakeCurrent: 0xadc34d60: ver 2 0 (tinfo 0xadc394d0)
07-22 09:53:59.701 9529-9561/com.example.test I/System.out: 230 OK. Current restricted directory is /
07-22 09:53:59.702 9529-9561/com.example.test I/System.out: PBSZ 0
07-22 09:53:59.714 9529-9561/com.example.test I/System.out: 200 PBSZ=0
07-22 09:53:59.717 9529-9561/com.example.test I/System.out: PROT P
07-22 09:53:59.727 9529-9561/com.example.test I/System.out: 200 Data protection level set to "private"
07-22 09:53:59.729 9529-9561/com.example.test I/System.out: TYPE I
07-22 09:53:59.743 9529-9561/com.example.test I/System.out: 200 TYPE is now 8-bit binary
07-22 09:53:59.743 9529-9561/com.example.test I/System.out: PASV
07-22 09:53:59.757 9529-9550/com.example.test D/EGL_emulation: eglMakeCurrent: 0xadc34d60: ver 2 0 (tinfo 0xadc394d0)
07-22 09:53:59.758 9529-9561/com.example.test I/System.out: 227 Entering Passive Mode (5,134,13,241,188,161)
07-22 09:53:59.777 9529-9550/com.example.test D/EGL_emulation: eglMakeCurrent: 0xadc34d60: ver 2 0 (tinfo 0xadc394d0)
07-22 09:53:59.782 9529-9561/com.example.test I/System.out: STOR pictures/test 18.07 1431/test 18.07 1431_19.6.2019_0.32.15.667.jpg
07-22 09:53:59.792 9529-9561/com.example.test I/System.out: 150 Accepted data connection
07-22 09:53:59.793 9529-9561/com.example.test W/System.err: java.io.IOException: java.lang.NoSuchFieldException: sessionHostPortCache
07-22 09:53:59.793 9529-9561/com.example.test W/System.err:     at com.example.test.functions.SSLSessionReuseFTPSClient._prepareDataSocket_(SSLSessionReuseFTPSClient.java:54)
07-22 09:53:59.793 9529-9561/com.example.test W/System.err:     at org.apache.commons.net.ftp.FTPSClient._openDataConnection_(FTPSClient.java:628)
07-22 09:53:59.793 9529-9561/com.example.test W/System.err:     at org.apache.commons.net.ftp.FTPClient._storeFile(FTPClient.java:653)
07-22 09:53:59.793 9529-9561/com.example.test W/System.err:     at org.apache.commons.net.ftp.FTPClient.__storeFile(FTPClient.java:639)
07-22 09:53:59.793 9529-9561/com.example.test W/System.err:     at org.apache.commons.net.ftp.FTPClient.storeFile(FTPClient.java:2030)
07-22 09:53:59.793 9529-9561/com.example.test W/System.err:     at com.example.test.functions.FTPfunctions2$BackGroundWorker.doInBackground(FTPfunctions2.java:81)
07-22 09:53:59.793 9529-9561/com.example.test W/System.err:     at com.example.test.functions.FTPfunctions2$BackGroundWorker.doInBackground(FTPfunctions2.java:41)
07-22 09:53:59.794 9529-9561/com.example.test W/System.err:     at android.os.AsyncTask$2.call(AsyncTask.java:292)
07-22 09:53:59.794 9529-9561/com.example.test W/System.err:     at java.util.concurrent.FutureTask.run(FutureTask.java:237)
07-22 09:53:59.794 9529-9561/com.example.test W/System.err:     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
07-22 09:53:59.794 9529-9561/com.example.test W/System.err:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
07-22 09:53:59.794 9529-9561/com.example.test W/System.err:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
07-22 09:53:59.794 9529-9561/com.example.test W/System.err:     at java.lang.Thread.run(Thread.java:818)
07-22 09:53:59.794 9529-9561/com.example.test W/System.err: Caused by: java.lang.NoSuchFieldException: sessionHostPortCache
07-22 09:53:59.794 9529-9561/com.example.test W/System.err:     at java.lang.Class.getDeclaredField(Class.java:890)
07-22 09:53:59.794 9529-9561/com.example.test W/System.err:     at com.example.test.functions.SSLSessionReuseFTPSClient._prepareDataSocket_(SSLSessionReuseFTPSClient.java:42)
07-22 09:53:59.794 9529-9561/com.example.test W/System.err:     ... 12 more

A: I have encountered the same error when I change java.security to use ssl security provider other then SunJSSE. Particularly in my case I change it to:
security.provider.4=org.bouncycastle.jsse.provider.BouncyCastleJsseProvider
instead
security.provider.4=com.sun.net.ssl.internal.ssl.Provider
1) Check your java.security file.
2) I have added a log message to the class which shows what implementation of SSLSessionContext is actually used.
logger.debug("sessionContext calss = " + sessionContext.getClass().getCanonicalName());
final Field sessionHostPortCache = sessionContext.getClass().getDeclaredField("sessionHostPortCache");

I found indeed that BouncyCastle
org.bouncycastle.jsse.provider.ProvSSLSessionContext class doesn't have a sessionHostPortCache member.
You can try this to discover the problem.
Another reason for getting java.lang.NoSuchFieldException is because JRE bytecode underwent obfuscation. Thus the sessionHostPortCache field could be named for example "b".
You can check this by opening the SSLSessionContext.class in your IDE and if you install decompiler plugin it will show the source code.


text:
Q: How to get external IP of VM from with VM I have a GCP compute instance VM and I would like to get the external IP of the instance from within it?
PS: gcloud is not setup on the instance

A: In shell script:
PUBLIC_IP=$(curl -s ifconfig.co)

From the site:

Please limit automated requests to 1 request per minute. No guarantee is made for requests that exceed this limit. They may be rate-limited, with a 429 status code, or dropped entirely.

A: For GCP there is also which is more reliable and fast:
curl -H "Metadata-Flavor:Google" http://metadata/computeMetadata/v1/instance/network-interfaces/0/access-configs/0/external-ip


text:
Q: Exclude babel polyfills for standard libraries While bundling our TS project into es5 using babel and webpack, we see polyfills for standard string methods like
String.replace, String.match, String.split
$ Added following core-js polyfill:
  es.array.join { "ie":"11" }

$ Added following core-js polyfills:
  es.string.replace { "edge":"17", "firefox":"67", "ie":"11", "ios":"12", "safari":"12.1", "samsung":"9.2" }
  es.string.split { "edge":"17", "ie":"11" }

As per compatibility charts of MDN & other trusted compat tables, these methods are fully supported by all these platforms. But why would babel add polyfills for them remains a question to us.
Is there a way to disable polyfills of these standard methods via babel config? Below is our babel configuration, Hint us if we are missing something.
const presets = [
  [
    '@babel/env', // Using babel preset-env
    {
      debug: true, // Disabling debug output in console
      targets: {
        browsers: ['> 1%', 'not dead', 'not ie < 8'], // Spit code for all browsers with usage > 1% and not dead.
      },
      useBuiltIns: 'usage', // Use polyfills for runtime feature support
      corejs: 3, // Use core-js 3 Polyfills.
    },
  ],
];

const plugins = [
  '@babel/plugin-transform-runtime', // Use Babel helpers to prevent code bloating with helpers
];

module.exports = { presets, plugins };


text:
Q: Digital regulator for DCM Boost - How does it relate to duty cycle? I really hope someone can help me here, I'm tearing my hair out trying to bridge the gap between control theory and electronics.
My aim is to control a discontinuous conduction mode boost converter using voltage mode control. I have modelled the small signal dynamics of the control to output voltage transfer function, as per Erickson's book (fundamentals of power electronics, second edition). I'm quite confident with it's model, shown below in Laplace form:
$$
T_{u} = G_{PWM} \cdot G_{vd}
$$
Where:
$$
G_{PWM} = \left.\frac{1}{M}\right|_{M=PWM\space Ramp\space Height}
$$
And:
$$
G_{vd} = \frac{\hat v}{\hat d} = \frac{G_{d0}}{1+\frac{s}{\omega_p}}
$$
where:
$$
G_{d0} = \frac{2\cdot V_{out}}{D}\cdot \frac{\frac{V_{out}}{V_{in}}-1}{2\cdot\frac{V_{out}}{V_{in}}-1}
$$
$$ D = \sqrt{\frac{2\cdot L \cdot I(V_{out}-V_{in})}{V_{in}^2 \cdot T_s}} $$
$$ \omega_p = \frac{2 \cdot \frac{V_{out}}{V_{in}}-1}{(\frac{V_{out}}{V_{in}}-1) \cdot RC}$$
This is a simplified model of the boost in DCM, as written in Erickson's book, by letting the inductance tend to zero. My final plant, the uncompensated loop, is the following:
$$
= \frac{1}{4.5}\cdot\frac{11.94}{0.0006644s + 1}
$$
So, I designed a controller which suits my needs, ~5 kHz BW, >50 degree phase margin:
$$ G_{C} = \frac{7.716s + 7.716 \cdot 10^4}{1 \cdot 10^-5 s^2 + s} $$
I simulated this in simulink, and it's behaviour is as I would expect. I have transformed the controller from the Laplace domain to the discrete domain, via a tustin/Bilinear transform (I didn't prewarp as it didn't seem to make a difference?) and I converted the resulting discrete transform function into a difference equation as follows:
$$ y(n) = 1.905 \cdot y(n-1) - 0.9048 \cdot y(n-2) + 0.7384 \cdot x(n-1) - 0.731 \cdot x(n-2) $$
And this is where I fail - I can't for the life of me understand how the value out of this function relates to duty cycle. In simulink, I can use the scope function to look at the output of the controller, but it doesn't seem to relate to duty cycle. The number initially goes well beyond 100% (almost to 150%), and then settles around 30%.
And so my question is, how does my controller, \$G_{C}\$, relate to duty cycle? I have the difference equation implemented in software, but I need to use this value to set the PWM output, and I'm sure where this number is! Is it a simple 1-1 mapping, or does it depend on other variables?
Any help would be greatly appreciated, thank you very much in advance!
EDIT:// Updated \$v_{g}\$ to be \$V{in}\$ also adding this picture to help explain simulink:

A:
And so my question is, how does my controller, GC, relate to duty
  cycle?

You need to implement a PWM block into your system as shown below: -

I've shown it in red after your gain stage but I'm not really sure what that gain stage is modeling and, depending on what that gain stage is in terms of modeled physical components, the PWM boost stage may need to precede it.
So, it comes down to these parameters: -

*

*Power uplift needed to raise the load to a voltage higher than \$V_{IN}\$

*This is the \$I_{OUT}\cdot (V_{OUT} - V_{IN})\$ terms in your D equation that I corrected for you in comments a few hours ago

*Your output inductance

*Your output load resistance = \$\dfrac{V_{OUT}}{I_{OUT}}\$

*The inverse of your PWM switching frequency, \$T_S\$


text:
Q: R's as.numeric function in python? I just started to translate a program from R to python and now i need a function in python, that does the same like the as.numeric function in R, but i have no idea yet.
At first i created a sequence with numpy and a dataframe with indices of half-open bins with pandas:
breaks = np.arange(0.0, 1.05, 0.05);
cut = pd.cut(data, breaks, right=False);

so i have something like that:
[1] [0.5,0.55) [0.6,0.65) [0.6,0.65) [0.6,0.65) [0.5,0.55) [0.55,0.6) [0.6,0.65) [0.6,0.65) [0.6,0.65)

now i want to give them a number like this (same indices get the same numbers):
[1] 11 13 13 13 11 12 13 13 13

How i can do it in python?

A: cut.codes should do the trick. It returns the category codes, similar to factor index levels on R.


text:
Q: Is there an MDX expression to filter a role on Dimension Data Invoice # where # starts with a particular character? I want to allow someone to only view certain types of invoices in an MS SQL Server OLAP  sales cube where the invoice type can be determined from the first character of the invoice number. I want to do this with a role that limits the data by this filter.
I tried using an MDX expression in the role properties for the dimension data invoice, using the advance tab, by editing the MDX for the allowed member set. Unfortunately I don't know MDX at all. I was unable to adapt an expression that I found in a search to my environment and situation.


text:
Q: How can I search Stack Overflow with strings containing punctuation? I would like to search this site (Stack Overflow) using strings containing punctuation.
Example: I want to search for the contents of the following line:
tools:layout="@layout/activity_item_detail"

I don't want to search for the words tools, layout activity item detail, but for exactly the line mentioned above.
Currently, for as far as I know, it is possible to enclose a search term into quotes, but my search expression contains quotes. I would call my kind of search a verbatim search. All other searches seem to split the entered search string into words, which is exactly what I don't want.
I was not successful in finding a solution in the FAQ.


text:
Q: How to speed up unzipping time in Java / Android? Unzipping files on android seems to be dreadfully slow. At first I thought this was just the emulator but it appears to be the same on the phone. I've tried different compression levels, and eventually dropped down to storage mode but it still takes ages.
Anyway, there must be a reason! Does anyone else have this problem? My unzip method looks like this:
public void unzip()
{
try{
        FileInputStream fin = new FileInputStream(zipFile);
        ZipInputStream zin = new ZipInputStream(fin);
        File rootfolder = new File(directory);
        rootfolder.mkdirs();
        ZipEntry ze = null;
        while ((ze = zin.getNextEntry())!=null){

            if(ze.isDirectory()){
                dirChecker(ze.getName());
            }
            else{
                FileOutputStream fout = new FileOutputStream(directory+ze.getName());

            for(int c = zin.read();c!=-1;c=zin.read()){
                fout.write(c);
            }
                //Debug.out("Closing streams");
                zin.closeEntry();
                fout.close();

        }
    }
    zin.close();
}
catch(Exception e){
            //Debug.out("Error trying to unzip file " + zipFile);

}
    }

A: Using above ideas and ideas from some other sources I have created this class
Create this new class
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import android.util.Log;

public class DecompressFast {
 private String _zipFile;
  private String _location;

  public DecompressFast(String zipFile, String location) {
    _zipFile = zipFile;
    _location = location;
    _dirChecker("");
  }

  public void unzip() {
    try  {
      FileInputStream fin = new FileInputStream(_zipFile);
      ZipInputStream zin = new ZipInputStream(fin);
      ZipEntry ze = null;
      while ((ze = zin.getNextEntry()) != null) {
        Log.v("Decompress", "Unzipping " + ze.getName());
        if(ze.isDirectory()) {
          _dirChecker(ze.getName());
        } else {
          FileOutputStream fout = new FileOutputStream(_location +  ze.getName());
          BufferedOutputStream bufout = new BufferedOutputStream(fout);
          byte[] buffer = new byte[1024];
          int read = 0;
          while ((read = zin.read(buffer)) != -1) {
              bufout.write(buffer, 0, read);
          }
          bufout.close();
          zin.closeEntry();
          fout.close();
        }
      }
      zin.close();
      Log.d("Unzip", "Unzipping complete. path :  " +_location );
    } catch(Exception e) {
      Log.e("Decompress", "unzip", e);
      Log.d("Unzip", "Unzipping failed");
    }
  }

  private void _dirChecker(String dir) {
    File f = new File(_location + dir);

    if(!f.isDirectory()) {
      f.mkdirs();
    }
  }
}

USAGE
just pass your file location of zip file  and your  destination Location to this class
 example
  String zipFile = Environment.getExternalStorageDirectory() + "/the_raven.zip"; //your zip file location
  String unzipLocation = Environment.getExternalStorageDirectory() + "/unzippedtestNew/"; // unzip location
  DecompressFast df= new DecompressFast(zipFile, unzipLocation);
    df.unzip();

Dont Forget to add following permissions in manifest(also Run time permission if version higher than marshmellow)
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

 <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

hope this helps

A: I don't know if unzipping on Android is slow, but copying byte for byte in a loop is surely slowing it down even more. Try using BufferedInputStream and BufferedOutputStream - it might be a bit more complicated, but in my experience it is worth it in the end.
BufferedInputStream in = new BufferedInputStream(zin);
BufferedOutputStream out = new BufferedOutputStream(fout);

And then you can write with something like that:
byte b[] = new byte[1024];
int n;
while ((n = in.read(b,0,1024)) >= 0) {
  out.write(b,0,n);
}

A: The URL that helped me learn how to zip and unzip can be found here.
I used that URL in conjuction with user3203118's answer above for unzipping. This is for future references for people who run in to this issue and need help solving it.
Below is the ZipManager code I am using:
public class ZipManager {

    private static final int BUFFER = 80000;

    public void zip(String[] _files, String zipFileName) {
        try {
            BufferedInputStream origin = null;
            FileOutputStream dest = new FileOutputStream(zipFileName);
            ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(
                dest));
            byte data[] = new byte[BUFFER];

            for (int i = 0; i < _files.length; i++) {
                Log.v("Compress", "Adding: " + _files[i]);
                FileInputStream fi = new FileInputStream(_files[i]);
                origin = new BufferedInputStream(fi, BUFFER);

                ZipEntry entry = new ZipEntry(_files[i].substring(_files[i]
                    .lastIndexOf("/") + 1));
                out.putNextEntry(entry);
                int count;

                while ((count = origin.read(data, 0, BUFFER)) != -1) {
                    out.write(data, 0, count);
                }
                origin.close();
            }
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void unzip(String _zipFile, String _targetLocation) {

        // create target location folder if not exist
        dirChecker(_targetLocation);

        try {
            FileInputStream fin = new FileInputStream(_zipFile);
            ZipInputStream zin = new ZipInputStream(fin);
            ZipEntry ze = null;
            while ((ze = zin.getNextEntry()) != null) {

                // create dir if required while unzipping
                if (ze.isDirectory()) {
                    dirChecker(ze.getName());
                } else {
                    FileOutputStream fout = new FileOutputStream(
                    _targetLocation + "/" + ze.getName());
                    BufferedOutputStream bufout = new BufferedOutputStream(fout);
                    byte[] buffer = new byte[1024];
                    int read = 0;
                    while ((read = zin.read(buffer)) != -1) {
                        bufout.write(buffer, 0, read);
                    }

                    zin.closeEntry();
                    bufout.close();
                    fout.close();
                }
            }
            zin.close();
        } catch (Exception e) {
            System.out.println(e);
        }
    }

    private void dirChecker(String dir) {
        File f = new File(dir);
        if (!f.isDirectory()) {
            f.mkdirs();
        }
    }
}

A: Thanks for the solution Robert.
I modified my unzip method and now it takes only a few seconds instead of 2 minutes.
Maybe someone's interested in my solution. So here you go:
public void unzip() {

    try {
        FileInputStream inputStream = new FileInputStream(filePath);
        ZipInputStream zipStream = new ZipInputStream(inputStream);
        ZipEntry zEntry = null;
        while ((zEntry = zipStream.getNextEntry()) != null) {
            Log.d("Unzip", "Unzipping " + zEntry.getName() + " at "
                    + destination);

            if (zEntry.isDirectory()) {
                hanldeDirectory(zEntry.getName());
            } else {
                FileOutputStream fout = new FileOutputStream(
                        this.destination + "/" + zEntry.getName());
                BufferedOutputStream bufout = new BufferedOutputStream(fout);
                byte[] buffer = new byte[1024];
                int read = 0;
                while ((read = zipStream.read(buffer)) != -1) {
                    bufout.write(buffer, 0, read);
                }

                zipStream.closeEntry();
                bufout.close();
                fout.close();
            }
        }
        zipStream.close();
        Log.d("Unzip", "Unzipping complete. path :  " + destination);
    } catch (Exception e) {
        Log.d("Unzip", "Unzipping failed");
        e.printStackTrace();
    }

}

public void hanldeDirectory(String dir) {
        File f = new File(this.destination + dir);
        if (!f.isDirectory()) {
            f.mkdirs();
        }
}

A: Just call this method and it will give you much better performance..
    public boolean unzip(Context context) {
    try {
        FileInputStream fin = new FileInputStream(_zipFile);
        ZipInputStream zin = new ZipInputStream(fin);
        BufferedInputStream in = new BufferedInputStream(zin);
        ZipEntry ze = null;
        while ((ze = zin.getNextEntry()) != null) {
            Log.v("Decompress", "Unzipping " + ze.getName());

            if (ze.isDirectory()) {
                _dirChecker(ze.getName());
            } else {
                FileOutputStream fout = new FileOutputStream(_location
                        + ze.getName());
                    BufferedOutputStream out = new BufferedOutputStream(fout);
                    byte b[] = new byte[1024];
                for (int c = in.read(b,0,1024); c != -1; c = in.read()) {
                    out.write(b,0,c);
                }
                zin.closeEntry();
                fout.close();
            }
        }
        zin.close();
        return true;
    } catch (Exception e) {
        Log.e("Decompress", "unzip", e);
        return false;
    }
}

    private void _dirChecker(String dir) {
    File f = new File(_location + dir);
    if (!f.isDirectory()) {
        f.mkdirs();
    }
}

A: In case of using BufferedOutputStream be sure to flush it. If you do not do it, size smaller than buffer will not be unzipped properly
if (ze.isDirectory()) {
                _dirChecker(ze.getName());
            } else {
                FileOutputStream fout = new FileOutputStream(_location
                        + ze.getName());
                    BufferedOutputStream out = new BufferedOutputStream(fout);
                    byte buffer[] = new byte[1024];
                for (int c = in.read(buffer,0,1024); c != -1; c = in.read()) {
                    out.write(buffer,0,c);
                }
                out.flush();//flush it......
                zin.closeEntry();
                fout.close();
            }


text:
Q: How to display .toggle or .Animate to all connected browser sessions using Meteor But how do you show the interaction of clicking on an element that toggles or animates?
The meteor checkers example:
http://checkers.meteor.com/
In the example below, I would like for every browser that's connected to the Meteor server to be able to see when one of the other browsers makes the shape change.
https://jsfiddle.net/qh2jyL3b/
HTML:

CSS:
.square {
  width: 100px;
  height: 100px;
  background: white;
  border: 10px solid black;
  cursor: pointer;

}

JavaScript:
$(".square").click(function() {
    $( this ).toggleClass("circle");
  });

A: You can store click state in Meteor.Collection. Changes in collections propagate reactively for all connected clients. Just create separate document for each square and save state here. Then you can create helper that displays correct class name depending on db items.
For example you can do this this way:
For each chess-table you can create separate document
on server side:
ChessTableCell = new Mongo.Collection('chesstablecell');
Then you can store state of each cell in each of this document. So initially you can insert
ChessTableCell.insert({name: 'a1', state: false);
ChessTableCell.insert({name: 'a2', state: false);

...etc

And on your client side you have access to cells states like this:
ChessTableCell.findOne({name: 'a1'}).state;
And on click you just need to toggle state of clicked cell. You can do it in a following way:
Template.chessboard.events({//or whatever your template is called like
    'click .cell': function(e,t) {
      var cellName = $(e.target).data('name'); //if you specify cell name in your html in data-name attribute
      var cellValue = ChessTableCell.findOne({name: cellName}).state;
      //here you can update the value
      ChessTableCell.update({name: cellValue}, {$set: { state: !cellValue}});
    }
});

Then state will change reactively on every connected client.
Of course you need to reflect those changes in your html like this:
{{#each ChessTableCells}}

{{/each}}

And in your client code:
Template.chessboard.helpers({
  ChessTableCells: function() { return ChessTableCell.find({}); }
});


text:
Q: Can you set the src of an input image using CSS? Can you set the src of an input image using CSS?
This has to work in IE.

A: No.
All you can do is define a background-image URL but that is different from a proper <img> in so many ways.
Why do you need this? Maybe there is a workaround.

A: Just use <input type="submit" class="foo"> instead of <input type="image" src="foo.png">.
E.g.
<input type="submit" name="save" value="" class="mybutton" />

with for example
.mybutton {
    border: 0;
    width: 40px;
    height: 20px;
    background-image: url('foo.png');
}

The <input type="image"> is meant to have sort of an image map as button. When submitted, it sends a name.x and name.y parameter to the server side which denotes the exact location where the client has pressed on the image map. This has likely not your interest here. You just want a submit button with a background image.

A: No, you can't do it without changing type of your input. But if you have to use image type input then there is a hack that I used before.
Set src of your input to a 1 by 1 pixel transparent PNG file and then use background-image to set the image via CSS.

A: What you're asking sounds like 'inline images'.  It's not generally a preferred method, but apparently there are some practical uses for it if you are trying to avoid caching of that image.
I borrowed the below code from the following link to give you an example:
http://www.websiteoptimization.com/speed/tweak/inline-images/
ul {list-style:none;}
ul > li {
margin:0 0 .1em;
background:url(data:image/gif;base64,R0lGODlhEAAOALMAAOazToeHh0tLS/7LZv/0jvb29t/f3//Ub//ge8WSLf/rhf/)
top left no-repeat; )
height:14px;
text-indent:1.5em;
}
</style>


text:
Q: PayFlow integration using transparent redirect. Invalid Merchant or Merchant doesn't exist I have a similar question like PayPal PayFlow Pro with Transparent Redirect - User Authentication Failed Issues / Documentation
Problem occurs on step 5
Secure token request for the transparent redirect (https://pilot-payflowpro.paypal.com)
PARTNER=PayPal
&VENDOR=myAuthUserName
&USER=myAuthUserName
&PWD=myPassword
&CREATESECURETOKEN=Y
&SECURETOKENID=f6153d8b0c6c42c789e61daa7daa55b1
&SILENTTRAN=TRUE
&TRXTYPE=A
&CURRENCY=USD
&AMT=20
&RETURNURL=myReturnURL
&CANCELURL=myCancelURL
&ERRORURL=myErrorURL

Response:
RESULT=0&RESPMSG=Approved&SECURETOKEN=9u5CH4WMKOkey9pVTgSJBwAqG&SECURETOKENID=f6153d8b0c6c42c789e61daa7daa55b1

So it seems like the account authenticates correctly.
Next I send post to https://pilot-payflowlink.paypal.com with params
SECURETOKEN=9u5CH4WMKOkey9pVTgSJBwAqG
&SECURETOKENID=f6153d8b0c6c42c789e61daa7daa55b1
&ACCT=4111111111111111
&EXPDATE=12%2F15
&CSC=123

Response:
Error: Invalid Merchant or Merchant doesn't exist!
What can cause this problem?
PayPal Manager settings are:
Service Summary:
Hosted Checkout Pages  Test
Payflow SDK/API (Full Access)  Test

Transaction Process Mode: Test
AVS: No
CSC: No
Enable Secure Token: Yes


text:
Q: Open mail client from browser with an byte[] attachment from the server I looked on SO an found several ways to do kind simmilar things, but those aren't the solution.
A user is on the web page and on a click on a file (which is stored in byte[] on server) should open the mail client, where the attachment, subject and mailfrom is set.
Subject and Mail From is no problem, but the attachment. Here are some points I need/need not to:

*

*I cannot/I am not allowed to Create a file such as mymailmessage.eml
on a client (access denied)

*I cannot use MailMessage
(System.Net.Mail) because for this I need to create a file to open the mail client with Process.Start(filename)

*I cannot use mailto: because there I cannot add an attachment

So the way I am on for now is to use MAPI. Unfortunately I have not found a solution. My source is a byte[] and I can write this in a MemoryStream. Is it possible to create a kind of virtual file path in C#? But I don't know how to open the mail client including the parameters. All the MAPI projects (like https://github.com/PandaWood/Simple-MAPI.NET or https://www.codeproject.com/Articles/10881/MAPIEx-Extended-MAPI-Wrapper are using local files. I tried those, but in my case the mail client isn't starting, so no mail message window is popping up.
So what I am looking for is: Create a MapiMessage with MailFrom, Subject, an attachment and then open the mail client (like with mailto) including the attachment.
An other C# project is this: https://www.codeproject.com/Articles/17561/Programmatically-adding-attachments-to-emails-in-C
According to this codeproject, I cannot find the line, where the programm is saying the mail client please open (like Process.Start()) and open the prepared mail message for me.
Is there any other way except MAPI, when I only have a byte[] in the web application and need to open a mail client message including the attachment not storing/downloading it on the user client?


text:
Q: Access google docs using gspread I am trying to access google docs using gspread utility , I was successful when i tried below code on my google doc
import gspread
g = gspread.login('gmailID', 'password')
worksheet = g.open('GoogleSheetName').get_worksheet(0)
val = worksheet.cell(2, 1).value
print val

But when I tried same code for my corporate account which uses google server, I am getting below error:
  raise AuthenticationError("Unable to authenticate. %s code" % ex.code)
gspread.exceptions.AuthenticationError: Unable to authenticate. 500 code

Can anyone please help me on this?

A: See what the author of gspread says here:

Two Factor Authorization
In case your Google Account protected with Two Factor Authorization,
  you have to create an application-specific password and use your email
  to login as usual.
Otherwise you will get an AuthenticationError: Unable to authenticate.
  403 code when trying to login.


text:
Q: Ionic 2 / Angular 2 - Timer event function to open model I have an Ionic 2 app, I want to launch a model every 10 minutes. In app.components.ts
I have simple function to launch this model.
openUpgradeModel() {
let modal = this.modalCtrl.create(UpgradeToFullVersionModel);
modal.present();
}

How can I get that function to launch every 10 minutes or so?
Update, so I tried using an Observable.timer, however it loops over and over.
  this.platform.ready().then(() => {
    let timer = Observable.timer(2000,1000);
    timer.subscribe(t=> {
   UpgradeToFullVersionModel();
});

Is there anyway to tell if the model is already open don't fire?

A: You need setInterval()
setInterval(() => { openUpgradeModal(); }, 1000 * 60 * 10);

https://stackoverflow.com/a/35829004/3221120

A:
Is there anyway to tell if the model is already open don't fire?

You can create a property in app.component.ts file
// Should be set to true the first time
private shouldShowModal: boolean = true;

Then set that property to false when showing the modal, but set it to true again when dismissing the modal:
openUpgradeModel() {
  let modal = this.modalCtrl.create(UpgradeToFullVersionModel);

  modal.onDidDismiss(() => {
    this.shouldShowModal = true;
  });

  this.shouldShowModal = false;

  // Show the modal
  modal.present();
}

And then, only show the modal if it's not being shown already:
this.platform.ready().then(() => {

  let timer = Observable.timer(2000,1000);
  timer.subscribe(t => {
    if(this.shouldShowModal) {
      this.openUpgradeModel();
    }
  });

//..
});


text:
Q: Vscode: vim plugin - Maximum call stack size exceeded In vsCode using vim plugin. I wanted to search regex in file (/), but it caused err :
TaskQueue: Error running task. Failed to handle key=/. Maximum call stack size exceeded. Source: Vim (Extension)

Does anyone know why is that and how to fix that?


text:
Q: How could I watch a prop in the composition api? How can I call a function when a prop is updated?
parent container:
<div>
  <Maintable :type="typeRef" :country="countryRef" />
</div>

child container:
    export default{

    props: ['type'],

    setup(props)
    {
        watch(props.type, () => {
            console.log('hello')
        })
    }

this code gets an error: Invalid watch source...
How can I listen for an update of tthe props?
Hope someone can help me out!! :-)

A: Try to return the prop from function as first parameter :
    export default{

    props: ['type'],

    setup(props)
    {
        watch(()=>props.type, (newVal) => {
            console.log('hello')
        })
    }

Instead of watch(props.type, do watch(()=>props.type, because ()=>props.type is an arrow function that returns the prop and it's the parameter of the watcher property.
Note :
if you want to watch a property of an object you should use a getter, but if you want to watch the whole object or a reactive primitive variable pass it directly as first parameter and add deep:true option

A: You have two possible solutions:

*

*Your can make a computed property and watch it

import {computed, watch} from 'vue';

export default {
  props: ['type'],

  setup(props) {
    const type = computed(() => props.type);

    watch(type, (newValue) => {
      console.log('hello');
    });
  }
}

*You can use arrow function like this

import {watch} from 'vue';

export default {

  props: ['type'],

  setup(props) {
    watch(() => props.type, (newValue) => {
        console.log('hello');
    });
  }
}


text:
Q: Angular UI-Router (1.x) Change Host Url I have a requirement from a client to change the web site Url to a subdomain when they enter the checkout section of the site we are developing for them. For example from www.mysite.com to checkout.mysite.com. We are using UI-Router in HTML5 mode and would like to have the router change the Url to the subdomain instead of going to www.mysite.com/checkout. Does anyone know a way that this can be accomplished? I've also tried using pushState but without success. All of the subdomain suggestions I've tried have not worked. Honestly even if I just put a "fake" url that would work fine too. Changing the Url is more of a visual thing instead of actually redirecting to a subdomain.

A: After much review I found that this cannot be done because it is a security issue; even switching to a subdomain (which is what I was trying to do) is not allowed.


text:
Q: XPATH / PHP trouble with last() I've tried reading various tutorials online but I can't make any headway on solving this issue which is easy to describe but which I can not conceive of a solution.
Here is some sample XML:
<AAA>
    <BBB>
        <CCC>1</CCC>
        <CCC>2</CCC>
    </BBB>
    <BBB>
        <CCC>3</CCC>
        <CCC>4</CCC>
    </BBB>
</AAA>

I want to be able to select the last <CCC> in each  container... in other words I want to be able to pull <CCC>2</CCC> and <CCC>4</CCC>. I've tried countless expressions to achieve this end but the best I can do is to get the very last <CCC> (which contains 4).
It seems like //BBB/CCC[last()] should work but it apparently selects all the CCC's that are children of BBB (4 total), and only then does it process the last() predicate - and therefor only returns a single element <CCC>4</CCC>
This is driving me nuts! Can anyone show me the light? Many thanks!!

A: /AAA/BBB/CCC[position() = last()]

//BBB/CCC[position() = last()] and //CCC[position() = last()] also seem to work. I found a cool site for xpath testing here: http://www.whitebeam.org/library/guide/TechNotes/xpathtestbed.rhtm


text: Q: How to change the intergenartion time in Simevents in Matlab. I want to change the inter generation time between different entities in simevents entity generator. For example for first 1000 entities i want to have inter generation time of 1 sec , then next 1000 entities i want to have a intergeneration time of 2.3 sec etc. Here i also want to set the intergeneration time to be random not fixed. Can anyone guide me how can i do that ?


text:
Q: How to find tight bound for $\Theta(n\cdot \lg n\cdot\lg\frac{n}{\lg n})$? I need to find tight bound for $\Theta\big(n\cdot \lg n\cdot\lg\frac{n}{\lg n}\big)$, ($\Theta$) bound specifically.
I thought doing a limit:
$$
\lim_{n\to \infty} \frac{n}{\lg n}=\lim_{n\to \infty} \frac{1}{1\over n}=\infty\implies\lg n=o(n)\implies\\\Theta\bigg(n\cdot \lg n\cdot\lg\frac{n}{\lg n}\bigg)=O(n\lg^2 n)
$$
So I can get only an upper bound. In addition I wonder if there's a simpler way to do this because of logarithmic identity:
$$
\Theta\bigg(n\cdot \lg n\cdot\lg\frac{n}{\lg n}\bigg)=\Theta(n\cdot \lg n\cdot(\lg n-\lg(\lg n)))
$$
but I don't know how to go about the minus when determining a bound.


text:
Q: Generating signed APK I'm trying to build my first signed APK for release and I got some error. It seems that work perfectcly but now I just cant generate APK. I've done research but couldn't find anything.
Error: java.util.concurrent.ExecutionException: com.android.builder.internal.aapt.v2.Aapt2Exception: AAPT2 error: check logs for details

Gradle version: 4.8,
Android Plugin Version 3.1.4
and here's my app gradle screenshot: link
distributionUrl=https\://services.gradle.org/distributions/gradle-4.4-all.zip

This is from assembleDebug:
Configuration on demand is an incubating feature.
Could not find google-services.json while looking in [src/nullnull/debug, src/debug/nullnull, src/nullnull, src/debug, src/nullnullDebug]
registerResGeneratingTask is deprecated, use registerGeneratedResFolders(FileCollection)

27 actionable tasks: 1 executed, 26 up-to-date

I used to have other problems with layout and deprecated functions but I fixed it. One of them just disappear but I had done nothing :-)
unchecked call to execute
new getToken().execute();
where Params,Progress,Result are type-variables:
Params extends Object declared in class AsyncTask
Progress extends Object declared in class AsyncTask
Result extends Object declared in class AsyncTask

Things that I have already tried:
1. android.enableAapt2=false
2. checked if strings (for character i.e. chinese)
3. added classpath ('com.google.firebase:firebase-plugins:1.1.0') {
        exclude group: 'com.google.guava', module: 'guava-jdk5'
    }

and many more but NOTHING! Same error -.-

A: Check your PNG images, corrupted maybe or not real png (jpeg for example)
You can get the list of unreal PNGs by typing following command in android terminal
find . -type f -name "*.png" | xargs -L 1 -I{} file  -I {} | grep -v 'image/png; charset=binary$'

A:
Could not find google-services.json while looking in

Probably your project needs google-services.json. Place the file in /app folder of project.
Since you are using FireBase, you may be forgotten to place the file in there and placing the file from FireBase console in there will help.
Check this out: https://stackoverflow.com/a/40800682/4409113


text:
Q: Android: How do I get the Settings menu to appear with NavigationUI? I'm trying to follow this: https://developer.android.com/guide/navigation/navigation-ui along with a review of https://codelabs.developers.google.com/codelabs/android-navigation/#8 (although the second link is in Kotlin and I'm coding in Javascript) to implement an App in Android with navigation drawer on the left and a settings button (preferences) on the top right.
I'm using the NavigationUI with fragments for each option from the drawer and the settings.
My problem is that my settings fragment is not appearing. I think I'm nearly there, but despite reviewing several articles and questions cannot get it to work.
This code allows me to switch fragment from the nav drawer:
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    DrawerLayout drawer = findViewById(R.id.drawer_layout);
    NavigationView navigationView = findViewById(R.id.nav_view);
    mAppBarConfiguration = new AppBarConfiguration.Builder(
            R.id.nav_home, R.id.nav_gallery, R.id.nav_slideshow)
            .setDrawerLayout(drawer)
            .build();
    NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
    NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
    NavigationUI.setupWithNavController(navigationView, navController);
    //NavigationUI.setupWithNavController(toolbar, navController, mAppBarConfiguration);
}

If I switch the commented code on the last two lines (so I execute the last line but not second to last), to match the guide then the switching of fragment fails.
My code to handle the Settings menu is:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.

    NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
    return NavigationUI.onNavDestinationSelected(item, navController)
            || super.onOptionsItemSelected(item);
/*
    int id = item.getItemId();
    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        // TODO: Do something to accept settings
        View contextView =  findViewById(R.id.nav_host_fragment); // Apparently any layout can be used
        Snackbar.make(contextView, "Settings", Snackbar.LENGTH_LONG)
                .setAction("Action", null).show();
        //changeFragment(new SettingsFragment());
        getSupportFragmentManager()
                .beginTransaction()
                .replace(R.id.nav_host_fragment, new SettingsFragment(), "nh")
                .addToBackStack("nh")
                .commit();
        return true;
    }
    return super.onOptionsItemSelected(item);
*/
}

The active portion matches the guide above, is getting called (proved by setting a breakpoint) but doing nothing.
If I alternatively switch this for the commented out code instead, then my settings fragment does appear but overlays the current fragment. I understand from another answer that this is because I am using two different methods to handle fragment visibility, which makes sense and is why I am trying to get my settings fragment to be handled by the NavigationUI framework.
I feel that it must be quite simple to cure, but having read and re-read the guide (and lots of answers cannot make it work)

A: You have different options:
Just define the SettingsFragment in your navigation graph:
<navigation xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <!--Your fragments-->

    <!--Settings fragment-->
    <fragment
        android:id="@+id/settingsFragment"
        android:name=".SettingsFragment"/>

</navigation>

Then inflate your menu with:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

In your menu use the same id used in the graph:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <item
        android:id="@+id/settingsFragment"
        .../>

</menu>

Finally override the onOptionsItemSelected method:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
    return NavigationUI.onNavDestinationSelected(item, navController)
            || super.onOptionsItemSelected(item);
}

You can also define a Global Action.
<?xml version="1.0" encoding="utf-8"?>
<navigation xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <!--Global action-->
    <action android:id="@+id/action_global_open_settings_fragment"
        app:destination="@id/settingsFragment"/>

</navigation>

Then in your code to navigate to a destination just use:
Navigation.findNavController(view).navigate(R.id.action_global_open_settings_fragment);

A: I'm not sure if I understand your problem well. But here is my solution and I hope it helps you.
Here is my Navigation Graph

And this is the Code. As you see I've an action in SettingsFragment:
    <fragment
    android:id="@+id/settingsFragment"
    android:name="packageName.SettingsFragment"
    android:label="Settings Fragment">
    <action
        android:id="@+id/actionSettingsToPassword"
        app:destination="@id/passwordDialogFragment"
        app:enterAnim="@anim/fragment_open_enter"
        app:exitAnim="@anim/fragment_open_exit" />

And this is my bottomNavigationMenu's XML:
<item
    android:id="@+id/settingsFragment"
    android:icon="@drawable/ic_settings"
    android:title="Settings" />

Remember that the ID in the Navigation & Menu should be the same. As you see in the codes, the ID of "Settings Fragment" is the same:

    android:id="@+id/settingsFragment"

I don't know if you know how to add preferences.xml in your resources. Just for sure I write it too:

Right Click on "res" New > Android Resource Directory

In the Resource Type field, pickup XML. Now you gonna have xml folder under "res". Again:

Right Click on "xml" New > XML Recourse File

Now, Here is my "preferences.xml":
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceCategory android:title="Weather Location">
    <SwitchPreference
        android:defaultValue="true"
        android:disableDependentsState="true"
        android:key="USE_DEVICE_LOCATION"
        android:summary="Allow The App To Get Your Location"
        android:title="Use Device Location" />
    <EditTextPreference
        android:defaultValue="Tehran"
        android:dependency="USE_DEVICE_LOCATION"
        android:key="CUSTOM_LOCATION"
        android:summary="The Location For Which The Weather Is Displayed"
        android:title="Location" />
</PreferenceCategory>
<PreferenceCategory android:title="Units">
    <ListPreference
        android:defaultValue="METRIC"
        android:entries="@array/unitSystemEntries"
        android:key="UNIT_SYSTEM"
        android:summary="%s"
        android:title="Unit System"
        android:entryValues="@array/unitSystemValues"/>
</PreferenceCategory>
</PreferenceScreen>

Then create a "Kotlin" or "Java" class and set the XML to your class like this (depend on which language are you writing):
class SettingsFragment : PreferenceFragmentCompat() {
override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
    addPreferencesFromResource(R.xml.preferences)
}

override fun onActivityCreated(savedInstanceState: Bundle?) {
    super.onActivityCreated(savedInstanceState)
    (activity as? AppCompatActivity)?.supportActionBar?.title = "Settings"
    (activity as? AppCompatActivity)?.supportActionBar?.subtitle = null
}
}

And here is my Application Class:
class ForecastApplication : Application(){
override fun onCreate() {
    super.onCreate()
    PreferenceManager.setDefaultValues(this, R.xml.preferences, false)
}
}

and in your application's Manifest, inside the application tag, define the Application class you already created.
        android:name=".ForecastApplication"

I hope this is what you needed.


text:
Q: How do I type German or Spanish characters in Linux when I don't use a desktop environment? I'm using Debian 9 x64 with the dwm window manager. I don't use Gnome, KDE, Xfce, or any other desktop environment; it's just the window manager.
I configured my keyboard layout to use the Generic 105-key international keyboard. I've tried AltGr (the right Alt key) plus various alt codes, to no avail. I've also tried AltGr and then " u or u ", with similarly disappointing results.
Ideally I would be able to type these characters anywhere, including text editors (all of mine support Unicode), web browsers, etc. I don't use LibreOffice, so some of the LibreOffice-specific solutions I find aren't enough.

A: You're missing a step. You need to set a Compose key first. For example, to set the right Alt key as the Compose key:
setxkbmap -layout us -option compose:ralt

Then:

*

*Press Compose (on my keyboard it's labelled Alt Gr) and release it.

*Press the sequence of keys that correspond to the letter/diacritic you want. These are sometimes intuitive, sometimes not. Sometimes the order doesn't matter, either, e.g. in the case of accents.

*

*To insert ß, press s s

*For umlauts, e.g. ü, press u "

*For accents, e.g. á, press a ' or ' a

*For ñ, press n Shift ~
You can see the full list on Wikipedia or in the image below:

A: If it is for a few char, you can use :
Ctrl+Shift+U Enter 'utf8 code of your char' Enter

You can find the utf8 code here


text:
Q: JHipster new User Registration -> MailConnectException I am getting to know JHipster and Spring better and better but I have an issue with registrating a new User. When I try to register a new User I receive the below error message. According to this Stackoverflow issue Email service in Jhipster I have to fill in the properties in application-dev.yml or application-prod.yml.
The web-app should be used from different persons, who should be able to register themselves. I don't think that this is the correct way to go? Am I missing something here? Do I need a SMTP Server for this to work?
2017-12-05 09:19:58.006  WARN 31208 --- [irpd-Executor-2] irpd.service.MailService                 : Email could not be sent to user 'test.test@gmail.com'

org.springframework.mail.MailSendException: Mail server connection failed; nested exception is com.sun.mail.util.MailConnectException: Couldn't connect to host, port: localhost, 25; timeout -1;
  nested exception is:
    java.net.ConnectException: Connection refused: connect. Failed messages: com.sun.mail.util.MailConnectException: Couldn't connect to host, port: localhost, 25; timeout -1;
  nested exception is:
    java.net.ConnectException: Connection refused: connect

I have the following entry in my application-dev.yaml:
 mail:
        host: localhost
        port: 25
        username:
        password:
    messages:
        cache-seconds: 1
    thymeleaf:
        cache: false
    http:
        multipart:
            max-file-size: 5MB
            max-request-size: 20MB

A: Yes you need an SMTP server. Check our tips section on www.jhipster.tech, you'll find how to configure email and how to use MailDev with Docker


text:
Q: how to use select and count in sql for search columns in diffrent table i have these tables :
course | course_id title dept_name(FK) credits
section | course_id(FK) sec_id semester year building(FK)
takes | ID course_id(FK) sec_id(FK) semester(FK) year(FK)
how to create SQL query that print course code, course name, and number of students taking the course held at Watson building ?
i can count just number of students for use
select count(distinct id) from takes natural join section where section.building = 'Watson';

A: I would try something like this
select course_id, titile, count(1) takes
from course c
inner join
section s on c.course_id = s.course_id and s.building = @building
left join
takes t on t.course_id = c.course_id
group by course_id, title


text:
Q: How to create an async method in C# 4 according to the best practices? Consider the following code snippet:
public static Task<string> FetchAsync()
{
    string url = "http://www.example.com", message = "Hello World!";

    var request = (HttpWebRequest)WebRequest.Create(url);
    request.Method = WebRequestMethods.Http.Post;

    return Task.Factory.FromAsync<Stream>(request.BeginGetRequestStream, request.EndGetRequestStream, null)
        .ContinueWith(t =>
        {
            var stream = t.Result;
            var data = Encoding.ASCII.GetBytes(message);
            Task.Factory.FromAsync(stream.BeginWrite, stream.EndWrite, data, 0, data.Length, null, TaskCreationOptions.AttachedToParent)
                .ContinueWith(t2 => { stream.Close(); });
        })
        .ContinueWith<string>(t =>
        {
            var t1 =
                Task.Factory.FromAsync<WebResponse>(request.BeginGetResponse, request.EndGetResponse, null)
                .ContinueWith<string>(t2 =>
                {
                    var response = (HttpWebResponse)t2.Result;
                    var stream = response.GetResponseStream();
                    var buffer = new byte[response.ContentLength > 0 ? response.ContentLength : 0x100000];
                    var t3 = Task<int>.Factory.FromAsync(stream.BeginRead, stream.EndRead, buffer, 0, buffer.Length, null, TaskCreationOptions.AttachedToParent)
                        .ContinueWith<string>(t4 =>
                        {
                            stream.Close();
                            response.Close();
                            if (t4.Result < buffer.Length)
                            {
                                Array.Resize(ref buffer, t4.Result);
                            }
                            return Encoding.ASCII.GetString(buffer);
                        });
                    t3.Wait();
                    return t3.Result;
                });
            t1.Wait();
            return t1.Result;
        });
}

It should return Task<string>, send HTTP POST request with some data, return a result from webserver in a form of string and be as much efficient as possible.

*

*Did you spot any problems regarding async flow in the example above?

*Is it OK to have .Wait() inside .ContinueWith() in this example

*Do you see any other problems with this peace of code (keeping aside exception handling for now)?

A: If async related C# 4.0 code is huge and ugly - there is a chance that it's implemented properly. If it's nice and short, then most likely it's not ;)
..though, you may get it look more attractive by creating extension methods on WebRequest, Stream classes and cleanup the main method.
P.S.: I hope C# 5.0 with it's new async keyword and library will be released soon.
Reference: http://msdn.microsoft.com/en-us/vstudio/async.aspx

A: You're correct in thinking that the Waits are unnecessary - Result will block until a result is ready.

However, an even easier way would be to base it off use the examples provided in the ParallelExtensionsExtras library.
They have made extensions for WebClient which do exactly what you're looking for:
static Task<string> FetchAsync()
{
    string url = "http://www.example.com", message = "Hello World!";

    return new WebClient().UploadStringTask(url, "POST", message);
}

You can read more about it in this post on the Parallel Programming with .NET blog.


text:
Q: Can you tell what types of card slots are in a PC without opening up the case and physically eyeballing it? I frequently find that I need to know what sorts of slots are in  PC and I'd rather not have to make that person stop working and shut down the PC and open it up to physically look at it.
Is there any place to look in the O/S [Windows XP] for this (or maybe a free/cheap utility that'll tell you this) ?
or even (gasp!) finding the Motherboard spec and looking that up.

A: Speccy from Piriform will provide you with fairly detailed info about the system. It is free and the detail is quite good. From motherboard model and revision to temperatures on the various sensors. Howerver, it does not appear to enumerate the PCI slots - so you will be stuck looking up the motherboard manufacturer's spec sheet after finding the model info with this util.

A: WMI is for memory banks or Dimms only. I say you probably have to crack the case or try Belarc Advisor.
wmic MEMORYCHIP get banklabel, devicelocator, caption, capacity

shows the following:
BankLabel  Capacity    Caption          DeviceL
BANK0      2147483648  Physical Memory  DIMM0
BANK1      2147483648  Physical Memory  DIMM1
BANK2      2147483648  Physical Memory  DIMM2
BANK3      2147483648  Physical Memory  DIMM3

Belarc shows the following:
Processor a     Main Circuit Board b
2.67 gigahertz Intel Core2 Quad
64 kilobyte primary memory cache
3072 kilobyte secondary memory cache
64-bit ready
Multi-core (4 total)
Not hyper-threaded      Board: ASUSTeK Computer INC. P5QL/EPU Rev X.0x
Serial Number: MS1C97B03902735
Bus Clock: 333 megahertz
BIOS: American Megatrends Inc. 0405 05/22/2009

A: I'm pretty sure that it's not physically possible to tell what "slots" are open in a machine without opening it up (other than memory).  You can tell what kind of cards are installed, but not necessarily "what else" you can install.
Motherboard information is typically available from the BIOS and reported in the System Information utility in Windows as System Model.  This tool will also report enough information about the system that you can tell, say, whether the video card is AGP or PCIe.
You can use a tool like Belarc Advisor on each machine to get basically the same information you can get from Windows, but with more detail... like how many memory slots are available and free, etc.
I haven't had to physically crack a case to make a decision in quite a while.  Usually I need to know things like "what video card do I need to get to replace this one?" or "what kind of power supply do I need to replace this one?" etc.  If you're in a similar boat, then either tool I mentioned will work well enough.
If you're providing support for a single company (i.e. you're the IT guy), then it sounds like some inventory management is in order.  You should be capturing all the necessary details to make these decisions without even having to physically go to a machine.  Free products like Spiceworks can help with this.
Other than all that, one "secret" tool that I rarely find mentioned is BGInfo; part of sysinternals.  I have BGInfo setup in a login script so that any time I login to a machine in my domain with my admin account, it runs a quick scan and sets the desktop wallpaper to an image containing a bunch of information about the system: name, processor, video card, memory, IP & mac address, etc.  It has a bunch of fields like this built in, but you can also configure it to query registry keys, WMI entries, or even run scripts to pull information.
Personally I rely on BGInfo and Spiceworks to find information about the machine I happen to be sitting at.

A: Call me crazy but… why don't you just look at the support docs for that particular model of workstation?

A: System Information in System Tools maybe will have the motherboard information in it. If it's a Dell/HP/etc it should tell you the Model number et al of the computer.

A: If I recall, SIW can do this. It also shows a plethora of other handy information about the PC, such as licensing, processor and HDD temps, ports, graphics capabilities, network info, etc. It's free for personal use, but costs for commercial use.

A: cpu-Z is a Great FREE program that tells you EVERYTHING that you need to know about a computer. Mother board, Bios Graphics, Memory speed and how many SLOTs you have and what memory you have in each dimm slot the S/N of each memory stick, Cpu speed multiplyer VOLTAGE CORE. and if you really want to find out about your video card try GPU-Z. i use this to get information about a computer to find drivers or look up errors WITHOUT needing to look at the MB directly.

A: WMI in Windows Management Instrumentation Command-line (WMIC) utility could help you.
Open the Command Prompt window.
run the command:
wmic MEMORYCHIP get banklabel, devicelocator, caption, capacity

A: HWiNFO will give you this information.
Install, Run then
SMBIOS DMI
System Slots
This will tell you about everything you want to know..

A: Well, if you were using a real OS ;) you could just type:
lspci

at the command line to find out what cards are installed and:
dmidecode

for motherboard information.
lspci man page
dmidecode man page
I know you're thinking, "Why's he telling me this, I run windows?" The answer is Knoppix. Probably one of the most useful tools for Windows troubleshooting, it's a Linux distro that runs directly from CD. Download it and give it a try.


text:
Q: Send Ctrl+Up to a window I'm trying to send messages to a window that says Ctrl and Up-arrow has been pressed. I've got the basics down, I can send presses of the space key that registeres fine. But I can't seem to get the ctrl+ ↑ working.
chosen code snippets:
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = false)]
static extern IntPtr SendMessage(IntPtr hWnd, int Msg, int wParam, int lParam);

Now this works fine for sending Space:
public static void SendKeyPress(IntPtr handle, VKeys key)
{
    SendMessage(handle, (int) WMessages.WM_KEYDOWN, (int) key, 0);
    SendMessage(handle, (int)WMessages.WM_KEYUP, (int)key, 0);
}

But this doesn't work for sending Ctrl+↑ to VLC to increase the sound volume:
public static void SendKeyPress(IntPtr handle, VKeys key, bool control)
{
    int lParamKeyDown = 0;
    lParamKeyDown |= 1;
    lParamKeyDown |= 1 << 24;

    int lParamKeyUp = lParamKeyDown;
    lParamKeyUp |= 1 << 30;
    lParamKeyUp |= 1 << 31; //it was down before

    int lParamCtrlDown = lParamKeyDown;
    int lParamCtrlUp = lParamKeyUp;

    lParamKeyDown |= (int)MapVirtualKey((uint)key, 0) << 16;
    lParamKeyUp |= (int)MapVirtualKey((uint)key, 0) << 16;
    lParamCtrlDown |= (int)MapVirtualKey((uint)VKeys.VK_CONTROL, 0) << 16;
    lParamCtrlUp |= (int)MapVirtualKey((uint)VKeys.VK_CONTROL, 0) << 16;

    IntPtr controlPtr = new IntPtr((int)VKeys.VK_CONTROL);
    IntPtr lParamCtrlDownPtr = new IntPtr(lParamCtrlDown);
    IntPtr lParamCtrlUpPtr = new IntPtr(lParamCtrlUp);
    IntPtr lParamKeyDownPtr = new IntPtr(lParamKeyDown);
    IntPtr lParamKeyUpPtr = new IntPtr(lParamKeyUp);
    IntPtr keyPtr = new IntPtr((int)key);
    object o = new object();
    HandleRef wndRef = new HandleRef(o, handle);
    PostMessage(wndRef, (uint)WMessages.WM_KEYDOWN, controlPtr, lParamCtrlDownPtr);
    PostMessage(wndRef, (uint) WMessages.WM_KEYDOWN, keyPtr, lParamKeyDownPtr);

    PostMessage(wndRef, (uint) WMessages.WM_KEYUP, controlPtr, lParamCtrlUpPtr);
    PostMessage(wndRef, (uint) WMessages.WM_KEYUP, keyPtr, lParamKeyUpPtr);
 }

What am I missing?
Edit3:
The Messages are exactly the same and there are no extra messages since I switched to PostMessage but VLC still won't increase or decrease the volume.
It's not just VLC either, Spotify won't accept the same command even though the messagess look exactly alike in Spy++.

A: I don't have a great way to test it, but would it work if the order of these two lines:
SendMessage(handle, (int) WMessages.WM_KEYDOWN, (int) key, 0);
SendMessage(handle, (int) WMessages.WM_KEYDOWN, (int)VKeys.VK_CONTROL, 0);

was changed to:
SendMessage(handle, (int) WMessages.WM_KEYDOWN, (int)VKeys.VK_CONTROL, 0);
SendMessage(handle, (int) WMessages.WM_KEYDOWN, (int) key, 0);

so that the control key being down essentially wraps the press of the other key?

A: I found a working solution. You use the SetKeyboardState function to depress the control key, and then you can send any key you want. This Delphi code sends Ctrl+Right to a Memo component.
var
  s: TKeyboardState;
  PrevState: byte;
begin
  GetKeyboardState(s);
  PrevState := s[VK_CONTROL];
  s[VK_CONTROL] := 128;
  SetKeyboardState(s);
  SendMessage(Memo1.Handle, WM_KEYDOWN, VK_RIGHT, 0);
  s[VK_CONTROL] := PrevState;
  SetKeyboardState(s)
end;

A: I now found a method to send Ctrl+Right (for example) to a window of another process. If hEdit is the handle of the window, then the following code works.
AttachThreadInput(GetCurrentThreadID, GetWindowThreadProcessId(hEdit, 0), true);
hEdit := SetFocus(hEdit);

keybd_event(VK_CONTROL, 0, 0, 0);
keybd_event(VK_RIGHT, 0, 0, 0);
keybd_event(VK_RIGHT, 0, KEYEVENTF_KEYUP, 0);
keybd_event(VK_CONTROL, 0, KEYEVENTF_KEYUP, 0);

SetFocus(hEdit); // restore focus
AttachThreadInput(GetCurrentThreadID, GetWindowThreadProcessId(hEdit, 0), false); // "Disconnect"

Update
The drawback of this method is that the focus is changed for a small duration of time. In fact, the best solution, I believe, is a combination of my previous and this post:
var
  s: TKeyboardState;
  PrevState: byte;

AttachThreadInput(GetCurrentThreadID, GetWindowThreadProcessId(hEdit, 0), true);

GetKeyboardState(s);
PrevState := s[VK_CONTROL];
s[VK_CONTROL] := 128;
SetKeyboardState(s);
SendMessage(hEdit, WM_KEYDOWN, VK_RIGHT, 0);
s[VK_CONTROL] := PrevState;
SetKeyboardState(s);

AttachThreadInput(GetCurrentThreadID, GetWindowThreadProcessId(hEdit, 0), false);


text:
Q: Firefox and firefox-esr packages in OpenBSD 5.5 After I issued sudo pkg_add -vi firefox, the ftp server responded:
Ambiguous:
0. firefox-esr
1. firefox
Enter choice:

I didn't know what to choose, so I chose and entered 0.
The installation was successful.
In an Xterm, when I typed firefox, the web browser refused to launch.
What happened?

A: The firefox package installs a binary called firefox. The firefox-esr package installs a binary called firefox-esr. The two are different so that you can install both and choose which one to run on a case-by-case basis. Since you installed firefox-esr, you need to run firefox-esr.
As the package description indicates, the ESR package contains the ESR (extended support release) version: a version that doesn't have all the latest features but remains stable for a long time with only bug fixes.


text:
Q: When should I open/close the windows/curtains to keep the room cool in summer? Folk wisdom has it that in order to keep your room cool, it's best to close the window. I assume the reasoning is that while a breeze of air feels cool, in most traditional houses the outside air temperature is actually warmer, heating up the room.
However, I live in a studio directly under the roof with giant east-facing windows. In summer inside temperature can be easily 5 degrees Celsius warmer than outside. Yet friends keep advising me to keep my windows closed.
What is the correct approach?
What I have been doing is opening the windows as soon as outside temperature is cooler than inside temperature (estimated based on weather forecast and room thermostat) and keeping the curtains closed until the window is in the shadow. (related: In summer, should I close curtains during the day?)


text:
Q: ImageContents not working on Wolfram Cloud iOS app I tried using the experimental ImageContents[] function, introduced in MMA 12, on my PC (using Mathematica) as well as on my iPad (using Wolfram Cloud app). On my PC it worked, but not on Wolfram Cloud. It said that it had to download some 200 MB of data from their servers, just like it did on Mathematica. However after the download nothing happened.
This was the image: https://i.stack.imgur.com/6Fd4n.jpg
And this is the result on my PC:
Does anyone know what is the issue?


text:
Q: What's the proper way to migrate from Date to LocalDate in Java 8? I'm currently working on a legacy codebase where Date was used everywhere, and continues to be used because Dates are everywhere (entities contain Dates, services expect Dates, etc.). For some cases where the time portion shouldn't be used, we remove it from the Date object by using basically the following standard snippet in a utility method.
final Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
return cal.getTime();

I'd like to start using LocalDate for these cases. From what I could find, the standard recommended way of converting is (at least in Java 8):
date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();

What I'm a bit uneasy about is the atZone(ZoneId.systemDefault()) part. Could I get different LocalDates depending on which system the code is executed? I guess I could extract the year, month and day from the Date and construct a new LocalDate by explicitly passing the year, month and day, but I would like to use the standard solution if I can be sure the semantics will be maintained (i.e. I won't get any off-by-one-day errors). I first tried:
date.toInstant().atOffset(ZoneOffset.UTC).toLocalDate()

but this did give an instance where the Date and LocalDate where off by 1 day.
Any pointers appreciated!


text:
Q: How to log pretty printed json in PHP? I'm building an API in php. This API processes json messages from a third party API.
I want to log invalid pretty printed json messages.
So I did this:
error_log("test\n" . json_encode($json_string, JSON_PRETTY_PRINT));

However, when I look at my logs, the json string is not pretty printed:
$ tailf error.log
2015-07-13 10:20:03: (mod_fastcgi.c.2701) FastCGI-stderr: test
"{\"info\":{\"status\":200,\"msg\":\"OK\"},\"response\":{\"foo\":\"bar\"}"

I want to see something like:
$ tailf error.log
2015-07-13 10:20:03: (mod_fastcgi.c.2701) FastCGI-stderr: test
{
  "info": {
     "status": 200,
     "msg ": "OK"
  },
  "response": {
     "foo": "bar"
  }
}

How can I achive this result?

A: error_log("test\n" . json_encode($json_string, JSON_PRETTY_PRINT));

json_encode() will actually not necessarily produce JSON: it will produce something that can be read by javascript. If you give it an array or an object, it will produce JSON; if you give it a string, it will produce a javascript string. And that's what you're doing, so that's what you're getting.
To be clear, $json_string is a string: (as far as PHP is concerned, it's a string; if you passed that same string to javascript, it would be interpreted as an object). You pass that through json_encode() and all you're going to get is another string (a string of doubly-encoded JSON).
JSON_PRETTY_PRINT is having no effect here, because you're not producing JSON: you're producing something that javascript too would see as a string.
Savvy?
So what you need to do is to (a) turn $json_string back into a PHP array, and then (b) reencode that as JSON, this time using the JSON_PRETTY_PRINT flag.
$log_array = json_decode($json_string, true);
$json_pretty_string = json_encode($log_array, JSON_PRETTY_PRINT);
error_log('test' . PHP_EOL . $json_pretty_string);

Rather than converting it back to a PHP array and then back to JSON, it would be better to add the JSON_PRETTY_PRINT flag to wherever you're getting $json_string from in the first place, if possible.

Alternatively, just log $json_string directly (no need to encode it: it's already a string, you can pass it to error_log() as it is), and worry about prettifying it only when you need to read your logs. This will make your logs considerably smaller.

A: Common unix error logs are not supposed to contain human-readable json or other unescaped characters. Many syslog/logging implementations are limited by character width and automatically add encoding (like \") or remove new line characters, PHP's error_log is not binary safe either - the behaviour when encountering a unicode character is unpredictable tho (not sure).
You should not be using the native syslog/error log functions, instead,
build your own logger, dedicated to json logging.
Personally I use MongoDB for logging json, because it's the kind of data MongoDB is supposed to work with.

A: You have two options in this case,
if you can use a str_replace like:
error_log("test\n" . str_replace('\"',"\n",json_encode($json_string, JSON_PRETTY_PRINT)));

or like @Karoly Horvath said:
You encode a string already encoded in a JSON. Your $json_string is already encoded. So you need to decode your first JSON and re-encode it with good parameters
error_log("test\n" . json_encode(json_decode($json_string), JSON_PRETTY_PRINT));

and give credit to @Karoly.


text:
Q: adding random noise for sending few Mbyte data using netem I am sending a 30Mbyte file from one machine to another(both raspi 4) using scp. I tried to add noise to the network using netem on the client.
sudo tc qdisc change dev wlan0 root netem delay 50ms 30ms distribution normal

and it takes 07:17 minutes (or rate of 70.6KB/s)
However, when I increase the mean of the added noise normal distribution using
sudo tc qdisc change dev wlan0 root netem delay 500ms 30ms distribution normal

it only takes 00:33 minutes (or rate of 920.1KB/s). Logically it has to take at least the same time as the former distribution, however, it is way faster. I repeated it multiple times, and I got the same result.
I was wondering if I am using the tc in a correct way.