Q: Filter List Debug I'm having trouble debugging this procedure I built. I have over 2 thousand workbooks I'm trying to filter through.
I'm feeding this function a dictionary with its key being the file path & name and the item being a 9 digit part number and the revision number. Based on the folder path and part number, I'm trying to filter out the older revision numbers.
The error message I am recieving is:

Run-time error '10':
This array is fixed or temporarily locked

The debugger is stoping at the line: For Each VKey02 In DUnsorted.Keys. The debug counting variables k1 and k2 end with the values 39 and 1 respectively at the crash.
Any suggestions on how to solve this issue will be appreciated.
Note: I have enabled the "Microsoft Scripting Runtime" reference for this code to work as intended.
Option Explicit

Function HighestRev(ByVal DUnsorted As Scripting.Dictionary) As Scripting.Dictionary
    Dim DSorted As Scripting.Dictionary
    'Keys
    Dim VKey01 As Variant
    Dim VKey02 As Variant
    Dim SKey01 As String
    Dim SKey02 As String
    'Items
    Dim SItem01 As String
    Dim SItem02 As String
    'SKUs
    Dim LSKU01 As Long
    Dim LSKU02 As Long
    'Revs
    Dim IRev01 As Long
    Dim IRev02 As Long
    'File Name
    Dim SName01 As String
    Dim SName02 As String
    'File Path
    Dim SPath01 As String
    Dim SPath02 As String

    'Debug Variables
    Dim k1 As Integer
    Dim k2 As Integer

    'Initializing
    Set DSorted = DUnsorted

    'Looping Through
    k1 = 0
    For Each VKey01 In DUnsorted.Keys

    k1 = k1 + 1: k2 = 1 '<-- Debug
    If VKey01 = "[A Particular File]" Then
        Debug.Print "1 - " & VKey01
        Debug.Print k1 & " - " & k2
    End If

    SKey01 = VKey01
    If Not DSorted.Exists(SKey01) Then GoTo SkipKey01
    SItem01 = DUnsorted(SKey01)
    LSKU01 = Split(SItem01, "-")(0)
    IRev01 = Split(SItem01, "-")(1)
    SName01 = Split(SKey01, "\")(UBound(Split(SKey01, "\")))
    SPath01 = Left(SKey01, Len(SKey01) - Len(SName01))
        For Each VKey02 In DUnsorted.Keys

        k2 = k2 + 1 '<-- Debug
        If VKey02 = "[A Particular File]" Then
            Debug.Print "2 - " & VKey02
            Debug.Print k1 & " - " & k2
        End If

        SKey02 = VKey02
        If Not DSorted.Exists(SKey02) Then GoTo SkipKey02
        SItem02 = DUnsorted(SKey02)
        LSKU02 = Split(SItem02, "-")(0)
        IRev02 = Split(SItem02, "-")(1)
        SName02 = Split(SKey02, "\")(UBound(Split(SKey02, "\")))
        SPath02 = Left(SKey02, Len(SKey02) - Len(SName02))

            'Identifying Match
            If SKey01 <> SKey02 Then
            If LSKU01 = LSKU02 Then
            If UBound(Split(SPath01, SPath02)) > 0 Or UBound(Split(SPath02, SPath01)) > 0 Then

                'Eliminating Older Revision
                If IRev01 > IRev02 Then
                    DSorted.Remove (SKey02)
                ElseIf IRev01 < IRev02 Then
                    DSorted.Remove (SKey01)
                Else    '<-- Last Modified Priority
                    DSorted.Remove (OlderDate(SKey01, SKey02))
                End If
                If Not DSorted.Exists(SKey01) Then GoTo SkipKey01
            End If
            End If
            End If
SkipKey02:
        Next VKey02
SkipKey01:
    Next VKey01
End Function

A: Well the error actually followed one of the workbooks. I'm still puzzled with where in the workbook path and file name it's giving me the issue, but the code itself is now working.


Q: R: Creating a function using dplyr functions I have a data frame with three variables of interest:

*

*survival time

*grouping factor

*event indicator (dead: yes or no)

I want to calculate incidence rate for each group. I do this daily, so it would be great to have a function doing this instead of a long script.
I've tried the following, but doesn't work.
library(survival)
data(lung) # example data
lung$death <- ifelse(lung$status==1, 0, 1) # event indicator: 0 = survived; 1 = dead.

# Function
func <- function(data_frame, group, survival_time, event) {
     library(epitools)
     table <- data_frame %>%
          filter_(!is.na(.$group)) %>%
          group_by_(.$group) %>%
          summarise_(pt = round(sum(as.numeric(.$survival_time)/365.25)),
                     events = sum(.$event)) %>%
          do(pois.exact(.$events, pt = .$pt/1000, conf.level = 0.95)) %>%
          ungroup() %>%
          transmute_(Category = c(levels(as.factor(.$group))),
                     Events = x,
                     Person_years = pt*1000,
                     Incidence_Rate = paste(format(round(rate, 2), nsmall=2), " (",
                                      format(round(lower, 2), nsmall=2), " to ",
                                      format(round(upper, 2), nsmall=2), ")",
                                      sep=""))
     return(table)
}

func(lung, sex, time, death)

**Error: incorrect length (0), expecting: 228 In addition: Warning message:
In is.na(.$group) : is.na() applied to non-(list or vector) of type 'NULL'**

Any ideas? I've read the post about NSE and SE in dplyr, but thought I applied the recommendations correctly?

A: Here is a part of the solution
data_frame = lung
group = "sex"
survival_time = "time"
event = "death"
data_frame %>%
  filter_(paste("!is.na(", group, ")")) %>%
  group_by_(group) %>%
  summarise_(
    pt = paste("round(sum(as.numeric(", survival_time, ") / 365.25))"),
    events = paste("sum(", event, ")")
  )


Q: Easy pattern detection for 3D reconstruction Im currently working on a 3d reconstruction/pose estimation project. To be more specific i have implemented a method which is able to estimate the pose, given horizontal and vertical  line correspondences.
In order to have this method work, i need to create an easily detected pattern (the reference view) in which every single line detected (in others shots-view) can be distinguished from the others in such way i can tell which line is detected with respect to the reference view.
The problem is that i have hard time thinking of a pattern both good looking and functional. What i have come up so far is the pattern above in which given the color of the region, the line is detected, i can tell whether the line is vertical or horizontal and given the color of the line i can discrete the line to tell its coordinates in the reference pattern. Unfortunatly i find myself lost in all these detection methods and i lack the experience of working in such tasks, are there any methods relative to my task ?
Any help or idea is greatly appreciated.
PS: it is worth mentioning that the camera is already calibrated and i need this method to work in case the patter is partially occluded.


Q: Creating a normal class with injections from Spring Well, I have a normal class (LovHelper) that is responsible for doing some utils tasks. When i say normal class is because LovHelper.java don't have @Component, @Service or @Repository annotation.
Inside of this "normal class" i wanna inject a bean from spring, but the bean is always null. Look my Class LovHelper.java bellow:
package br.com.odontonew.helper;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import br.com.odontonew.bean.Lov;
import br.com.odontonew.dao.BasicDAO;

public class LovHelper {

    @Autowired
    private BasicDAO dao;

    private static LovHelper instance;

    private LovHelper(){

    }

    public static LovHelper getInstance(){
        if (instance == null)
            instance = new LovHelper();

        return instance;
    }

    public Lov getLovByCodigo(Class lovClass, String codigo){
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("codigo", codigo);
        List<Lov> lovs = (List<Lov>)dao.findByQuery("SELECT c FROM "+lovClass.getName()+" c WHERE c.codigo = :codigo", map);
        if (lovs.size() == 1)
            return lovs.get(0);
        else
            return null;
    }

    /*Getters and Setters*/
    public BasicDAO getDao() {
        return dao;
    }

    public void setDao(BasicDAO dao) {
        this.dao = dao;
    }

}

So, in another class i just call: LovHelper.getInstance().getLovByCodigo(param1, param2). But i always get a NullPointerException because the bean "dao" within LovHelper is NULL.
After think a little i decided to change my LovHelper.java (using singleton pattern) to a Bean for Spring inject, then I put @Component annotation and remove all singleton pattern the was developed.
And in another class i inject "lovHelper" and use like this: lovHelper.getLovByCodigo(param1, param2). This second solution works fine, but the first not.
Finally, my doubt is: Why the original code (as posted) don't works.

A: Spring will only handle injection dependencies to a class that is constructed by the container. When you call getInstance(), you are allocating the object itself... there is no opportunity there for Spring to inject the dependencies that you have @Autowired.
Your second solution works because Spring is aware of your LovHelper class; it handles constructing it and injecting it into your other class.
If you don't want to mark the class with@Component, you can declare the class as a bean directly in your XML configuration. If you don't want to have it be a singleton, you can set it with prototype scope.
If you really need to manage the class yourself, you could consider looking at @Configurable. I believe it is intended to solve this problem but it requires aspects and I have not played with it myself.

A: Your helper should be context aware, but you can make it static:
@Component
public class LovHelper {

    private static LovHelper instance;

    @PostConstruct
    void init() {
        instance = this;
    }

    // do stuff

In this case static instance will keep reference to Spring aware bean.


Q: Обработка нажатий или жестов в Android Пишу Android приложение на движке Monogame/XNA. Столкнулся с проблемой того, что не могу обрабатывать нажатия и жесты. Я читал про класс TouchLocation, но со свойством Position у меня возникают проблемы (Всегда в нулевой точке). Подскажите пожалуйста, как получить точку касания и статус скрола.


Q: Ways to convert a PDF file into byte array..(for flushing out using outputstream())
*

*Is there any other way to convert a file (PDF) into byte array other than using FileInputStream or toByteArray(InputStream input)..

*Is there any method to convert it directly. I found Files.readAllBytes in java.nio.file.* package but it gives ClassNotFoundException in my RAD. I am having Java 8 JDK in my system.

*Is java.nio.file.* package not available in Java 8?

*My requirement is that i should not to stream the file using InputStram.

A: Seems like you're loading the whole content of your file into a byte[] directly in memory, then writing this in the OutputStream. The problem with this approach is that if you load files of 1 or 2 GBs entirely in memory then you will encounter with OutOfMemoryError quickly. To avoid this, you should read the data from InputStream in small chunks and write these chunks in the output stream. Here's an example for file downloading:
BufferedInputStream bis = new BufferedInputStream(
    new FileInputStream(new File("/path/to/folder", "file.pdf")));
ServletOutputStream outStream = response.getOutputStream();
//to make it easier to change to 8 or 16 KBs
//make some tests to determine the best performance for your case
int FILE_CHUNK_SIZE = 1024 * 4;
byte[] chunk = new byte[FILE_CHUNK_SIZE];
int bytesRead = 0;
while ((bytesRead = bis.read(chunk)) != -1) {
    outStream.write(chunk, 0, bytesRead);
}
bis.close();
outStream.flush();
outStream.close();


Q: Parallel axis theorem non-uniform density The parallel axis theorem says that if the moment of inertia of a body rotating about the body's centre of mass is $I_{cm}$, then the moment of inertia of the body rotating about an axis parallel to the original axis and displaced from it a distance $d$ is $I_{S}=I_{cm}+Md^2$, where $M$ is the body's mass.
I know for a fact that this applies in cases of uniform density. Does this same theorem apply if the body's density is not uniform?


Q: Java Thread creation process flow I was reading section ThreadPools section 6.2.3 java concurrency in practice by Brian Goetz. A statement I came across is
"Reusing an existing thread instead of creating a new one amortizes thread creation and teardown costs."
1) I wanted to get some metrics involved in the java thread creation process which as we know will involve the creation/allocation of a stack and the program counter register to the created thread. Is there a tool/utility/visual vm tracer/jmx bean that I can use for the same which can give me some indicators on memory and time usage for thread creation. Can some one guide me to the same ?
2) Is there a text which can guide me to the whole process of java thread creation in detail which should cover the respective OS calls to windows ?
Why is creating a Thread said to be expensive? has given me some information, but I wanted to study the internals of java thread creation in detail
Thanks

A: Concerning your second question:

2) Is there a text which can guide me to the whole process of java
  thread creation in detail which should cover the respective OS calls
  to windows ?

