text:
Q: Local copy of Xcode (Lion) I have old macbooks with Lion. Because these are testing machines for different tasks, many reinstallations happens. Downloading the Xcode from the AppStore every time (2.5GB) is slow. Further complicating matters is the "download size" of Xcode 4.3.6 (the latest Xcode for Lion) is 2.5GB, but the application size in /Applications is 3.5GB - so happens some unpacking or so.. and want ensure than the simple copy of the Xcode.app is safe as I don't want a heavy solution that requires:

*

*time machine

*SuperDuper or command line dd nor any other disk-copy utility

*any other backup strategy - incremnetal or not...

Simpy want to know:

*

*is enough copy the Xcode.app from the /Applications folder to another machine?

*when I just installed the Xcode from the AppStore, is enough copy the Xcode.app to another notebook (same HW, same OS version).

*if not - why - what is the difference in the RESULT (exactly) between copy and installing Xcode from the AppStore.

How can I safely reuse one download for multiple installs?

A: I believe your best option is to use SuperDuper! to make a backup image of each machine with a clean instal of the OS and any software you know will be needed for testing every time. Once you have created the backup image it will make reinstalls much faster and easier.
I have not tried copying the Xcode.app before, but I think you would be missing a lot of preferences and command line tools if all you copied was the app.
EDIT:
If you download Xcode from the App Store and copy that Xcode.app package to another machine without ever launching it, it should work fine. There should be no preference files or app support until after the first time Xcode is launched. From my point of view though, this is not a very useful way of putting test/development machines together though because when I use Xcode I have it set-up a certain way with command line tools installed which would need to be done on each machine when you copy the Xcode.app.


