text:
Q: pgf/tikz with genealogytree and the 'before upper' setting for boxes \documentclass{standalone} %or standalone
\usepackage[all]{genealogytree}

\gtrset{info separators={\par}{. }{}{}} %no period after comment

\begin{document}
\begin{tikzpicture}

        \genealogytree[
                processing=fit,
                level distance=1cm,
                level size=1.5cm,
                node size from=2cm to 4cm,
                box clear,
                box={enhanced,fit basedim=8pt,
                        halign=center,valign=center,
                        before upper={\parskip 0.15\tcbfitdim plus 0pt minus 0pt},
                        drop fuzzy shadow
                },
                database content interpreter,
                database format=full,
                list separators hang,
                edges=rounded,
                date format=dd.mm.yyyy]{
                parent{
                        g[female]{
                                female,
                                name = {Name \surn{Long Surname}},
                                birth- = {1865-10-08},
                                death- = {1945-08-20},
                                comment = {born NameWithfxx},
                        }
                }
        }

\end{tikzpicture}
\end{document}

with that I get this:

this is bad since I don't know why exactly more space is left on the left and right and the font is smaller.
If I now replace the character 'f' in the comment by an 'r' I get this:

which is really weird since what characters I use shouldn't matter in this way (I tried it with other characters too, some seem to be working, some not).
I tried some things and finally I got that if I remove the "before upper" option of the boxes I get this with the r

and this with the f
.
Does anyone have an Idea why it is that way, why does it matter which character is used and what does the "before upper" option do? (I just took it from the signpost template and wasn't able to find what the option does on the internet)
EDIT: Figured finally out that the before upper option (before upper={\parskip 0.15\tcbfitdim plus 0pt minus 0pt},) is processed by tcolorbox (the given code is placed after the color and font settings but before the content). But I still don't know why this conflicts with characters like f,g or q

A: Solution 1: Allow variable node width and font size shrinking. Slightly enlarge the level size=1.5cm to, for example level size=1.6cm, to handle the specific situation (f causes font shrinking).
Solution 2: Allow variable node height with the cost of fixed node width and fixed font size. (see below)
Explanation
It is the total height of node g[female] that matters. Here the "node" is a genealogytree concept and is different from the tikz node.
Initially, genealogytree sets option timeflow=down. This fixes the height of every node to level size, and let option node size from sets the range of node width. If the natural height or width of node is larger than the fixed height or minimum width, respectively, genealogytree tries to firstly enlarge the width. If maximum width (with fixed height) is still not big enough, then font size is shrunk, using fitting library of tcolorbox.
In your example,

*

*level size=1.5cm and node size from=2cm to 4cm sets the node size;

*by setting \gtrset{info separators={\par}{. }{}{}}, the node content is split into four paragraphs, joined by three vertical skip \parskip;

*by setting before upper={\parskip=0.15\tcbfitdim plus 0pt minus 0pt}, \parskip is set, at the beginning of node content, to be variable with font size. Here \tcbfitdim represents the used font size set by fitting library of tcolorbox. (By setting fit basedim=8pt, \tcbfitdim starts from 8pt).

*Here comes the most tricky part: the f (with a depth) in comment = {born NameWithfxx} makes the natural (total) height of node slightly bigger than 1.5cm, which causes node width enlarging. But even using maximum width will not solve the too-high problem, font size is then shrunk (with the maximum width applied). This makes the output of f and r differs in two ways: the node width and the font size. But these differences has a same cause.

*The change to \parskip is nothing more than adding vertical spaces and making the node higher.

Some examples to show how tricky it is:

\documentclass{article} %or standalone
\usepackage[all]{genealogytree}

\gtrset{info separators={\par}{. }{}{}} %no period after comment

\begin{document}

\newcommand\testGTree[3][]{
  \par
  \parbox{20em}{\texttt{%
    \detokenize{\parindent= #2} ... \\
    comment = \detokenize{#3}
  }}
  \begin{tikzpicture}[baseline=(current bounding box.center)]
    \genealogytree[
      processing=fit,
      level distance=1cm,
      level size=1.5cm,
      node size from=2cm to 4cm,
      box clear,
      box={enhanced,fit basedim=8pt,
        halign=center,valign=center,
        before upper={\parskip=#2 plus 0pt minus 0pt},
        drop fuzzy shadow
      },
      database content interpreter,
      database format=full,
      list separators hang,
      edges=rounded,
      date format=dd.mm.yyyy,
      #1]
    {
      parent{
        g[id=xxx]{
          female,
          name = {Name \surn{Long Surname}},
          birth- = {1865-10-08},
          death- = {1945-08-20},
          comment = {#3\smash{, \the\tcbfitdim}},
        }
      }
    }
    \draw (0, 0) grid (4, .1); % to measure node width
  \end{tikzpicture}
  \par
}

\parindent=0pt
\paragraph{Group 1} zero \verb|\parindent| is ok
\testGTree{0pt}{f}
\testGTree{0pt}{r}

\paragraph{Group 2} \verb|\parindent=.8pt ...| is enough to trigger width enlarging and font size shrinking
\testGTree{.8pt}{f}
\testGTree{.8pt}{r}

\paragraph{Group 3} with \verb|\parindent=0.15\tcbfitdim ...|, depth \verb|0.2pt| is enough to trigger.

\newlength{\charDepth}
\newcommand{\showDepth}[1]{%
  \settodepth\charDepth{#1}%
  #1\smash{, \the\charDepth}
}

\testGTree{0.15\tcbfitdim}{\showDepth f}
\testGTree{0.15\tcbfitdim}{\showDepth r}
\testGTree{0.15\tcbfitdim}{r \rule[-.2pt]{1pt}{5pt}}

\paragraph{Group 4} a slightly larger \verb|level size=1.6cm| fixes the original problem.
\testGTree[level size=1.6cm]{0pt}{f}
\testGTree[level size=1.6cm]{0pt}{r}
\end{document}

Solution 2
Result: fix node width and let node height change by content. Restricted by the package implementation, you cannot have both width and height variable.
Main change: use tcolorbox option natural height. Search natural height in doc of genealogytree to see more examples.
Changes in detail:

*

*Add option natural height inside box={...}.

*Change processing=fit to processing=tcolorbox, to allow variable node height. Also add size=title inside box={...} to set tcolorbox margins.

*Adjust node size to some appropriate value. This would be used as the fixed node width.

*Replace useless fitting related options. Inside box={...},

*

*replace fit basedim=8pt by fontupper=\fontsize{8}{9.6}\selectfont

*replace 0.15\tcbfitdim used in before upper={...} by 1.2pt (8pt * 0.15).

\documentclass{article} %or standalone
\usepackage[all]{genealogytree}

\gtrset{info separators={\par}{. }{}{}} %no period after comment

\begin{document}
\begin{tikzpicture}[baseline=(current bounding box.center)]
  \genealogytree[
      processing=tcolorbox,
      level distance=1cm,
      level size=1.5cm,
      node size=3cm,
      box clear,
      box={enhanced,
        fontupper=\fontsize{8}{9.6}\selectfont,
        halign=center, valign=center, size=title,
        % 1.2pt = 8pt * 0.15
        before upper={\parskip=1.2pt plus 0pt minus 0pt},
        drop fuzzy shadow,
        natural height
      },
      database content interpreter,
      database format=full,
      list separators hang,
      edges=rounded,
      date format=dd.mm.yyyy]
  {
    parent{
      g[id=xxx]{
        female,
        name = {Name \surn{Long Surname}},
        birth- = {1865-10-08},
        death- = {1945-08-20},
        comment = {born NameWithfxx},
      }
    }
  }
\end{tikzpicture}
\end{document}


text:
Q: Swift 2 load image from url variable error I have load_image function and works with
load_image("http://blabla.com/bla.png")

But when i add variable like this
 load_image(detailDesc2!)

gives this error
fatal error: unexpectedly found nil while unwrapping an Optional value

My codes here
ViewController table view selected codes. Here send detailDesc1 , and detailDesc 2 to DetailView Controller
  func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        let subcatVC = self.storyboard?.instantiateViewControllerWithIdentifier("Detail") as! DetailViewController
        subcatVC.detailDesc1 = self.arrayCategory[indexPath.row][API_PARAM_CAT_ID] as! String
        subcatVC.detailDesc2 = self.arrayCategory[indexPath.row][API_PARAM_CAT_IMAGE] as! String
        _ = UINavigationController(rootViewController: subcatVC)
        self.navigationController?.pushViewController(subcatVC, animated: false)
    }

DetailViewController
   var detailDesc1:String?
    var detailDesc2:String?

    load_image(detailDesc2!)  // HERE GIVES ERROR

My load_image function
func load_image(urlString:String)
{
    let imgURL: NSURL = NSURL(string: urlString)!
    let request: NSURLRequest = NSURLRequest(URL: imgURL)

    let session = NSURLSession.sharedSession()
    let task = session.dataTaskWithRequest(request){
        (data, response, error) -> Void in

        if (error == nil && data != nil)
        {
            func display_image()
            {
                self.imagetbig.image = UIImage(data: data!)
            }

            dispatch_async(dispatch_get_main_queue(), display_image)
        }

    }

    task.resume()
}

Also when i add this codes success working label and textviews shows.
textbig.text = detailDesc1
textim.text = detailDesc2

A: For some reason your variable detailDesc2 is nil and you force the unwrapping using the ! telling the compiler that the variable always have a value when the variable was declared optional(it could be non-value). According to Apple:

Trying to use ! to access a non-existent optional value triggers a runtime error. Always make sure that an optional contains a non-nil value before using ! to force-unwrap its value.

You can avoid the runtime error using optional binding, checking before use the variable like in the following way:
if let url = detailDesc2 {
    load_image(url)
}

As @LeoDabus recommend now in Swift 2, you can use too the guard statement that you can use like in the following way:
guard if let url = detailDesc2 else {
   return
}

load_image(url)

According to Apple:

A guard statement, like an if statement, executes statements depending on the Boolean value of an expression. You use a guard statement to require that a condition must be true in order for the code after the guard statement to be executed. Unlike an if statement, a guard statement always has an else clause—the code inside the else clause is executed if the condition is not true.

I hope this help you.

A: I expect self.arrayCategory[indexPath.row][API_PARAM_CAT_IMAGE] returns nil
You can check the variable before using:
if let imageUrl = detailDesc2 {
    load_image(imageUrl)
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: New developer - how to build some of the tutorial applications? I successfully installed Eclipse, JDK, etc., and have a working IDE. (Windows 7)
Pretty easily worked through HelloAndroid, both hard-coded text based and xml resourced.
Located the .apk, loaded it onto my tablet, and it worked!
Now, trying to do something a little more extensive and interactive, so I am trying to build the TimePicker tutorial application. There seems to be a big jump in what the budding programmer is expected to just "know" to do!
Step 1 - creating a new project, fine.
Step 2 - "inserting" the xml resource code was pretty clear - it replaces all.
Step 3 - "inserting" the class members. Not so clear, but I finally did get them into the proper place in the java source after several tries, AND after recalling the Tip, to Ctrl-Shift-O to import packages. Without that, it naturally threw all sorts of errors, that I couldn't distinguish from inserting the code in the wrong place.
Step 4 - "inserting" code for the onCreate() method: I have NO idea where this goes or exactly what it may replace.  Steps 5, 6, 7 don't look promising!
The code offered is protected void onCreate(); does that replace the default generated public void onCreate()? Does it go in in addition to it? Above? Below? Inside the closing }? After?
Needless to say, every place I've tried to put it, I only get more errors...
I don't really want or have the time resources to go take a java course! I've been programming for 40 years, and it's probably an "old dog / new tricks" issue. I'd really appreciate some guidance to get started on this learning curve!
Dave

A: Well I am not an Android developer but lets say I am in the very same situation as you are. I come from another background and want to get into Android.
This is what I would do as I suppose you know XML and programming languages that support OOP.
I just guess you come from c++ or delphi...
I would first of all look for an android forum on the web for android development some kind of community that just deals with android.
Than I would see - because those boards usually have some kind of threads such as:
Useful resources and BOOKs for android beginner.
Than I would have a look at amazon and check some reviews and compare some books.
I would just go from there with a book or two books. Does not really take time to scan those books. I am also sure they would simply show some basic Java syntax and programming excersises as most iPhone books have some C and C++ - to Objective-C introduction.
From there I would see how much those book cover and have a look at the "simple" adroid apps that are already outside and try to clone them for practice suppose.
And if there are any kind of Java specific questions just googling the sense of how to approach that in java and then just look for the class/method descriptions at:
http://download.oracle.com/javase/tutorial/reallybigindex.html
I suppose with this way you could easily dive into Android within a month or two to cover all the basics and have some simple apps running?
Well as I said, I am not an Android developer and therefore cannot answer your other question but thats the way I would get into Android with a fast learning curve.

A: Before programming in Android you should know:

*

*Java

*Object Oriented Proggramming

*XML in general (Most importantly, for the UI)

i'm writing down the tutorials steps in a way that might help you, If you follow them, you would have finished the tutorial, but you might not learn anything. I'd recommend you to start by reading a verry small java tutorial (that gets to object oriented proggraming in java).
After that, you will understand this much better.
This video is also a verry good video for getting started. Learn how to develop for Android, Beyond HelloWorld. (It's long, but i really recommend it, it will help you get going fast)
Then, i would recommend you to finish the layout tutorials (those are much easier and more usefull for basic programs). The Layout totorials are better for starting to learn. (at least do the linearLayout, RelativeLayout and ScrollView tutorials). After the video (in case you saw the video), some of this tutorials might seem easy.
After that, if you still don't understand this code, read a more complex java tutorial (or get to the interface part of the tutorial).
I know the video is long, but its a verry good way of getting started. It helped me A LOT.

Ok, I'm going to write a few things you should know in order to program in android. This things are explained in the HelloWorld tutorial, but in case you didn't understand them there, I'm writing them here.
In android, the different "Windows" are called Activities and are subclases of Activity. For example, an activity can be:
public class MyExampleActivity extends Activity
{

...

}

All activitis should be declared in the android manifest (Like you should have seen in the HelloAndroid example). The first Activity called in the aplication is the activity that has the tag:
<category android:name="android.intent.category.LAUNCHER" />
For the rest of the activities you should change that tag for: <category android:name="android.intent.category.DEFAULT" />.
For example, in the manifest my first activity should be declared like:
<activity android:name=".MyExampleActivity" android:label="@string/app_name">
<intent-filter>
    <action android:name="android.intent.action.MAIN" />
    <category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>

All activities should override a method called onCreate. That method is the first method called when an activity starts.
So in all activities you should create a methjod like this:
public class MyExampleActivity extends Activity
{
    //The On Create Method - Is the first method called in an activity.
    @Override
    public void onCreate(Bundle savedInstanceState) {
        //Executes the onCreate of the superclass (Activity)
        super.onCreate(savedInstanceState);

        //Adds the xml layout to the activity (In the first activity, the layout is usually
        //main, but in other activities you should replace main for the laout of that activity
        setContentView(R.layout.main);

        //Just to prevent mistakes, ALWAYS make the findViewById(R.id.xxx) calls after the
        // setContentView

        // (onCreate CODE SHOULD BE HERE)
    }
...

}

About the tutorial you selected, Its not the one I recommend right after the HeloWorld one, but if you want to finish it:
Step 4: Create the onCreate Method in the HelloTimePicker class (Or however you called it) and copy the code where i wrote (onCreate CODE SHOULD BE HERE).
at this point the class ahould look something like :
public class HelloTimePicker extends Activity
{

    private TextView mTimeDisplay;
    private Button mPickTime;

    private int mHour;
    private int mMinute;

    static final int TIME_DIALOG_ID = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        // capture our View elements
        mTimeDisplay = (TextView) findViewById(R.id.timeDisplay);
        mPickTime = (Button) findViewById(R.id.pickTime);

        // add a click listener to the button
        mPickTime.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                showDialog(TIME_DIALOG_ID);
            }
        });

        // get the current time
        final Calendar c = Calendar.getInstance();
        mHour = c.get(Calendar.HOUR_OF_DAY);
        mMinute = c.get(Calendar.MINUTE);

        // display the current date
        updateDisplay();
    }

    //NEW METHODS GO HERE
}

Now you can see:
Class xx extends activity

Global variables (private TextView mTimeDisplay;, etc)
OnCreate metho with super.onCreate, setContentView and extra code for the TimePicker.
Step 5 is adding two new methods to the t class:
// updates the time we display in the TextView
private void updateDisplay() {
    mTimeDisplay.setText(
        new StringBuilder()
                .append(pad(mHour)).append(":")
                .append(pad(mMinute)));
}

private static String pad(int c) {
    if (c >= 10)
        return String.valueOf(c);
    else
        return "0" + String.valueOf(c);
}

just cop paste this where i wrote (//NEW METHODS GO HERE).
Step 6 is the same as step 5, but with a listener (its like a method thatis called automatically when something happens). i would recommend reading about Listeners to understand this better.
You should just paste:
    // the callback received when the user "sets" the time in the dialog
private TimePickerDialog.OnTimeSetListener mTimeSetListener =
    new TimePickerDialog.OnTimeSetListener() {
        public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
            mHour = hourOfDay;
            mMinute = minute;
            updateDisplay();
        }
    };

after the two methods and before the } at the end of the class.
Step 7 is like step 6 but with
    @Override
protected Dialog onCreateDialog(int id) {
    switch (id) {
    case TIME_DIALOG_ID:
        return new TimePickerDialog(this,
                mTimeSetListener, mHour, mMinute, false);
    }
    return null;
}

.
tutorial is finished. You should have:
public class HelloTimePicker extends Activity
    {

        private TextView mTimeDisplay;
        private Button mPickTime;

        private int mHour;
        private int mMinute;

        static final int TIME_DIALOG_ID = 0;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);

            // capture our View elements
            mTimeDisplay = (TextView) findViewById(R.id.timeDisplay);
            mPickTime = (Button) findViewById(R.id.pickTime);

            // add a click listener to the button
            mPickTime.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    showDialog(TIME_DIALOG_ID);
                }
            });

            // get the current time
            final Calendar c = Calendar.getInstance();
            mHour = c.get(Calendar.HOUR_OF_DAY);
            mMinute = c.get(Calendar.MINUTE);

            // display the current date
            updateDisplay();
        }

        // updates the time we display in the TextView
    private void updateDisplay() {
        mTimeDisplay.setText(
            new StringBuilder()
                    .append(pad(mHour)).append(":")
                    .append(pad(mMinute)));
    }

    private static String pad(int c) {
        if (c >= 10)
            return String.valueOf(c);
        else
            return "0" + String.valueOf(c);
    }

 // the callback received when the user "sets" the time in the dialog
    private TimePickerDialog.OnTimeSetListener mTimeSetListener =
        new TimePickerDialog.OnTimeSetListener() {
            public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                mHour = hourOfDay;
                mMinute = minute;
                updateDisplay();
            }
        };

        @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
        case TIME_DIALOG_ID:
            return new TimePickerDialog(this,
                    mTimeSetListener, mHour, mMinute, false);
        }
        return null;
    }