This guide, though slightly off topic is great: http://blog.jamesdbloom.com/JVMInternals.html
And the following book The Java Virtual Machine Specification, Java SE 7 Edition (google book link) explains the JVM internals in depth and as such would be my best bet (disclaimer: I had only skimmed through the visible parts)
If that is not good enough, you could always download the source code for the open jdk (7) and crawl through the code...
An excerpt from the open jdk code is this (openjdk\hotspot\src\share\vm\runtime\thread.cpp - c'tor):
// Base class for all threads: VMThread, WatcherThread, ConcurrentMarkSweepThread,
// JavaThread

Thread::Thread() {
  // stack and get_thread
  set_stack_base(NULL);
  set_stack_size(0);
  set_self_raw_id(0);
  set_lgrp_id(-1);

  // allocated data structures
  set_osthread(NULL);
  set_resource_area(new ResourceArea());
  set_handle_area(new HandleArea(NULL));
  set_active_handles(NULL);
  set_free_handle_block(NULL);
  set_last_handle_mark(NULL);

  // This initial value ==> never claimed.
  _oops_do_parity = 0;

  // the handle mark links itself to last_handle_mark
  new HandleMark(this);

  // plain initialization
  debug_only(_owned_locks = NULL;)
  debug_only(_allow_allocation_count = 0;)
  NOT_PRODUCT(_allow_safepoint_count = 0;)
  NOT_PRODUCT(_skip_gcalot = false;)
  CHECK_UNHANDLED_OOPS_ONLY(_gc_locked_out_count = 0;)
  _jvmti_env_iteration_count = 0;
  set_allocated_bytes(0);
  _vm_operation_started_count = 0;
  _vm_operation_completed_count = 0;
  _current_pending_monitor = NULL;
  _current_pending_monitor_is_from_java = true;
  _current_waiting_monitor = NULL;
  _num_nested_signal = 0;
  omFreeList = NULL ;
  omFreeCount = 0 ;
  omFreeProvision = 32 ;
  omInUseList = NULL ;
  omInUseCount = 0 ;

  _SR_lock = new Monitor(Mutex::suspend_resume, "SR_lock", true);
  _suspend_flags = 0;

  // thread-specific hashCode stream generator state - Marsaglia shift-xor form
  _hashStateX = os::random() ;
  _hashStateY = 842502087 ;
  _hashStateZ = 0x8767 ;    // (int)(3579807591LL & 0xffff) ;
  _hashStateW = 273326509 ;

  _OnTrap   = 0 ;
  _schedctl = NULL ;
  _Stalled  = 0 ;
  _TypeTag  = 0x2BAD ;

  // Many of the following fields are effectively final - immutable
  // Note that nascent threads can't use the Native Monitor-Mutex
  // construct until the _MutexEvent is initialized ...
  // CONSIDER: instead of using a fixed set of purpose-dedicated ParkEvents
  // we might instead use a stack of ParkEvents that we could provision on-demand.
  // The stack would act as a cache to avoid calls to ParkEvent::Allocate()
  // and ::Release()
  _ParkEvent   = ParkEvent::Allocate (this) ;
  _SleepEvent  = ParkEvent::Allocate (this) ;
  _MutexEvent  = ParkEvent::Allocate (this) ;
  _MuxEvent    = ParkEvent::Allocate (this) ;

#ifdef CHECK_UNHANDLED_OOPS
  if (CheckUnhandledOops) {
    _unhandled_oops = new UnhandledOops(this);
  }
#endif // CHECK_UNHANDLED_OOPS
#ifdef ASSERT
  if (UseBiasedLocking) {
    assert((((uintptr_t) this) & (markOopDesc::biased_lock_alignment - 1)) == 0, "forced alignment of thread object failed");
    assert(this == _real_malloc_address ||
           this == (void*) align_size_up((intptr_t) _real_malloc_address, markOopDesc::biased_lock_alignment),
           "bug in forced alignment of thread objects");
  }
#endif /* ASSERT */
}


Q: How do I add double-quotes to each item in my input string? I'm trying to concatenate a string into an object, with the format of "test@yahoo.com,abc@gmail.com,123@yahoo.com". However, the parameter is expecting every value in the string to be surrounded by quotes, such as ""test@yahoo.com","abc@gmail.com","123@yahoo.com"". The error is "Property validation failed", and it is expecting a System.String. How do I go about resolving this?
The exact lines of code are...
$existingconfig = get-mailboxjunkemailconfiguration $_.address
$existingconfig.trustedsendersanddomains += $_.approved_senders

where $_.approved_senders = "test@yahoo.com,abc@gmail.com,123@yahoo.com"

A: Using Get-MailboxJunkEmailConfiguration -Identity BSmith | Get-Memeber shows that the TrustedSendersAndDomains property is a multiValuedProperty string, i.e. an Array.  You can try changing the value of the $_.approved_senders into an array with -Split
$existingconfig = get-mailboxjunkemailconfiguration $_.address
$existingconfig.trustedsendersanddomains += ($_.approved_senders -Split ",")


Q: Get XML Node while using tsql I would like to know, if anyone can help how to get NODE name o XML variable using TSQL.
<ROOT>
<IDS>
<ID>
<NAME>bla1</NAME>
<AGE>25</AGE>
</ID>
<ID>
<NAME>bla2</NAME>
<AGE>26</AGE>
</ID>
</IDS>
</ROOT>

After my query, I should be able to get the nodes names: NAME, AGE
My SQL server is MSSQL 2005.

A: This would give you the node names for the children of the first ID node:
DECLARE @x xml

SET @x = '<ROOT>
<IDS>
<ID>
<NAME>bla1</NAME>
<AGE>25</AGE>
</ID>
<ID>
<NAME>bla2</NAME>
<AGE>26</AGE>
</ID>
</IDS>
</ROOT>'

SELECT T.c.value('local-name(.)', 'varchar(50)')
FROM @x.nodes('/ROOT/IDS/ID[1]/*') T(c)


Q: OLS Regression Results R-squared value ca r2_squared by scikitlearn I followed a tutorial online and used OLS to build the model (from statsmodel!) The OLS analysis result gave me an amazing R^2 value (0.909). However, when I tried using the r2_score function by scikit-learn to evaluate the R^2 score, I only got 0.68.
Can someone tell what the difference is here?
The dataset came from here: https://www.kaggle.com/harlfoxem/housesalesprediction
Attached is my code!
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error, accuracy_score, r2_score
import matplotlib.pyplot as plt
import seaborn as sns

import statsmodels.api as sm

df = pd.read_csv('kc_house_data.csv')

df = df.drop(['id','date'], axis = 1)

X = df.iloc[:, 1:]
y= df.iloc[:, 0]

X = sm.add_constant(X)

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 1/3, random_state = 0)

reg_OLS = sm.OLS(endog=y_train, exog=X_train).fit()

reg_OLS.summary()

y_pred = reg_OLS.predict(X_test)

print(r2_score(y_test, y_pred))

Output from OLS Regression Results
OLS Regression Results
Dep. Variable:  price   R-squared (uncentered): 0.909
Model:  OLS Adj. R-squared (uncentered):    0.909
Method: Least Squares   F-statistic:    8491.
Date:   Thu, 17 Mar 2022    Prob (F-statistic): 0.00
Time:   23:36:48    Log-Likelihood: -1.9598e+05
No. Observations:   14408   AIC:    3.920e+05
Df Residuals:   14391   BIC:    3.921e+05
Df Model:   17
Covariance Type:    nonrobust
coef    std err t   P>|t|   [0.025  0.975]
bedrooms    -2.898e+04  2217.526    -13.068 0.000   -3.33e+04   -2.46e+04
bathrooms   3.621e+04   3845.397    9.416   0.000   2.87e+04    4.37e+04
sqft_living 100.2140    2.690   37.257  0.000   94.942  105.486
sqft_lot    0.2609  0.057   4.563   0.000   0.149   0.373
floors  1.201e+04   4187.373    2.867   0.004   3798.844    2.02e+04
waterfront  6.237e+05   2.01e+04    31.012  0.000   5.84e+05    6.63e+05
view    5.237e+04   2566.027    20.410  0.000   4.73e+04    5.74e+04
condition   2.844e+04   2774.191    10.250  0.000   2.3e+04 3.39e+04
grade   9.613e+04   2558.509    37.571  0.000   9.11e+04    1.01e+05
sqft_above  63.2770 2.638   23.985  0.000   58.106  68.448
sqft_basement   36.9370 3.127   11.813  0.000   30.808  43.066
yr_built    -2529.7423  80.708  -31.344 0.000   -2687.940   -2371.544
yr_renovated    13.0704 4.307   3.035   0.002   4.629   21.512
zipcode -510.0820   21.216  -24.043 0.000   -551.667    -468.497
lat 6.084e+05   1.27e+04    47.725  0.000   5.83e+05    6.33e+05
long    -2.076e+05  1.55e+04    -13.371 0.000   -2.38e+05   -1.77e+05
sqft_living15   33.6926 3.996   8.432   0.000   25.860  41.525
sqft_lot15  -0.4850 0.092   -5.275  0.000   -0.665  -0.305
Omnibus:    9620.580    Durbin-Watson:  1.997
Prob(Omnibus):  0.000   Jarque-Bera (JB):   363824.963
Skew:   2.694   Prob(JB):   0.00
Kurtosis:   27.021  Cond. No.   1.32e+17

Output from r2_score
0.6855578295481021

A: Your R2=0.909 is from the OLS on the train data, while the R2_score=0.68 is based on the correlation of the test data.
Try predicting the train data and use R2_score on the train and predicted train data.


Q: filter on the_content stopped working when I updated to WP 3.6.1 I created a filter to add a pin button on to my blog posts' images, which after much playing worked. Then, a few weeks later, I updated to 3.6.1, and the filter stopped working.
Did something change in the new release that would prevent filters on the_content from working?
function cd_insert_pinterest($content) {
        global $post;
        $postID = $post->ID;
           if( is_singular() && is_main_query() ) {
                $posturl = urlencode(get_permalink()); //Get the post URL
                $pindiv = '';
                $pinurl = '';
                $pinend = '';
                $pattern = '//i';
                $replacement = $pindiv.$pinurl.'$2.$3'.$pindescription.$pinfinish.''.$pinend;
                $content = preg_replace( $pattern, $replacement, $content );
                $newpattern = '/<\/a><\/span><\/a>/i';
                $replacement = '';
                $content = preg_replace( $newpattern, $replacement, $content );
           }
                                return $content;

}

add_filter( 'the_content', 'cd_insert_pinterest');

A: It appears to be an issue with your RegEx pattern matching images.
I modified $pattern to the following and it worked on a test page I setup.
$pattern = '//i';

There were some extra spaces which were throwing it off.
I suggest using a RegEx tester to help you make sure your pattern is correctly matching your content coming out of wordpress. This is the one I used to check your pattern:
http://gskinner.com/RegExr/
On a separate note, in general it's a bit hard to tell what you're trying to achieve with the two preg_replace functions. I'm sure it could be significantly simplified...


Q: Eigenvalues of matrix with linear dependent rows Why is it that, if a matrix has a linear dependent row, e.g.:
$$
A=\begin {pmatrix} 1 \ 2 \\ 2 \ 4 \end {pmatrix},
$$
at least one eigenvalue is zero?