text:
Q: maximum call stack size exceeded jquery cytoscape I am working with cytoscape and jquery with large data. My html code is
<script src="jquery.js"></script>
<script src="jquery.qtip.js"></script>
<script src="cytoscape.js"></script>
<script src="cytoscape-qtip.js"></script>
<script src="my_java_script.js"></script>`

My java script code is
$(function(){ //
var cy = cytoscape({
container: document.getElementById('cy'),
boxSelectionEnabled: false,
autounselectify: true,
style: cytoscape.stylesheet()
.selector('node')
.css({'label': 'data(label)',
'width': '60px','height': '60px',      })
.selector('edge')
.css({'width': '10px','line-color':'#000000'})

.selector("#22").css({"line-color":"red"})
.selector("#44").css({"line-color":"red"})
.selector("#55").css({"line-color":"red"})

I have almost 20000 selectors. Because of such large data I am getting following error in Chrome 70 browser:
Uncaught RangeError: Maximum call stack size exceeded
at k (jquery.js:2)
at Object.fireWith [as resolveWith] (jquery.js:2)
at Function.ready (jquery.js:2)
at HTMLDocument.D (jquery.js:2)

How can I get rid of this ?

A: Consider using classes for your selectors and not unique id's, the way you use them is not the way you are supposed to do that. Especially if the selectors are just a line color, you can always define the selector with a more dynamic option:
style: [
    {
        selector: 'node',
        style: {
            'shape': 'data(faveShape)',
            'content': 'data(DisplayName)',
            'height': 'data(faveHeight)',
            'width': 'data(faveWidth)',
            'background-color': 'data(faveColor)',
            'line-color': 'data(faveLineColor)',
            'font-family': 'data(faceFontFam)',
            'font-size': 'data(faveFontSize)'
       }
    },
    ...

]
And when you add nodes/edges, use the logic from your python code and get the color of the element, after that, just put that variable in the cy.add() and you are good to go:
cy.add({
    data: {
        id: 'yourId',
        ...
        faveLineColor: 'yourLineColor',
        ...

    },
    ...
});

redpajama_set_name: RedPajamaStackExchange


text:
Q: typing module - String Literal Type I'm using the new Python 3.5 module typing and it has been joyous.
I was wondering how one might specify a type based on an exact string literal. For example, a function is guaranteed to return one of the four strings - "North", "West", "East", "South - how can we express that as a specific type variable, instead of just str.
I looked through the documentation, finding the Union type and the TypeVar function, but was unable to find an answer.
An example function expressing this problem:
def compute_quadrant(x: int, y: int) -> str:
    if x > 0 and y > 0:
        return 'I'
    elif x < 0 and y > 0:
        return 'II'
    elif x < 0 and y < 0:
        return 'III'
    elif x > 0 and y < 0:
        return 'IV'

Instead of just returning str, I'd like to to return a more specific type that is one of four values - "I", "II", "III", or "IV".
In Typescript, one can do: type Quadrant = "I" | "II" | "III" | "IV" - is there any nice Python sugar for this use case with the typing module?

A: Disregarding the typing module you asked about, one solution to your problem could be the use of an Enum as supposed in multiple comments. The code for this would look like this:
from enum import Enum

class Quadrant(Enum):
    I = 1
    II = 2
    III = 3
    IV = 4

def compute_quadrant(x: int, y: int) -> Quadrant:
    if x > 0 and y > 0:
        return Quadrant.I
    elif x < 0 and y > 0:
        return Quadrant.II
    elif x < 0 and y < 0:
        return Quadrant.III
    elif x > 0 and y < 0:
        return Quadrant.IV
    # return None  # this is what happens without an else clause!

if __name__ == "__main__":
    quad = compute_quadrant(1, -1)
    print(quad, type(quad))              # -> Quadrant.IV <enum 'Quadrant'>
    print(quad.name, type(quad.name))    # -> IV <class 'str'>
    print(quad.value, type(quad.value))  # -> 4 <class 'int'>

As you can see you can use the Enums name and value. The name is one of the strings you asked for.
One issue I see here is the missing else clause in the function and mypy's current behaviour of accepting None as a valid return value for Quadrant. This should be handled manually.


text:
Q: Electron (Atom-Shell) Run unix command from link in page I am trying to learn Electron (Atom-Shell) but I am finding it pretty tough to find documentation for it...
I am simply trying to figure out how to create a link with  in index.html, and have it open a terminal window or run some sort of program.
I learn languages by learning specific tasks as I need them in a program, so that is why I am asking so then I can utilize the technique used in other ways in my programs.
Thank you for helping.

A: Well, essentially Electron is just a customised version of a Chromium browser that comes packaged with Nodejs and some really cool packages that basically allow you to run the custom browser as if it was a native platform application. Because of that creating an Electron app is very similar to creating a web-app that has a Nodejs back-end.
So to get started with a simple "Hello World!" app, you can just run the following npm...
npm install electron-prebuilt --save-dev

Once the npm is installed you'll need three files to run an Electron app.

*

*A package.json file

*A javascript file (default is main.js)

*An html file   (default is index.html)

See this GitHub repo for a quick copy/paste version of each and more detailed instructions: https://github.com/mafintosh/electron-prebuilt
after that you're ready to simply run your app...
$ electron .

Finally, one way to open a terminal window would be to use an onclick attribute in your html to trigger a child_process, found here, in a function.
That's it! You should be able to edit your html and javascript files as you would for any web-app, and take advantage of the added features that Electron provides.
I'd also check out these resources for more info:
A Quick Start intro to how Electron works -- https://github.com/atom/electron/blob/master/docs/tutorial/quick-start.md
The Atom discussion forum (Because Atom was built with Electron, and is made to be hackable, the community is quite active) -- https://discuss.atom.io/c/electron
A cool repo to keep up with the latest info. It includes links for apps that currently use Electron, tutorials, videos, and more --
https://github.com/sindresorhus/awesome-electron
I hope that helps!


text:
Q: Durrett, probability theory and examples exercise 2.7,5 The problem is as below.
Suppose $EX_i=0$ and $E\exp(\theta X_i)=\infty$ for all $\theta>0$.
Let $S_n=X_1+\dots+X_n$.
Then
$$\frac{1}{n}\log P(S_n \geq na) \rightarrow 0\quad\text{for all}\quad a>0.$$
The solution uses the fact that
$$P(S_n\geq na)\;\geq\; P(S_{n-1}\geq -n\epsilon)\;P(X_n\geq n(a+\epsilon)).$$
This is different from the original large deviation proof, where we use
$$P(S_n \geq na)\;\geq\; P(S_{n-1} \geq (a-a'+\epsilon)n)\;P(X_{n}\in[(a'-\epsilon)n,(a'+\epsilon)n]).$$
The solution says that $Ee^{\theta X}=\infty$ implies $\limsup_{n\rightarrow\infty}\frac{1}{n}\log P(X_n >na)=0.$
How do you prove this and how does the result follows from this fact?

A: Here is an answer to the second part of your question; I will try to find time tomorrow to address the first part.
The equality
$$
\tag{*}
P(S_n\geq na)\;\geq\; P(S_{n-1}\geq -n\epsilon)\;P(X_n\geq n(a+\epsilon))$$
follows from the inclusion
$$
\left\{S_n\geq na\right\}\supset \{S_{n-1}\geq -n\epsilon\}\cap \{X_n\geq n(a+\epsilon)\}
$$
and independence between $S_{n-1}$ and $X_n$. Then applying $\log$ and multiplying by $-1/n$ shows that
$$
0\leqslant -\frac 1n\log P(S_n\geq na)\leqslant -\frac{1}{n}\log P(S_{n-1}\geq -n\epsilon)
-\frac 1n\log P(X_n\geq n(a+\epsilon)).
$$
Since the random variables $X_i$ are centered  and identically distributec, $S_n/(n-1)\to 0$ in probability hence $P(S_{n-1}\geq -n\epsilon)\to 1$. Moreover, $X_n$ has the same distribution as $X_1$ hence it suffices to check that
$$
\frac 1n\log P(X_1\geq n(a+\epsilon))\to 0.
$$

A: For the first part, if the lim sup was $<0$, we could pick $\beta>0$ such that for $n$ large enough
$$
\frac{1}{n}\log P(X_n>na)\le-\beta
$$
Then
$$
\begin{split}
\int e^{\theta x}dF
&\le P(X_i<0)+\sum_{n=0}^\infty\int_{na\le X_i\le (n+1)a}e^{\theta x}dF\\
&\le 1+\sum_{n=0}^{N-1}\int_{na\le X_i\le (n+1)a}e^{\theta x}dF+\sum_{n=N}^\infty\int_{na\le X_i\le (n+1)a}e^{\theta x}dF\\
&\le C+\sum_{n=N}^\infty e^{a(n+1)\theta}\cdot e^{-\beta n}\\
&\le C+\sum_{n=N}^\infty e^{-n(\beta-a\theta)+a\theta}
\end{split}\tag{$*$}
$$
Here $C$ and $N$ are constants. \
We can pick $\theta>0$ so small that
$$
\beta-a\theta>0
$$
and thus the last term  of $(*)$ would converge, which is a contradiction to $Ee^{\theta X_i}=\infty$.


text:
Q: How to group data in PostgreSQL? This PostgreSQL query basically displays a list of data that is older for 12hours.
SELECT * FROM listing_websites
WHERE ( ( NOW() - last_visited ) > INTERVAL '12 hour'  OR last_visited IS NULL )
GROUP BY url,pkey ORDER by pkey ASC

Displayed data will look like these. pkey is the "primary key"
pkey |  url   | last_visited
12   | link1  | 2012-11-08 17:06:49.553515
13   | link2  | 2012-11-07 05:36:55.270243
14   | link1  | 2012-11-09 08:54:33.51958
15   | link3  | 2012-11-03 16:29:17.20889
17   | link1  | 2012-11-08 05:54:33.51958

What I want to achieve is to group the url column for example:
pkey |  url   | last_visited
12   | link1  | 2012-11-08 17:06:49.553515
13   | link2  | 2012-11-07 05:36:55.270243
15   | link3  | 2012-11-03 16:29:17.20889

Thanks in advance whoever can figure this out. I'm still learning postgresql anyway especially in the GROUP BY function. TIA

A: Grouping by the primary key doesn't make sense. Because it is - by definition - unique, you will always get one group per primary key.
Apparently you want to see each url only once. In that case you have to decide which pkey and last_visited value you want to see with that.
The following selects the first last_visited and the lowest pkey value for each unique url value:
select min(pkey), url, min(last_visited)
from listing_websites
where ( ( NOW() - last_visited ) > INTERVAL '12 hour'  OR last_visited IS NULL )
group by url;

It gives the example output, but I'm not sure if that is what you want.
See the SQLFiddle demo here: http://sqlfiddle.com/#!12/2cbf7/1
If you need more columns, you need a different approach (and you should have mentioned that from the beginning):
select *
from (
    select pkey, url, last_visited, url2, url3,
           row_number() over (partition by url order by pkey) as rn
    from listing_websites
    where ( ( NOW() - last_visited ) > INTERVAL '12 hour'  OR last_visited IS NULL )
) t
where rn = 1;

See my updated SQLFiddle example: http://sqlfiddle.com/#!12/6236f/1
Next time please include all requirements in your initial question and don't feed them to us bit by bit.

A: You can use DISTINCT ON:

SELECT DISTINCT ON (url) pkey,url,last_visited FROM listing_websites  WHERE ( ( NOW() - last_visited ) > INTERVAL '12 hour' OR last_visited IS NULL ) ORDER BY url ASC;


text:
Q: Need help making a sticky Nav bar on scroll - using jade and stylus in nodejs/express Here is the code that's in my body section:
header.main-header
  h1 Reshared
  p This site is still under construction.
nav.main-nav
  ul
      li
        a(href="#") About
      li
        a(href="#") Services
      li
        a(href="#") Contact
.main
  h2 This is a Column
  p This is a test

Here is the code in the main.styl file. I would of also added in an image but of what the site looks like now but I cant at the moment because I need 10 reputation points.
@import 'nib'

global-reset()

*
  box-sizing border-box

body
  font-size 16px
  font-family arial, sans-serif

.main-header
  background #f07057
  height 100vh
  position fixed
  width 100%
  top 0
  text-align center
  color #f7f7f7
  display flex
  align-items center
  justify-content center
  flex-direction column

  h1
    font-size 2em

body
  padding-top calc(100vh - 5em)

.main-nav
  background #f7f7f7
  height 80px
  z-index 50
  border-bottom #f07057 5px solid
  text-align center
  display flex
  align-items center
  justify-content center

  li
    display inline

  a
    text-decoration none
    color #111
    font-family arial, sans-serif
    padding 20px
    font-size 20px

.main-nav, .main
   position relative
.main
   background #f2f2e8

From what I have how do I go about making my nav sticky ounce the user scrolls past it.
Here is an image of what the site looks like:

Here is what happens when the user scrolls down. I than want the nav bar to stick to the top when it hits past it.

A: Just adding static: top to the navigation bar should do the trick. Then, you should add a top margin to the main page so no content hides under the navbar.


text:
Q: firebase-admin-python is slow when calling get_user with multiple requests From an endpoint, we are retrieving the user data from firebase using the get_user method from the firebase-admin-python library. The problem is that, when calling the endpoint with high load, the requests to firebase degrade the endpoint's response time.
The application is built on top of Django Rest Framework and deployed on gcloud Kubernetes cluster. We are using gunicorn, eventlet workers.


text:
Q: Sequential Copy and Paste Macro to a reference cell I need some help with a macro.
Currently, I have a macro set up that will produce a form based off of a set of data.
The reference value has to be entered one by one to pull the data.
Does anyone know how to have for example
A2 = sheet("results").range "C3"
activecell.offset(0 1).select
Keep going till no value in cell

I'm trying to have A2 contain the value from the other sheet's row 3 (starting at column C), then run the rest of the script and loop back and then have the A2 value have the next value in line (1st loop would be C3, second loop would be D3, etc) until the cell on the results sheet is empty?
I'm stuck.

A: Welcome to SO, Comie B! Suggest you go this way:
Put the list of reference values in Sheet2, row 3, starting in column C. Have script loop through that row until empty cell is encountered (then break). For each iteration, put the current cell value from row 3 into the cell of your "form" (assuming you don't mean a UserForm but one in a table grid with cell A2 being where your want the reference value be placed and the rest of the form being pulled from other sources.
Sub Test()
    Dim reference_list As Range
    With ThisWorkbook.Sheets("Sheet2")
        Set reference_list = .Range(.Cells(3, 3), .Cells(3, .UsedRange.Columns.Count))
        For Each reference In reference_list
            If reference.Value = "" Then Exit For
            ThisWorkbook.Sheets("Sheet1").Range("A2").Value = reference.Value
            ' do whatever you were going to do with the filled out form
            ' ...
        Next reference
    End With
End Sub

Note that Excel sheets are limited to 16k columns, so if you have more reference values than that, you'd have to switch to putting them in a column instead of a row.


text:
Q: java.lang.IllegalStateException: The content of the adapter has changed but ListView did not receive a notification. Make sure the content of your… The pattern of this crash is kinda weird. sometimes it is okay, but after a while when I try to navigate from one activity to another it happen (for example: from MainActivity to AnotherActivity), but sometimes it doesn't crash. And sometimes it also crashes when I click next page or previous page  option, which display the next 7 or previous 7 contents from the database. Sometimes it gets even weirder that it crashes the moment I run the program.
I already used this function:
@Override
public void onProgressUpdate(Integer... progress) {
     imageAdapter.notifyDataSetChanged();
}

Please, please help is needed the most F1 me please, I'm newbie???
Thank you very much!
LogCat:
11-20 18:34:01.183: E/AndroidRuntime(1746): FATAL EXCEPTION: main
11-20 18:34:01.183: E/AndroidRuntime(1746): java.lang.IllegalStateException: The content of the adapter has changed but ListView did not receive a notification. Make sure the content of your adapter is not modified from a background thread, but only from the UI thread. [in ListView(2131361798, class android.widget.ListView) with Adapter(class com.mysoft.saddis.MainActivity$ImageAdapter)]
11-20 18:34:01.183: E/AndroidRuntime(1746):     at android.widget.ListView.layoutChildren(ListView.java:1545)
11-20 18:34:01.183: E/AndroidRuntime(1746):     at android.widget.AbsListView.onLayout(AbsListView.java:2012)
11-20 18:34:01.183: E/AndroidRuntime(1746):     at android.view.View.layout(View.java:14289)
11-20 18:34:01.183: E/AndroidRuntime(1746):     at android.view.ViewGroup.layout(ViewGroup.java:4562)
11-20 18:34:01.183: E/AndroidRuntime(1746):     at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1671)
11-20 18:34:01.183: E/AndroidRuntime(1746):     at android.widget.LinearLayout.layoutHorizontal(LinearLayout.java:1660)
11-20 18:34:01.183: E/AndroidRuntime(1746):     at android.widget.LinearLayout.onLayout(LinearLayout.java:1436)
11-20 18:34:01.183: E/AndroidRuntime(1746):     at android.view.View.layout(View.java:14289)
11-20 18:34:01.183: E/AndroidRuntime(1746):     at android.view.ViewGroup.layout(ViewGroup.java:4562)
11-20 18:34:01.183: E/AndroidRuntime(1746):     at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1671)
11-20 18:34:01.183: E/AndroidRuntime(1746):     at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1525)
11-20 18:34:01.183: E/AndroidRuntime(1746):     at android.widget.TableLayout.onLayout(TableLayout.java:448)
11-20 18:34:01.183: E/AndroidRuntime(1746):     at android.view.View.layout(View.java:14289)
11-20 18:34:01.183: E/AndroidRuntime(1746):     at android.view.ViewGroup.layout(ViewGroup.java:4562)
11-20 18:34:01.183: E/AndroidRuntime(1746):     at android.widget.FrameLayout.onLayout(FrameLayout.java:448)
11-20 18:34:01.183: E/AndroidRuntime(1746):     at android.view.View.layout(View.java:14289)
11-20 18:34:01.183: E/AndroidRuntime(1746):     at android.view.ViewGroup.layout(ViewGroup.java:4562)
11-20 18:34:01.183: E/AndroidRuntime(1746):     at com.android.internal.widget.ActionBarOverlayLayout.onLayout(ActionBarOverlayLayout.java:349)
11-20 18:34:01.183: E/AndroidRuntime(1746):     at android.view.View.layout(View.java:14289)
11-20 18:34:01.183: E/AndroidRuntime(1746):     at android.view.ViewGroup.layout(ViewGroup.java:4562)
11-20 18:34:01.183: E/AndroidRuntime(1746):     at android.widget.FrameLayout.onLayout(FrameLayout.java:448)
11-20 18:34:01.183: E/AndroidRuntime(1746):     at android.view.View.layout(View.java:14289)
11-20 18:34:01.183: E/AndroidRuntime(1746):     at android.view.ViewGroup.layout(ViewGroup.java:4562)
11-20 18:34:01.183: E/AndroidRuntime(1746):     at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:1976)
11-20 18:34:01.183: E/AndroidRuntime(1746):     at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1730)
11-20 18:34:01.183: E/AndroidRuntime(1746):     at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1004)
11-20 18:34:01.183: E/AndroidRuntime(1746):     at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5481)
11-20 18:34:01.183: E/AndroidRuntime(1746):     at android.view.Choreographer$CallbackRecord.run(Choreographer.java:749)
11-20 18:34:01.183: E/AndroidRuntime(1746):     at android.view.Choreographer.doCallbacks(Choreographer.java:562)
11-20 18:34:01.183: E/AndroidRuntime(1746):     at android.view.Choreographer.doFrame(Choreographer.java:532)
11-20 18:34:01.183: E/AndroidRuntime(1746):     at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:735)
11-20 18:34:01.183: E/AndroidRuntime(1746):     at android.os.Handler.handleCallback(Handler.java:730)
11-20 18:34:01.183: E/AndroidRuntime(1746):     at android.os.Handler.dispatchMessage(Handler.java:92)
11-20 18:34:01.183: E/AndroidRuntime(1746):     at android.os.Looper.loop(Looper.java:137)
11-20 18:34:01.183: E/AndroidRuntime(1746):     at android.app.ActivityThread.main(ActivityThread.java:5103)
11-20 18:34:01.183: E/AndroidRuntime(1746):     at java.lang.reflect.Method.invokeNative(Native Method)
11-20 18:34:01.183: E/AndroidRuntime(1746):     at java.lang.reflect.Method.invoke(Method.java:525)
11-20 18:34:01.183: E/AndroidRuntime(1746):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
11-20 18:34:01.183: E/AndroidRuntime(1746):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
11-20 18:34:01.183: E/AndroidRuntime(1746):     at dalvik.system.NativeStart.main(Native Method)

MainActivity.java
package com.mysoft.saddis;

//all the necessary imports are imported

public class MainActivity extends Activity {

    private ListView lstView;
    private ImageAdapter imageAdapter;

    public int currentPage = 1;
    public int TotalPage = 0;

    public Button btnNext;
    public Button btnPre;

    public boolean orientation;
    boolean verOk = Splash.version;

    public static String urlPageNumHolder;

    public ProgressDialog dialog;

    ArrayList<HashMap<String, Object>> MyArrList = new ArrayList<HashMap<String, Object>>();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);
        getActionBar().setHomeButtonEnabled(true);
        // Bets orientation
        onConfigurationChanged(null);

        // ListView and imageAdapter
        lstView = (ListView) findViewById(R.id.listView1);
        lstView.setClipToPadding(false);
        imageAdapter = new ImageAdapter(getApplicationContext());
        lstView.setAdapter(imageAdapter);

        // Next
        btnNext = (Button) findViewById(R.id.btnNext);
        // Perform action on click
        btnNext.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                currentPage = currentPage + 1;
                ShowData();
            }
        });

        // Previous
        btnPre = (Button) findViewById(R.id.btnPre);
        // Perform action on click
        btnPre.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                currentPage = currentPage - 1;
                ShowData();
            }
        });

        // Show first load
        ShowData();

        // OnClick
        lstView.setOnItemClickListener(new OnItemClickListener() {
            @SuppressLint("NewApi")
            public void onItemClick(AdapterView<?> parent, View v,
                    int position, long id) {
                loadPage(position);

                if(verOk==true){
                    Intent subActivity = new Intent(MainActivity.this,
                            Webber.class);

                    Bundle translateBundle = ActivityOptions
                            .makeCustomAnimation(MainActivity.this,
                                    R.anim.slide_in_left, R.anim.slide_out_left)
                            .toBundle();
                    startActivity(subActivity, translateBundle);
                } else{
                    Intent subActivity = new Intent("com.mysoft.saddis.WEBBER");
                    startActivity(subActivity);
                }

            }
        });

        Log.i(TAG, "onCreate");

    }

    public void ShowData() {
        btnNext.setEnabled(false);
        btnPre.setEnabled(false);

        new LoadContentFromServer().execute();

        if (orientation == false)
            dialog = ProgressDialog
                    .show(this, "ዜና", "ትንሽ ይታገሱ...", true, false);
        else
            dialog = ProgressDialog.show(this, "News", "Loading...", true,
                    false);

    }

    public void loadPage(int position) {

        // Hold Detail's URL
        urlPageNumHolder = MyArrList.get(position).get("id").toString();

    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        Configuration c = getResources().getConfiguration();

        if (c.orientation == Configuration.ORIENTATION_PORTRAIT) {
            orientation = true; // portrait

        } else if (c.orientation == Configuration.ORIENTATION_LANDSCAPE) {
            orientation = false; // landscape

        }
    }

    class LoadContentFromServer extends AsyncTask<Object, Integer, Object> {

        @Override
        protected Object doInBackground(Object... params) {

            String url = "http://10.0.2.2/android/saddis/mobile/news/getNews.php";

            JSONArray data;
            try {
                data = new JSONArray(getJSONUrl(url));

                MyArrList = new ArrayList<HashMap<String, Object>>();
                HashMap<String, Object> map;

                int displayPerPage = 7; // Per Page
                int TotalRows = data.length();
                int indexRowStart = ((displayPerPage * currentPage) - displayPerPage);

                if (TotalRows <= displayPerPage) {
                    TotalPage = 1;
                } else if ((TotalRows % displayPerPage) == 0) {
                    TotalPage = (TotalRows / displayPerPage);
                } else {
                    TotalPage = (TotalRows / displayPerPage) + 1;
                    TotalPage = (int) TotalPage;
                }
                int indexRowEnd = displayPerPage * currentPage;
                if (indexRowEnd > TotalRows) {
                    indexRowEnd = TotalRows;
                }

                String imgPath;

                for (int i = indexRowStart; i < indexRowEnd; i++) {
                    JSONObject c = data.getJSONObject(i);
                    map = new HashMap<String, Object>();
                    map.put("id", (String) c.getString("id"));
                    map.put("title_en", (String) c.getString("title_en"));
                    map.put("description_en", (String) c.getString("description_en"));

                    map.put("title_am", (String) c.getString("title_am"));
                    map.put("description_am", (String) c.getString("description_am"));

                    map.put("posteddate", (String) c.getString("posteddate"));

                    // Thumbnail Get ImageBitmap To Object
                    imgPath = "http://10.0.2.2/android/saddis/addis_img_gallery/news_thumb_"+c.getString("id")+".png";
                    map.put("imagepath", imgPath);
                    Bitmap newBitmap = loadBitmap(imgPath);
                    map.put("ImagePathBitmap", newBitmap);

                    MyArrList.add(map);

                    publishProgress(i);

                }

            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            return null;
        }

        @Override
        public void onProgressUpdate(Integer... progress) {
            imageAdapter.notifyDataSetChanged();
        }

        @Override
        protected void onPostExecute(Object result) {

            // Disabled Button Next
            if (currentPage >= TotalPage) {
                btnNext.setEnabled(false);
            } else {
                btnNext.setEnabled(true);
            }

            // Disabled Button Previous
            if (currentPage <= 1) {
                btnPre.setEnabled(false);
            } else {
                btnPre.setEnabled(true);
            }

            // dismiss the progress dialog
            if (dialog != null)
                dialog.dismiss();
        }
    }

    class ImageAdapter extends BaseAdapter {

        private Context mContext;

        public ImageAdapter(Context context) {
            mContext = context;
        }

        public int getCount() {
            return MyArrList.size();
        }

        public Object getItem(int position) {
            return MyArrList.get(position);
        }

        public long getItemId(int position) {
            return position;
        }

        public View getView(int position, View convertView, ViewGroup parent) {
            // TODO Auto-generated method stub

            LayoutInflater inflater = (LayoutInflater) mContext
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

            if (convertView == null) {
                convertView = inflater.inflate(R.layout.activity_column, null);
            }

            // ImagePath
            ImageView imageView = (ImageView) convertView
                    .findViewById(R.id.ColImagePath);
            imageView.getLayoutParams().height = 150;
            imageView.getLayoutParams().width = 150;
            imageView.setPadding(5, 5, 5, 5);
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            try {
                imageView.setImageBitmap((Bitmap) MyArrList.get(position).get(
                        "ImagePathBitmap"));
            } catch (Exception e) {
                imageView
                        .setImageResource(android.R.drawable.ic_menu_report_image);
            }

            //String qen = simpleDateFormat.format(MyArrList.get(position).get("posteddate"));

            // ID, Title, Desc and DateTime
            TextView txtTitle = (TextView) convertView
                    .findViewById(R.id.title);
            txtTitle.setPadding(10, 0, 0, 0);
            TextView txtDesc = (TextView) convertView
                    .findViewById(R.id.description);
            txtDesc.setPadding(10, 0, 0, 0);
            TextView txtDateTime = (TextView) convertView.findViewById(R.id.dateTime);
            //txtDateTime.setText(MyArrList.get(position).get("posteddate").toString());
            txtDateTime.setText(MyArrList.get(position).get("posteddate").toString());

            if (orientation == false) {
                txtTitle.setText(MyArrList.get(position).get("title_am").toString());
                txtDesc.setText(MyArrList.get(position).get("description_am")
                    .toString());
            }
            else{
                txtTitle.setText(MyArrList.get(position).get("title_en").toString());
                txtDesc.setText(MyArrList.get(position).get("description_en")
                        .toString());
            }

            return convertView;

        }

    }

    /*** Get JSON Code from URL ***/
    public String getJSONUrl(String url) {
        StringBuilder str = new StringBuilder();
        HttpClient client = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(url);
        try {
            HttpResponse response = client.execute(httpGet);
            StatusLine statusLine = response.getStatusLine();
            int statusCode = statusLine.getStatusCode();
            if (statusCode == 200) { // Download OK
                HttpEntity entity = response.getEntity();
                InputStream content = entity.getContent();
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(content));
                String line;
                while ((line = reader.readLine()) != null) {
                    str.append(line);
                }
            } else {
                Log.e("Log", "Failed to download file..");
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return str.toString();
    }

    /***** Get Image Resource from URL (Start) *****/
    private static final String TAG = "Image";
    private static final int IO_BUFFER_SIZE = 4 * 1024;

    public static Bitmap loadBitmap(String url) {
        Bitmap bitmap = null;
        InputStream in = null;
        BufferedOutputStream out = null;

        try {
            in = new BufferedInputStream(new URL(url).openStream(),
                    IO_BUFFER_SIZE);

            final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
            out = new BufferedOutputStream(dataStream, IO_BUFFER_SIZE);
            copy(in, out);
            out.flush();

            final byte[] data = dataStream.toByteArray();
            BitmapFactory.Options options = new BitmapFactory.Options();
            // options.inSampleSize = 1;

            bitmap = BitmapFactory.decodeByteArray(data, 0, data.length,
                    options);
        } catch (IOException e) {
            Log.e(TAG, "Could not load Bitmap from: " + url);
        } finally {
            closeStream(in);
            closeStream(out);
        }

        return bitmap;
    }

    private static void closeStream(Closeable stream) {
        if (stream != null) {
            try {
                stream.close();
            } catch (IOException e) {
                android.util.Log.e(TAG, "Could not close stream", e);
            }
        }
    }

    private static void copy(InputStream in, OutputStream out)
            throws IOException {
        byte[] b = new byte[IO_BUFFER_SIZE];
        int read;
        while ((read = in.read(b)) != -1) {
            out.write(b, 0, read);
        }
    }

    /***** Get Image Resource from URL (End) *****/

    @Override
    public void finish() {
        super.finish();
        if(verOk==true){
            overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_right);
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        // TODO Auto-generated method stub
        super.onSaveInstanceState(outState);
        // webview.saveState(outState);
        Log.i(TAG, "onSaveInstanceState");
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onRestoreInstanceState(savedInstanceState);
        // webview.restoreState(savedInstanceState);
        // lstView.restoreState(savedInstanceState);
        Log.i(TAG, "onRestoreInstanceState");
    }

}


text:
Q: How to download Wordpress source code when you have access to ftp servers & wordpress admin panel? I got my first job as a programmer.
The client gave me the credentials for an ftp server and wordpress admin panel.
I need to fix an issue.
How do I download to source code of the website?

A: Use this plugin:
By using this plugin you can download whole file and database without losing anything..
https://wordpress.org/plugins/duplicator/
Video: https://youtu.be/oc73jtvHWYQ
Duplicator gives WordPress users the ability to migrate, copy, move or clone a site from one location to another and also serves as a simple backup utility. Duplicator handles both serialized and base64 serialized string replacement. WordPress migration and WordPress backups are easily handled by this plugin.

A: If you want change something in code then you can use any ftp clients. first download code form server and change in file and then you can upload that file.


text:
Q: Gradle generate sources.jar for only public interfaces I am working on a closed-source Android library (published as an AAR), and want to include some javadocs for consumers, which requires a sources.jar.
I know I could cherry-pick each file using an includes property or maybe even a whole package/folder.
task('androidSourcesJar', type: Jar) {
    classifier = 'sources'
    baseName = artifactBaseName
    from android.sourceSets.main.java.srcDirs
    include ('MyInterface1.kt', 'MyInterface2.kt', 'MyInterface3.kt')
}

Instead, is there a way to include only public classes, interfaces, methods, etc? This seems like a problem that would've come up before.

A: You could try adding something like this, instead of your include:
from 'src/main/java'
eachFile { currentFile ->
    String contents = new File(currentFile.getSourcePath()).text
    if(!contents.contains("public class")) {
        currentFile.exclude()
    }
}

I'm not entirely sure if that works, but it should set you on the right path to where you want to go.
Since Gradle does not actually do any code analysis, you can't just simply say "only include files that have classes that are public". Instead, you have to either write a custom plugin that will only include public classes, or do something like what I provided. It includes everything from the source directory, but runs a little bit of code on each file. First, it gets the contents of the file, then it checks if that file contains public class. If not, the file does't have a public class, and should be excluded.
Hope this helps! Feel free to ask any more questions if you have any.


text:
Q: What is the best way to Lint Angular 2, 4, 5 template html files prior to AOT compilation I have found this gulp html angular validate
but I am not entirely sure if this is event for angular 2 +.  Also, I was looking for something that was more like a lint, while you are working, versus during  a build process because AOT already does this upon building.

A: I stumbled upon HTMLHint NG2, an extension for HTMLHint, but both seem to be dead since they aren't updated for almost a year.
Apart from that, I didn't find any alternative.


text:
Q: Get specific words from Word to Excel I have Word documents that contain certain serial numbers (all of them begin with either 3BMS*, or 7SGA*) that I need to extract into Excel. Each Word document contains hundreds of serial numbers.
The method I am trying is that the VBA opens up the Word document and uses search to find the words that contain the first four digits of the serial number. I would then run the code for each of the two codes.
I have VBA to find paragraphs that contains the search word.
While oRange.Find.Execute = True

    oRange.Select

    myPara = oDoc.Range(0, oWord.Selection.Paragraphs(1).Range.End).Paragraphs.Count

    CurrRowShtExtract = CurrRowShtExtract + 1

    shtExtract.Cells(CurrRowShtExtract, 1) = oDoc.Paragraphs(myPara).Range

    oRange.Collapse wdCollapseEnd

Wend

How do I return only the word containing the search result, not the whole paragraph?

A: With your previous code in mind, something like the following should work. This will search the document for each instance of 3BMS plus the alphanumeric values directly after it and insert that value into the referenced cell. It will then do the same for 7SGA*.
' Search the document for the first serial number type
Set oRange = oDoc.Content
Do While oRange.Find.Execute("3BMS[a-zA-Z0-9]{1,}", MatchWildcards:=True)
    CurrRowShtExtract = CurrRowShtExtract + 1
    shtExtract.Cells(CurrRowShtExtract, 1) = oRange.Text
Loop

' Search the document for the second serial number type
Set oRange = oDoc.Content
Do While oRange.Find.Execute("7SGA[a-zA-Z0-9]{1,}", MatchWildcards:=True)
    CurrRowShtExtract = CurrRowShtExtract + 1
    shtExtract.Cells(CurrRowShtExtract, 1) = oRange.Text
Loop


text:
Q: Cannot attach debugger to a node.js application running inside a Docker container in host-mode I'm trying to attach the Visual Studio Code (v1.7) debugger to a node.js app that is running inside a Docker container in host-mode.
DEBUG=* /usr/bin/node --debug-brk /home/app/node_modules/homebridge/bin/homebridge -- -U /home/data -P /home/app

Command:
docker run -it --rm --net="host" \
    --name homebridge \
    -p "51826:51826" -p "5858:5858" \
    -v `pwd`:/home/app \
    dev/homebridge

using default launch.json:
{
"version": "0.2.0",
"configurations": [
    {
        "name": "Docker: Attach to Node",
        "type": "node",
        "request": "attach",
        "port": 5858,
        "address": "localhost",
        "restart": false,
        "sourceMaps": false,
        "outFiles": [],
        "localRoot": "${workspaceRoot}",
        "remoteRoot": "/home/app"
    }
]}

Diagnose:
Docker for Mac: version: 1.12.3 (583d1b8)
OS X: version 10.12.1 (build: 16B2555)
logs: /tmp/E06B6538-E61C-41B8-81C0-90EB5A538452/20161204-214523.tar.gz
[OK]     vmnetd
[OK]     dns
[OK]     driver.amd64-linux
[OK]     virtualization VT-X
[OK]     app
[OK]     moby
[OK]     system
[OK]     moby-syslog
[OK]     db
[OK]     env
[OK]     virtualization kern.hv_support
[OK]     slirp
[OK]     osxfs
[OK]     moby-console
[OK]     logs
[OK]     docker-cli
[OK]     menubar
[OK]     disk
Failure: Could not upload diagnostic data to remote server (docker-diagnose exit code is 1)

Now, when I start the application and attach the debugger i get:
Cannot connect to runtime process (timeout after 10000 ms).
However, if I start the container without the host mode (docker run -it --rm --name ...), then it works...
Any idea ???


text:
Q: Different REST-ful representations of the same Entity and content negotiation Given the REST-ful web service
/product/{product-id}

that returns Product XML documents of the Content-Type
x-esvc/product+xml

I also need to support
x-esvc/prices+xml

(x-esvc is a custom MIME type; product and prices are two subtypes and +xml is a hint that it is an XML based format as per RFC 3023)
The question is whether this second format should be have its own web service
/prices/{product-id}

... or whether I should use content negotiation and the Accept HTTP header to differentiate between the two formats in the existing product web service?
Please note that there is only one real entity involved (Product) and that "prices" is a list of dependent objects in OO terms. The same identifier can, however, be used in both cases.
Another way to formulate the issue is whether "prices" could be considered a different representation of the same resource or if it should be considered another resource given that the information is different?
I do know that content negotiation is typically used to differentiate between different technical formats like JPG and PNG for the same image; i.e. the information is the same but the format is different. In this case content negotiation would be used to differentiate between different information for the same entity.
Would this be a valid use of Content Negotiation and the Accept HTTP header in a REST-ful web service?

A: i'd favor different web services. it simplifies the use by any consumer as the request can be expressed completely by specifying the url alone. this might be irrelevant at the current stage of your project but might change as it evolves - it's easier to assemble and maintain web service calls without having to fiddle around with request headers.
if you don't need/want this separation server-side you can still unify the two url locations by directives in your web server configuration.
operating the web service might also become easier: think load balancing and maintenance downtime.
depending on your project's scale, your mileage may vary. for some in-house PoC you probably best cling to what you have.


text:
Q: Does Read have any limit i'm trying to implement a client-server application with sockets, the case is that i want to read in the server a message that is large. And the read is doing unexpected things.
This is my read message implementation (I have received the size of the message first)
        ssize_t bytesRead=0;
        while (bytesRead < size_msg_){
            ssize_t ret = read(s_conec,msg+bytesRead,SSIZE_MAX);
            if (ret == 0)
                break; //EOF
            bytesRead +=ret;
            int aux = ( (bytesRead * 100)/size_msg_ );
            printf("I have read a %d percent \n", aux);
}

Now, if i try to see what the server is reading with strace i get this:
read(7, "En un lugar de la Mancha, de cuy"..., 2147483647) = 873056
read(7, " sino de amores -respondi\303\263 don "..., 2147483647) = 523864
read(7, "o, por parecerme que, en la ley "..., 2147483647) = 458381
read(7, " con \303\251l se defend\303\255a de la nube"..., 2147483647) = 458381
read(7, " que all\303\241 quedan y aqu\303\255 van le"..., 2147483647) = 458381
read(7, " otros semejantes pasaron la noc"..., 2147483647) = 458381
read(7, "rlas. Acudi\303\263 Sancho a su asno p"..., 2147483647) = 458381
read(7, " Quijote dec\303\255a, y, celoso de qu"..., 2147483647) = 2160939

And so on, with no pattern. What i want to know is if there is any limit assiciated with the read function that i could change because this implementaion takes to long to read the full message


text:
Q: Java, convert between two different generic instances I want to make an adapter interface (and implementations) to use multiple similar external libraries.
For example, there are interfaces of external libraries. These libraries guide to implement Converter and register it to extend features.
Lib A
public interface AConverter<S, D> {
    D convert(S source);
}

Lib B
public interface BConverter<S, D> {
  D convert(S source);
}

Both interfaces specify the same method.
What I want is to use my own MyConverter interface.
public interface MyConverter<S, D> {
  D convert(S source);
}

A user implements this class and my library converts the implementation to either LibA's implementation of AConverter or LibB's implementation of BConverter. Is this possible?
EDIT:
I do not want factory pattern or extends LibA interface and LibB interface. MyConverter is core library, LibA and LibB are external plugable libraries.
What I am trying is,
public ALibAdapter {
    AConverter change(MyConverter convert) {
        /**
         * Anything I can do?
         */
        return aConverter;
    }
}

A: Your interface can extend the existing interfaces:
public interface MyConverter<S, D> extends AConverter<S, D>, BConverter<S, D> {
  ...
}

You can now use it in place of either one of the library interfaces.
If all methods have the same name (convert), they can be overridden. Else you'd have to make sure to call those implementations from your own method using Java 8 default method implementations.


text:
Q: WP8.1 InvokeScript Error I am working on a Windows Phone 8.1 App. I have a problem with the InvokeScript method of the WebBrowser class.
I have this in my XAML:

And when I run this code:
myWebBrowser.Loaded += (object sender, RoutedEventArgs e) =>
{
    webBrowser.IsScriptEnabled = true;
    webBrowser.InvokeScript("eval", "alert('foo')");
};

I get a System.SystemException on the line with InvokeScript that tells me this:

An unknown error has occurred. Error: 80020006.

When I run the same code for Windows Phone 8 (not 8.1) I don't get the exception.
Any ideas why I get an error with WP 8.1?

A: I found the solution here.
The Loaded event is called too early. I used the LoadCompleted event instead. As long as I navigate to something (I've been putting webBrowser.NavigateToString(""); ) the LoadCompleted event will be called only when the WebBrowser control has fully loaded content.
Here is the new code :
webBrowser.LoadCompleted += (object sender, NavigationEventArgs e) =>
{
    webBrowser.IsScriptEnabled = true;
    webBrowser.InvokeScript("eval", "alert('foo');");
};


text:
Q: referring a global string variable in UIViewController Extension Let's say there is a global string variable in a ViewController class. Within another extension file (ViewControllerExtension.swift) of this ViewController class, I want to be able to make adjustments to this global variable within a function.
Right now, there is a function in the extension which takes the global string variable as an input :
func doSomething(inputString: String){
//something is being done and the adjustment will be reflected in the ViewController instance.
}

My question is:

*

*Is there a way for get access to the ViewController's global string variable without having to refer it by going through a function as it's input?

*What would be a good designed way to go about this? How would a seasoned programmer go about solving this issue?

Thanks in advance.

A: I think that what you should do is use a the didSet method of a variable,
it goes something like this:
var Name = "" {
    didSet{
        print("The name has been change")
    }
}

Now with that in mind you could say
class Your_class {
    var Name = "" {
        didSet{
            //something is being done and the adjustment will be reflected in the ViewController instance.
        }
    }

}

extension Your_class {
   self.Name = "Paco"
}

Now this will actually do the same thing, it is a little bit more appropriate for swift but at the end what you are doing seems fine. the problem that  I see in your code is that if you call that function or even what I just posted and the VC is not on the screen this won't work, if that is the case please post more info so we can help you. ;)

A: I'm quite confused about what are you trying to achieve but, you are not defining a global variable. A global variable is difined out side of your view controller scope, so what you can access it from anywhere in your project.
Personnally, I don't think a global variable is necessary. There are so many ways Apple provided to pass data around. You can pass data from a view controller to another by using segue or unwind. You can also have a delegate to broadcast function calls. You can also use notification center to do so. Unless it's absolutely needed, I do not suggest you to use a global variable.


text:
Q: Some kind of weird injection on SO? I just ran across this answer while on comment patrol. It seems normal in almost every regard... Except it isn't. For one, it's cut off - look at the source and you see that there's quite a bit more that isn't shown.
Another thing: the code block formatting is.. um... overflowing:

I don't know if this is an injection of some kind or what, but it certainly doesn't look good for security. What's wrong?

A: To echo from chat: Posts are only run through the Markdown parser at the time they're posted or last edited, and the generated HTML is saved. Running every post in a question through the Markdown parser on every page load would be a huge performance hit, so it's permanently cached until it's updated or the magical beings at SE manually refresh it (if they even do that).
So whatever happened there, happened in 2009, and the post just hasn't been updated since then to fix the problem. Any bug that might have caused it is likely long gone by now, and this probably isn't reproducible anywhere else.


text:
Q: Need help solving inequality with trigonometric terms $$ \frac{\cos x}{2\sin\frac\pi2 - \sin x} > 0 $$
This is the question I need help solving. The first thing I did was turn $2\sin\frac\pi2$ into 2(1) but I'm not sure how to simplify it further.

A: Because $2-\sin x \in [1,3]$, this means that the denominator is always positive. So the only thing you have to worry about is the numerator. So, if
$$
\frac{a}{b} >0
$$
and $b>0$, what can you conclude about the numerator?


text:
Q: starting plone instance: Error: '$' not followed by '$' or name I was working on my Plone instance and at a certain moment I was not able to stop/start my instance anymore.
./bin/instance start

Error: '$' not followed by '$' or name

What's the meaning of this error?


text:
Q: Why I have to use python-dotenv in order to load env variables to Python? I am trying to read in a python script some variables that I have in an environment file myfile.env:
LOCALHOST='1'

If in my python script I just run:
import os
print(os.environ)

It prints:
environ({'PATH': '....', 'HOSTNAME': '...', 'PYCHARM_HOSTED': '1', 'PYTHONUNBUFFERED': '1'})

But in these array I don't have the LOCALHOST variable. I found that I can use python-dotenv and now I see it and working, but I don't get why I have to use it, and it's not feasible to load them only using os module.

A: Because a .env file is not the environment.
os.environ gets data from the environment which, somewhat oversimplified, is a string-to-string (name-to-value) mapping maintained by the operating system for each process, and inherited by child processes. Things are typically put there using export statements in a shell – they will then be inherited by all processes started from that shell — but there are other ways.
.env files are an application-level thing; the operating system does not know about them and they are not automatically loaded into the environment (and hence not picked up by os.environ). That is what python-dotenv takes care of for you.


text:
Q: Format HD using disk utility I have a new hard drive that I will use only for storing data.
I am following the instructions from: http://www.ubuntulinuxguide.com/ubuntu-1204-lts/hard-disk-partition -  but I can't find this window!
My problem right now is that I seem to have 3 partitions!
I want to format the whole damn thing and make it just one partition (with filesystem NTFS) for private data.
When I try to format or delete the disk, it formats/deletes every partition individually - instead of merging everything and cleaning out the entire disk. What am I doing wrong?


text:
Q: What is the difference between ptr->thing and *ptr->thing in C? My understanding is that the -> operator is shorthand for dereferencing a pointer to a struct, and accessing the value of one struct member.
struct point {
   int x;
   int y;
};
struct point my_point = { 3, 7 };
struct point *p = &my_point;  /* p is a pointer to my_point */
(*p).x = 8;                   /* set the first member of the struct */
p->x = 8;                     /* equivalent method to set the first member of the struct */

So the last 2 lines of the example above are equivalent. But I've encountered some code similar to this:
*p->x = 8

Using both the asterisk and arrow together. What does this do? Would this try to "double dereference" the pointer and assign to memory address 8, or something else? Maybe undefined behavior, or just a compiler error?

A: *p->x is equivalent to *(p->x) - you are dereferencing the result of p->x, which implies the x member itself has pointer type.  Given a line like
*p->x = 8;

that implies x has type int *:
struct foo {
  ...
  int *x;
  ...
};

Note that x must be assigned a valid pointer value before you can assign to *x.  You can allocate memory dynamically:
struct foo *p = malloc( sizeof *p ); // dynamically allocate space for 1 instance of struct foo
if ( !p )
  // handle allocation failure and exit here.

p->x = malloc( sizeof *p->x ); // dynamically allocate space for 1 int.
if ( !p->x )
  // handle allocation failure and exit here.

Or you can set x to point to an existing int object:
int a;
...
p->x = &a;
*p->x = 8;

A: For a structure
struct tagp
{
   int *x=someaddress;
}p0;
struct tagp *p=&p0;

*p->x accesses the address stored in the pointer x inside the structure. It is same as *((*p).x) and *(p0.x) which accesses the memory at Someaddress.
Check this link


text:
Q: Libreoffice only convert from odt to pdf, not other formats I'm trying to convert documents from html,txt to pdf,odt and vice versa.. But only odt to pdf seems to work.. No other file formats are converted
Here are my commands
libreoffice --headless --convert-to pdf test.html [Not working]
libreoffice --headless --convert-to odt test.html [Not working]
libreoffice --headless --convert-to pdf test.docx [Not working]
libreoffice --headless --convert-to pdf test.odt  [Working]

A: The following works
libreoffice  --invisible -convert-to pdf myFile.html

libreoffice  --invisible -convert-to docx myFile.odt
The option --invisible does not start up the GUI but gives some clues on the command line what is happening.
Tested on Linux Mint 13.

A: Try closing all running instances of LibreOffice before executing the command.  This was the root cause of my pain.

A: This worked for me on LibreOffice 4.2 / Linux:
soffice --headless --convert-to txt:Text /path_to/document_to_convert.odt

Credit: http://ask.libreoffice.org/en/question/14130/how-do-i-install-filters-for-the-soffice-command/

A: For me.  The problem I had was that --headless does not work, AT ALL (just returns in 15 milli-seconds), if a local libreoffice process already has the document open.
Make sure you only do headless operations on a document that is NOT already open in LibreOffice.

A: This is a known issue in LibreOffice that was fixed in version 5.3.0. Before this fix when an instance of LibreOffice is running --convert-to or any other command would silently terminate without doing anything.
If your version is older than that you could consider the solution suggested by Frank Yin here. That is close all open LibreOffice documents before running the conversion.
If you cannot close all open LibreOffice documents to run the conversion, or if you find it inconvenient, you could try a solution suggested in the comments to the original bug.
If you have LibreOffice version before 4.5 run
soffice -env:UserInstallation=file:///$HOME/.libreoffice-headless/ \
--headless --convert-to pdf test.docx

If you are running LibreOffice version between 4.5 and 5.3 run
soffice -env:UserInstallation=file:///$HOME/.libreoffice-headless/ \
--convert-to pdf test.docx

Here $HOME/.libreoffice-headless is a new profile directory different from your main LibreOffice profile.

A: The real problem is that the libreoffice/soffice command line doesn't provide any error message or debugging information, so it's all guesswork.  If you are up to it, then try strace for hints.
In my case (Linux), I didn't have the correct packages installed - for example, to convert spreadsheets, libreoffice-calc is needed (duh), and also libreoffice-headless (double-duh).  But the command line won't tell you that - it just hangs, or runs and doesn't do anything.

A: For me, the following two packages were the minimum needed to get headless docx to pdf conversion working on CentOS 7 :
yum install libreoffice-headless  libreoffice-writer

A: One of the problems that I encountered with libreoffice was the problem with empty spaces. After I slugged the name ("test-document.docx" instead of test "documnet.docx") it worked perfectly.
From version 4.2.8.2 - 5.3.

A: On Windows I encountered the following problem: I tried to convert all DOC files to PDF using the following command:
soffice --invisible --convert-to pdf *.doc

It failed without any error message. But it worked when I put a filename of one of the files instead of *.doc. So apparently it was a problem with resolving wildcard in *.doc. What I did is execute exactly the same command as above but from Git Bash instead of normal command prompt (cmd.exe). It worked. What is more: in Git Bash it displayed progress information and informative messages!
So my advice is: if you're running soffice.exe on Windows and don't get any output, run the command from Git Bash (you can get Git Bash by installing Git for Windows)

A: I had to install the xvfb package (yum install xorg-x11-server-Xvfb), it is the xserver dummy.


text:
Q: How to remove labeling and tickering in WFDB, python? enter image description here
The plots have label and tick information and I'd like to remove them.
I downloaded ECG data from Pysionet(https://physionet.org/content/?topic=ecg) and try to analze the images.
Since I just need the signal images, want to remove any other parts including labels and ticks.
However, there are no parameters related to it and doesn't work with any plt options.
How could I get just the sinal images?

A: You can get access to the matplotlib figure generated by wfdb_plot via return_fig=True. This way, you can disable any axis annotations and titles:
fig = wfdb.plot_wfdb(record=rcbr, figsize=(10,4), return_fig=True)
fig.axes.axis("off")  # disable ticks, labels, etc.
fig.axes.set_title("")  # remove title


text:
Q: Java directory polling strategy There is a directory in which files arrive at unpredictable times, but suppose that probability distribution is normal.
Average intervals for polling must be 1 minute.
Does there exist some strategy - e.g. change near 20% (+ or -) interval for polling or better polling in equal intervals?
If yes - if possible please point to an algorithm in java

A: Instead of polling yourself you might want to look at FileAlterationMonitor or JNotify or NIO (Java 7 only).

A: It might yet be too early for you, but Java 7 has new class WatchService for monitoring a directory for changes.

A: You can also implement this using awaitility. Please check here


text:
Q: Keep rows with one particular value in one column using some condition in another column in same dataframe I have the below dataframe:

col1
col2
col3

Device1
A
true

Device1
A
false

Device1
C
false

Device1
B
false

I want to keep first two rows (where col2 value = A) where A is identified because col3 has a 'true' in row 1. In other words, for device 1, I want to keep all those rows where col2 has at least 1 value in col3 as 'true'.
I expect the below result after the filter:

col1
col2
col3

Device1
A
true

Device1
A
false

A: You can do it with window functions: partitioning by col1 and col2, ordering by col3 descending. Use the first function over the window.
from pyspark.sql import functions as F, Window as W
df = spark.createDataFrame(
    [('Device1', 'A', True),
     ('Device1', 'A', False),
     ('Device1', 'C', None),
     ('Device1', 'B', False)],
    ['col1', 'col2', 'col3'])

w = W.partitionBy('col1', 'col2').orderBy(F.desc('col3'))
df = df.withColumn('keep', F.first('col3').over(w))
df = df.filter('keep').drop('keep')

df.show()
# +-------+----+-----+
# |   col1|col2| col3|
# +-------+----+-----+
# |Device1|   A| true|
# |Device1|   A|false|
# +-------+----+-----+


text:
Q: Android, Error inflating при использовании Vector если API =< 19 Имею кнопку:
<android.support.v7.widget.AppCompatImageButton
    android:id="@+id/event_favourite"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginEnd="16dp"
    android:background="@drawable/favourite_selector"
    app:layout_constraintBottom_toBottomOf="@+id/event_title"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintTop_toTopOf="@+id/event_title" />

Функционально это переключатель. Ничего необычного.
Фоном ставлю:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/ic_favorite_filled" android:state_selected="true" />
    <item android:drawable="@drawable/ic_favorite_filled" android:state_pressed="true" />
    <item android:drawable="@drawable/ic_favorite_empty" />
</selector>

ic_favorite_filled  и ic_favorite_empty это векторы, svg перегнаное в vector asset.
Всё работает и переключается на API => 21, но при меньших API вылетает с ошибкой:
Error inflating class android.support.v7.widget.AppCompatImageButton
В ходе расследования создал отдельный фон для API 19, где в качестве изображений использовались простые png:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/avatar_anon" android:state_selected="true" />
    <item android:drawable="@drawable/avatar_deanon" android:state_pressed="true" />
    <item android:drawable="@drawable/avatar_anon" />
</selector>

И всё заработало.
Однако кнопок таких планируется много, и я хочу узнать: можно ли всё же как - нибудь использовать мои векторные ic_favorite_filled и ic_favorite_empty в качестве фона в API 19? Не хочу плодить лишние Drawable, их и без того очень много.

A: Решил благодаря ссылкам от TimurVI.
Убрал android:background и устанавливаю фон программно:
binding.eventFavourite.setBackgroundDrawable(ContextCompat.getDrawable(context,R.drawable.favourite_selector));


text:
Q: Porting OpenGL 1.x code to WebGL I am trying to port OpenGL 1.x code here (original code is written by a Super User regular, BenRichards) to the WebGL-safe subset of OpenGL 2.x. My plan is to compile the code using Emscripten so that this C++/SDL app runs as JS/WebGL in a modern browser, but to achieve that, I must eliminate the use of the GL 1.x API, since Emscripten is not properly supporting the GL 1.x code that we are using with its imperfect/broken 1.x emulation code. BenRichards is also interested in seeing his "newbie" GL 1.x code forward-ported to a more modern GL API, as long as it runs on both the desktop and in the browser.
Both BenRichards and myself are new-ish to OpenGL in general, so we have a lot of learning to do in order to understand how to forward-port it. The general approach seems to be to avoid client-side data for performance reasons (see here), but I wanted to learn by example.
Take this little snippet from here for example:
void TCell::OnRender() {
  glPushMatrix();
  glColor3ub(color.red, color.green, color.blue);

  glBegin(GL_QUADS);
  glVertex2i(20 * column - 40, 20 * row - 40);
  glVertex2i(20 * column - 20, 20 * row - 40);
  glVertex2i(20 * column - 20, 20 * row - 20);
  glVertex2i(20 * column - 40, 20 * row - 20);
  glEnd();
  //....
  glPopMatrix();
}

If someone could write a heavily commented port of this general rendering pattern into WebGL-ish code (still C++ though, not JavaScript), that would be great. This should provide me a starting point to port the remainder of the app.
A good answer to this question will be generally useful beyond the immediate problem I am facing, by explaining the thought process of how to translate this type of immediate-mode GL 1.x code into the deferred rendering model of GL 2.x. External references to blogs, guides, etc. are welcome/encouraged.

A: If you consider keeping GL 1.x style instead, you may be interested in this stuff:
https://github.com/stefanhaustein/WebGLue
Edit: For use with emscripten, you may want to build something like MeshBuilder (in webglue.js) and the fixed function emulation in C. MeshBuilder makes it relatively easy to port begin/end style GL code to modern GL by using basically the same calls to fill a buffer that can be resused. We have used a similar approach to port Quake II to WebGL (but in Java/GWT instead of C)


text:
Q: How can get ahead node and behind node in codeQL? I want to get a ahead token and behind token based on DotExpr in codeQL.
Example:
<span>${msg.data}</span>
In this example, DotExpr is ${msg.data} and Both of ahead and behind nodes are <span> and </span>.
In this case, if i can get ${msg.data} expression how can i get <span> and </span> nodes with codeQL syntax?


text:
Q: Open outlook email search from Java/JavaScript Recently, I saw a form on SharePoint where user can select/search emails from a widget. It seemed to me that the emails were not locally stored and that SharePoint is somehow getting the emails from Outlook or an email server.
My question here would be that whether something like this is possible in Java/Javascript or not? So that I do not store emails locally and the search widget may bring the emails from an email server.
Thanks a lot.


text:
Q: Where is the location that gradle downloads dependency in Android Studio? Where is the location that gradle downloads dependency in Android Studio?
How to find them?

A: With my setup, I can find the files at the following location:
~/.gradle/caches/modules-2/files-2.1/
For example, Picasso artifacts were downloaded at the following location on Mac:
emphasized text/Users/USER_NAME/.gradle/caches/modules-2/files-2.1/com.squareup.picasso/picasso/
This folder has three directories for .pom file, sources, and actual jar file.
This is not in project specific .gradle folder but is in the global .gradle cache instead.

A: In my case the modules on which my app depend are downloaded to the project folder, alongside my app folder.
project_folder
|-app
|-module_1
|-module_2
|-...


text:
Q: Probability: Information contained in sigma-algebras Consider a sample space $\Omega$ and a sigma-algebra $F$ over it. Let $A$ be a class of $F$-sets. $A$ then generates a partition of $\Omega$  based on the following equivalence relation: Points $w_{1}$ and $w_{2}$ of $\Omega$ are related if, for every set $B$ in $A$, they both belong or they both don't belong to $B$ [ref: Billingsley, 3rd edition, Chapter 1, Section 4, Subfields]. Further, this partition is the same as that generated by the sigma-algebra of $A$ [$\sigma(A)$] defined using the same relation.
Q1. Does it mean that $\sigma(A)$ gives exactly the same information that $A$ gives? In other words, is knowing either $A$ or its sigma-algebra enough to extract any information that we could possibly seek?
Q2. Is there any condition for the above to hold? For example, if $A$ is not a pi-system (not closed under finite intersections) does it hold?
Q3. Can independence  of 2 classes $C$ and $D$ (or the lack of it) be inferred by studying their sigma-algebras? For example, if a set in $D$ lies in $\sigma(C)$, is it enough to ensure that $C$ and $D$ are not independent? If so, why?

A: Q3. Independence is related to what probability measure you are using. So I'd say it cannot be inferred from the sigma-algebras. Regarding your example $\Omega$ is always in $\sigma(C)$, but it can also be in an independent sigma algebra.

A: Q1: The answer is no. Let $\Omega=[0,1]$. Let $A_1$ be the Borel $\sigma$-algebra on $\Omega$ and let $A_2$ be the $\sigma$-algebra consisting of subsets of $\Omega$ that are countable or have a countable complement. Both lead to the partition into singletons, yet are quite different. In particular, a $A_2$-measurable real valued function is constant on a set with Lebesgue measure $1$. To see this, let $f:\Omega\to\mathbb{R}$ be $A_2$-measurable. Note that for each $n$, there is a set of the form $[z/2^n,(z+1)/2^n]$ for some $z\in\mathbb{Z}$ such that $\mu f^{-1}\big([z/2^n,(z+1)/2^n]\big)=1$. Picking such a set for each $n$ and taking their countable intersection, you get a singleton set $\{x\}$ such that $\mu f^{-1}(\{x\})=1$.
Q2: There is a class of measurable spaces for which the answer is almost yes. A countably generated measurable space in which all points are measurable is strongly Blackwell if any two countably generated sub-$\sigma$-algebras that generate the same partition are equal. David Blackwell has shown (corollary 1) that any analytic set is strongly Blackwell.


text:
Q: Difference between type and __class__ Django source code:
def new_method_proxy(func):
    def inner(self, *args):
        if self._wrapped is empty:
            self._setup()
        return func(self._wrapped, *args)
    return inner

class LazyObject(object):

    _wrapped = None

    def __init__(self):
        self._wrapped = empty

    __getattr__ = new_method_proxy(getattr)

    def _setup(self):
        # Must be implemented by subclasses to initialize the wrapped object.
        raise NotImplementedError('subclasses of LazyObject must provide a _setup() method')

    def __deepcopy__(self, memo):
        if self._wrapped is empty:
            # We have to use type(self), not self.__class__, because the
            # latter is proxied.
            result = type(self)()
            memo[id(self)] = result
            return result
        return copy.deepcopy(self._wrapped, memo)

In __deepcopy__() function, the comment:
We have to use type(self), not self.__class__, because the latter is proxied.

What does it mean? What is the difference between type() and __class__?

A: A bit further down in the source code:
# Need to pretend to be the wrapped class, for the sake of objects that
# care about this (especially in equality tests)
__class__ = property(new_method_proxy(operator.attrgetter("__class__")))

Here you see that the __class__ attribute (which is ultimately just a normal attribute) is overridden with a custom definition. This new definition is a property that returns the value of the proxied class.
type(obj) bypasses the new __class__ property, and returns the LazyObject class, instead of the proxied class.


text:
Q: Search 'refiner' on first letter of sitename In our SharePoint Online tenant, we use multiple site collections for teams and other collaborations. We want to make those site collections available via a search page on a site in the root site collection. Because we're talking about a few hundred sites, we want to make it possible to filter the sites by the first letter of the sitename. For now, we're using the following query:
Title:letter*
The problem with this query, is that it gives us the sites with a title where one of the words begins with the given letter (so not just the site where the first word of the sitename begins with the letter). Even better, in some cases it gives us sites that doesn't contain the given letter at all.
I've already been searching on the internet a bit for other solutions and I came across the following suggestion:
Search refiner on first letter of the title
I tried to apply method 2. I did manage to create a refinement filter that only showed the first letters of the filter options, but not in the way I wanted. For example, when we get the results Administration,  Accounting, Production and Sales, the refinement panel shows the following filter options:
Title
A
A
P
S
So the question is; in what way should the given method be implemented to work in the correct way?
Moreover, if somebody knows an other way to make it possible to filter on the first letter of the complete sitename, I appreciate it if you could share it with us.

A: The results make sense. You are using a colon in your query. The colon is a contains operator. I think what you want is Title=letter*


text:
Q: How do I get the button I created in PageView to switch to a new page on the last page?  Row(
            children: [
              ...List.generate(data.length,(index) => Padding(padding: EdgeInsets.only(right: 4),
              child: DotIndicator(isActive: index== pageIndex),)),
              Spacer(),
              SizedBox(
                height: 60,
                width: 60,
                child: ElevatedButton(onPressed: () {
                  _pageController.nextPage(duration: Duration(milliseconds: 300), curve: Curves.ease);
                },
                style: ElevatedButton.styleFrom(shape: CircleBorder(),),
                child: Image.asset('assets/arrow.png', color: Colors.white,),),
              ),
            ],
          )

I've designed an onboarding and I'm having a problem with the last page. I go forward with the button I created, but on the last page, the progress ends because there is no other page left. So how can I redirect to the home page of the application only when the button is clicked on the last page?
I designed the part in the lower left side of the DotIndicator. In the list, there is information such as title and image on the pages. How should I write a code for the onPressed method so that it redirects me to a new page of the application on the last page?

A: You can use animate to or jumpto
_controller.animateToPage(pageIndex);

//Or

_controller.jumpToPage(pageIndex);

Or if you wish to navigate to someother screen then you can check index
First get index of page
int currentPage = 0;

onPageChanged: (page){
                  setState(() {
                    currentPage=page;
                  });
                },

Add this code to pageview..
Then in the elevated button you can check the index
child: ElevatedButton(onPressed: () {
  if(currentPage >= 3){
    Navigator.push(context, builder: ()=>YourClass());
  }
  else{
   //Do next page code here to switch page in pageview
  }
 },


text:
Q: How to capture key presses in a Cocoa application that runs in the background? I am making a small utility that will detect when the numlock key is pressed.
I am currently able to execute a script to control numlock with a tool called Spark, by Shadow Lab:
https://www.shadowlab.org/softwares/spark.php
So, I know that it is possible.
In fact, there are applications such as Quicksilver and many others that do this, so it must be possible (despite obvious security concerns).
How can I achieve this?
From googling, I have found suggestions to use NSEvent.addGlobalMonitorForEvents(matching: .keyDown) as well as Quartz Event Services.
I have tried with NSEvent and it does not seem to capture the keyDown events, and there is not much documentation on the best way to use Quartz Event Services.
To be clear, my application does not have a window and I would like to be able to capture key-down events system-wide.
Can somebody please advice the best way to capture a keypress?
Thanks!


text:
Q: thycotic REST call returns http instead of json We have two Secret Server servers - prod with cert from CA and test with self signed cert.
We've been developing on the test one with self signed cert ignoring ssl warnings (showed here as curl with --insecure). And all works fine – e.g.:
Unauthenticated GET call (returns 403):
curl --header "Content-Type: application/json" --request GET --insecure https://192.168.100.191/secretserver/api/v1/users

{
  "message": "Authentication failed or expired token."
}

Authentication token request:
curl --header "Content-Type: application/x-www-form-urlencoded" --request POST --data "username=Admin&password=passw0rd&grant_type=password" --insecure https://192.168.100.191/secretserver/oauth2/token

{"access_token":"XRVpc2S7SotSAVDv...GH8GZtw","token_type":"bearer","expires_in":1199}

However we can not get working the same requests on the prod env with cert from CA. Whatever service we call, we get 200 with html document in the body – e.g. (the same examples as above):
Unauthenticated GET call (supposed to get 403, but getting 200 with html):
curl --header "Content-Type: application/json" --request GET https://ssserver.com/secretserver/api/v1/users

<title>Object moved</title>

Object moved to here.

Authentication token request:
curl --header "Content-Type: application/x-www-form-urlencoded" --request POST --data "username=Admin&password=passw0rd&grant_type=password" https://ssserver.com/secretserver/oauth2/token

<title>Object moved</title>
Object moved to here.

A: The problem was that the server use non default URL ,which I wasn't aware of.


text:
Q: How to override the NSObject methods without inheriting from NSObject in swift I actually want to know how to access the encodeWithCoder, init etc methods from the NSObject or any other class without inheriting from NSObject class.
Because I read that if we inherit from the NSObject class then it has performance issues in Swift or similar performance to the Objective - C.
So please let me know how to do it.

A: You want to override a super class method from a class that doesn't inherit from that super class, this doesn't make sense. If you need to use encodeWithCoder method, you'll have to extend NSObject class or any other class that conforms to NSCoding protocol. Otherwise you can create your custom class that conforms to NSCoding protocol and implement the same functionality in encodeWithCoder method.
From Apple documentation

Any class that does not inherit from another class is known as a base class.
NOTE
Swift classes do not inherit from a universal base class. Classes you
  define without specifying a superclass automatically become base
  classes for you to build upon.


text:
Q: Secure method to execute a script remotely with ssh I woud like to I'd like to allow a user to connect to a server using SSH and execute a script, and nothing else. how can I do to that ? how can I secure it ?
thanks you!

A: Make that script the user's shell.

A: SSH is already secure, make sure you use token based authentication and eliminate password based access.

OK, now I think I got you wrong. I thought you were asking securily connecting.
To allow, user to just execute the shell script. Create a non-root, non-sudoer user and permit him to execute the shell script. http://www.dartmouth.edu/~rc/help/faq/permissions.html

A: (I think this is more appropriate for serverfault.com).
Anyways, to answer your question, look up "ssh command keys".


text:
Q: How to replace photos of contacts in Phone Contacts with new Photos? I want to replace photos of contacts. But now what I am doing is not replacing photos with new one.
The old photo remains as it is.
My code for adding photos is
String thumbnail = "";
    if(contact_map.get("photos")!=null)
    {
        thumbnail = contact_map.get("photos").toString();

        Log.i("--: VALUE :--","thumbnail  = "+thumbnail);

        URL image_url = null;
        Bitmap bitmap_image = null;
        ByteArrayOutputStream stream_image = null;
        try
        {
          image_url = new URL(thumbnail);
          bitmap_image = BitmapFactory.decodeStream(image_url.openConnection().getInputStream());
          stream_image = new ByteArrayOutputStream();
          bitmap_image.compress(Bitmap.CompressFormat.JPEG , 100, stream_image);
        }
        catch(Exception e)
        {
            Log.e("My Exception",""+e.getMessage());
        }

        //INSERT IMAGE
        ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactInsertIndex)
                .withValue(ContactsContract.Data.MIMETYPE,ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE)
                .withValue(ContactsContract.CommonDataKinds.Photo.PHOTO, stream_image.toByteArray())
                .build());

    }

Its been so long no body even commented it please suggest me anything.
Thanks

A: Here's the code sample http://developer.android.com/reference/android/provider/ContactsContract.RawContacts.DisplayPhoto.html


text:
Q: ionic 4 https://ionicframework.com/docs/native/camera-preview toBack:true not working
*

*I am Working on ionic 4 angular type application

*I am want custom camera application

*so that i am using camera-preview cordova plugins

In my componenet TS
import { CameraPreview, CameraPreviewOptions,CameraPreviewPictureOptions } from '@ionic-native/camera-preview/ngx';

 private cameraPreview: CameraPreview

 taskphoto(){
this.imgurl = ''
    this.cameraPreview.startCamera(this.cameraOpts).then(res=>{
     // this.cameraPreview.
     console.log(res);
      this.imgurl = 'data:image/jpeg;base64,' + res;
    }, (err) => {
      console.log(err);
      this.imgurl =''
      //this.imgurl = 'assets/img/test.jpg';
      alert(err)
    });

}
in HTML
<ion-fab class="fbtn"  vertical="bottom" (click)="takePicture()" horizontal="center" slot="fixed">
  <ion-fab-button>
    <ion-icon name="camera"></ion-icon>
  </ion-fab-button>
</ion-fab>
<ion-fab  class="fbtn" vertical="bottom" (click)="stop()" horizontal="start" slot="fixed">
  <ion-fab-button>
    <ion-icon name="arrow-back"></ion-icon>
  </ion-fab-button>
</ion-fab>
<ion-fab  class="fbtn" vertical="bottom" (click)="switchCamera()" horizontal="end" slot="fixed">
  <ion-fab-button>
    <ion-icon name="repeat"></ion-icon>
  </ion-fab-button>
</ion-fab>

so when i am build camera no showing but capture sound are working ,
toback:false means camera comes my designs are hidding,
also that in index.html i am add
  html, body, .ion-app, .ion-content {

background-color: transparent;
}
and component scss i am  add
 ion-content {--background-color: transparent !important}

body.camera-transparent, .camera-transparent ion-nav-view, .camera-transparent ion-view { background-color: transparent !important; }

this lines still not working


text:
Q: .htaccess redirect all files/folders after www.website.com/ Hi I am currently moving a site to new hosting, previously they had lots of folders/files in the document root which i have moved to another server i.e. www.website.com/foldera/test.zip or just www.website.com/file.mp3 now on hosting.website.com/file.mp3
because these url's are still in circulation i need to redirect all files to the new location so if the old link is clicked it will re-direct correctly.
They have a large amount of files/folders. Please advise on the best way to do this?
Thanks

A: Just add this to the htaccess file in the document root of your old website:
Redirect 301 / http://hosting.website.com/

Or, if you'd rather use mod_rewrite:
RewriteEngine On
RewriteCond %{HTTP_HOST} ^(www\.)?website\.com$ [NC]
RewriteRule ^(.*)$ http://hosting.website.com/$1 [L,R=301]


text:
Q: Dynamically importing module in python3 - issue In a project, I want to dynamically import the right module based on a version-number.
For this I'm using importlib, and works find as long as the package is part of the source.
AdminApi = import_module(f"{self.version}", "AdminApi").AdminApi

The folder-structure looks like:
Admin-Package /
    - __init__.py  # Contains dynamic class loader
    - admin64/
        - __init__.py  # contains AdminApi v6.4
        - ...
    - admin65/...
        - __init__.py  # contains AdminApi v6.5
        - ...

However, now I find myself needing to decouple the code into its own package to re-use in another project.   So I've packaged this part of the source.  This however seems to cause path-related issues.  This seems to mean that importlib cannot help me.
So far, thanks to: https://stackoverflow.com/a/54138717/5731101
I've come to this point:
import importlib
from pathlib import Path

path = Path(__file__).resolve().parent
script_path = os.path.join(path, version, '__init__.py')

spec = importlib.util.spec_from_file_location(f"AdminApi", script_path)
AdminApi = importlib.util.module_from_spec(spec)
spec.loader.exec_module(AdminApi)

Unfortunately the spec.loader.excec_module fails with error: ModuleNotFoundError: No module named 'AdminApi' Even thought the class is clearly available in the file supplied via the path.
I would be grateful if anyone can help me out on this.

A: I decided to try another tool in the toolbox of importlib Based on this answer: https://stackoverflow.com/a/67692/5731101
from importlib.machinery import SourceFileLoader

foo = SourceFileLoader("AdminAPI", "/path/to/file.py").load_module()
foo.AdminAPI()

This approach had no problems detecting the class and simply imported everything correctly.


text:
Q: Returning 0 if resullt is None to avoid 'NoneType' and 'decimal.Decimal' I am trying to add return 0 in case the final result of an equation is None to get away from:
TypeError: unsupported operand type(s) for *: 'NoneType' and 'decimal.Decimal'
but it is not working for me.
The reason for this is that the no. of sold count can be zero so it returns Type Error.
Here is the function:
    def designer_total_discount_price(self):
        total_sold_discount = self.count_sold * self.discount_price
        return 0 if total_sold_discount is None else total_sold_discount

    def designer_total_price(self):
        total_sold_regular = self.count_sold * self.price
        return 0 if total_sold_regular is None else total_sold_regular

    def designer_total(self):
        if self.discount_price:
            return self.designer_total_discount_price()
        return self.designer_total_price()

    def get_designer_final(self):
        return self.designer_total() * self.designer_profit

A: The problem may be that self.count_sold is None. You can't multiply a number with None. Other than making sure self.count_sold is always None you could add this method:
    def get_count_sold(self):
        return 0 if self.count_sold is None else self.count_sold

And then you would swap out self.count_sold with self.get_count_sold(). You can also remove the if statement in the return statement. So something like this:
    def designer_total_discount_price(self):
        return self.get_count_sold() * self.discount_price

    def designer_total_price(self):
        return self.get_count_sold() * self.price

This is my first answer on Stack Overflow. I hope it helped! :)


text:
Q: Trying to populate a singly linked list So I have a singly linked list in java
 public class ListNode {
      int val;
      ListNode next;

      ListNode(int x){
         val = x;
      }
  }

Now what I am trying to do, is populate the list with the String number = "213214" which is essentially just a  number. Now each node will be  a single digit from that number.
This is what I have currently.
   int firstnode = Integer.parseInt(String.valueOf(m.charAt(0)));
    ListNode root = new ListNode(firstnode);

    for(int i = 1; i<m.length(); ++i) {

    while (root.next ==  null) {

       root.next = new ListNode(Integer.parseInt(String.valueOf(m.charAt(i))));

    }
    root = root.next;

    }

So I am trying to make it so that
root(2)->node(1)->node(3)->node(2)->node(1)->node(4)->ListEND

Any ideas?

A: So as I checked, your code is working fine. just that you lost the root node(head) when you change the root variable for inserting a new ListNode. Use a temp varaiable for that. Following is the altered code.
public static void main(String[] args) {
    String m = "213214";
    int firstnode = Integer.parseInt(String.valueOf(m.charAt(0)));
    ListNode root = new ListNode(firstnode);

    ListNode temp = root;
    for (int i = 1; i < m.length(); ++i) {

        while (temp.next == null) {
            temp.next = new ListNode(Integer.parseInt(String.valueOf(m.charAt(i))));
        }
        temp = temp.next;
    }

    temp = root;

    while (temp != null) {
        System.out.print("->" + temp.val);
        temp=temp.next;
    }
}

Also you don't need a while loop inside the for loop. It always runs just once.

A: I think this should work for you. Since root is assigned to new root element, you cannot print. Keep the root element reference and use it for print logic
ListNode root = new ListNode(firstnode);
        ListNode printRoot = root;

    for (int i = 1; i < m.length(); i++) {

        if (root.next == null) {

            root.next = new ListNode(Integer.parseInt(String.valueOf(m.charAt(i))));
            root = root.next;
        }
    }

    while(printRoot !=null) {
        System.out.println(printRoot.val);
        printRoot = printRoot.next;
    }

A: Try this way
 public class SingleLinkedList {

        LinkedList root = null;

        public static void main(String[] args) {
            SingleLinkedList sll = new SingleLinkedList();
            sll.root = new LinkedList(1);
            sll.root.next = new LinkedList(2);
            sll.root.next.next = new LinkedList(3);
            sll.root.next.next.next = new LinkedList(4);
            sll.root.next.next.next.next = new LinkedList(5);

            while (sll.root != null){
                System.out.println("sll.root.value = " + sll.root.value);
                sll.root = sll.root.next;
            }
        }
    }

    class LinkedList{
        int value;
        LinkedList next;

        LinkedList(int data){
            value = data;
            next = null;
        }
    }

A: Since there is a root node. Following codes works.
import java.util.*;
import java.util.stream.*;

public class ListNode {

    public static void main(final String... args) {
        final ListNode root = new ListNode(0);
        "213214".chars()
            .map(Character::getNumericValue)
            .mapToObj(ListNode::new)
            .reduce(root, (n1, n2) -> {
                    n1.next = n2;
                    return n2;
                });
        ;
        System.out.println(root);
    }

    ListNode(final int value) {
        super();
        this.value = value;
    }

    @Override
    public String toString() {
        return super.toString() + "{"
            + "value=" + value
            + ",next=" + next
            + "}";
    }

    private int value;

    private ListNode next;
}