//Sorry for the indexing


text:
Q: Proof this Endomorphism has an eigenvalue Let $\mathbb{F}=\mathbb{R}, \Phi:\mathbb{R}^7\rightarrow\mathbb{R}^7$ be an endomorphism,
Proof that there exists an eigenvalue of $\Phi$
I know that every function with an odd degree takes on the value 0. But how can I prove this algebraically? Can I use the fundamental Theorem of Algebra, even if the field is $\mathbb{R}$?


text:
Q: not implies, not Leftarrow, description in the middle of an arrow in TikZ-cd Is there a way to put $\nLeftarrow$ instead of some arrows in TikZ? Specifically, how do I change it to "B does not imply A" in the following code.
\documentclass{article}
\usepackage{tikz-cd}
\begin{document}
\begin{tikzcd}[arrows=Rightarrow]
   A \arrow[out=30,in=150]{r}{}\arrow{d} & B \arrow[out=210,in=330]{l}{}\arrow{d}  \\
   E  \arrow{r}{} & F
\end{tikzcd}
\end{document}

One very primite way is to do something similar to the following, where at the description part in the middle of the arrow, use \Big\backslash.
\documentclass{article}
\usepackage{tikz-cd}
\begin{document}
\begin{tikzpicture}
\matrix (m) [matrix of math nodes, row sep=3em, column sep=3em]
             { A & B \\
          & C \\ }; \path[->,font=\scriptsize] (m-1-1) edge node
   {$\Big\backslash$} (m-1-2) edge node {$\Big\backslash$} (m-2-2);
    \end{tikzpicture}
 \end{document}

But then, how do I put a description in the middle of an arrow in the first code?

A: This is probably the same mechanism for description key in the manual of tikz-cd but more explicit.
\documentclass{article}
\usepackage{tikz-cd}
\usetikzlibrary{decorations.markings}
\tikzset{degil/.style={
            decoration={markings,
            mark= at position 0.5 with {
                  \node[transform shape] (tempnode) {$\backslash$};
                  %\draw[thick] (tempnode.north east) -- (tempnode.south west);
                  }
              },
              postaction={decorate}
}
}
\begin{document}
\begin{tikzcd}[arrows=Rightarrow]
   A \arrow[out=30,in=150,degil]{r}{}\arrow[degil]{d} & B \arrow[out=210,in=330]{l}{}\arrow{d}  \\
   E  \arrow{r}{} & F
\end{tikzcd}
\end{document}

If you want to keep the backslashes upright(unrotated) regardless of the arrow direction, you can remove the transform shape option and give it a try.


text:
Q: run time error Could Not Find Class com.google.android.gms.maps.SupportMapFragment I know this question has been asked before in several post, but I've tried everything and none of them solved my problem.
I'm trying  on an app that uses Google Maps v2 API to display a map. the project is compiled without error, but it crashes at run time on the device with this error in LogCat :
Could not find class 'com.google.android.gms.maps.SupportMapFragment'