A: Ok, so I found an answer with the help of Bye_World's comment and want to provide it in case anybody else is also wondering: In order to find eigenvalues of a matrix, we need its characteristic polynomial, which is calculated as follows:
$$
\det (\lambda I-A)=\det \begin {pmatrix} \lambda -a_{11} & -a_{12} \\ -a_{21} & \lambda -a_{22} \end{pmatrix}=\lambda ^2 - (a_{11}+a_{22}) \lambda + a_{11}a_{22}-a_{12}a_{21}=0,
$$
where
$$
\det (A)= a_{11}a_{22}-a_{12}a_{21}.
$$
So we can see that if $det (A)=0$, which is the case if there is a linear dependent row, then $\lambda=0$ is a solution.

A: If λ=0, then A=A-λI, and det(A)=det(A-λI).
There's a linear dependent row (as you said) in A, and that implies that det(A)=0. But det(A)=det(A-λI), so det(A-λI)=0, and λ=0 is an eigenvalue of A.


Q: What US sci-fi TV series has an ill doctor from Desert Storm and a conspiracy? I'm looking for a TV series but I only remember a few details because I just caught the final minutes of the episode.

*

*I saw it on a French channel, but it's American.

*The hero is a doctor who was in Desert Storm.

*I believe he was sick.

*There's some kind of conspiracy that he gets involved with.

*At the the end of the episode a female doctor, Asian looking, gives him a vial with what might be a cure for his illness, probably Gulf War Syndrome.

*I don't know for sure but I believe it was only a pilot.

Can anyone help?

A: I suspect that you're referring to the short-lived Strange World.

Strange World was a short-lived sci-fi series in the tradition of The
X-Files. ABC cancelled it after airing three episodes due to poor
ratings. The remaining ten episodes were picked up and aired by the
SciFi Channel.
Strange World revolves around Captain Paul Turner. While serving in
the Gulf War he was exposed to chemical weapons and developed aplastic
anemia. Also a doctor, Turner works for USAMRIID (United States Army
Medical Research Institute of Infectious Diseases) where he
investigates the unethical uses of science, medicine, and related
technologies. He is approached by a mysterious Asian woman who gives
him a temporary cure for his symptoms. She works for a shadow
organization whose goals run counter to USAMRIID.
In Lullaby, Cass is a young pregnant woman. She fears her doctor is
trying to kill her unborn child. As Turner investigates, he learns
that Cass is a surrogate mother and there may be something to her
story. Many of her doctor's patients mysteriously miscarry at 6
months. There's a medical experiment being performed on Cass and the
others. Callum plays Vince, Cass's boyfriend, who tries very hard to
do what he believes is right.
CKR: Review - Lullaby


Q: MysqL: Perform fulltext search over multiple columns and 100 % match I'd like to do a fulltext search over multiple columns in a MySQL database, only using 1 Input field to search for addresses.
So far my code works but I also get rows returned where not all search words are present.
SELECT *, ((1.3 * (MATCH (city) AGAINST ('+$search*' IN BOOLEAN MODE)))
+ (0.6 * (MATCH (name, zip, str) AGAINST ('+$search*' IN BOOLEAN MODE)))) AS relevance
FROM service
WHERE (MATCH (name, city, zip, str) AGAINST ('+$search*' IN BOOLEAN MODE))
HAVING relevance > 0 ORDER BY relevance DESC LIMIT 10

This could return sth like:
$search = "Anderson City ZIP"

1. Anderson, City, ZIP, street x
2. Anderson, City, ZIP, street y
3. Smith, City, ZIP, street x

So line 3 is wrong because it does not contain Anderson but Smith.
I already tried to add the + operator in the $search string (Anderson City ZIP --> +Anderson +City +ZIP) but then the result often does not show anything.
Is it possible to return only rows with 100 % match?

A: The plus sign is the good thing to do but you have to be sure that one of the strings you are searching for is not in more than 50% of the rows of your table.
Also consider using  quotes to match the full expression: +"Anderson City ZIP"


Q: Dynamic or Conditional display of Jenkins job's parameters (rather than their value population) Let's say I have two(or more) types of projects: app(Application) and svc (Service) and I have created a Jenkins job (common job) which have bunch of parameters. This common job might call another downstream/individual project type jobs (Trigger other project builds etc and pass respective parameters) but it's out of scope of this question.
For ex:
PROJ_TYPE  (a choice parameter type with values: app, svc)
Param2     (of some type)
Param3     (of Cascading type i.e. it depends upon the value of parent parameter PROJ_TYPE).
Param4     (Lets say I want to show this parameter only when PROJ_TYPE is selected as "app")
Param5     (of some type)
Param6     (Lets say I want to show this parameter only when PROJ_TYPE is selected as "svc". This parameter can be of any type i.e. choice, dynamic, extended choice, etc )
If I have the above parameters in a Jenkins job, then Jenkins job will show / prompt all of the parameters when a user will try to build (i.e. Build with Parameters).
Is it possible in Jenkins to show parameter (Param4) only if PROJ_TYPE parameter was selected as app otherwise, I don't want to show this parameter at all -or somehow if it's possible to grey it out? i.e. in this case, the job will show only PROJ_TYPE, Param2, Param3, Param4 and Param5 (and will not show Param6 or it's disabled/greyed out).
Similarly, I want to show parameter (Param6) only if PROJ_TYPE parameter was selected as svc otherwise, I don't want to show this parameter at all -or somehow if it's possible to grey it out? i.e. in this case, the job will show only PROJ_TYPE, Param2, Param3, Param5 and Param6 (and will not show Param4 or it's disabled/greyed out).

A: I know this is an oldie, but I had been searching for something similar until I found Active Choices Plugin. It doesn't hide the parameters, but it's possible to write a Groovy script (either directly in the Active Choices Parameter or in Scriptler) to return different values. For example:
Groovy
if (MY_PARAM.equals("Foo")) {return ['NOT APPLICABLE']}
else if (MY_PARAM.equals("Bar")) {return ['This is the only choice']}
else if (MY_PARAM.equals("Baz")) {return ['Bazoo', 'Bazar', 'Bazinga']}
/Groovy
In this example MY_PARAM is a parameter in the Jenkins job. As long as you put 'MY_PARAM' in the Active Choices 'Referenced Parameters' field the script will re-evaluate the parameter any time it is changed and display the return value (or list of values) which match.
In this way, you can return a different list of choices (including a list of one or even zero choices) depending on the previous selections, but I haven't found a way to prevent the Parameter from appearing on the parameters page. It's possible for multiple Active Choice Parameters to reference the same Parameter, so the instant someone selects "App" or "Svc" all the irrelevant parameters will switch to 'Not Applicable' or whatever suits you. I have played with some HTML text color as well, but don't have code samples at hand to share.
Dirk

A: According to the description you may do this with Dynamic-Jenkins-Parameter plugin:

A Jenkins parameter plugin that allows for two select elements. The second select populates values depending upon the selection made for the first select.

Example provided on the wiki does exactly what you need (at least for one conditional case). I didn't try it by myself.

A: @derik It worked! for me
the second list is populating based on the choice of the first element.
I used Active Choice reactive parameter plugin,
the requirement was the first param will list my servers,
based on the fist selection, the second parm is to connect to selected server and list the backup.
so the list of available backup will the shown here to restore.

*

*enabled parameterized.

*Select Choice Parameter
Name: Server
Choices : Choose..
       qa
       staging
       master
Description : Select the server from the list

*Add new parameter "Active Choice Reactive Parameter"
Name: Backup
Script: Groovy Script
def getbackupsqa = ("sshpass -f  /opt/installer/pass.txt /usr/bin/ssh -p 22 -o StrictHostKeyChecking=no myuser@111.22.33.44 ls /opt/jenkins/backup").execute()

if (Server.equals("Choose..")) {return ['Choose..'] }
else if (Server.equals("qa")) {return getbackupsqa.text.readLines()}
else if (Server.equals("staging")) {return ['Staging server not yet configured']}
else if (Server.equals("master")) {return ['Master server not yet configured']}
Description : Select the backup from the list
Referenced parameters : Server
The result as here


Q: R: Way to map over all entries in a sparse matrix I have a sparse matrix created from R's Matrix package. I would like to iterate over each entry in the matrix and perform an operation, saving the result in another sparse matrix with the same indexes as the original matrix.
For example, let's say I have sparse matrix A:
1 . 1
2 . .
. . 4

ColSums would look like:
3 . 5

RowSums would look like:
2
2
4

I would like to iterate over A and do this
(1,1) > 3*2
(2,1) > 2*3
(1,3) > 2*5
(3,3) > 4*5

Creating B:
6 . 10
6 . .
. . 20

How would I go about doing this in a vectorized way?
I would think the function foo would look like:
B=fooMap(A,fun)

And fun would look like:
fun(row,col) = RowSums(row) * ColSums(col)

What's fooMap?
EDIT:
I went with flodel's solution. It uses summary to convert the sparse matrix into an i,j,x data frame, then uses with & friends to perform an operation on that frame, and then turns the result back into a sparse matrix. With this technique, the with/within operator is fooMap; the sparse matrix just has to be converted into the i,j,x data frame first so that with/within can be used.
Here's a one-liner that solved this particular problem.
B = with(summary(A), sparseMatrix(i=i, j=j, x = rowSums(A)[i] * colSums(A)[j]))

A: Whenever I have element-wise operations on sparse matrices, I go back and forth between the matrix itself and its summary representation:
summ.B <- summary(A)
summ.B <- within(summ.B, x <- rowSums(A)[i]*colSums(A)[j])
B <- sparseMatrix(i = summ.B$i, j = summ.B$j, x = summ.B$x)
B
# 3 x 3 sparse Matrix of class "dgCMatrix"
#
# [1,] 6 . 10
# [2,] 6 .  .
# [3,] . . 20

A: Here's an approach that works with sparse matrices at each step.
## Load library and create example sparse matrix
library(Matrix)
m <- sparseMatrix(i = c(1,2,1,3), j = c(1,1,3,3), x = c(1,2,1,4))

## Multiply each cell by its respective row and column sums.
Diagonal(x = rowSums(m)) %*% (1*(m!=0)) %*% Diagonal(x = colSums(m))
# 3 x 3 sparse Matrix of class "dgCMatrix"
#
# [1,] 6 . 10
# [2,] 6 .  .
# [3,] . . 20

(The 1* in (1*(m!=0)) is being used to coerce the logical matrix of class "lgCMatrix" produced by m!=0 back to a numeric matrix class "dgCMatrix". A longer-winded (but perhaps clearer) alternative would to use as(m!=0, "dgCMatrix") in its place.)


Q: convertir longitud y latitud a direccion geografica Amigos quiero convertir la longitud y latitud que obtengo con este código a dirección geográfica
.controller('CtrlUbi', function($scope) {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(position) {
      $scope.$apply(function() {
        $scope.position = position;
        console.log(position.coords.latitude);
        console.log(position.coords.longitude);
        console.log(position)
      });
    });
  }
});

A: Tecnicamente, position ya es una dirección geográfica.
Ahora bien, si lo que necesitas es crear un objeto compatible con la APIv3 de google maps, se hace de esta manera:
var miDireccion = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);

Si necesitas centrar el mapa respecto a esta posición:
miGoogleMap.setCenter(miDireccion);

Si lo que quieres es mostrarlo en el mapa como un marcador:
var marker = new google.maps.Marker({
        position : miDireccion,
        map      : miGoogleMap,
        title    : "Mi marcador",
});

Si quieres mostrar más de un marcador en el mapa y modificarlos o dar mas información, conserva un array de marcadores como variable global (var markers [];) e inserta cada marcador alli para conservarlo markers.push(marker).