as I Checked :
1- Last version of Google Service is installed on the device.
2- google-play-services_lib project is under same folder as referencing project and it is currectly added to project as Library (as below) :

3- Google service library is shown under Android dependencies :
4- I decompiled the project's apk and surprisingly in the 'classes' folder I saw gms folder without map folder and without SupportMapFragment class :

5- I added the lib to build path :

I would be very grateful if anyone could give an idea to solve my problem.

A: You need to add the library to the classpath.
For that just right click the library file in the package explorer of eclipse and select add to build path.
Then clean and rebuild and everything should be fine.


text:
Q: Why is regionWillChangeAnimated: never called while panning? The problem:
My MKMapViewDelegate's - (void)mapView:(MKMapView *)mapView regionWillChangeAnimated:(BOOL)animated selector is never called while i pan the map (but is called while zooming) in iPhone 5.0 simulator. It works as it should (or at least i suppose it should) on 4.3 simulator and 4.3 device. I don't have access to 5.0 device at the moment.
Situation:
I have a MKMapView instance (created in Interface Builder) - i double checked it in viewWillLoad
- (void)viewDidLoad {
    assert(self.myMapView);
    [self.stopMapView setDelegate:self];
}

I further define some of the MKMapViewDelegate's selectors, but the ones that concern me are:
- (void)mapView:(MKMapView *)mapView regionWillChangeAnimated:(BOOL)animated
{
    RKLogDebug(@"Will Change map longSpan: %lf", mapView.region.span.longitudeDelta);
}

- (void)mapView:(MKMapView *)mapView regionDidChangeAnimated:(BOOL)animated
{
    RKLogDebug(@"Did Change map longSpan: %lf", mapView.region.span.longitudeDelta);
}