A: este codigo te servirá para devolver una dirección al obtener directamente la latitud y longitud
if (navigator.geolocation) {
     navigator.geolocation.getCurrentPosition(function(position) {
         $scope.createMarker(map);
         $scope.posicion_actual = {
           lat: position.coords.latitude,
           lng: position.coords.longitude
         };

         var geocoding ='https://maps.googleapis.com/maps/api/geocode/json?latlng=' + $scope.posicion_actual.lat + ',' + $scope.posicion_actual.lng + '&sensor=false';
         console.log(geocoding);

         $.getJSON(geocoding).done(function(location) {
            console.log(location.results[0].formatted_address);
            $scope.search_entidad = location.results[0].formatted_address;
            $scope.$digest();
         });
}


Q: Plot $2|z|=|z-2|$ over the complex plain I was given a home work to Sketch $2|z|=|z-2|$ on the complex plane.I tried to simplify and found out that the last expression was $3x^2+3y^2+4x-4$. However I don't know how to sketch this on the complex plane and how I can describe the set of points

A: The equation $2|z| = |z - 2|$ represents the locus of points in the complex plane such that the distance from $(2,0) = 2 + 0i$ is twice the distance from the origin.  So one obvious example of such a point would be $z = 2/3$, since the distance from the origin is $2/3$ and the distance from $2$ is $2 - 2/3 = 4/3$.
Another (slightly less) obvious example would be $z = -2$, since its distance to the origin is $2$, but the distance to $2$ is $4$.
Since you found an equation $3x^2 + 3y^2 + 4x - 4$, where $x$ is the real part of $z$ and $y$ the imaginary part (i.e., $z = x + iy$), what happens when you plug in $(x,y) = (2/3, 0)$?  What happens when you plug in $(x,y) = (-2, 0)$?  Why do both of these choices give you $0$ for this expression?
Now, what does the equation $$3x^2 + 3y^2 + 4x - 4 = 0$$ correspond to in the Cartesian coordinate plane?  What curve does it look like?

A: Hint
$$2|z|=|z-2| \Leftrightarrow \\
4|z|^2 = |z-2|^2 \Leftrightarrow \\
4z \bar{z}= (z-2)(\bar{z}-2) = z \bar{z}-2z -2 \bar{z}+4 \Leftrightarrow \\
3z \bar{z} +2z +2 \bar{z}-4 =0 \Leftrightarrow \\
9z \bar{z} +6z +6 \bar{z}-12 =0\Leftrightarrow \\
(3z+2)(3 \bar{z}+2)=8\Leftrightarrow \\
|3z+2|^2=8
$$

A: Note that $\phi(z) = {z-2 \over 2z}$ is a Möbius transformation and you are looking for $\{ z | |\phi(z)|=1 \} = \phi^{-1}(\partial B(0,1))$.
Since the inverse of a Möbius transformation is a Möbius transformation, and Möbius transformations transform circles into circles, we see that the set in question is a circle.
It is simple to verify that $-2, {2 \over 3}$ and ${2 \over \sqrt{3}}i$ are in this locus and from these three points we can easily plot the set.


Q: Cant Get Bootstrap Table To Resize Im trying to get a bootstrap table to resize so that the maximum content height is 200px and anything greater will scroll.
I have the css for the table set to:
table.jSpeeds tr:hover, table.jSpeeds tr td:hover{
  cursor:pointer;
}

table.table-fixed thead {
  width: 97%;
}
table.table-fixed tbody {
  height: 230px;
  overflow-y: auto;
  width: 100%;
}

& HTML:

Time	Speed

TestRow	TestVal

However the table is still the height and width of the page. I was wondering if anyone could help.
Please see the JSBin example here
Thanks.

A: Use bootstrap's responsive-table. Wrap your
 with this.

    // your table here

Then add the class fix-table-height on the wrapper so you could define the height of the wrapper. In your case you want 200px;. So you can do this :
.fix-table-height{
    max-height:200px;
}

This is the output jsFiddle

A: You'll need to change your table's body and rows display to block. Do something like this:
table.jSpeeds tr:hover, table.jSpeeds tr td:hover{
  cursor:pointer;
}

table.table-fixed thead {
  width: 100%;
}

table.table-fixed tbody {
  height: 230px;
  overflow-y: auto;
}

table.table-fixed tbody,
table.table-fixed tr {
  display: block;
  width: 100%;
}

table.table-fixed th,
table.table-fixed td {
  width: 300px;
}

EDIT
Since I was challenged to give a robust solution, here is comes:
table.jSpeeds tr:hover, table.jSpeeds tr td:hover{
  cursor:pointer;
}

table.table-fixed thead {
  width: 100%;
}

table.table-fixed tbody {
  height: 230px;
  overflow-y: auto;
}

table.table-fixed tbody,
table.table-fixed tr {
  display: block;
  width: 100%;
}

table.table-fixed th,
table.table-fixed td {
  display: block;
  float: left;
  width: 50%;
}

Gist Link

A: just adjust your css to this:
tbody {
    display: block;
    overflow: auto;
    height: 230px;
}

tbody tr {
    display: table;
    width: 100%;
    table-layout: fixed;
}


Q: Find initial system from solution of a RREF matrix. I was looking at the solution's of my exam.
I used a different technique: I first found the RREF of the matrix giving the solution. Then I worked backward to find the initial system.
Can anyone explain what my prof is doing? I have no idea what he's trying to do.

A: The second row represents the equation: $x+3y+4z=??$. Plugging in the given solution, $x=-1,y=2, \text{ and } z=-1$, then the missing value must be
$$
(-1)+3(2)+4(-1)=1.
$$
The final row could be anything you wanted it to be, as long as it is consistent with the given solution. The easiest could have been $0x+0y+z=-1$. But other solutions could have looked like $x+2y+3z=0$ since $-1+2(2)+3(-1)=0$ or $256x-14y-23z=-261$ because $256(-1)-14(2)-23(-1)=-261$.
Does this help understand your prof's comment? He meant there were infinitely many different systems of equations that give rise to the given unique solution.

A: To be honest, I don't know what your professor is doing. The question you posted is either not complete, or straight weird. Geometrically, if the first two row represent a system of linear equations, then they cannot have "a unique solution." It would be two planes intersecting.


Q: How might I add a watermark effect to an image in Android? I have an image with frames and I need to add a watermark effect. How might I do this?

A: I found great tutorial on Android Image Processing here.
public static Bitmap mark(Bitmap src, String watermark, Point location, Color color, int alpha, int size, boolean underline) {
    int w = src.getWidth();
    int h = src.getHeight();
    Bitmap result = Bitmap.createBitmap(w, h, src.getConfig());

    Canvas canvas = new Canvas(result);
    canvas.drawBitmap(src, 0, 0, null);

    Paint paint = new Paint();
    paint.setColor(color);
    paint.setAlpha(alpha);
    paint.setTextSize(size);
    paint.setAntiAlias(true);
    paint.setUnderlineText(underline);
    canvas.drawText(watermark, location.x, location.y, paint);

    return result;
}

Thanks to Pete Houston who shares such useful tutorial on basic image processing.

A: It seems you are looking for a waterrippleeffect as this one. Checkout the complete source code. Also check the screenshot how does the effect look like.

A: For others reference, if you want to add the logo of your application (which is in your drawable folder(s)) on top of image use following method:
private Bitmap addWaterMark(Bitmap src) {
        int w = src.getWidth();
        int h = src.getHeight();
        Bitmap result = Bitmap.createBitmap(w, h, src.getConfig());
        Canvas canvas = new Canvas(result);
        canvas.drawBitmap(src, 0, 0, null);

        Bitmap waterMark = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.logo);
        canvas.drawBitmap(waterMark, 0, 0, null);

        return result;
    }

A: If someone is still searching for this, I found a good solution here
It adds a watermark to the bottom right portion and scales it according to the source image which was exactly what I was looking for.
/**
 * Embeds an image watermark over a source image to produce
 * a watermarked one.
 * @param source The source image where watermark should be placed
 * @param watermark Watermark image to place
 * @param ratio A float value < 1 to give the ratio of watermark's height to image's height,
 *             try changing this from 0.20 to 0.60 to obtain right results
 */
public static Bitmap addWatermark(Bitmap source, Bitmap watermark, float ratio) {
    Canvas canvas;
    Paint paint;
    Bitmap bmp;
    Matrix matrix;
    RectF r;

    int width, height;
    float scale;

    width = source.getWidth();
    height = source.getHeight();

    // Create the new bitmap
    bmp = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
    paint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.DITHER_FLAG | Paint.FILTER_BITMAP_FLAG);

    // Copy the original bitmap into the new one
    canvas = new Canvas(bmp);
    canvas.drawBitmap(source, 0, 0, paint);

    // Scale the watermark to be approximately to the ratio given of the source image height
    scale = (float) (((float) height * ratio) / (float) watermark.getHeight());

    // Create the matrix
    matrix = new Matrix();
    matrix.postScale(scale, scale);

    // Determine the post-scaled size of the watermark
    r = new RectF(0, 0, watermark.getWidth(), watermark.getHeight());
    matrix.mapRect(r);

    // Move the watermark to the bottom right corner
    matrix.postTranslate(width - r.width(), height - r.height());

    // Draw the watermark
    canvas.drawBitmap(watermark, matrix, paint);

    return bmp;
}

And it is well commented which is what is a huge plus!

A: In Kotlin:
Note: Its just modified code of above answers
private fun mark(src: Bitmap, watermark: String): Bitmap {
        val w = src.width
        val h = src.height
        val result = Bitmap.createBitmap(w, h, src.config)
        val canvas = Canvas(result)
        canvas.drawBitmap(src, 0f, 0f, null)
        val paint = Paint()
        paint.color = Color.RED
        paint.textSize = 10f
        paint.isAntiAlias = true
        paint.isUnderlineText = true
        canvas.drawText(watermark, 20f, 25f, paint)
        return result
    }

val imageBitmap = mark(yourBitmap, "Your Text")
binding.meetProofImageView.setImageBitmap(imageBitmap)

A: You can use androidWM to add a watermark into your image, even with invisible watermarks:
add dependence:
dependencies {
  ...
  implementation 'com.huangyz0918:androidwm:0.2.3'
  ...
}

and java code:
 WatermarkText watermarkText = new WatermarkText(“Hello World”)
                    .setPositionX(0.5)
                    .setPositionY(0.5)
                    .setTextAlpha(100)
                    .setTextColor(Color.WHITE)
                    .setTextFont(R.font.champagne)
                    .setTextShadow(0.1f, 5, 5, Color.BLUE);

 WatermarkBuilder.create(this, backgroundBitmap)
                    .loadWatermarkText(watermarkText)
                    .getWatermark()
                    .setToImageView(backgroundView);

You can easily add an image type watermark or a text watermark like this, and the library size is smaller than 30Kb.

A: I tried a few libraries mentioned in other posts, like this, but unfortunately it is missing, and not downloadable now. So I followed AndroidLearner 's answer above, but after tweaking the code a little bit, for those of you who are having trouble rotating the watermark, and what values are valid for the various methods of Paint class, so that the text shows rotated at an angle(like most of the company watermarks do), you can use the below code.
Note that, w and h are the screen width and height respectively, which you can calculate easily, there are tons of ways you can find on stackoverflow only.
public static Bitmap waterMarkBitmap(Bitmap src, String watermark) {
    int w = src.getWidth();
    int h = src.getHeight();
    Bitmap mutableBitmap = Utils.getMutableBitmap(src);
    Bitmap result = Bitmap.createBitmap(w, h, mutableBitmap.getConfig());

    Canvas canvas = new Canvas(result);
    canvas.drawBitmap(src, 0f, 0f, null);

    Paint paint = new Paint();
    paint.setColor(Color.RED);
    paint.setTextSize(92f);
    paint.setAntiAlias(true);
    paint.setAlpha(70);  // accepts value between 0 to 255, 0 means 100% transparent, 255 means 100% opaque.
    paint.setUnderlineText(false);
    canvas.rotate(45, w / 10f, h / 4f);
    canvas.drawText(watermark, w / 10f, h / 4f, paint);
    canvas.rotate(-45, w / 10f, h / 4f);

    return result;
}