What's going on here? The delegate is not somehow informed about the 'panning' in the MKMapView while on iPhone 5.0 Simulator. I already tried to reset simulator content but to no avail. I wonder whether is it just some simulator bug or iOS5's intended behavior? (I'm on 10.7.2 & Xcode 4.2).

A: I added the two methods to my project.
Tested iPhone 5.0 simulator: zooming / panning -> methods get called
I'm on 10.7.2 & Xcode 4.2 too.
So I can confirm it's not intented behavior as you thought it could be.
Hope it helps.


text:
Q: How to update column in SQL Server 2008 I'm new to SQL Server so any help with this would be greatly appreciated. I can not find the error while update the existing column with autogenerated record
Here is my table structure:-
CREATE TABLE [dbo].[EmployeeRegistration]
(
    [ID] [int] NULL,
    [Sr_no] [int] IDENTITY(1,1) NOT NULL,
    [Branch_Code] [varchar](200) NULL,
    [City] [varchar](200) NULL,
    [Employee_Name] [varchar](200) NULL,
    [Designation] [varchar](200) NULL,
    [Department] [varchar](200) NULL,
    [Date_of_Joining] [varchar](200) NULL,
    [Reporting_To] [varchar](200) NULL,
    [Staff_Code] [varchar](50) NULL,
    [Reporting_To_1] [varchar](200) NULL,
    [Staff_Code_1] [varchar](50) NULL,
    [Emp_Staff_Code]  AS ('T'+right('0000'+CONVERT([varchar](8),[Sr_no],(0)),(8))),
    [Password] [varchar](50) NULL,
    [confirmPassword] [varchar](50) NULL,
    [EMAIL_id] [varchar](50) NULL,
    [IsActive] [varchar](200) NULL,
    [Created_By] [varchar](200) NULL,
    [Created_On] [date] NOT NULL,
    [Modified_By] [varchar](200) NULL,
    [Modified_Date] [date] NOT NULL
)

I want to update Password column with below query:-
use AxpressDB

alter table EmployeeRegistration
   alter column Password AS ('XP'+right('0123'+CONVERT([varchar](50),[Sr_no],(0)),(8)))

A: The syntax for the column altering :
 ALTER TABLE tablename
    ALTER COLUMN columnname columndatatype(size)

and the example :
 ALTER TABLE dbo.doc_exy
    ALTER COLUMN column_a DECIMAL (5, 2) ;

Try these manner

A: You cannot alter an existing column and make it as computed column, you need to drop and recreate
alter table EmployeeRegistration
   drop column Password
alter table EmployeeRegistration
   add Password AS ('XP'+right('0123'+CONVERT([varchar](50),[Sr_no],(0)),(8)))


text:
Q: Resharper is flagging my Promise as an error I have the following Typescript code:
private getWorkbookFromFile(excelFile: File): Promise<xlsx.IWorkBook> {
    var loadedPromise = new Promise<xlsx.IWorkBook>((resolve, reject) => {
        // stuff to come up with the resolve.
    });

    return loadedPromise;
}

Visual studio is turning the word Promise red (as an error).  But when I compile and run, it works fine.
I hit my head on the wall for this for a while then decided to turn off Resharper.  Once I did syntax highlighting showed no errors!  (And I can still compile and run.)
I am running Typescript targeting es6 (es2015).  When you do that, you don't need extra typing (ie es6-promise) for Promises.  Visual Studio knows that, but Resharper does not seem to know it.
So, the question is, how can I get Resharper to realize that my Typescript is targeting es6 (es2015) and that promise is OK?
I will have to develop without resharper for now, but I like the other things it gives, so I would LOVE a fix for this.
Things I have tried:
• Setting Javascript to ES6 (and Experimental) in the Resharper Options.
• Setting my Compiler Options to be ES6 (I also tried ES2015) in the tsconfig.json file.

A: I updated to Resharper 2016.2 and this issue was resolved.


text:
Q: Send sms from default sms application I am trying to send a SMS from my application that already set as default SMS application. I have tried to send using SmsManager, but it does not work.
Here is what I have tried:
SmsManager smsMan = SmsManager.getDefault();
smsMan.sendTextMessage(Name, null, body, null, null);

This approach works when my application was not set as default app, but it didn't when my app is the default one.
Is there any other approach to send a SMS from inside the default SMS application?

A: Try the below code to send message
String number = "12346556";  // The number on which you want to send SMS
     startActivity(new Intent(Intent.ACTION_VIEW, Uri.fromParts("sms", number, null)));


text:
Q: Download file in jenkins job I have a jenkins job which will execute node application. This job is configured to run on docker only during execution.
Is it possible to download file from node application everytime when job gets executed?
I tried using nodejs plugins to save and download file. File is getting saved in local but not able to download.

A: If your docker container runs some job and creates a file as the output of the job, and you want it available outside the container after the job is done, my suggestion is that you create the file in a location that is mapped to a host folder via the volume option. Run your docker container as follows:
sudo docker -d -v /my/host/folder:/my/location/inside/container mynodeapp:latest

Ensure that your node application writes the output file to the location /my/location/inside/container. When the job is completed, the output file can be accessed on the host-machine at /my/host/folder.


text:
Q: invalid context 0x0 within custom UIView - follow-up question This post:
invalid context 0x0 within custom UIView
...should have given me the key to solve my problem, but I could not avoid the invalid context error. Some clarification would be much appreciated.
I want to draw lines in a subview presented when the ViewController loads. To do that, I create a subclass to UIView, which is similar to SplitCircleView posted by StartPlayer.
To run the code, create a new project and replace the contents of the ViewController file with:
import UIKit
@IBDesignable

class ViewController: UIViewController {
    let mySubViewInstance = SplitCircleView()

    override func viewDidLoad() {
        super.viewDidLoad()

        //let mySubViewInstance = SplitCircleView()
        mySubViewInstance.setNeedsDisplay(mySubViewInstance.frame)
    }
}

class SplitCircleView: UIView {
    override init(frame: CGRect) {
        super.init(frame: frame)
        //self.setNeedsDisplay()
        //draw(frame)
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        //self.setNeedsDisplay()
        //draw(frame)
    }

    override func setNeedsDisplay(_ rect: CGRect) {
        self.backgroundColor = .clear

        drawSlice(rect: rect, startPercent: 87.5, endPercent: 37.5, color: .green)
        drawSlice(rect: rect, startPercent: 37.5, endPercent: 87.5, color: .red)
    }

    func drawSlice(rect: CGRect, startPercent: CGFloat, endPercent: CGFloat, color: UIColor) {
        let center = CGPoint(x: rect.origin.x + rect.width / 2, y: rect.origin.y + rect.height / 2)
        let radius = (min(rect.width, rect.height) / 2)
        let startAngle = startPercent / 100 * .pi * 2 - .pi
        let endAngle = endPercent / 100 * .pi * 2 - .pi
        let path = UIBezierPath()

        path.move(to: center)
        path.addArc(withCenter: center, radius: radius, startAngle: startAngle, endAngle: endAngle, clockwise: true)
        path.close()
        color.setFill()
        path.fill()
    }
}

How can I avoid the invalid context error and draw something in the subview when the ViewController loads?

A: You should be overriding draw, not setNeedsDisplay.
override func draw(_ rect: CGRect) {
    self.backgroundColor = .clear

    drawSlice(rect: rect, startPercent: 87.5, endPercent: 37.5, color: .green)
    drawSlice(rect: rect, startPercent: 37.5, endPercent: 87.5, color: .red)
}

And the setting of the background color only needs to be done once so draw is not really the ideal place for that line. Move it to the init.
setNeedsDisplay is an indication that drawing needs to be updated. But it is draw that does the actual drawing.

A: There are two places to fix.
You are creating a new view , so you need to add to the view of your viewController
 override func viewDidLoad() {
    super.viewDidLoad()

    let mySubViewInstance = SplitCircleView.init(frame: self.view.bounds)
    self.view.addSubview(mySubViewInstance)

  //  mySubViewInstance.setNeedsDisplay(mySubViewInstance.frame)
}

second is to draw function not using setNeedsDisplay();
override func draw(_ rect: CGRect) {

       self.backgroundColor = .clear
    drawSlice(rect: rect, startPercent: 87.5, endPercent: 37.5, color: .green)
    drawSlice(rect: rect, startPercent: 37.5, endPercent: 87.5, color: .red)
}

Thus, you will get your beautiful drawing here.


text: Q: Magento2 Fatal error due to not found interface in indexinterface.php Fatal error: Interface 'Magento\Catalog\Controller\Product\View\ViewInterface' not found in C:\xampp\htdocs\magento2\vendor\magento\module-wishlist\Controller\IndexInterface.php on line 15


text:
Q: node.js doesn't log errors in test environment I have a little node.js/express.js app that I'm running in test environment. I'm just wondering why node.js doesn't log errors.
In development environment I can see errors.
TypeError: Cannot read property 'cardValue' of null

I've added this code but it's not enough.
var express           = require('express'),
    app               = module.exports = express(),
    server            = require('http').Server(app),
    logger            = require('morgan'),
    methodOverride    = require('method-override'),
    bodyParser        = require('body-parser'),
    multer            = require('multer'),
    errorHandler      = require('errorhandler');

process.env.NODE_ENV = process.env.NODE_ENV || 'development';
app.set('port', process.env.PORT || Config.service.port);
app.use(logger('dev'));
app.use(methodOverride());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(multer());
app.use(function (req, res, next) {
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type,Authorization');
    res.setHeader('Access-Control-Allow-Credentials', false);
    next();
});
console.log(process.env.NODE_ENV); // it prints test
if ('development' == app.get('env') || 'test' == app.get('env')) {
  app.use(errorHandler({ log : true}));
}
server.listen(app.get('port'), function(){
    console.log("Ronda.as server listening on port " + app.get('port') + " " + app.get('env'));
});

A: The fine manual states:

log
Provide a function to be called with the error and a string representation of the error.
...
The default value for this option is true unless process.env.NODE_ENV === 'test'

In other words, the default for errorhandler is to not log anything when $NODE_ENV equals test.
To fix, use this to force it to log:
app.use(errorHandler({ log : true }));


text:
Q: R data.table sliding window What is the best (fastest) way to implement a sliding window function with the data.table package?
I'm trying to calculate a rolling median but have multiple rows per date (due to 2 additional factors), which I think means that the zoo rollapply function wouldn't work. Here is an example using a naive for loop:
library(data.table)
df <- data.frame(
  id=30000,
  date=rep(as.IDate(as.IDate("2012-01-01")+0:29, origin="1970-01-01"), each=1000),
  factor1=rep(1:5, each=200),
  factor2=1:5,
  value=rnorm(30, 100, 10)
)

dt = data.table(df)
setkeyv(dt, c("date", "factor1", "factor2"))

get_window <- function(date, factor1, factor2) {
  criteria <- data.table(
    date=as.IDate((date - 7):(date - 1), origin="1970-01-01"),
    factor1=as.integer(factor1),
    factor2=as.integer(factor2)
  )
  return(dt[criteria][, value])
}

output <- data.table(unique(dt[, list(date, factor1, factor2)]))[, window_median:=as.numeric(NA)]

for(i in nrow(output):1) {
  print(i)
  output[i, window_median:=median(get_window(date, factor1, factor2))]
}

A: data.table doesn't have any special features for rolling windows, currently. Further detail here in my answer to another similar question here :
Is there a fast way to run a rolling regression inside data.table?
Rolling median is interesting. It would need a specialized function to do efficiently (same link as in earlier comment) :
Rolling median algorithm in C
The data.table solutions in the question and answers here are all very inefficient, relative to a proper specialized rollingmedian function (which isn't available for R afaik).

A: I managed to get the example down to 1.4s by creating a lagged dataset and doing a huge join.
df <- data.frame(
  id=30000,
  date=rep(as.IDate(as.IDate("2012-01-01")+0:29, origin="1970-01-01"), each=1000),
  factor1=rep(1:5, each=200),
  factor2=1:5,
  value=rnorm(30, 100, 10)
)

dt2 <- data.table(df)
setkeyv(dt, c("date", "factor1", "factor2"))

unique_set <-  data.table(unique(dt[, list(original_date=date, factor1, factor2)]))
output2 <- data.table()
for(i in 1:7) {
  output2 <- rbind(output2, unique_set[, date:=original_date-i])
}

setkeyv(output2, c("date", "factor1", "factor2"))
output2 <- output2[dt]
output2 <- output2[, median(value), by=c("original_date", "factor1", "factor2")]

That works pretty well on this test dataset but on my real one it fails with 8GB of RAM. I'm going to try moving up to one of the High Memory EC2 instance (with 17, 34 or 68GB RAM) to get it working. Any ideas on how to do this in a less memory intensive way would be appreciated

A: This solution works but it takes a while.
df <- data.frame(
  id=30000,
  date=rep(seq.Date(from=as.Date("2012-01-01"),to=as.Date("2012-01-30"),by="d"),each=1000),
  factor1=rep(1:5, each=200),
  factor2=1:5,
  value=rnorm(30, 100, 10)
)

myFun <- function(dff,df){
    median(df$value[df$date>as.Date(dff[2])-8 & df$date<as.Date(dff[2])-1 & df$factor1==dff[3] & df$factor2==dff[4]])
}

week_Med <- apply(df,1,myFun,df=df)

week_Med_df <- cbind(df,week_Med)

A: I address this in a related thread: https://stackoverflow.com/a/62399700/7115566
I suggest looking into the frollapply function. For instance, see below
library(data.table)
set.seed(17)
dt <- data.table(i = 1:100,
             x = sample(1:10, 100, replace = T),
             y = sample(1:10, 100, replace = T))
dt$index <- dt$x == dt$y
dt[,`:=` (MA = frollapply(index,10,mean)), ]
head(dt,12)


text:
Q: Matlab convert patch values to vertex value I have n (2|3|4) adjacent patches sharing a vertex. Each patch is characterized by its normal vector (ok not normalized) and a scalar.
I would like to determine at the common vertex a vector (direction and magnitude) representative of the ones at the adjoining patches.
Is there a simple/elegant way to perform this operation (averaging the normalized vectors and scalars) to get a vertex value?
Ultimately, I am prepping data for Paraview (vtk file).


text:
Q: Do Java Executors run in a daemon thread? I had a short java program that created a single thread scheduled executor and I scheduled a task.
ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();

scheduledExecutorService.schedule(cloudWatchReporter, accumulateForMillis, TimeUnit.MILLISECONDS);

Before the scheduled time arrived, my main thread ended and the JVM exited.  I had expected that it would wait for the timer to complete and the scheduled task to execute before shutting down.  This is not what happened.  If I added a sufficient sleep just before my main thread ended  my task would then execute before the JVM shut down.
Do Executors have a master thread that manages the timer?  Or is the timer effect achieved in some other way?  If managed by some master thread, is it a daemon thread or a non-daemon thread?

A: This simple complete example contradicts what you're claiming in your question:
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

class Test {

    public static void main(String[] args) {
        ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
        scheduledExecutorService.schedule(() -> System.out.println("hello"), 10, TimeUnit.SECONDS);
    }
}

Run it, and you'll see that not only the message is printed after 10 seconds, but the program doesn't exit. So your main thread didn't simply end. You probably call System.exit().


text:
Q: How to synchronize Oracle data with SQL Server An Oracle11g database on one machine with unique IP, and a SQL Server 2008 database on another machine.
A table X in Oracle has some columns, same as the columns of table Y in SQL Server.
Now I want to synchronize the column's values in X with the column's values in Y, that is (maybe it is wordy!), when values changed in X, so it is IMMEDIATELY and automatically to update the values in Y without any more manual operation in SQL Server.
How to get this done!?
THANKS!!

A: You can link the two databases either via an Oracle Gateway and a database link in the Oracle database or via a Linked Server in SQL Server instance.
If you really want to have two exact copies of the table one in each database, rather than storing it in one location and accessing it directly from both databases, and updates must be immediate (ish because immediate is really only available in the one table scenario) then you'll need to use a trigger to update the other table via the link.


text:
Q: Cannot read properties of undefined (reading 'navigation') Unhandled Runtime Error
TypeError: Cannot read properties of undefined (reading 'navigation')
onSwiper={(swiper) => {
            setTimeout(() => {
              swiper.params.navigation.prevEl = navigationPrevRef.current;
              swiper.params.navigation.nextEl = navigationNextRef.current;
              swiper.navigation.destroy();
              swiper.navigation.init();
              swiper.navigation.update();
            });
          }

A: This error means that swiper or swiper.params is undefined and navigation cannot be read from it.
You can check it by adding a console.log(swiper) and console.log(swiper.params) before the setTimeout.

A: Add A If Condition
it worked for me
setTimeout(() => {
            // Override prevEl & nextEl now that refs are defined
            if (swiper.params) {
              swiper.params.navigation.prevEl = navigationPrevRef.current;
              swiper.params.navigation.nextEl = navigationNextRef.current;

              // Re-init navigation
              swiper.navigation.destroy();
              swiper.navigation.init();
              swiper.navigation.update();
            }
          }, 500);


text:
Q: x509 cert with email address in subject are different in java .vs net I have a website with multiple web applications that relies on the end user authenticating with their x509 client certificate. We are observing that the same certificate, when processed by a .Net application, shows a different Subject DN than when processed by a Java application, when the DN contains an e-mail address attribute.
In .Net, I see the server variable CERT_SUBJECT like this:
C=US, S=Delaware, L=Wilmington, O=IDFC Dev, OU=Test, CN=Richard Sand, E=rsand@idfconnect.lan

In Java, when I explore the x509 certificate object for the same cert (same browser session), the subject is:
EMAILADDRESS=rsand@idfconnect.lan, CN=Richard Sand, OU=Test, O=IDFC Dev, L=Wilmington, ST=Delaware, C=US

Ignoring the reversed order of the attributes (which is a known phenomenon), the problem we're having is that in Java the e-mail address attribute is EMAILADDRESS whereas in .Net the same attribute shows as E.
Digging further, OpenSSL shows this output:
openssl.exe pkcs12 -in my.pfx -info

subject=/C=US/ST=Delaware/L=Wilmington/O=IDFC Dev/OU=Test/CN=Richard Sand/emailAddress=rsand@sidfconnect.lan

Whereas when I view the same certificate in either the IE or Firefox certificate stores, they show E=, e.g.:
E = rsand@idfconnect.lan
CN = Richard Sand
OU = Test
O = IDFC Dev
L = Wilmington
S = Delaware
C = US

I know it may seem trivial to just shim in some code to change one "interpretation" of the Subject DN to the other, but the problem is we have two COTS products that we cannot alter, and before we start hacking around the problem I want to understand which (or are both?) correct and if there is something on some layer that is causing the discrepancy. The RFCs all seem to reference EMAILADDRRESS, but as said both IE and FF as well as the .Net app all seem to be using "E"
Can anyone explain why this is happening?
Thanks!

A: E and EMAILADDRESS are synonyms.
When an electronic mail address is embedded in the subject distinguished name (deprecated, should be used subject alternative name extensions) it uses the identifier pkcs-9-at-emailAdress defined in PCKS#9 (RFC2985).
It means the emailAddress is not stored with a string E or EMAILADDRESS,  but as an ASN.1 structure with the identifier 1.2.840.113549.1.9.1, and what .NET, Java or IE are showing is a representation of this attribute.
If you want to check if the subject of a certificate  match, you need to compare each RDN field, not the string.


text:
Q: "www.mydomain.com" reachable, "subdomain.mydomain.com" is not I have an Amazon EC2 Debian instance running NGINX.
I can reach "www.mydomain.com" just fine.
however, despite modifying the web server (NGINX) configuration to support "subdomain.mydomain.com" -- it's unreachable from outside.
I try to curl (of course I'm replacing my real subdomain with "subdomain.mydomain.com" in the output)
curl -v subdomain.mydomain.com

output:
* Rebuilt URL to: subdomain.mydomain.com/
* Hostname was NOT found in DNS cache
*   Trying 92.242.140.21...
* Connected to subdomain.mydomain.com (92.242.140.21) port 80 (#0)
> GET / HTTP/1.1
> User-Agent: curl/7.37.1
> Host:subdomain.mydomain.com
> Accept: */*
>
< HTTP/1.1 200 OK
* Server nginx/1.0.15 is not blacklisted
< Server: nginx/1.0.15
< Date: Sat, 21 Mar 2015 20:14:28 GMT
< Content-Type: text/html; charset=UTF-8
< Transfer-Encoding: chunked
< Connection: close
< Cache-control: no-cache, no-store
< Expires: Thu, 01 Jan 1970 00:00:00 GMT
< Pragma: no-cache
<

From this point I get the verizon FIOS "Sorry we can't find your page"
* Closing connection 0
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><meta http-equiv="refresh" content="0;url=http://searchassist.verizon.com/main?InterceptSource=0&ClientLocation=us&ParticipantID=euekiz39ksg8nwp7iqj2fp5wzfwi5q76&FailureMode=1&SearchQuery=&FailedURI=http%3A%2F%2Fsubdomain.mydomain.com%2F&AddInType=4&Version=2.1.8-1.90base&Referer=&Implementation=0&method=GET"/>

My suspicion is that the "subdomain" domain isn't configured on my Debian DNS. How do I do that? on the virtual machine itself? on EC2 somewhere?

A: If you're hosting your own DNS server, simply add a CNAME Record to your zone file to make your subdomain resolvable, like this:
subdomain             IN      CNAME   mydomain.com.

If your DNS server is hosted by AWS or whatever then use their interface to add the record.

A: Accepted answer is not full. See why here Setup CNAME for subdomain issue
Now shortly, simple DNS map:
somehost.com              A    127.0.0.1
www.somehost.com        CNAME somehost.com
subdomain.somehost.com  CNAME somehost.com
subdomain1.somehost.com   A    127.0.0.1

In that case - www.somehost.com and subdomain.somehost.com would pointing to somehost.com and will server same content, while subdomain1.somehost.com could serve different content on the same host with "virtual server" feature, if they is supported by server.


text:
Q: Simple Snippet to read and show content from file I am looking for a simple solution to add a Snippet in my index.php file to load and display the content shown in a file from an other Domain.
Plan was to add the Code to the 'Footer' before  to show a floating ad on several of my websites.
Sourcesite: http://domainX.tld/floating/floater.txt
Content of file: little bit css for styling of the ad + script snippet for a close button + html to get it into shape.
Target Site gets a simple snippet to show content from txt file as its own content.
I have tried by now
<?php
    $StrLessDescription = ("//domainX.tld/floating/floater.txt");
    $file_contents = file_get_contents($StrLessDescription);
?>

Site loads but doen't shows anything of my code.
<?php
    $handle = fopen("//domainX.tld/floating/floater.txt", "rb");
    $delimiter = ",";
    while (!feof($handle) ) {
        $line = fgets($handle);
        $data = explode($delimiter, $line);
        foreach($data as $v) {
            echo $v;
        }
    }
    fclose($handle);
?>

Site wouldn't even load.
<?php
    $f = fopen("//domain.tld/floating/floatr.txt", "r");
    // Read line by line until end of file
    while(!feof($f)) {
        echo fgets($f) . "<br />";
    }
    fclose($f);
?>

Creates an endless amount of  where my Code should be
Other Fails i have deleted already.
Once i had a simple snippet that had done the trick, does one have any idea how to accomplish that again?

A: This should do the trick:
<?php
echo file_get_contents('//domain.tld/floating/floatr.txt');

A: Sticking to the straightest way to do it as your intention is and supposing that:

*

*URL you provide for the txt file is correct

*you have read access to it

*the file has contents to display

*your PHP version is (PHP 4 >= 4.3.0, PHP 5, PHP 7) to support
the file_get_contents() function

You are missing in your first approach to echo the contents of your variable $StrLessDescription to send it to output.
<?php

    $StrLessDescription = ("//domainX.tld/floating/floater.txt");
    $file_contents = file_get_contents($StrLessDescription);
    echo $file_contents;

?>

Remember that for large projects you could consider using a framework to achieve the same goal in a more organized way. This is a solution to a quick-and-dirty approach you inquiry.


text:
Q: Equivalent in English when you ask for something back How do you say when...You lent some money and are asking it back...
In portuguese we can say "Adriano está me cobrando os 10 dollars."
But I am not sure if I can say this in English "Adriano is charging me."
I would like to know if there is an equivalent expression to be used as the example.

A: We generally put the emphasis on the one who was lent the money, that is, the one who owes:
"I owe Andriano 10 dollars". One could also say, "Andriano expects 10 dollars from me." - but it may be helpful (or necessary, depending on context) to put it this way: "Andriano expects 10 dollars back from me," which is a perfectly comfortable way of implying the money was lent and is expected to be returned/paid.


text:
Q: Get twitter user username or id from twitter url I only have the twitter url of person  like http://twitter.com/#!/tomcruise
I am using an Wrapper class around the Twitter API for PHP where a function userTimeline(user recent tweets etc) can be retrevied only by its id or username, but I have only the url.  Is there anything where I can retreive the username or id ?
I am using this wrapper class  for twitter api

A: You're going to have to use regex to extract the username from the URL. Even if you were to pass that URL to some service that would extract the username for your, the chances are it would just use regex.
Here's a regex that will match the username from a twitter URL (with or without hashbang)
(?<=/)([\w]+?)$

I'm not really conversed with the Twitter API but I think you can use the users/lookup API call to get an ID from a username.
Hopefully that should be everything you need to get what you want done.


text:
Q: js/clear throws an error when called from repl I am using reagent and am connected to the browser using weasel (tenzing template using boot). In my browser (chrome) console I am able to call clear() and it works.
However when I type (js/clear) in my cider repl, it throws an error -
ReferenceError: clear is not defined
I am however able to run (js/alert "Hello") without any problems. Any ideas what is wrong ?

A: When you're typing clear() into the console you're not using the Console API, but the Command Line API.
It's not possible to call this function from javascript:

This API complements the Console API, the Command Line API is only
  available from within the console itself.

Note that: Some are available in both. Such as console.dir or console.clear which you can call with (.clear js/console).

A: Try this:
(.clear js/console)
(.log js/console "asdasd")

Worked in my Figwheel REPL. You should try Figwheel, btw: https://github.com/bhauman/lein-figwheel
In case you ask "why" but not "how", this question should clear the situation: clear javascript console in Google Chrome


text:
Q: Reading data from a file in vertical "blocks" in C++ Let me first show you the structure of the data I'm reading (it will be hard to convey what I want otherwise):
 Mode:                 1                      2                      3
 Frequency:      -307.68                  57.11                  82.39
 Force Cnst:      0.6182                 0.0089                 0.0283
 Red. Mass:      11.0830                 4.6138                 7.0866
 IR Active:          YES                    YES                    YES
 IR Intens:       17.343                  7.786                  0.017
 Raman Active:       YES                    YES                    YES
               X      Y      Z        X      Y      Z        X      Y      Z
 H         -0.093 -0.046 -0.050    0.002 -0.268  0.324   -0.084 -0.209  0.128
 C         -0.072 -0.019 -0.063    0.003 -0.159  0.195   -0.048 -0.148  0.087
 C         -0.001 -0.046 -0.072    0.007 -0.001  0.001   -0.001 -0.229  0.139
 H         -0.001 -0.120 -0.089    0.006 -0.001  0.001   -0.001 -0.345  0.213
 C          0.073 -0.023 -0.057    0.003  0.158 -0.194    0.047 -0.151  0.090
 H          0.096 -0.052 -0.043    0.002  0.266 -0.322    0.083 -0.214  0.134
 ............................................................................

So, I want to store the data for each Mode under its own struct object (nmode), and store each nmode in a vector. However, as you can see, the data for each Mode is output in this vertical formatting (I cannot change the format of this file).
Currently, my workaround solution has been to tell the program to get the data for three Modes at once, using ifstream as normal (I'll post an example of this below). This solution breaks on any number of Modes not divisible by 3, for obvious reasons. My question is therefore "what is the best way for me to have the program read this data from these vertical blocks for an arbitrary number of Modes?"
Here is the current solution (that breaks if the number of Modes is not divisible by 3), as well as a case on which it breaks:
ifstream ifile
nmode mode_1;
nmode mode_2;
nmode mode_3;
std::cout << "Getting normal mode numbers..." << std::endl;

ifile >> mode_1.mode;
ifile >> mode_2.mode;
ifile >> mode_3.mode;
ifile >> trash;
std::cout << "Getting normal mode frequencies..." << std::endl;
ifile >> mode_1.freq;
ifile >> mode_2.freq;
ifile >> mode_3.freq;

etc.

EXAMPLE THAT BREAKS ABOVE CODE

 Mode:                 1
 Frequency:      2670.34
 Force Cnst:     58.8309
 Red. Mass:      14.0031
 IR Active:          YES
 IR Intens:        0.000
 Raman Active:       YES
               X      Y      Z        X      Y      Z        X      Y      Z
 N         -0.000 -0.000 -0.707
 N          0.000  0.000  0.707

A: Unfortunately there is no quick answer.
You really need to parse line by line . . .
This will result in a lot of code. YOuld be optimzed by writing functions to parse similar line. But le's go with the full approach here:
Please see:
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
#include <iomanip>
using namespace std::string_literals;

// Definition of data structures
struct XYZ {
    char Indicator{};
    double x{};
    double y{};
    double z{};
};

struct Data {
    std::size_t ID{};
    double frequency{};
    double forceCnst{};
    double redMass{};
    bool irActive{};
    double irIntensity{};
    bool ramanActive{};
    std::vector<XYZ> xyz{};
};
// Function to read data in given format
std::vector<Data> readData(std::istream& is) {

    bool parsingOKsoFar{true};

    // Here we will store the resuting values
    std::vector<Data> data{};

    // First read the modes -------------------------------------------------------
    if (std::string id{}; std::getline(is>>std::ws, id, ':') and (id == "Mode"s)) {

        // Read the rest of the first line to get information about number of modes
        std::string line{}; std::getline(is, line);
        std::istringstream iss{ line };

        // Read and with that count the number of modes
        std::vector<std::size_t> modeIDs{};
        for (size_t m; iss >> m; modeIDs.push_back(m))
            ;
        // Now, we know the number of Modes. Resize the resulting vector accordingly
        data.resize(modeIDs.size());

        // Copy mode IDs into structs
        for (std::size_t i{}; i < data.size(); ++i)
            data[i].ID = modeIDs[i];
    }
    else {
        std::cerr << "\n*** Error: Mode could not be read\n\n";
        parsingOKsoFar = false;
    }

    // Now read frequencies -------------------------------------------------------
    if (std::string id{}; parsingOKsoFar and std::getline(is >> std::ws, id, ':') and (id == "Frequency"s)) {

        // Read the rest of the line to get information about frequencies
        std::string line{}; std::getline(is, line);
        std::istringstream iss{ line };

        // Read the values
        std::vector<double> frequency{};
        for (double f{}; iss >> f; frequency.push_back(f));

        // Sanity check
        if (frequency.size() == data.size())

            // Copy into structs
            for (std::size_t i{}; i < data.size(); ++i)
                data[i].frequency = frequency[i];
        else {
            std::cerr << "\n***Error: Mismatch in number of frequencies and modes\n\n";
            parsingOKsoFar = false;
        }
    }
    else {
        std::cerr << "\n*** Error: Frequency could not be read\n\n";
        parsingOKsoFar = false;
    }

    // Now read force constants -------------------------------------------------------
    if (std::string id{}; parsingOKsoFar and std::getline(is >> std::ws, id, ':') and (id == "Force Cnst"s)) {

        // Read the rest of the line to get information about frequencies
        std::string line{}; std::getline(is, line);
        std::istringstream iss{ line };

        // Read the values
        std::vector<double> forceConst{};
        for (double f{}; iss >> f; forceConst.push_back(f));

        // Sanity check
        if (forceConst.size() == data.size())

            // Copy into structs
            for (std::size_t i{}; i < data.size(); ++i)
                data[i].forceCnst = forceConst[i];
        else {
            std::cerr << "\n***Error: Mismatch in number of force constant and modes\n\n";
            parsingOKsoFar = false;
        }
    }
    else {
        std::cerr << "\n*** Error: Force Constant could not be read\n\n";
        parsingOKsoFar = false;
    }

    // Now read red mass -------------------------------------------------------
    if (std::string id{}; parsingOKsoFar and std::getline(is >> std::ws, id, ':') and (id == "Red. Mass"s)) {

        // Read the rest of the line to get information about frequencies
        std::string line{}; std::getline(is, line);
        std::istringstream iss{ line };

        // Read the values
        std::vector<double> redMass{};
        for (double rm{}; iss >> rm; redMass.push_back(rm));

        // Sanity check
        if (redMass.size() == data.size())

            // Copy into structs
            for (std::size_t i{}; i < data.size(); ++i)
                data[i].redMass = redMass[i];
        else {
            std::cerr << "\n***Error: Mismatch in number of Red Rass and modes\n\n";
            parsingOKsoFar = false;
        }
    }
    else {
        std::cerr << "\n*** Error: Red Mass could not be read\n\n";
        parsingOKsoFar = false;
    }

    // Now read IR Active -------------------------------------------------------
    if (std::string id{}; parsingOKsoFar and std::getline(is >> std::ws, id, ':') and (id == "IR Active"s)) {

        // Read the rest of the line to get information about frequencies
        std::string line{}; std::getline(is, line);
        std::istringstream iss{ line };

        // Read the values
        std::vector<std::string> irActive{};
        for (std::string ira{}; iss >> ira; irActive.push_back(ira));

        // Sanity check
        if (irActive.size() == data.size())

            // Copy into structs
            for (std::size_t i{}; i < data.size(); ++i)
                data[i].irActive = (irActive[i]=="YES"s) ? true : false;
        else {
            std::cerr << "\n***Error: Mismatch in number of IR Active and modes\n\n";
            parsingOKsoFar = false;
        }
    }
    else {
        std::cerr << "\n*** Error: IR Active could not be read\n\n";
        parsingOKsoFar = false;
    }

    // Now read IR Intensity -------------------------------------------------------
    if (std::string id{}; parsingOKsoFar and std::getline(is >> std::ws, id, ':') and (id == "IR Intens"s)) {

        // Read the rest of the line to get information about frequencies
        std::string line{}; std::getline(is, line);
        std::istringstream iss{ line };

        // Read the values
        std::vector<double> irIntens{};
        for (double irt{}; iss >> irt; irIntens.push_back(irt));

        // Sanity check
        if (irIntens.size() == data.size())

            // Copy into structs
            for (std::size_t i{}; i < data.size(); ++i)
                data[i].irIntensity = irIntens[i];
        else {
            std::cerr << "\n***Error: Mismatch in number of IR intensity and modes\n\n";
            parsingOKsoFar = false;
        }
    }
    else {
        std::cerr << "\n*** Error: IR intensity could not be read\n\n";
        parsingOKsoFar = false;
    }

    // Now read Raman Active -------------------------------------------------------
    if (std::string id{}; parsingOKsoFar and std::getline(is >> std::ws, id, ':') and (id == "Raman Active"s)) {

        // Read the rest of the line to get information about frequencies
        std::string line{}; std::getline(is, line);
        std::istringstream iss{ line };

        // Read the values
        std::vector<std::string> ramanActive{};
        for (std::string ra{}; iss >> ra; ramanActive.push_back(ra));

        // Sanity check
        if (ramanActive.size() == data.size())

            // Copy into structs
            for (std::size_t i{}; i < data.size(); ++i)
                data[i].ramanActive = (ramanActive[i] == "YES"s) ? true : false;
        else {
            std::cerr << "\n***Error: Mismatch in number of Raman Active and modes\n\n";
            parsingOKsoFar = false;
        }
    }
    else {
        std::cerr << "\n*** Error: Raman Active could not be read\n\n";
        parsingOKsoFar = false;
    }

    // Now read XYZ header line and throw away -------------------------------------------------------
    if (parsingOKsoFar) {
        std::string line{};
        parsingOKsoFar = !!std::getline(is, line);
    }
    // Read xyz data-------------------------------------------------------
    // Read all lines until we find a "....." pattern

    for (std::string line{}; parsingOKsoFar and std::getline(is, line) and (line.substr(0, 5) != "....."s);) {

        // End condition for reading the file
        if (line.substr(1, 5) == "....."s) break;

        std::istringstream iss(line);
        // First read indicator
        if (char indicator{}; iss >> indicator) {

            std::vector<XYZ> xyz{};
            for (XYZ tmp{}; iss >> tmp.x >> tmp.y >> tmp.z; xyz.push_back(tmp));

            // Sanity check
            if (xyz.size() == data.size()) {
                // Copy into structs
                for (std::size_t i{}; i < data.size(); ++i)
                    data[i].xyz.push_back({ indicator, xyz[i].x, xyz[i].y,xyz[i].z });
            }
            else {
                std::cerr << "\n***Error: Mismatch in number of xyz and modes\n\n";
                parsingOKsoFar = false;
            }
        }
        else
            std::cerr << "\n***Error: Could not read XYZ\n\n";
    }
    return data;
}

int main() {
    if (std::ifstream ifs{ "r:\\data.txt" }; ifs) {
        std::vector data = readData(ifs);
        for (const Data& d : data) {
            std::cout << "\n\n\n----------------------\nMode:\t" << d.ID << "\nFrequency:\t" << d.frequency << "\nForce Cnst:\t" << d.forceCnst
                << "\nRed. Mass:\t" << d.redMass << "\nIR Active:\t" << (d.irActive ? "YES"s : "NO"s)
                << "\nIR Intens:\t" << d.irIntensity << "\nRaman Active:\t" << (d.ramanActive ? "YES"s : "NO"s) << '\n';
            for (const XYZ& xyz : d.xyz)
                std::cout << "\nX:\t\t" << xyz.x << "\nY:\t\t" << xyz.y << "\nZ:\t\t" << xyz.z << '\n';

        }
    }
    else
        std::cerr << "\n***Error: Could not open source file\n\n";
}


text:
Q: bundle format not recognized when I checked out a project from server, and will run it. I met a issue is    :

Code sign error /Users/PanChao/Library/Developer/Xcode/DerivedData/YZTUser-cvcnntqoopwxrtcxdnabdqzxtllp/Build/Products/Debug-iphonesimulator/MWPhotoBrowser.bundle:
  bundle format unrecognized, invalid, or unsuitable Command
  /usr/bin/codesign failed with exit code 1 .

I spend many hours to fix it ,but this error is alway exist! if anyone knows that how to fixed it, please help me thanks .

A: Make sure these following things
1.your bundle ID should be valid.
2.your provisioning profile should be valid.
3.your certificate should work.

A: In your pod project,find the target which goes wrong,and correct the Identity and Signing area by choosing infolist and signing profile.This works fine for me
the result should be like this


text:
Q: Wordpress transients with dynamically generated name as parameter in function hopefully you can help me with this scenario:
I have several queries of different post types inside shortcode function.
Now I´m trying to store those queries with transients.
But those transients need to have a unique name for each page from where the shortcode is called.
$trans_posts_golfcourse_ = 'trans_posts_golfcourse_'.$landingpage;

if( false === ( $$trans_posts_golfcourse_ = get_transient( 'trans_posts_golfcourse_' ) ) ) {

    $args = array (
        'posts_per_page'=> 5,
        'post__in'      => $posts_golfcourse,
        'post_type'     => 'golfcourse',
        'post_status'   => 'publish',
        'cache_results' => false,
    );

    $$trans_posts_golfcourse_ = new WP_Query( $args );

    set_transient( 'trans_posts_golfcourse_', $$trans_posts_golfcourse_, 60*60*4 );
}

The dynamically generated variable name is
$$trans_posts_golfcourse_

But how does this have to look like as a parameter?:
get_transient( 'trans_posts_golfcourse_' )

Thanks in advance!
EDIT: found solution for dynamic variable as parameter
The parameter(string) has to be generated the same way as the variable name:
 get_transient( 'trans_posts_golfcourse_'.$landingpage )

complete code:
$trans_posts_golfcourse_ = 'trans_posts_golfcourse_'.$landingpage;
if( false === ( ${$trans_posts_golfcourse_} = get_transient( 'trans_posts_golfcourse_'.$landingpage ) ) ) {

    $args = array (
        'posts_per_page'=> 5,
        'post__in'      => $posts_golfcourse,
        'post_type'     => 'golfcourse',
        'post_status'   => 'publish',
        'cache_results' => false,
    );

    ${$trans_posts_golfcourse_} = new WP_Query( $args );

    set_transient( 'trans_posts_golfcourse_'.$landingpage, ${$trans_posts_golfcourse_}, 60*60*4 );
}

EDIT: Transient is not reducing queries, although transient seems to be called correctly. Does anybody have an idea?

A: The solution is to put the query and the loop inside a transient.
Two methods are possible:

*

*Inside a function (shortcode f.e.)
    function get_content( $dynamic_var ){
        $transient_time = 60*60*4;
        $transient_name = "transient_name_" . $dynamic_var;

        $content = get_transient( $transient_key );
        if( !empty($content)  ) { return $content; }

        $args = array ('');
        $query = new WP_Query( $args );

        $content = '';
        if( $query->have_posts() ):
            while( $query->have_posts() ) : $query->the_post();
                $content.= 'some_content';
            endwhile; wp_reset_postdata();
        endif;

        set_transient( $transient_name, $content, $transient_time );
        return $content;
    }

*Inside a template
        $transient_time = 60*60*4;
        $transient_name = 'transient_name_' . $page_id;
        // ${$transient_name} > name of variable is dynamically created by
        // the value of variable $transient_name (search for > php variable variables)

        $content = '';
        if( false === ( ${$transient_name} = get_transient( $transient_name ) ) ) {
            $args = array ('');
            $query = new WP_Query( $args );

            $content_inner = '';
            if( $query->have_posts() ):
                while( $query->have_posts() ) : $query->the_post();
                    $content_inner.= 'some_content';
                endwhile; wp_reset_postdata();
            endif;

            set_transient( $content_inner, ${$transient_name}, $transient_time );
        }
        $content.= ${$transient_name};


text:
Q: document scopes with JSDOC I`m having difficult times to documents scopes with JSDOC, anyone can tell what is the right way to document the following code :
(Right now, jsdoc generates all the methods in GLOBAL functions and they should belong to the WorkAreaPlugin )
/**
 * @namespaces Retalix.StoreOfficeClient.Web.Scripts.General.WorkArea
 * @scope WorkAreaPlugin
 */
(function ($, undefined) {

/**
 * Description
 * @constructor
 * @method ctor
 * @param {} options
 * @return
 */
var ctor = function (options) {
    var self = this;
    var _data;
    var _new;
    var _grids = {};

    if (this.setupAjaxCrud) {
        this.setupAjaxCrud();
    }

    $.extend(self,
        {
        /**
         * Sets the data property of the current scope and setups the set_isDirty and the get_isDirty functions if not exist to the data object
         * @method set_data
         * @param {} data
         * @param {} triggerChange
         * @return
         */
        set_data: function (data, triggerChange) {
            _data = data || {};
            if (!_data.set_isDirty) {
                $.setupDirtyFunctions(_data);
            }
            if (triggerChange !== false) {
                self.trigger("dataChanged", [_data, self]);
            }
        }
    });

    this.bind("login", function () {
        var isDirty = self.isDirty();
        if (!isDirty && self.loader && $.isFunction(self.loader.doLoading)) {
            self.reload();
        }
    });
};

StoreOfficeClient.Plugins.Register("workArea", undefined, undefined, ctor);

})(jQuery);

A: Let me preface by pointing out that documenting JavaScript code with jsdoc often boils down to a matter of convention and how you want to present the relationship between JS entities to the people reading the documentation. So the following is one possible answer.
The following would put everything in a single namespace:
/**
 * @namespace Retalix.StoreOfficeClient.Web.Scripts.General.WorkArea.WorkAreaPlugin
 *
 */
(/** @lends Retalix.StoreOfficeClient.Web.Scripts.General.WorkArea.WorkAreaPlugin */ function ($, undefined) {

/**
 * Description
 * @constructor
 * @param {} options
 */
var ctor = function (options) {
    var self = this;
    var _data;
    var _new;
    var _grids = {};

    if (this.setupAjaxCrud) {
        this.setupAjaxCrud();
    }

    $.extend(self,
             /** @lends Retalix.StoreOfficeClient.Web.Scripts.General.WorkArea.WorkAreaPlugin~ctor# */ {
        /**
         * Sets the data property of the current scope and setups the set_isDirty and the get_isDirty functions if not exist to the data object
         * @param {} data
         * @param {} triggerChange
         */
        set_data: function (data, triggerChange) {
            _data = data || {};
            if (!_data.set_isDirty) {
                $.setupDirtyFunctions(_data);
            }
            if (triggerChange !== false) {
                self.trigger("dataChanged", [_data, self]);
            }
        }
    });

    this.bind("login", function () {
        var isDirty = self.isDirty();
        if (!isDirty && self.loader && $.isFunction(self.loader.doLoading)) {
            self.reload();
        }
    });
};

StoreOfficeClient.Plugins.Register("workArea", undefined, undefined, ctor);

})(jQuery);


text:
Q: Want to return to Main Menu in Switch Case Below is my code to calculate age.
I want to show the main menu: Select your choice:... once again when Case 1 is executed.
I was giving break but that is not working.
Here in my console showing Enter your Birth date(DD): again when it completes.
I want to show:Select your choice. Any Idea?
    import java.util.Calendar;
    import java.util.Scanner;

    public class Switch {
        public static void main(String args[])
        {
            System.out.println("Select your choice");
            System.out.println("1. To Calculate your Age");
            System.out.println("2. Calculator");
            System.out.println("3. To Exit");
            boolean exit=false;
            Scanner sc1=new Scanner(System.in);
            int choice=sc1.nextInt();
            do{
                switch(choice)
                {
                case 1:

                    Calendar c1 = Calendar.getInstance();
                    int currDate = c1.get(Calendar.DATE);
                    //System.out.println(currDate);

                    int currMonth = c1.get(Calendar.MONTH)+1;
                    //System.out.println(currMonth);

                    int currYear=c1.get(Calendar.YEAR);
                    //System.out.println(currYear);
                    Scanner sc2=new Scanner(System.in);
                    System.out.println("Enter your Birth date(DD): ");
                    int birthDate=sc2.nextInt();

                    System.out.println("Enter your Birth month(MM): ");
                    int birthMonth=sc2.nextInt();

                    System.out.println("Enter your Birth year(YYYY): ");
                    int birthYear=sc2.nextInt();
                    int calculateDate=0;

                    calculateDate=currDate-birthDate;

                    int calculateMonth=currMonth-birthMonth;
                    int calculateYear=currYear-birthYear;

                    System.out.println("You are : "+ calculateDate+"days "+" "+calculateMonth+"months "+calculateYear+"years OLD");
                    System.out.println("thank you..");
                    System.out.println("\n");
                    break;
            case 2:

                   System.out.println("This is case 2");
                   break;

            case 3:

                    exit=true;
                    break;

            }
        }while(!exit);
    }
}

A: Move your below lines inside do...while as do while is executed atleast once.
        System.out.println("Select your choice");
        System.out.println("1. To Calculate your Age");
        System.out.println("2. Calculator");
        System.out.println("3. To Exit");
        Scanner sc1 = new Scanner(System.in);
        int choice = sc1.nextInt();

SwitchCase.java
import java.util.Calendar;
import java.util.Scanner;

public class SwitchCase {
    public static void main(String args[]) {
        boolean exit = false;
        do {
            System.out.println("Select your choice");
            System.out.println("1. To Calculate your Age");
            System.out.println("2. Calculator");
            System.out.println("3. To Exit");
            Scanner sc1 = new Scanner(System.in);
            int choice = sc1.nextInt();
            switch (choice) {
            case 1:
                Calendar c1 = Calendar.getInstance();
                int currDate = c1.get(Calendar.DATE);
                // System.out.println(currDate);
                int currMonth = c1.get(Calendar.MONTH) + 1;
                // System.out.println(currMonth);
                int currYear = c1.get(Calendar.YEAR);
                // System.out.println(currYear);
                Scanner sc2 = new Scanner(System.in);
                System.out.println("Enter your Birth date(DD): ");
                int birthDate = sc2.nextInt();
                System.out.println("Enter your Birth month(MM): ");
                int birthMonth = sc2.nextInt();
                System.out.println("Enter your Birth year(YYYY): ");
                int birthYear = sc2.nextInt();
                int calculateDate = 0;
                calculateDate = currDate - birthDate;
                int calculateMonth = currMonth - birthMonth;
                int calculateYear = currYear - birthYear;
                System.out.println("You are : " + calculateDate + "days " + " "
                        + calculateMonth + "months " + calculateYear
                        + "years OLD");
                System.out.println("thank you..");
                System.out.println("\n");
                break;
            case 2:
                System.out.println("This is case 2");
                break;
            case 3:
                exit = true;
                break;
            }
        } while (!exit);
    }
}

Sample Run
Select your choice
1. To Calculate your Age
2. Calculator
3. To Exit
1
Enter your Birth date(DD):
1
Enter your Birth month(MM):
1
Enter your Birth year(YYYY):
1920
You are : 14days  6months 97years OLD
thank you..

Select your choice
1. To Calculate your Age
2. Calculator
3. To Exit

A: Just assign "true" to the variable exit when case 1 is executed.

A: You have given option to select the choices outside the loop.The code for selecting the options must be inside loop.
Below is the updated code which may work:
import java.util.Calendar;
import java.util.Scanner;

import java.util.Calendar;
import java.util.Scanner;

public class Switch {
    public static void main(String args[])
    {
        boolean exit;
        do{
                System.out.println("Select your choice");
                System.out.println("1. To Calculate your Age");
                System.out.println("2. Calculator");
                System.out.println("3. To Exit");
                exit=false;
                Scanner sc1=new Scanner(System.in);
                int choice=sc1.nextInt();
                    switch(choice)
                    {
                    case 1:

                        Calendar c1 = Calendar.getInstance();
                        int currDate = c1.get(Calendar.DATE);
                        //System.out.println(currDate);

                        int currMonth = c1.get(Calendar.MONTH)+1;
                        //System.out.println(currMonth);

                        int currYear=c1.get(Calendar.YEAR);
                        //System.out.println(currYear);
                        Scanner sc2=new Scanner(System.in);
                        System.out.println("Enter your Birth date(DD): ");
                        int birthDate=sc2.nextInt();

                        System.out.println("Enter your Birth month(MM): ");
                        int birthMonth=sc2.nextInt();

                        System.out.println("Enter your Birth year(YYYY): ");
                        int birthYear=sc2.nextInt();
                        int calculateDate=0;

                        calculateDate=currDate-birthDate;

                        int calculateMonth=currMonth-birthMonth;
                        int calculateYear=currYear-birthYear;

                        System.out.println("You are : "+ calculateDate+"days "+" "+calculateMonth+"months "+calculateYear+"years OLD");
                        System.out.println("thank you..");
                        System.out.println("\n");
                        break;
                case 2:

                       System.out.println("This is case 2");
                       break;

                case 3:

                        exit=true;
                        break;

                }
            }while(!exit);
    }
}


text:
Q: How to load data without changing the scrolling position? Why does the scroll position change when I prepend data in given data. I scroll to top it prepend data but scroll position goes to top. But I saw lot of example in Facebook and whatsapp in which when it load previous data scroll position remain same.
Can we retain the scroll position ? http://jsfiddle.net/cQ75J/17/
if ($(this).scrollTop() === 0 && pages.length) {
        console.log("up");
        $("#next").html('')
        $("#pre").html('')
        $("#next").html($("#current").html());
        $("#current").html('');

           $("#current").html(pages.pop())
            .prependTo($("#fullContainer"));
    }

A: This has to be done in Javascript:
One way to do this is to use a hidden div of the same height and width as the one you are prepending and measure it's scrollHeight when you add the content to it. Then, after you prepend the text, simply set the content div's scrollTop to the scrollHeight of the hidden div:
$(document).ready(function(){

    setTimeout(function(){

        $("div#hiddenDiv").html("Testing

");

        var coffset = document.getElementById("hiddenDiv").scrollHeight;

        $("div#content").prepend($("div#hiddenDiv").html());
        document.getElementById("content").scrollTop += coffset;

    }, 5000);

});

In the following fiddle, text will be prepended to the div after a few seconds, but the scroll
position will not change.
JSFiddle


text:
Q: How can I add a git tag for a specific jenkins build? I am looking for a way to tag a git changeset from withing Jenkins. I enabled the Jenkins build tagging plugin which allow me to tag builds in jenkins but these are not git-tags, as this seems to me more like a way to rename build in jenkins.
I need a manual git tagging option in Jenkins, not an automatic one.
For automating tagging I am already using the Git Published post-build step, but that's another kind of tagging.

A:
I need a manual git tagging option in Jenkins, not an automatic one.

use this line of code in your script:
git tag -a <tag> -m <message>

This will create annotated tag with the given message attached to the given tag.

-a = annotated tag.
  Annotated tags is a full blob which contains the same information as commit (author, email, date message etc).

A: The Git Publisher plugin for Jenkins might be worth a look:


text:
Q: Building a Multi-Port Server : Java I'm trying to build a Multi-port server with threads. I also have a ClientManager class and a Client class. What needs to happen is the user enters a range of ports...say ports 8000-8010. The Server needs to listen at all of those ports for connections. The ClientManager then gets the range of ports and creates a Client instance for each one. The Client then sends messages to the Server in random intervals between 0-1 seconds. After 100 messages are sent by a client, it should disconnect. The server needs to print out how many messages it has received every 5 seconds.
So far I've managed to get the user inputs for the range of ports and then send them over to the ClientManager via Runtime.exec() parameters. Here's my current code for the Server and ClientManager:
import java.io.*;

public class Server{

    public static void main(String[] args){
        try{
            InputStreamReader isr = new InputStreamReader(System.in);
            BufferedReader userInputReader = new BufferedReader(isr);
            String lowPortRange = null;
            String highPortRange = null;

            System.out.println("Enter low end of port range:");
            if((lowPortRange = userInputReader.readLine())!=null){
                System.out.println("Low Range: " + lowPortRange);
            }
            System.out.println("Enter high end of port range:");

            if((highPortRange = userInputReader.readLine()) != null){
                System.out.println("High Range: " + highPortRange);
            }

            int lowPort = Integer.parseInt(lowPortRange);
            int highPort = Integer.parseInt(highPortRange);
            int totalPorts = highPort - lowPort+1;

            System.out.println("Total ports: " + totalPorts);
            System.out.println("...Port numbers...");

            for(int port = lowPort; port<=highPort; port++){
                System.out.println(port);
            }

            System.out.println("Done!");
            System.out.println();

            Process p = Runtime.getRuntime().exec("java ClientManager " + lowPort + " " + highPort);

            BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
                    String line = null;
                    while ((line = in.readLine()) != null) {
                        System.out.println(line);
                    }
        }catch(IOException e){
            System.out.println("IOException!");
            e.printStackTrace();
        }
    }
}

import java.io.*;

public class ClientManager{
    private int lowPort;
    private int numPorts;

    public static void main(String[] args){
        System.out.println("ClientManager Started.");

        int firstPort = Integer.parseInt(args[0]);
        int lastPort = Integer.parseInt(args[1]);

        System.out.println("First Port: " + firstPort);
        System.out.println("Last Port: " + lastPort);
    }

}

My question is basically this: Could someone explain, theoretically, where I should go from here?

A: You need to create one ServerSocket for every port you're listening on. Because accept() blocks until a client connects, you'll need to create one thread to listen on each ServerSocket. If more than one client may be connected to a given port at the same time (doesn't seem that way from your description), you'll also have to create one thread for every client connection. And one more to print and zero the message count every 5 seconds – this might as well be the main thread.
Of course, access to the message count will have to be properly synchronised, and the description doesn't mention when the server should shut down if it has to be done gracefully at all.
(Sidenote: not accepting new connections while a client is connected is obviously unacceptable in a "real" server, and one-thread-per-client is not the optimal way to avoid this if you have many clients.)

A: See ThreadPoolExecutor for more Info. It will make your sever robust. And you can structure it to suit your demands. If you have never worked it with Executors, not at all an issue. very simple. You will have to just give it Runnable which you need to process, in this case once you get the connection, then the interaction with client etc. Most of your load will get reduced.


text:
Q: MinGW compiler cannot be recognized in Clion Clion cannot compile C++, because it cannot find it.
I checked it many times and it was exactly where I installed MinGW.
I tried many ways online but it didn't work.

A: Add MinGW to the path of your operating System.


text:
Q: If concurrent queries are made with ON CONFLICT DO UPDATE, will every update take place sequentially? I have a need to insert into a table and ensure that one column is being incremented each time.
My insert looks like:
INSERT INTO my_tbl (id) VALUES ($1)
 ON CONFLICT (id) DO UPDATE SET total = my_tbl + 1 RETURNING *;

(where total = an integer field that defaults to 0)
Assuming I don't have any rollbacks or anything going on, is it safe to assume that multiple executions of this statement with the same parameters at once would be locked and ordered safely such that each execution would return (given the RETURNING * bit) three different values in the total field?
My apologies for the phrasing of this question and its title as I'm not sure how to categorize what I'm trying to do.

A: Yes, you can safely assume that. Concurrent updates to a single row are serialized by FOR UPDATE or FOR NO KEY UPDATE row locks.


text:
Q: Remove weapon effect How can I remove the visual effect of a weapon in Diablo3 Reaper of Souls? I attached a picture of my character with my one hand crossbow with a glowing/flame effect or any other effect like lightning, etc.  How do I remove the effect on that weapon?
I tried transmogrification on the original weapon that had the effect and chose a different look but the effect seem to have stayed. I am playing on a PS4.

A: If you use the Mystic to Transmogrify the look, you'll get a different looking weapon but the same holy glow.
If you use the Mystic to Enchant the '+x-y to holy damage' on to be some other stat, the glow will change or go away, depending on the stat. If you want to use the weapon, you'll likely want the plain '+x-y damage' stat, though that may not improve the overall weapon damage as much as if you modify another stat.

A: It is part of the graphic for that weapon, so there is no way to remove it. Turning down the graphics for the game all the way to Low everywhere might tone it down a little bit, but I still have my doubts. Doing that would also make your game look like Duck Hunt.
The only way to change this would be to change the elemental damage type of the weapon by going to the Mystic and enchanting it to some other damage type. This would result in a different graphic, but may be undesirable because you can only enchant one property and damage may not always be the best choice.


text:
Q: How to escape whitespace when running Rscript from command line? I am currently trying to call Rscript on a file that has white spaces:
Rscript "File Name with White Spaces.R"

and it keeps giving an error that the file could not be found. I have tried to add in escapes, such as
Rscript "File\ Name\ with\ White\ Spaces.R"

all the way up to three escapes, but to no avail. Is there a simple trick to doing this? Thanks.


text:
Q: Java Runtime not Work EXP Oracle db Process p = Runtime.getRuntime().exec("EXP MASTER/MASTER@localhost FILE=C:\\Users\\Administrator\\Desktop\\BKP.DMP STATISTICS=NONE");

        int processComplete = p.waitFor();
        if (processComplete==0) {
            jLabel1.setText("Backup Ok");
        }else{
            jLabel1.setText("Backup not Ok");
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

I used this code, but EXP in task manager not exit this code export the dmp file but not done, the program locking


text:
Q: Sleep for X seconds before posting API - Python I need to post some records to the website. I feel I am done with the complex part - the code itself, now I need to tweak the code so that my account doesn't get blocked when doing the posting - yep, just happened.
#importing libraries
import csv
import json

#changing data type
field_types = [('subject', str),
('description', str),
('email', str)]
output = []

#opening the raw file
with open('file.csv','r',encoding = 'utf-8-sig') as f:
    for row in csv.DictReader(f):
        row.update((key, conversion(row[key]))
        for key, conversion in field_types)
        output.append(row) #appending rows
    with open('tickets.json','w') as outfile: #saving records as json
        json.dump(output,outfile,sort_keys = True, indent = 4)
with open('tickets.json','r')as infile:
    indata = json.load(infile)
output =[]
for data in indata:
    r= requests.post("https://"+ domain +".domain.com/api/", auth = (api_key, password), headers = headers, json=data)
    output.append(json.loads(r.text))
#saving the response code
with open('response.json', 'w') as outfile:
    json.dump(output, outfile, indent = 4)

I searched and found time.sleep(5) but now sure how to use it. Will it go before output.append(json.loads(r.text))?


text:
Q: Unable to download SDK components from android.com Running Windows XP, 32 bit.
I had no problem downloading the installer and android-sdk_r10-windows.zip, but when running the installer, it gets stuck opening
https://dl-ssl.google.com/android/repository.xml
When I try browsing to that URL, I get a 404.
I've read some of the other answers suggested, but most either direct me to the sdk download (already done) or mention some obscure command line approach that doesn't seem relevant to a Windows installation.
Thanks for any help!
Dave

A: First thing to try is to click on the Settings tab and turn on the option to Force https sources to be fetched using http. Then try to refresh the packages.
If that doesn't help are you behind a corporate proxy? If so make sure your proxy server and port are correct in the Settings tab.
If that doesn't work try http://code.google.com/p/android/issues/detail?id=5944#c7 .
And if that doesn't work try Download the Android SDK components for offline install .


text:
Q: Angular.js: URL validation always returns 200 I got a website (Angular.js based) with an online form where users may enter any URL. I would like to instantly check out of the browser, whether the entered domain is valid (=reachable, can be connected to).  I therefore only need the header information (status code), NOT the actual website content. I tried this piece of code, but it keeps returning code 200, no matter what the address is:
$scope.checkURL = function(index){
        if($scope.items[index].address != ""){
            $http({
                method: 'GET',
                url: $scope.items[index].address
                })
                .success(function(data, status, headers, config){
                    if(status){
                        alert('yes!!'+status.toString()); //<--- always getting this!!!!
                    }

                })
                .error(function(data, status, headers, config){
                    if(status){
                        alert('error!!'+status.toString());
                    }
            });
        }
    };

I am aware that I am running into CORS-issues here. I just wanted to ask if:
There is any way to reliably (!) perform this kind of URL-checking out of the browser (again, I just need header/status information, not any actual website content) - preferably using AngularJs.
Unless anyone tells me otherwise, I'd alternatively set up a REST-service on my node.js webserver that I query every time, although I wanted to keep that load away from my server. Any suggestions?


text:
Q: Getting list of values from column in QGIS I have one "column D" with a b c values for my entities (1-2-3-4).
Something like that :
 1. b
 2. c
 3. c
 4. e
 5. j
 6. b

I would like to generate a list of each different value of "column D". so I would have b,c,e,j. How can I perform this?

A: Use the Field Calculator with this expression:
array_to_string(
    array_distinct(
        array_agg(expression:="column D")
        )
    )

This expression utilizes the following functions: array_to_string(), array_distinct(), and array_agg().

A: You can create a virtual layer to fetch the distinct values
Go to the menu Layer > Add Layer > Add/Edit Virtual Layer... and enter the query:
SELECT DISTINCT "column D"
FROM myLayer;

or to get it as a single list
SELECT group_concat(nme, ', ')
FROM (
  SELECT DISTINCT "column D" as nme
  FROM myLayer
)