It rotates the text watermark by 45 degrees, and places it at the centre of the bitmap.
Also note that, in case you are not able to get watermark, it might be the case that the bitmap you are using as source is immutable. For this worst case scenario, you can use below method to create a mutable bitmap from an immutable one.
public static Bitmap getMutableBitmap(Bitmap immutableBitmap) {
    if (immutableBitmap.isMutable()) {
        return immutableBitmap;
    }

    Bitmap workingBitmap = Bitmap.createBitmap(immutableBitmap);
    return workingBitmap.copy(Bitmap.Config.ARGB_8888, true);
}

I found above method inside here. I have tested using both the methods in my application, and it works perfectly after I added above tweaks. Try it and let me know if it works or not.

A: use framelayout. put two imageviews inside the framelayout and specify the position of the watermark imageview.


Q: Request jenkins rest api using the authtoken got from by organization's SSO I have a webportal where user login using our organization's SSO, After logging in i get the authtoken for the logged in session.
And currently i have the Jenkins authentication setup using organization LDAP.
From our webportal we will be issuing some jenkins REST APIs. I can see jenkins support API token for the REST APIs.
1. All our jenkins users don't have the token generated
2. Even they do generate, we will have to map each users id with token , which would be very bad.
Is there any way to execute rest api with the auth token got from SSO login ?


Q: Character entry causing infinite loop in C Ok, so I've searched several places for an answer to this, and I found the answer to the same problem in C++, but it involved clearing cin and that stuff, and I'm not sure how to translate that to C. I apologize in advance if this was, in fact, answered somewhere else, and I just missed it. Also, keep in mind that I'm basically teaching myself C, and I don't know much beyond what you see in this code.
Basically, my problem is this: I am running a loop that asks for input and then uses a switch statement to choose what happens. The switch takes an int, and it works fine with any numerical entry. When you enter a char, however, it just loops infinitely, giving no chance to input anything else.
Assuming this is the same problem as it was in the C++ examples I looked up - and I'm not 100% sure it is - when I enter a char it gets added to the buffer, and never gets cleared, so each time it loops the invalid input gets used again. Clearing the buffer seemed simple enough in C++, but I was unable to find anything I could understand in C.
Here's my code, for reference:
int main()
{

  while(1)
  {
    printf("(1-10) -> Run a program | (-1) -> Display menu | (0) -> Quit : ");

    int quit = 0;
    int select;
    scanf("%d", &select);
    switch(select)
    {
      case 1:
        printf("%s", pgmRun);
        helloWorld();
        printf("%s", pgmEnd);
        break;

      //More cases here

      case 0:
        quit = 1;
        break;
      default:
        printf("\n");
        printf("Error: Invalid input\n");
        printf("\n");
    }

    if(quit == 1)
      break;
  }
return 0;
}

Thanks in advance for your help, and sorry for such a lengthy post. I tend to be long-winded. :P

A: fflush(stdin) has undefined behavior. If you want to discard characters entered after the scanf() call, you can read and discard them.
You can use getchar() to clear the character.


Q: Wine applications have no sound after moving drive_c folder I moved the drive_c of Wine to another partition. Now everything is good except sound. Wine applications no longer have sound. What's the problem?
Edit:
The main problem (I think) is that I have deleted all config text files in /home/[user-name]/.wine Then wine created new ones.

A: Run winecfg and go to the audio tab then click OK (you don't have to do anything, wine configure audio automatically when you open that tab)


Q: Wpf: Prism + MVVM: Changing Modules/Views I'm developing a WPF application using MVVM + Prism.
The Shell is devided into two regions: Menu + MainScreenArea.
The Menu includes navigation: Search Entity, Add Entity, Edit Entity. And Basically the mainScreenArea should load the appropriate module/View. If Search Entity is chosen in the Menu Region, The mainScreenArea should display the SearchEntity Module/View.
I still haven't coded it, but I think I will create A module for each purpose: SearchEntityModule, AddEntityModule and etc.
Then the MainWorkArea will change modules on demand by the corresponding click on Menu Region.
Now, how do I change between the modules in the MainScreenArea Region? Should I load the nameOfModule to eventAggregator from MenuRegion and and MainScreenArea will get the name of screen from the aggregator?
Anyways, I'm new to this, so if I'm going in the wrong direction, please post me your suggestion. Thanks!

A: The prism documentation has a whole section on navigation. The problem with this question is that there are a number of different ways to go when loading modules on demand. I have posted a link that I hope leads you in the right direction. If it does, please mark this as answered. thank you
http://msdn.microsoft.com/en-us/library/gg430861(v=pandp.40).aspx

A: As has been said, there are a number of ways of accomplishing this. For my case, I have a similar shell that has a nav region and a main region, and my functionality is broken into a number of modules. My modules all add their own navigation view to that nav region (in the initialise of the module add their own nav-view to the nav-region). In this way my shell has no knowledge of the individual modules and the commands they may expose.
When a command is clicked the nav view model it belongs to does something like this:
/// <summary>
/// switch to the view given as string parameter
/// </summary>
/// <param name="screenUri"></param>
private void NavigateToView(string screenUri)
{
    // if there is no MainRegion then something is very wrong
    if (this.regionManager.Regions.ContainsRegionWithName(RegionName.MainRegion))
    {
        // see if this view is already loaded into the region
        var view = this.regionManager.Regions[RegionName.MainRegion].GetView(screenUri);
        if (view == null)
        {
            // if not then load it now
            switch (screenUri)
            {
                case "DriverStatsView":
                    this.regionManager.Regions[RegionName.MainRegion].Add(this.container.Resolve<IDriverStatsViewModel>().View, screenUri);
                    break;
                case "TeamStatsView":
                    this.regionManager.Regions[RegionName.MainRegion].Add(this.container.Resolve<ITeamStatsViewModel>().View, screenUri);
                    break;
                case "EngineStatsView":
                    this.regionManager.Regions[RegionName.MainRegion].Add(this.container.Resolve<IEngineStatsViewModel>().View, screenUri);
                    break;
                default:
                    throw new Exception(string.Format("Unknown screenUri: {0}", screenUri));
            }
            // and retrieve it into our view variable
            view = this.regionManager.Regions[RegionName.MainRegion].GetView(screenUri);
        }
        // make the view the active view
        this.regionManager.Regions[RegionName.MainRegion].Activate(view);
    }
}

So basically that module has 3 possible views it could place into the MainView, and the key steps are to add it to the region and to make it active.


Q: MySQL LEFT JOIN Query with WHERE clause Hope someone can help as I am having a hard time understanding how to query properly
I have a Member table and a Member_Card table. Member_Card has a column Member, so the card is associated to a member. Both tables have a LastModifiedDate column. A member can have none, one or several cards.
I need to return all members whose LastModifiedDate >= sinceDate (given date) OR whose card (if any) LastModifiedDate >= sinceDate.
Imagine sinceDate is 2013-01-01 00:00:00. I want to output something like this:
[{
    "Id": "001O000000FsAs7IAF",
    "LastModifiedDate": 2013-01-01 00:00:00,
    "Member_Card": null
}, {
    "Id": "001O000000FrpIXIAZ",
    "LastModifiedDate": 2012-12-12 00:00:00,

    "Member_Card": [{
        "Id": "a00O0000002w8FGIAY",
        "Member": "001O000000FhDSoIAN",
        "LastModifiedDate": 2013-01-01 00:00:00

    }, {
        "Id": "a00O0000002uYMtIAM",
        "Member": "001O000000FhDSoIAN",
        "LastModifiedDate": 2012-12-12 00:00:00
    }]
}, {
    "Id": "001O000000FsAg7IAF",
    "LastModifiedDate": 2013-01-01 00:00:00,
    "Member_Card": [{
        "Id": "a00O0000002w8FFIAY",
        "Member": "001O000000FhDSoIAN",
        "LastModifiedDate": 2012-12-12 00:00:00
    }]
}]

The 1st is a member with a matching LastModifiedDate without cards. The 2nd is a member with a non-matching LastModifiedDate, but he has 2 cards associated, and 1 of them has a matching LastModifiedDate. The 3rd one is a member with a matching LastModifiedDate with a card.
Thanks to SO I got the following query:
SELECT member.*,card.* from member inner join (
SELECT distinct member.id as  mid FROM Member
INNER JOIN Member_Card
    ON Member_Card.Member = Member.id
and ( Member.LastModifiedDate >= sinceDate
    OR Member_Card.LastModifiedDate >= sinceDate ) ) a on a.mid=member.id
inner join member_card card on card.member=a.mid

Which works fine but is missing the case where the member doesn't have any card associated.
I tried to change some INNER JOINs to LEFT JOINs but then it's ignoring the date comparison :-(
Can you help me with this one?

A: You want to move the date check to the where of the inner query.
Try something like:
SELECT member.*,card.*
FROM member
LEFT JOIN member_card card on card.member=member.id
WHERE member.id IN (
    SELECT DISTINCT m.id FROM Member m
        LEFT JOIN Member_Card mc ON (mc.Member = m.id)
        WHERE ( m.LastModifiedDate >= sinceDate
        OR mc.LastModifiedDate >= sinceDate )
)

A: Try this... (yet to be tested)
SELECT * FROM member m1
JOIN card c1 ON c1.member = m1.id
WHERE m1.id IN (
SELECT DISTINCT m.id from member m
JOIN card c ON c.member = m.id
WHERE (c.LastModifiedDate >=sinceDate  OR m.LastModifiedDate >= sinceDate))

A: You can try like this,
SELECT o.status, o.date, c.name
FROM cliente c
LEFT JOIN orders o
ON c.id=o.id
WHERE o.date = '2/1/2015'


Q: Nvidia Optimus with Nouveau drivers

I'm trying to get the optirun command to work with the FOSS Nouveau drivers on my computer that has an embeddded graphics unit and a discrete graphics processing unit. Here's my setup provided by the lspci | egrep -i 'vga|3d'command:
00:02.0 VGA compatible controller: Intel Corporation Skylake GT2 [HD Graphics 520] (rev 07)
01:00.0 3D controller: NVIDIA Corporation GK208BM [GeForce 920M] (rev a1)

According to the Nouveau CodeNames website page, my GPU is supported by the NV108 (GK208) Nouveau driver. So there's no reason why I can't make it work with the optirun command, right? However, after having followed the classic installation procedure

*

*uninstall proprietary drivers

*install bumblebee & mesa-utils packages

*install VirtualGL
I can't get the optirun command to work. As an example, optirun glxgears gives the error
[ERROR]Cannot access secondary GPU - error: [XORG] (EE)
[ERROR]Aborting because fallback start is disabled

The problem seems to be with the Nouveau module in the kernel:
$ optirun -vv glxgears
----------------------
[DEBUG]Reading file: /etc/bumblebee/bumblebee.conf
[DEBUG]optirun version 3.2.1 starting...
[DEBUG]Active configuration:
[DEBUG] bumblebeed config file: /etc/bumblebee/bumblebee.conf
[DEBUG] X display: :8
[DEBUG] LD_LIBRARY_PATH:
[DEBUG] Socket path: /var/run/bumblebee.socket
[DEBUG] Accel/display bridge: auto
[DEBUG] VGL Compression: proxy
[DEBUG] VGLrun extra options:
[DEBUG] Primus LD Path: /usr/lib/x86_64-linux-gnu/primus:/usr/lib/i386-linux-gnu/primus:/usr/lib/primus:/usr/lib32/primus
[DEBUG]Using auto-detected bridge virtualgl
[INFO]Response: No - error: [XORG] (EE)
[ERROR]Cannot access secondary GPU - error: [XORG] (EE)
[DEBUG]Socket closed.
[ERROR]Aborting because fallback start is disabled.
[DEBUG]Killing all remaining processes.

What I tried
I tried to force Optimus to use the Nouveau drivers in the /etc/bumblebee/bumblebee.conf by setting Driver=nouveau. It makes no difference.

What I fixed
Initially I had another error while executing the command:
[ERROR]Cannot access secondary GPU - error: [XORG] (EE)
[ERROR]Failed to load module "mouse" (module does not exist, 0)

I fixed it by installing the missing package xserver-xorg-input-mouse.

A: I finally found a solution to my problem by continuing my research.
Solution: do not use Optimus to switch between GPU
The Primus and Optimus programs are made to be used with Nvidia proprietary drivers. It is therefore not recommended to use them with Nouveau drivers. The Linux kernel has tools that allow you to switch GPUs without installing additional programs. The tool in question is VGA Switcheroo. Note that this tool only works with open source drivers.
The tool may not be active by default on your system, some manipulations are then necessary. To check if the tool is enabled, look for the switch file with
# cat /sys/kernel/debug/vgaswitcheroo/switch

In my case, the tool was not activated, I just had to uninstall Bumblebee to fix the problem. If the problem persists after uninstalling Bumblebee, follow the instructions in this article.
Now that vga_switcheroo is enabled, you can switch off the active GPU with
# echo OFF > /sys/kernel/debug/vgaswitcheroo/switch

and activate the dedicated card with
# echo DIS > /sys/kernel/debug/vgaswitcheroo/switch

or activate the integrated card with
# echo IGD > /sys/kernel/debug/vgaswitcheroo/switch

References

*

*HybridGraphics - Communauty Help Wiki by Ubuntu

*VGA Switcheroo - Linux Kernel Documentation

*VGA_Switcheroo by Chibi-nah


Q: FileNotFoundException : /storage/emulated/0/xyz/a bc/abc_06-07-2017 06-12-121481589883.amr I am trying to upload file from my device storage to cloud but whenever I try to upload I am getting following excaption.
java.io.FileNotFoundException: /storage/emulated/0/xyz/a bc/abc_06-07-2017 06-12-121481589883.amr: open failed: ENOENT (No such file or directory)

Here is my code.
        DropboxInstance objDropboxInstance = new DropboxInstance();
        String filePath = intent.getExtras().getString("filePath");
        // filePath is  = /storage/emulated/0/xyz/a bc/abc_06-07-2017 06-12-121481589883.amr
        StringBuilder sb = new StringBuilder();
        InputStream is;
        String name = "abc_06-07-2017 06-12-121481589883";
        try {
            File file = new File(filePath);

            is = new FileInputStream(file);
            long size = f.length();
            objDropboxInstance.getDropBoxStorage(this).upload("/" + name, is, size, true);

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

I don't know what's happening. I think path is correct. But I am not getting why I am getting this error. Please suggest me.


Q: DockerHub set tag alias in automated build I'm using Docker Hub's automated build system to build a docker image. That image comes in two flavors (Debian jessie and wheezy based). I like to have speaking tags for both of those (:jessie and :wheezy) but would also like to have a :latest tag pointing to the :jessie flavor.
For now I simply duplicated the jessie line in the automated build config:

But this seems to actually build the image twice. What I would need is a way to specify a tag alias, but I am not sure if that's possible. And if so how to do it.

A: It's currently not possible to have more than one docker tag name by build. Duplicating the build is the only solution.

A: You can use the tags regexp
Look at the last tag that gets created.


Q: Date string not recognized in Safari My JavaScript code is working on on Chrome, IE, and Firefox, but when it gets to safari it doesn't work. I believe I have narrowed down the problem: When creating a 'new Date' in JavaScript, all other browsers recognize my string except safari.
HTML:
<form>
<input id="timeIn" value="1:00 AM"/>
<input id="dateIn" value="1/20/2012"/>
<input id="timeOut" value="2:00 AM"/>
<input id="dateOut" value="1/21/2012"/>
</form>

JavaScript:
function calcHours() {
    // Build datetime objects and subtract
    var timeIn = new Date($('#timeIn').val() + $('#dateIn').val());
    if(!isValidDate(timeIn)) return -1;
    var timeOut = new Date($('#timeOut').val() + $('#dateOut').val());
    if(!isValidDate(timeOut)) return -1;
    var hours = (timeOut - timeIn)/(1000*60*60);
    return hours.toFixed(1);
}

function isValidDate(d) {
    console.log(d);
    if ( Object.prototype.toString.call(d) === "[object Date]" ) {
      // it is a date
      if ( isNaN( d.getTime() ) ) {  // d.valueOf() could also work
        // date is not valid
          console.log("isn't valid");
          return 0;
      }
      else {
        // date is valid
          console.log("is valid");
          return 1;
      }
    }
    else {
      // not a date
        console.log("isn't valid");
        return 0;
    }
}
var hours = calcHours();
console.log("Hours:", hours);

I have made a js fiddle: http://jsfiddle.net/mq72k/7/. If you open it up in chrome, it will work fine. If you open it up in Safari, it will say invalid date for the same inputs and not work at all. I have also tried varying the string a bit, adding spaces, different order ect.
Does any one have any ideas how to fix this cross browser compatibility issue?

A: Try using an external plugin to parse your dates, something like Datejs

A: Frankly, I'm surprised other browsers parse the string correctly, as the string you give to the date object is 1:00 AM1/20/2012. Put the date first and add a space in between.
var timeIn = new Date($('#dateIn').val() + ' ' + $('#timeIn').val());
var timeOut = new Date($('#dateOut').val() + ' ' + $('#timeOut').val());

http://jsfiddle.net/mq72k/8/

A: Javascript does not parse string dates very well at all, including ISO8601 formats. You must parse the string yourself. You especially should not expect a minor format like month/day/year to be parsed since it is used by a small minority of the global population.
Incidentally, this has nothing to do with jQuery.
Edit
To reliably parse m/d/y format:
function toDate(ds) {
  var a = ds.split('/');
  return new Date(+a[2], (a[0] - 1), +a[1]);
}

The above assumes a correct date string is supplied. To check that it's a valid date at the same time:
function toDate(ds) {
  var a = ds.split('/');
  var d = new Date(+a[2], (a[0] - 1), +a[1]);

  if (d.getDate() == a[1] && d.getFullYear() == a[2]) {
    return d;

  } else {
    return NaN; // or some other suitable value like null or undefined
  }
}


Q: jquery addClass and removeClass slow in IE 11 I'm creating an app to monitor nodes on a cluster and this is an example of the visual state. Each small box in the grid represents a node and currently, when hovering over one node, the rest in that respective rack (grid) fadeout.
Here is the link via photobucket since I can't insert images due to my minimal reputation:
visual state
In Chrome and Firefox, hovering in and out a single node will instantly fadein/out the rest of the nodes in the rack, but in IE 11 it has a noticeable lag. I know that IE's javascript engine is slower than Chrome and Firefox, but I'm throwing this out there to see if the SO community can pick apart my code and suggest better ways of doing this as I am not the greatest front end programmer. Thank you and here is snippets of my code:
from the django template (each node has id="matrix-box-<node #>"):

    visual state

        {% for row in v.22 %}
            {% if v.23 == "ca" %}
                {% if forloop.counter0|divisibleby:4 %}

                {% endif %}
            {% elif v.23 ==  "cs" %}
                {% if forloop.counter0|divisibleby:8 %}

                {% endif %}
            {% endif %}

            {% for elem in row %}
                {% if elem.1 == "#49E20E" %}

                {% elif elem.1 == "#0000CD" %}

                {% elif elem.1 == "yellow" %}

                {% elif elem.1 == "#E3170D" %}

                {% elif elem.1 == "brown" %}

                {% elif elem.1 == "orange" %}

                {% elif elem.1 == "black" %}

                {% elif elem.1 == "#cccccf" %}

                {% endif %}
            {% endfor %}

       ... other code

from css code:
    .node {
        width: 4px;
        height: 4px;
        float: left;
        border: 1px solid #B0B0B0;
        background: #cccccf;
        margin: 0 !important;
        cursor: pointer;
        filter: alpha(opacity=100);
        opacity: 1;
        }

    .faded .node-faded {
        width: 4px;
        height: 4px;
        filter: alpha(opacity=50);
        opacity: .5;
     }

    .active {
        width: 4px;
        height: 4px;
        float: left;
        border: 1px solid black;
        background: #cccccf;
        margin: 0 !important;
       cursor: pointer;
       filter: alpha(opacity=100);
       opacity: 1;
     }

from js code:
    var node = null;
    var node_id = null;
    var rack = null;
    var nodes = null;

    $(document).ready(function(){
        $('[id^=matrix-box]').on({
            mouseenter: function(){
                node = $(this);
                rack = node.parent().parent();
                rack.addClass('faded');
                node.removeClass('node-faded').addClass('active');
            },
            mouseleave: function(){
                node.removeClass('active').addClass('node-faded');
                rack.removeClass('faded');
            },
            click: function(e){

            ...other code

Also, any constructive criticism (albeit helpful and not malicious) is always welcome. Thanks again!

A: As you gave no possibility to test, this is kind of a guessing game. What you do is the following:
$('[id^=matrix-box]').on({ mouseenter: function(){});

This adds a new event listener on each element with an id starting with matrix-box. Not the worst idea, but it can be slow if you have a lof of these items.
Here is demo to validate this: http://jsfiddle.net/k3mjmdzp/3/
A good idea to overcome performance issues is to use a delegated event listener.
Try to rewrite your code like this:
$(function () {
    $('#matrix').on('mouseenter mouseleave click', '[id^=matrix-box]', function (event) {
        console.log(event);
    });
});

Here you have the demo: http://jsfiddle.net/k3mjmdzp/2/
This will leave your code with having only event listeners on $('#matrix') and not on each child node. This is also nice if you append new items via ajax later on.
You can check for event listeners on the event Listeners tab in chrome developer tools.


Q: What is a type inference? Does it only exist in statically typed languages? And is it only there when the language is not strongly typed (i.e., does Java have one)? Also, where does it belong - in the compilation phase assuming it's a compiled language?
In general, are the rules when the type is ambiguous dictated by the language specification or left up to the implementation?

A: Type inference is a feature of some statically-typed languages.  It is done by the compiler to assign types to entities that otherwise lack any type annotations.  The compiler effectively just 'fills in' the static type information on behalf of the programmer.
Type inference tends to work more poorly in languages with many implicit coercions and ambiguities, so most type inferenced languages are functional languages with little in the way of coercions, overloading, etc.
Type inference is part of the language specification, for the example the F# spec goes into great detail about the type inference algorithm and rules, as this effectively determines 'what is a legal program'.
Though some (most?) languages support some limited forms of type inference (e.g. 'var' in C#), for the most part people use 'type inference' to refer to languages where the vast majority of types are inferred rather than explicit (e.g. in F#, function and method signatures, in addition to local variables, are typically inferred; contrast to C# where 'var' allows inference of local variables but method declarations require full type information).

A: A type inferencer determines what type a variable is from the context. It relies on strong typing to do so. For example, functional languages are very strongly, statically typed but completely rely on type inference.
C# and VB.Net are other examples of statically typed languages with type inference (they provide it to make generics usable, and it is required for queries in LINQ, specifically to support projections).
Dynamic languages do not infer type, it is discovered at runtime.

A: Type inferencing is a bit of a compromise found in some static languages.  You can declare variables without specifying the type, provided that the type can be inferred at compile time.  It doesn't offer the flexibility of latent typing, but you do get type safety and you don't have to write as much.
See the Wikipedia article.

A: A type inferencer is anything which deduces types statically, using a type inference algorithm. As such, it is not just a feature of static languages.
You may build a static analysis tool for dynamic languages, or those with unsafe or implicit type conversions, and type inference will be a major part of its job. However, type inference for languages with unsafe or dynamic type systems, or which include implicit conversions, can not be used to prove the type safety of a program in the general case.
As such type inference is used:

*

*to avoid type annotations in static languages,

*in optimizing compilers for dynamic languages (ie for Scheme, Self and Python),

*In bug checking tools, compilers and security analysis for dynamic languages.


Q: Exibir texto HTML em Popover do Twitter-Bootstrap Criei um Popover provido pelo Twitter-Bootstrap neste Popover é exibido uma mensagem formatada com tags HTML, porém quando abro a página o texto que deveria ser formato em HTML esta formatado como texto plano, como fazer para que seja exibido formatado em HTML?
Código do popover
$("#pass_ca").popover({
    title:'A senha deve conter entre 8 e 16 caracteres, incluindo:',
    content:'

Letras Maiusculas

Letras Minusculas

Numeros

',
    trigger:'hover',
    placement:'right'
});

Tag que possui o popover
<input type="password" name="password" class="form-control" placeholder="Senha" id="pass_ca">

A: Acrescente html: true à definição do popover:
$("#pass_ca").popover({
    title:'A senha deve conter entre 8 e 16 caracteres, incluindo:',
    content:'

Letras Maiusculas

Letras Minusculas

Numeros

',
    trigger:'hover',
    placement:'right',
    html: true
});

Veja a funcionar no JsFiddle.
O valor por default de html e falso, o que faz com que a função text do jQuery seja usada para validar o texto do popover.

A: Alternativamente a inserção do html: true no objeto passado ao popover é possível inserir um atributo data-html="true" diretamente na tag que haverá o popover.
<input type="password" name="password" class="form-control" placeholder="Senha" id="pass_ca" data-html="true">


Q: Cannot download card from Hyperledger Composer Playground I'm trying to export my Network Admin card from the Playground UI, but the export icon is disabled. In addition, I see the following error in my Chrome console:
Error: The current identity, with the name 'admin' and the identifier 'ddae16d6f23947e9349627051b8ca5933cef53d2918f52295352d7dd24cdabcb', must be activated.
How do I export the Network Admin card from the Playground?
Here's the full Firefox log:
Establishing admin connection ...
main.d12285adf00f2401cf60.bundle.js:1:346887
@JS : ModelManager            :addSystemModels()        [object Object]
main.d12285adf00f2401cf60.bundle.js:1:848811
@JS : Resolver                :resolveRelationship()    Failed to resolve relationship [object Object]
main.d12285adf00f2401cf60.bundle.js:1:848759
@JS : IdentityManager         :<ResourceManager>()      Binding in the tx names and impl
main.d12285adf00f2401cf60.bundle.js:1:848811
@JS : EngineTransactions      :createHistorianRecord()  created historian record
main.d12285adf00f2401cf60.bundle.js:1:848811
@JS : Resolver                :resolveRelationship()    Failed to resolve relationship [object Object]
main.d12285adf00f2401cf60.bundle.js:1:848759
@JS : EngineTransactions      :createHistorianRecord()  created historian record
main.d12285adf00f2401cf60.bundle.js:1:848811
@JS : Resolver                :resolveRelationship()    Failed to resolve relationship [object Object]
main.d12285adf00f2401cf60.bundle.js:1:848759
@JS : EngineTransactions      :createHistorianRecord()  created historian record
main.d12285adf00f2401cf60.bundle.js:1:848811
@JS : ConnectionProfileManager:getConnectionManagerByTy Looking up a connection manager for type web
main.d12285adf00f2401cf60.bundle.js:1:848811
Establishing admin connection ...
main.d12285adf00f2401cf60.bundle.js:1:346887
@JS : ConnectionProfileManager:getConnectionManagerByTy Looking up a connection manager for type web
main.d12285adf00f2401cf60.bundle.js:1:848811
@JS : IdentityManager         :validateIdentity()       Error: The current identity, with the name 'admin' and the identifier 'ddae16d6f23947e9349627051b8ca5933cef53d2918f52295352d7dd24cdabcb', must be activated (ACTIVATION_REQUIRED)
main.d12285adf00f2401cf60.bundle.js:1:848759
@JS : Engine                  :query()                  Caught error, rethrowing [object Object]
main.d12285adf00f2401cf60.bundle.js:1:848759
@JS : IdentityManager         :validateIdentity()       Error: The current identity, with the name 'admin' and the identifier 'ddae16d6f23947e9349627051b8ca5933cef53d2918f52295352d7dd24cdabcb', must be activated (ACTIVATION_REQUIRED)
main.d12285adf00f2401cf60.bundle.js:1:848759
@JS : IdentityManager         :<ResourceManager>()      Binding in the tx names and impl
main.d12285adf00f2401cf60.bundle.js:1:848811
@JS : EngineTransactions      :createHistorianRecord()  created historian record
main.d12285adf00f2401cf60.bundle.js:1:848811
@JS : ConnectionProfileManager:getConnectionManagerByTy Looking up a connection manager for type web
main.d12285adf00f2401cf60.bundle.js:1:848811
@JS : ModelManager            :addSystemModels()        [object Object]
main.d12285adf00f2401cf60.bundle.js:1:848811
connected
main.d12285adf00f2401cf60.bundle.js:1:61666

A: This is the answer I got on GitHub:

The reason that the export is greyed out is because you are using the
  bluemix staged Playground that is in the 'web-connector' mode. In
  order to meaningfully export a business network card, you will need to
  create a connection to Hyperledger Fabric. The steps you outline above
  will not create a business network in Hyperledger Fabric, but within a
  web connector.
If you follow the developer tutorial
  (https://hyperledger.github.io/composer/tutorials/developer-tutorial)
  you will be taken through the process of creating a (local) Fabric,
  from which you can connect Playground and export business network
  cards.

A: You can create the admin card via composer-cli.
composer card create
-p connection.json
-u PeerAdmin -c Admin@org1.example.com-cert.pem
-k 114aab0e76bf0c78308f89efc4b8c9423e31568da0c340ca187a9b17aa9a4457_sk
-r PeerAdmin -r ChannelAdmin

Add connection.json file as following:
{
  "name": "fabric-network",
  "type": "hlfv1",
  "mspID": "Org1MSP",
  "peers": [
      {
          "requestURL": "grpc://localhost:7051",
          "eventURL": "grpc://localhost:7053"
      }
  ],
  "ca": {
      "url": "http://localhost:7054",
      "name": "ca.org1.example.com"
  },
  "orderers": [
      {
          "url" : "grpc://localhost:7050"
      }
  ],
  "channel": "composerchannel",
  "timeout": 300
}

The certificate file can be found in the signcerts subdirectory (fabric-tools/fabric-scripts/hlfv1/composer/crypto-config/peerOrganizations/org1.example.com/users/Admin@org1.example.com/msp) and is named Admin@org1.example.com-cert.pem.
The private key file can be found in the keystore subdirectory. The name of the private key file is a long hexadecimal string, with a suffix of _sk, for example 114aab0e76bf0c78308f89efc4b8c9423e31568da0c340ca187a9b17aa9a4457_sk.
Step by step tutorial is available in Hyperledger Composer
Tutorials @ https://hyperledger.github.io/composer/tutorials/deploy-to-fabric-single-org.


Q: Best orientation line bearing of a vector polygon in QGIS to fit the best Let say, I have a country vector layer like Lebanon in this example, for us as humans we can easly see that the country extends the best not from north to south like Chile, or from east to west like Turkey but oblique from Northeast to Southwest.
If I calculate the centroid of Lebanon C as in image below, is there an approach or possibility to find the angle theta between the line passing through C and the vertical line North-South to fit the best like the orientation of the country?
I drawn the blue lines with paint to show my idea, see image below

A: In later versions of QGIS, you can use the function main_angle in the field calculator.
main_angle($geometry)

From the help panel of the field calculator:

Function main_angle
Returns the angle of the long axis (clockwise, in degrees from North) of the oriented minimal bounding rectangle, which completely covers the geometry.

Note: the minimal bounding rectangle in the image was created for visualisation purposes using the function oriented_bbox


Q: Unable to call locally declared scope function via ng-click in a directive
*

*I have a directive (Just a button).

*This directive has an isolated scope.

*I want to update the object in my parent scope by clicking on the button.

*But the function is not being called.

This is the plunker.
I've tried defining the function in both the link function and the controller, and they didn't work
I know I am missing something very basic. Need some form of explanation on why this is happening. Have tried looking through a lot of the other questions but I still couldn't find a clear answer.
Thanks in advance!

A: You forget to scope.$apply()! See forked plunk: http://plnkr.co/edit/zo1GrfwyQ8T82TJiW16h?p=preview
You need to call $apply() every time an external source touches Angular values (in this case the "external source" is the browser event handled by on()).


Q: display the back and next button between half the height of image android i have a problem in xml layout for displaying next and back button besides the image and should be in middle of height of image.
pls see this url
http://screencast.com/t/zE47nb0rkFE
two buttons are above the image,it is left and right but not the middle height of image.
and it should be for every resolution size of screen.
my xml is
       <?xml version="1.0" encoding="utf-8"?>

A: you can use scrollview in code like this ::
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
 android:layout_height="fill_parent"
android:background="#FFFFFF">
<ScrollView android:id="@+id/ScrollView01"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<WebView
android:id="@+id/imv"
android:orientation="vertical"
android:layout_width="fill_parent"
 android:layout_height="55dip"
 />

 <ImageView
 android:id="@+id/imagegallery"
 android:layout_width="70sp"
  android:layout_height="70sp"
  android:layout_alignParentRight="true"
   android:layout_below="@id/imv"/>
 <ProgressBar
  android:id="@+id/Bar"
  android:layout_width="wrap_content"
  android:layout_centerInParent="true"
  android:layout_height="wrap_content"
  android:layout_above="@id/imagegallery"
  android:layout_below="@id/imv"
 />

 <TextView android:layout_height="wrap_content"
  android:id="@+id/textView1"
  android:text="Art Gallery"
  android:textColor="#000000"
  android:layout_width="wrap_content"

  android:layout_below="@id/imv"
  />
  <TextView android:layout_height="wrap_content"
  android:id="@+id/textView2"
  android:textColor="#00C000"
  android:textSize="20dip"
  android:text=" "
  android:layout_width="wrap_content"
  android:layout_toLeftOf="@id/imagegallery"
  android:layout_alignParentLeft="true"
  android:layout_below="@id/textView1"
  />
  <TextView android:layout_height="wrap_content"
android:id="@+id/textopeningnow"
android:text="Opening Now"
android:textColor="#000000"
android:layout_width="wrap_content"
    android:layout_below="@id/textView2"
/>
 <TextView android:layout_height="wrap_content"
android:id="@+id/diosas"
 android:textSize="20dip"
android:text="Diosas/Godesses"
android:textColor="#00C000"
android:layout_width="wrap_content"
    android:layout_below="@id/textopeningnow"
/>

    <Button
     android:id="@+id/back"
     android:layout_height="wrap_content"
     android:layout_width="25dip"
     android:layout_centerVertical="true"
     android:background="@drawable/leftarrow"/>
     <Button
     android:id="@+id/next"
     android:layout_height="wrap_content"
     android:layout_width="25dip"
     android:layout_alignParentRight="true"
     android:layout_centerVertical="true"
     android:background="@drawable/rightarrow"/>

<ImageView android:id="@+id/imageLoader"
    android:layout_width="wrap_content"
    android:layout_height="200dip"
    android:layout_toLeftOf="@id/next"
    android:layout_toRightOf="@id/back"
    android:layout_below="@id/diosas"
  />

    <TextView
    android:id="@+id/artistname"
    android:textColor="#000000"
    android:text=" "
    android:layout_height="wrap_content"
    android:layout_width="wrap_content"
    android:layout_below="@id/imageLoader"
    android:layout_centerInParent="true"
    />
</LinearLayout>
</ScrollView>
     </RelativeLayout>

A: I'd enclose your image in a separate RelativeLayout, and add the buttons to it. It's way too hard to try to achieve what you want with just a global relative layout.


Q: Is it possible to pass an argument to a Svelte component that specifies a particular file to import? I'm building a photography site. The user can click on links to various photo album components, e.g. an album of black and white portraits, an album of black and white architecture, etc.
The displayed contents (i.e., image file paths and corresponding image captions) for each album are detailed in a json file that is imported at the top of the album component, e.g. import {images} from './albums/bwportraits.js';, import {images} from './album/bwarchitecture.js';, etc.
Apart from the album-specific imports, the rest of each album component is identical. I would like a generic <Album /> component but be able to pass the json file to import as a prop, i.e. <Album album = "bwportraits" />, <Album album = "bwarchitecture" /> and the import within the <Album /> to be something equivalent to (the non-valid) import {images} from './albums/{album}';.
That is, I would like to dynamically specify which file to import. This does not appear possible - or, at least, I do not know how to do this.
It would, of course, be possible to import every album json file into the <Album /> component; they are reasonably small and the performance hit would be negligible. But this feels a little unclean to me. Is there a 'cleaner' workaround that anyone can suggest?


Q: meaning of "Bird titi = new Swan();" I currently read a java book and I am stuck at an example including this line :
Bird titi = new Swan();

where Swan is a subclass of Bird.
I could explain this as follow:

when java executes this line, it stores memory for the value titi, and the memory stored can contain an information for an object of type Bird. next, the second part of the line call the Swan constructor without any argument, which initializes the titi value.

if I am right, I can't explain why a Swan instance can be stored in a Bird type because Swan, as a subclass, contains more information than Bird.
so I think I am something wrong. where?
and, extra-question : in which case this type of statement is useful?
thank you

A: You may have a method that only takes an instance of Bird. Since Swan is a Bird, you can use an instance of Swan and treat it as Bird.
That's the beauty of polymorphism. It allows you to change out the implementation of the class' internals without breaking the rest of your code.

A: Where it is calling new Swan(), it is creating a new Swan object in memory.
When the Swan object is assigned to the Bird variable (possible because a Swan is a sub type of Bird) the Bird variable simply has a pointer to the Swan in memory. Because titi is a verb, this object can now be accessed / treated like a bird for static time type checking and functionality... though it is always a Swan, and can be cast to a Swan to extended Swan functionality.

A: Bird titi = new Swan();

is actually known as: programming to superclass but sometimes programming to interfaces
means:
titi is a Bird, pointing to a Swan reference... note that this is only valid because of inheritance... which means in this case that Swan is a class that extends the Bird class
why: it allows modifications in the code... you can latter decide not to use a Swan but an Owl so
Bird titi = new Swan(); will be replaced with Bird titi = new Owl(); and everything will work fine
programming to interfaces is more elegant because you can do:
IFly titi = new Swan();

which is valid if the Swan implemtents the interface IFly, so it is:
titi is something that can fly, pointing to a Swan ref.

A: Bird titi = new Swan();

It's all about Polymorphism.
A Parent class/Interface type  can hold it's Child class's Object.
Here Bird is Parent class/Interface and Swan is Child.
The same example is below :
List list = new ArrayList();

Here List is Parent Interafce and ArrayList it's Child class.


Q: Using python generics and inheritance I need to implement a bunch classes, that all need to do the same modification to the parent class. As a skilled C++ programmer, I would look for a template class. But this needs to be implemented in Python. Here I am a rookie. I found the "Generic" and has constructed this example to show the core in my problem. The real program is somewhat more complicated(using ReportLab to generate PDF documents). I need to subclass to benefit from the class framework, which leads me into trying to implement a Generic using inheritance.
The problem is that cannot understand how I can pass argument to the "super" class, which here I try to make a Generic.
First attempt:
super().__init__(*argv, **kwargs)

Second attempt:
super(G, self).__init__(*argv, **kwargs)

Third attempt:
T.__init__(*argv, **kwargs)

Here is the complete example:
from typing import Generic, TypeVar

class A():
    def __init__(self, i : int):
        self.i = i

    def draw():
        print(self.i)

class C():
    def __init__(self, s : str):
        self.s = s

    def draw():
        print(self.s)

T = TypeVar('T')

class G(Generic[T]):
    def __init__(self, *argv, **kwargs):
        super().__init__(*argv, **kwargs)

    def draw():
        # Here is some special going to happen
        super().draw()

gA = G[A](5)
gB = G[B]('Hello')

gA.draw()
gB.draw()

The output that I get:
Traceback (most recent call last):
  File "<string>", line 34, in <module>
File "/usr/lib/python3.8/typing.py", line 729, in __call__
    result = self.__origin__(*args, **kwargs)
  File "<string>", line 28, in __init__
TypeError: object.__init__() takes exactly one argument (the instance to initialize)

A: You have understood Python generics wrong. A Generic, say Generic[T], makes the TypeVar T act as whatever you provide the instance with.
I found this page to be very useful with learning Generics.

A: typing.Generic is specifically for type annotations; Python provides no runtime concept equivalent to either:

*

*Template classes, or

*Function overloads by parameter count/type

The latter has extremely limited support from functools.singledispatch, but it only handles the type of one argument, and the runtime type-checking is fairly slow.
That said, you don't need a template-based class or a polymorphic inheritance hierarchy here; Python is perfectly happy to call draw on anything that provides a method of that actual name. The code you're writing here can just do:
a = A(5)
b = B('Hello')

a.draw()
b.draw()

with no use of G needed.


Q: Evaluating $\lim\limits_{n\to \infty}\left\{(1+\frac{1}{n})(1+\frac{2}{n})\dots(1+\frac{n}{n})\right\}^{\frac{1}{n}}$ Question is to evaluate :
$$\lim_{n\to \infty}\left\{ \left(1+\frac{1}{n}\right)\left(1+\frac{2}{n}\right)\dots\left(1+\frac{n}{n}\right)\right\}^{\frac{1}{n}}$$
I tried to do something like this but it is not getting better...
$(1+\frac{1}{n})(1+\frac{2}{n})\cdots(1+\frac{n}{n})=(\frac{n+1}{n})(\frac{n+2}{n})\cdots (\frac{n+n}{n})=\frac{1}{n^n}(n+1)(n+2)\dots(n+n)$
please give some hint to proceed further.

A: Consider the log of $[(1+\frac{1}{n})(1+\frac{2}{n})\dots(1+\frac{n}{n})]^{\frac{1}{n}}$:
$$\frac{1}{n}\sum_{k=1}^n \ln \left( 1+\frac{k}{n}\right).$$
The limit of this sum is equal to $\int_0^1\ln(1+x)dx$, so
$$
\begin{aligned}
\lim_{n\to\infty} [(1+\frac{1}{n})(1+\frac{2}{n})\dots(1+\frac{n}{n})]^{\frac{1}{n}}
&= \lim_{n\to\infty} \exp\left(\frac{1}{n}\sum_{k=1}^n \ln \left( 1+\frac{k}{n}\right) \right)\\
&= \exp\left(\lim_{n\to\infty}\frac{1}{n}\sum_{k=1}^n \ln \left( 1+\frac{k}{n}\right) \right)\\
&= \exp \left( \int_0^1\ln(1+x)dx\right)
\end{aligned}$$

A: $$(\frac{n+1}{n})(\frac{n+2}{n})\dots (\frac{n+n}{n})=\frac{1}{n^n}(n+1)(n+2)\dots(n+n)$$
$$=\lim_{n\rightarrow \infty}\left[\frac{1}{n^n}\frac{(2n)!}{n!}\right]^{1/n}=\lim_{n\rightarrow \infty}\left[\frac{\sqrt{4\pi n}\cdot 2^{2n}\frac{n^{2n}}{e^{2n}}}{\sqrt{2\pi n}\cdot \frac{n^{2n}}{e^n}}\right]^{1/n}=\lim_{n\rightarrow \infty }[\sqrt{2}]^{1/n}\cdot \frac{4}{e}=\frac{4}{e}$$
Here I've used the Stirling approximation of $n!$,i.e- $n!=\sqrt{2\pi n}\left(\frac{n}{e}\right)^{n}$


Q: Enterprise VNC client? I'm a little new to Enterprise Mac management but have 10 years experience as a Mac tech.  I am in charge of deployment of 3k + macs for a LARGE international corporation.  We are using Casper Suite.
To use VNC right now I have to ask people to get their IP then enable sharing so I can ask for permission.  For some people, this is really annoying since they are "higher ups" and only has a couple minutes at a time.
My question is this.  Is there a good Enterprise solution to VNC quickly?  Maybe where I have a special login that either automatically logs me into their computer or asks them for permission without having them go through the annoyance of getting me the info and checking the box.
FYI, I was told that automatically checking that "anyone can request access" would be a security loophole so I can have that checked at deployment.
Thanks in advance.


Q: disable component functionality based on page I a navigation where the menu items are hidden until you get to a certain point on the page then they show.
This works great on the homepage, because it is a relatively long page. But, some of my other pages are short and do not go past the height of the viewport. So when the page loads there are no navigation menu options and it shows the navigation is blank.
Is there a way in react to say disable a component conditionally according to what layout or page you are on?
Example: In Jekyll you can create an if statement and hide a class or section using somehting like {% if page.layout == 'home' %}hide{% endif %}. Is there an equivalent/similar method when using react?
Code:
import React from 'react';
import { Collapse, Navbar, NavbarToggler, NavbarBrand, Nav, NavItem, NavLink } from 'reactstrap';

export default class Example extends React.Component {
  constructor(props) {
    super(props);

    this.toggle = this.toggle.bind(this);
    this.state = {
      isOpen: false,
      isTop: true,
      width: 0,
      height: 0
    };
    this.updateWindowDimensions = this.updateWindowDimensions.bind(this);
  }
  toggle() {
    this.setState({
      isOpen: !this.state.isOpen
    });
  }

  componentDidMount() {
    this.updateWindowDimensions();
    window.addEventListener('resize', this.updateWindowDimensions);
    document.addEventListener('scroll', () => {
      const isTop = window.scrollY < window.innerHeight - 50;
      if (isTop !== this.state.isTop) {
        this.setState({ isTop })
      }
    });
  }

  componentWillUnmount() {
    window.removeEventListener('resize', this.updateWindowDimensions);
  }

  updateWindowDimensions() {
    this.setState({ width: window.innerWidth, height: window.innerHeight - 50 });
  }

  render() {
    return (

        <Navbar color="light" light expand="md">
          <NavbarBrand href="/">Maryland Brand</NavbarBrand>
          <NavbarToggler onClick={this.toggle} />
          <Collapse isOpen={this.state.isOpen} navbar>

              <NavItem className={this.state.isTop ? 'hide' : 'show fadeIn'}>
                <NavLink className="active" href="/">Our Brand</NavLink>
              </NavItem>
              <NavItem className={this.state.isTop ? 'hide' : 'show fadeIn'}>
                <NavLink href="/">Logos</NavLink>
              </NavItem>
              <NavItem className={this.state.isTop ? 'hide' : 'show fadeIn'}>
                <NavLink href="/">Color</NavLink>
              </NavItem>
              <NavItem className={this.state.isTop ? 'hide' : 'show fadeIn'}>
                <NavLink href="/">Typography</NavLink>
              </NavItem>
              <NavItem className={this.state.isTop ? 'hide' : 'show fadeIn'}>
                <NavLink href="/">Imagery</NavLink>
              </NavItem>
              <NavItem className={this.state.isTop ? 'hide' : 'show fadeIn'}>
                <NavLink href="/">Editorial</NavLink>
              </NavItem>
              <NavItem>
                <NavLink className="red bold uppercase show" href="/">Communicators Toolkit</NavLink>
              </NavItem>

          </Collapse>
        </Navbar>

    );
  }
}

A: Gatsby comes with reach router, so you can use it to get location.pathname and then render something conditionally.
import React from 'react'
import { Location } from '@reach/router'

const HomepageOnly = () => (
  <Location>
    {({ location }) =>
      location.pathname === '/' ? (

This is the homepage

      ) : (

This is not

      )
    }
  </Location>
)

export default HomepageOnly

Codesandbox