text:
Q: AngularJS - Upload Image to SharePoint Library/Corrupted File I am using the following Angular Module to attempt to upload images to SharePoint through a Web browser: https://github.com/nervgh/angular-file-upload
I am getting successful 200 POST messages and a file is being uploaded... However, it is not showing the image itself in the preview or opening of the image, but rather an [X]. I am guessing this is related to how the content is encoded, but unsure of what to do next. Here is my controller:
appControllers.controller('appUploadImageCtrl', ['$scope', '$location', 'FileUploader', function ($scope, $location, FileUploader) {
    var uploader = $scope.uploader = new FileUploader({
        url: "/sites/_api/web/lists/getByTitle('Images')/RootFolder/Files/add(url='test.jpg',overwrite='true')",
        processData: false,
        transformRequest: angular.identity,
        headers: {
            'Accept': 'application/json;odata=verbose', 'content-type': undefined, 'X-RequestDigest': $("#__REQUESTDIGEST").val() }
    });

    // FILTERS

    uploader.filters.push({
        name: 'imageFilter',
        fn: function (item /*{File|FileLikeObject}*/, options) {
            var type = '|' + item.type.slice(item.type.lastIndexOf('/') + 1) + '|';
            return '|jpg|png|jpeg|bmp|gif|'.indexOf(type) !== -1;
        }
    });

    // CALLBACKS

    uploader.onWhenAddingFileFailed = function (item /*{File|FileLikeObject}*/, filter,

    options) {
        console.info('onWhenAddingFileFailed', item, filter, options);
    };
    uploader.onAfterAddingFile = function (fileItem) {
        console.info('onAfterAddingFile', fileItem);
    };
    uploader.onAfterAddingAll = function (addedFileItems) {
        console.info('onAfterAddingAll', addedFileItems);
    };
    uploader.onBeforeUploadItem = function (item) {
        console.info('onBeforeUploadItem', item);
    };
    uploader.onProgressItem = function (fileItem, progress) {
        console.info('onProgressItem', fileItem, progress);
    };
    uploader.onProgressAll = function (progress) {
        console.info('onProgressAll', progress);
    };
    uploader.onSuccessItem = function (fileItem, response, status, headers) {
        console.info('onSuccessItem', fileItem, response, status, headers);
    };
    uploader.onErrorItem = function (fileItem, response, status, headers) {
        console.info('onErrorItem', fileItem, response, status, headers);
    };
    uploader.onCancelItem = function (fileItem, response, status, headers) {
        console.info('onCancelItem', fileItem, response, status, headers);
    };
    uploader.onCompleteItem = function (fileItem, response, status, headers) {
        console.info('onCompleteItem', fileItem, response, status, headers);
    };
    uploader.onCompleteAll = function () {
        console.info('onCompleteAll');
    };

    console.info('uploader', uploader);

    $scope.cancel = function () {
        $location.path('/');
    }
}]);

HTML:

Select files

                    Base drop zone

                        Another drop zone with its own settings

            Multiple
            <input type="file" nv-file-select="" uploader="uploader" multiple />

            Single
            <input type="file" nv-file-select="" uploader="uploader" />

Upload queue

Queue length: {{ uploader.queue.length }}

                        Name
                        Size
                        Progress
                        Status
                        Actions

                        {{ item.file.name }}
                        {{ item.file.size/1024/1024|number:2 }} MB

                            <button type="button" class="btn btn-success btn-xs" ng-click="item.upload()" ng-disabled="item.isReady || item.isUploading || item.isSuccess">
                                 Upload
                            </button>
                            <button type="button" class="btn btn-warning btn-xs" ng-click="item.cancel()" ng-disabled="!item.isUploading">
                                 Cancel
                            </button>
                            <button type="button" class="btn btn-danger btn-xs" ng-click="item.remove()">
                                 Remove
                            </button>

                    Queue progress:

                <button type="button" class="btn btn-success btn-s" ng-click="uploader.uploadAll()" ng-disabled="!uploader.getNotUploadedItems().length">
                     Upload all
                </button>
                <button type="button" class="btn btn-warning btn-s" ng-click="uploader.cancelAll()" ng-disabled="!uploader.isUploading">
                     Cancel all
                </button>
                <button type="button" class="btn btn-danger btn-s" ng-click="uploader.clearQueue()" ng-disabled="!uploader.queue.length">
                     Remove all
                </button>

A: The problem with your code is that you are trying to upload your image as a normal byte array, which isn't possible when you are uploading to libraries through the SharePoint REST API.
To be able to upload non-text files to SharePoint, they have to be uploaded as a base64 encoded byte array.
Your options are to either use another Angular module such as Angular-Base64-Upload, or to encode the image file before you upload it using your first choice of file upload module.
In case you go for option two, you can encode the image using the following technique, though how it will work with your selected file uploader, I cannot say. It appears you can modify the file attribute of the FileItem in the file uploader, so it should not be that hard.
Encoding the image file to a base64 binary arraybuffer
//Create a new FileReader object
var reader = new FileReader();
reader.onload = processImage;

//Read the file as a base64 encoded string
reader.readAsDataURL(input.files[0]);

function processImage () {
    //The image file has been read by the filereader
    //and can be converted to an arraybuffer
    var arrayBuffer = base64ToBinary(this.result);

    //Upload the image to the SharePoint images library
    uploadImage(arrayBuffer);
}

function base64ToBinary (base64EncodedFile) {
    var BASE64_MARKER = ';base64,';
    var base64Index = base64EncodedFile.indexOf(BASE64_MARKER) + BASE64_MARKER.length;
    var base64 = base64EncodedFile.substring(base64Index);
    var raw = atob(base64);
    var rawLength = raw.length;
    var array = new Uint8Array(rawLength);

    for (i = 0; i < rawLength; i++)
    {
        array[i] = raw.charCodeAt(i);
    }
    return array.buffer;
}

When I wrote a similar piece of code for a project, I noticed that SharePoint (or just IE) had trouble getting the MIME types correct. I ended up stripping it from the image to make it work, as below.
var raw = atob(base64.replace(/^data:image\/(png|jpg);base64,/, ""));

Uploading to SharePoint image library using the REST API and Ajax
If you decide to not go for an Angular module to upload your file, you can instead upload files directly to a SharePoint library through the REST API using normal ajax calls with jQUery. This might have to be modified for the Angular syntax, but the concept is the same.
var requestUrl = String.format("{0}/_api/web/lists/getByTitle('Images')/rootfolder/files/Add(url='{1}', overwrite=true)", _spPageContextInfo.siteAbsoluteUrl, fileName);

$.ajax({
    url: requestUrl,
    type: "POST",
    data: buffer, //This is the base64 encoded buffer from the above step
    processData: false,
    headers: {
        Accept: "application/json;odata=verbose",
        "X-RequestDigest": $("#__REQUESTDIGEST").val()
    },
    success: function(result) {
        console.log("Upload complete!");
    },
    error: function(error) {
        console.log("Something went wrong!");
    }
});


text:
Q: quickly toggle RTS manually when RTS_CONTROL_TOGGLE is enabled On Windows XP, I've got a standard (on the motherboard) RS-232 serial port opened and configured with
dcb.fRtsControl = RTS_CONTROL_TOGGLE;

This works fine for my needs.
Now while there is no RX pending, I sometimes need to briefly toggle the RTS line under the control of my application.  I can't just call EscapeCommFunction, as that fails when RTS_CONTROL_TOGGLE is enabled.
I tried to this:
dcb.fRtsControl = RTS_CONTROL_ENABLE; // manual RTS control and turns on RTS
SetCommState( hDevice, &dcb );
dcb.fRtsControl = RTS_CONTROL_TOGGLE; // turns off RTS since there is no TX pending
SetCommState( hDevice, &dcb );

However, this never seems to work. I never see RTS toggle.  It's like the device driver notices that I just set RTS and am clearing it now, so it just aborts what I was doing.
If I put a sleep in there:
dcb.fRtsControl = RTS_CONTROL_ENABLE; // turn on RTS
SetCommState( hDevice, &dcb );
Sleep(1);
dcb.fRtsControl = RTS_CONTROL_TOGGLE; // turns off RTS since there is no TX pending
SetCommState( hDevice, &dcb );

Then I see the toggle, but it's extremely variable in length, anywhere from 1 to 15 ms (which is to be expected I guess).  I use timeBeginPeriod to setup 1ms scheduling and my thread is already high priority (should I go to real time priority?).
So, is there something I can to do "flush" the RTS change to the hardware so I don't have to do the Sleep?  I can busy wait (using QueryPerformanceCounter to wait for the amount of time I want), but I'm concerned that this would still not "flush" the RTS change to the device.
Thanks.

A: Turns out that the serial port I was using to monitor the RTS line was faulty.  It was USB based and was missing the short transitions.
I put an O-scope on it and I can see a 1ms blip when I just toggle RTS on/off as I tried initially.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Keeping MediaController on the screen in a VideoView I have trouble finding a way to keep the MediaController on the screen when using it with a VideoView. I want to play an Audio file which is located in res/raw in my app. The file is playing but I would like to keep the controller on the screen for the user to see the length of the file and how much time is left before the end etc. I found many time on forums that we should use the method .show(time) in order to do that, but I cannot figure out how to make it work.
Here is the code I am using:

package com.sample.VideoViewExample;
import android.app.Activity;
import android.net.Uri;
import android.os.Bundle;
import android.view.SurfaceHolder;
import android.widget.MediaController;
import android.widget.VideoView;

public class VideoViewExample extends Activity implements SurfaceHolder.Callback{
   private VideoView mVideoView;
   private MediaController mMedia;

   @Override
   public void onCreate(Bundle icicle) {
     super.onCreate(icicle);
     setContentView(R.layout.main);

     mVideoView = (VideoView) findViewById(R.id.surface_view);
     //mVideoView.getHolder().addCallback(this);
     //mMedia.show(50000);
     //mVideoView.setMediaController(mMedia);

     MediaController mMedia = new MediaController(this);
     mMedia.setMediaPlayer(mVideoView);
     mMedia.setAnchorView(mVideoView);
     mVideoView.setMediaController(mMedia);

     mVideoView.setVideoURI(Uri.parse("android.resource://" + getPackageName() +"/"+R.raw.osa_patient));

     mVideoView.requestFocus();
     mVideoView.start();

   }

@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
        int height) {
    // TODO Auto-generated method stub

}

@Override
public void surfaceCreated(SurfaceHolder holder) {
    // TODO Auto-generated method stub
    mMedia.show(500000);

}

@Override
public void surfaceDestroyed(SurfaceHolder holder) {
    // TODO Auto-generated method stub

}
}

When I add the line mVideoView.getHolder().addCallback(this); the app bug, I am not sure why.
Any help or alternative to what I would like to do is more than welcome :)
Thanks,
JB

A: Ok I have found! After spending hours on it!!
So there is to my knowledge no clue on how to do it on the different forums. Here is a trick I found:
FIRST CLASS (example...)
package com.sample.VideoViewExample;
import android.app.Activity;
import android.net.Uri;
import android.os.Bundle;
import android.view.SurfaceHolder;
import android.view.Window;
import android.view.WindowManager;
import android.widget.VideoView;

public class VideoViewExample extends Activity implements SurfaceHolder.Callback{
   private VideoView mVideoView;

   @Override
   public void onCreate(Bundle icicle) {
     super.onCreate(icicle);
     setContentView(R.layout.main);

     mVideoView = (VideoView) findViewById(R.id.surface_view);
     mVideoView.setKeepScreenOn(true);

        Window window = getWindow();
        window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

     SurfaceHolder holder = mVideoView.getHolder();
     holder.addCallback(this);
     MediaController_2 mMedia = new MediaController_2(this);

     mMedia.setMediaPlayer(mVideoView);
     mMedia.setAnchorView(mVideoView);
     mVideoView.setMediaController(mMedia);
     mVideoView.setVideoURI(Uri.parse("android.resource://" + getPackageName() +"/"+R.raw.osa_patient));
     mVideoView.requestFocus();
     mVideoView.start();
}

@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
        int height) {
    // TODO Auto-generated method stub

}

@Override
public void surfaceCreated(SurfaceHolder holder) {

}

@Override
public void surfaceDestroyed(SurfaceHolder holder) {
    // TODO Auto-generated method stub

}
}

SECOND CLASS (WITH THE TRICK)
package com.sample.VideoViewExample;

import android.content.Context;
import android.widget.MediaController;

public class MediaController_2 extends MediaController{

    public MediaController_2(Context context) {
        super(context);

        // TODO Auto-generated constructor stub
    }

    public void hide() {
    }

}

the trick is just to create a new MediaController that extends Mediacontroller and which function hide() does nothing!
If you want to have a look at the MediaController source code for a better understanding, you can look here: // source code for MediaController http://hi-android.info/src/android/widget/MediaController.java.html
Hope this will be of help to sb,
JB

A: this worked for me. Just extend the media controller class. And override the hide method.
    MediaController mediaController = new MyMediaController(this, true);

public class MyMediaController extends MediaController {

    public MyMediaController(Context context, boolean useFastForward) {
        super(context, useFastForward);
    }

    @Override
    public void hide() {
        mediaController.show(0);
    }

}

A: From the answers given so far , now the issue is that back functionality will not work so to fix it follow this code.
public class CustomMediaController extends MediaController {

public CustomMediaController(Context context) {
    super(context);

    // TODO Auto-generated constructor stub
}

public void hide() {

}

// Needed to make the back functionality working
@Override
public boolean dispatchKeyEvent(KeyEvent event) {

    if(event.getKeyCode() == KeyEvent.KEYCODE_BACK) {

        super.hide();
        Activity activity = (Activity)getContext();
        activity.finish();

    }
   return super.dispatchKeyEvent(event);
}}

A: All you have to do is override the MediaController with your own class and then override the onTouchEvent.
public class SmartLinkVideoController extends MediaController implements MediaPlayerControl {

//declare needed variables
private SmartLinkVideoPlayer mVideoPlayer;

public SmartLinkVideoController(Context context) {
    super(context);
}

public SmartLinkVideoController(Context context, SmartLinkVideoPlayer videoPlayer) {
    this(context);
    this.setMediaPlayer(this);
    this.mVideoPlayer = videoPlayer;
}

@Override
public boolean onTouchEvent(MotionEvent event) {
    //super implementation sets default time to hide of ~ 3 seconds
    show(0);
    return true;
}

@Override
public void start() {
    mVideoPlayer.start();
}

@Override
public void pause() {
    mVideoPlayer.pause();
}

@Override
public int getDuration() {
    return mVideoPlayer.getDuration();
}

@Override
public int getCurrentPosition() {
    return mVideoPlayer.getCurrentPosition();
}

@Override
public void seekTo(int pos) {
    mVideoPlayer.seekTo(pos);
}

@Override
public boolean isPlaying() {
    return mVideoPlayer.isPlaying();
}

@Override
public int getBufferPercentage() {
    return mVideoPlayer.getPercentBuffered();
}

@Override
public boolean canPause() {
    return true;
}

@Override
public boolean canSeekBackward() {
    return true;
}

@Override
public boolean canSeekForward() {
    return true;
}

@Override
public int getAudioSessionId() {
    return 0;
}

public boolean hasVideoPlayer() {
    return (mVideoPlayer != null);
}

public void prepareVideo() {
    if(mVideoPlayer.getVideoType() == SmartLinkVideoPlayer.VIDEO_TYPE_INTERNAL
            || mVideoPlayer.getVideoType() == SmartLinkVideoPlayer.VIDEO_TYPE_EXPANSION)
        mVideoPlayer.prepare();
    else
        mVideoPlayer.prepareAsync();
}

public void prepareSurface(SurfaceHolder holder) {
    mVideoPlayer.setDisplay(holder);
}

public void rewindVideo() {
    mVideoPlayer.seekTo(0);
}

public void setVideoPlayer(SmartLinkVideoPlayer videoPlayer) {
    mVideoPlayer = videoPlayer;
}

public void stopVideoPlayer() {
    mVideoPlayer.stop();
}

public void resetVideoPlayer() {
    mVideoPlayer.reset();
}

public void releaseVideoPlayer() {
    mVideoPlayer.release();
    mVideoPlayer = null;
}
}


text:
Q: Should i still use Nexus Repository Manager even if I am the only developer in my network? I recently wanted to integrate Nexus to my home-based Java Project, just to learn what it is good for. As i read from the posts here, and from the nexus Website, its main usage aim is:

*

*Maven Central Repo has more than 200k artifacts. Get a local copy of your artifacts. Do not download every time you need them. When you specify an artifact, first nexus will be asked if it has the artifact, if yes it will be read from your local cache. if not nexus will download it from the central repo. Your build will continue to work regardless of the original artifact in Central Repo. Speed up your builds etc.

Now what i don't understand here is:  Is it not the same as maven does? First time when i define a new artifact in a pom.xml, the jar will be downloaded from the central repo. It will be placed in ~/.m2/repository. Next time it will be read from here as long as there is a copy of it. Even if i create a new project, the downloaded jars will be used from this repository.
I think, I would need Nexus if i have another developer in my network, who also needs these jars. So we would not need to download these jars separately from central. We would define a network based repo (Nexus) and the jars would be downloaded to this repository. Other developers would reach this repo without the need of reaching central repo.
In my case, i cant see any advantages of nexus. I now have this settings.xml which Nexus suggests to use:
<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0
                      http://maven.apache.org/xsd/settings-1.0.0.xsd">
  <localRepository/>
  <interactiveMode/>
  <usePluginRegistry/>
  <offline/>
  <pluginGroups/>
  <servers/>
    <mirrors>
    <mirror>
      <!--This sends everything else to /public -->
      <id>nexus</id>
      <mirrorOf>*</mirrorOf>
      <url>http://localhost:8081/nexus/content/groups/public</url>
    </mirror>
  </mirrors>
  <profiles>
    <profile>
      <id>nexus</id>
      <!--Enable snapshots for the built in central repo to direct -->
      <!--all requests to nexus via the mirror -->
      <repositories>
        <repository>
          <id>central</id>
          <url>http://central</url>
          <releases><enabled>true</enabled></releases>
          <snapshots><enabled>true</enabled></snapshots>
        </repository>
      </repositories>
     <pluginRepositories>
        <pluginRepository>
          <id>central</id>
          <url>http://central</url>
          <releases><enabled>true</enabled></releases>
          <snapshots><enabled>true</enabled></snapshots>
        </pluginRepository>
      </pluginRepositories>
    </profile>
  </profiles>
  <activeProfiles>
    <!--make the profile active all the time -->
    <activeProfile>nexus</activeProfile>
  </activeProfiles>
  <proxies/>
</settings>

The jars i have in /.m2/repository/ directory are exactly same as the jars in http://localhost:8081/nexus/content/groups/public/.
What is the advantage of Nexus in my case?

A: There are several advantages:

*

*When you start a new project, such as building an open source project from scratch, the downloads will be faster.

*If Maven Central is ever offline or responding slowly, it won't impact you as severely. The Nexus cache will buffer you from that.

*You can set up your own hosted repository and deploy your snapshot releases (complete with timestamp in the version name) "for real" - rather than just with -SNAPSHOT as in your .m2 cache

*It's a great way to learn how real Maven repositories work, which is an important skill inside a larger organization (and which you don't want to learn through trial-and-error on a production Nexus repo).

Edit
See: Sonatype: Why use a repository?


text:
Q: Networkx Multigraph from_pandas_dataframe Update:
The question, as written, is relevant to Networkx version < 2.0. The from_pandas_dataframe method has been dropped.
To accomplish the same task in Networkx >= 2.0, see the update to the accepted answer.
Trying to create a MultiGraph() instance from a pandas DataFrame using networkx's from_pandas_dataframe.  What am I doing wrong in the example below?
In [1]: import pandas as pd
        import networkx as nx

        df = pd.DataFrame([['geneA', 'geneB', 0.05, 'method1'],
                           ['geneA', 'geneC', 0.45, 'method1'],
                           ['geneA', 'geneD', 0.35, 'method1'],
                           ['geneA', 'geneB', 0.45, 'method2']],
                           columns = ['gene1','gene2','conf','type'])

First try with the default nx.Graph():
In [2]: G= nx.from_pandas_dataframe(df, 'gene1', 'gene2', edge_attr=['conf','type'],
                                    create_using=nx.Graph())

As a non-MultiGraph(), I'm missing one of the duplicate edges:
In [3]: G.edges(data=True)
Out[3]: [('geneA', 'geneB', {'conf': 0.45, 'type': 'method2'}),
         ('geneA', 'geneC', {'conf': 0.45, 'type': 'method1'}),
         ('geneA', 'geneD', {'conf': 0.35, 'type': 'method1'})]

With MultiGraph():
In [4]: MG= nx.from_pandas_dataframe(df, 'gene1', 'gene2', edge_attr=['conf','type'],
                             create_using=nx.MultiGraph())

This:
TypeError                                 Traceback (most recent call last)
<ipython-input-49-d2c7b8312ea7> in <module>()
----> 1 MG= nx.from_pandas_dataframe(df, 'gene1', 'gene2', ['conf','type'], create_using=nx.MultiGraph())

/usr/lib/python2.7/site-packages/networkx-1.10-py2.7.egg/networkx/convert_matrix.pyc in from_pandas_dataframe(df, source, target, edge_attr, create_using)
    209         # Iteration on values returns the rows as Numpy arrays
    210         for row in df.values:
--> 211             g.add_edge(row[src_i], row[tar_i], {i:row[j] for i, j in edge_i})
    212
    213     # If no column names are given, then just return the edges.

/usr/lib/python2.7/site-packages/networkx-1.10-py2.7.egg/networkx/classes/multigraph.pyc in add_edge(self, u, v, key, attr_dict, **attr)
    340             datadict.update(attr_dict)
    341             keydict = self.edge_key_dict_factory()
--> 342             keydict[key] = datadict
    343             self.adj[u][v] = keydict
    344             self.adj[v][u] = keydict

TypeError: unhashable type: 'dict'

Question
How do I instantiate a MultiGraph() from a pandas dataframe?

A: That's a nice question. I tried to reproduce your problem building your MultiGraph() in a different way, using only three/four columns with:
MG = nx.MultiGraph()

MG.add_weighted_edges_from([tuple(d) for d in df[['gene1','gene2','conf']].values])

this correctly returns as MG.edges(data=True):
[('geneA', 'geneB', {'weight': 0.05}), ('geneA', 'geneB', {'weight': 0.45}), ('geneA', 'geneC', {'weight': 0.45}), ('geneA', 'geneD', {'weight': 0.35})]

I tried also with your from_pandas_dataframe method using only three columns but it doesn't work:
MG = nx.from_pandas_dataframe(df, 'gene1', 'gene2', edge_attr='conf', create_using=nx.MultiGraph())

this returns the same error you encountered. I don't know if it is a bug or that method doesn't support more than one weight type for MultiGraph(). In the meantime you can use the above workaround to build your MultiGraph, at least with only one weight type. Hope that helps.

A: Networkx < 2.0:
It's was a bug, I opened an issue on GitHub, once I made the suggested edit:
It changed line 211 of convert_matrix.py to to read:
g.add_edge(row[src_i], row[tar_i], attr_dict={i:row[j] for i, j in edge_i})

Results from that change: (which have since been incorporated)
MG= nx.from_pandas_dataframe(df, 'gene1', 'gene2', edge_attr=['conf','type'],
                                 create_using=nx.MultiGraph())

MG.edges(data=True)
[('geneA', 'geneB', {'conf': 0.05, 'type': 'method1'}),
         ('geneA', 'geneB', {'conf': 0.45, 'type': 'method2'}),
         ('geneA', 'geneC', {'conf': 0.45, 'type': 'method1'}),
         ('geneA', 'geneD', {'conf': 0.35, 'type': 'method1'})]

Networkx >= 2.0:
In DataFrames with this format (edge list), use from_pandas_edgelist
MG= nx.from_pandas_edgelist(df, 'gene1', 'gene2', edge_attr=['conf','type'],
                             create_using=nx.MultiGraph())

MG.edges(data=True)
MultiEdgeDataView([('geneA', 'geneB', {'conf': 0.05, 'type': 'method1'}),
                   ('geneA', 'geneB', {'conf': 0.45, 'type': 'method2'}),
                   ('geneA', 'geneC', {'conf': 0.45, 'type': 'method1'}),
                   ('geneA', 'geneD', {'conf': 0.35, 'type': 'method1'})])


text:
Q: How to fix error in bitrise with android project Everything works fine for years and after one more build, error start occurs with build failed in bitirse.
install-missing-android-tools@3.0 (exit code: 1)

* What went wrong:
A problem occurred configuring root project 'src'.
> Could not resolve all artifacts for configuration ':classpath'.
   > Could not resolve commons-io:commons-io:2.6.
     Required by:
         project : > com.android.tools.build:gradle:7.0.3
         project : > com.android.tools.build:gradle:7.0.3 > androidx.databinding:databinding-compiler-common:7.0.3
      > Skipped due to earlier error
   > Could not resolve com.squareup:javapoet:1.13.0.
     Required by:
         project : > com.android.tools.build:gradle:7.0.3
[...]
and all others libs don't work

I'm not sure where to start find the source of the problem.
I have done my research and somehow it could be related to libraries, but that is only assumption.
Thanks


text:
Q: How to connect the library for http requests? I'm trying to connect the library to work with queries.
At first I tried to connect this
My steps:

*

*pip install requests

*in views.py:

    import requests
    ....
    def my_view(request):
        ...
        req = requests.get('https://api.github.com/events')`

And I get an error Internal Server Error
Also I tried to use urllib.request
in views.py:
    import urllib.request
    ....
    def my_view(request):
        ...
        req = urllib.request.Request('https://api.github.com/events')`

And I get an error Internal Server Error again
What am I doing wrong?
P.S
views.py file:
from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login, logout
import requests
import json
import urllib.request

def check_auth(request):

    #req = requests.get('https://api.github.com/events')

    #req = urllib.request.Request('https://api.github.com/events')

    return render(request, 'authorization/lc.html')

A: Ran the code from my own Django site, it seems to work. So it's probably a problem with the rest of your code.
One way to check is trying requests separately in your console
import requests

req=requests.get('https://api.github.com/events')
print(req.status_code)

If it works in console, it should work in Django view.
And just curious, why do you need to request another site on your own site?


text:
Q: Changing the boundaries in this double integral problem.
I am going to attempt this but with the following modification to the boundaries:
$$x=0\quad to\quad x=sin^{-1}y\\
y=0\quad to\quad y=1\\m=\int_0^1\int_0^{sin^{-1}y}ydxdy\\=\int_0^1ysin^{-1}ydy\\=\pi/8$$
I computed the inner integral assuming y is constant. It seems like I am not getting the same answer. Any reason why?


text:
Q: how to implement buttonless Dfu in App (Flutter Dart )without using any library i want to use Buttonless Dfu in flutter without any library , there is already one for Android+ios , but i wanted to implement for all platforms , so expecting that i can connect/read/write and set notifications by using ble , is there any tutorial or something if i can implement dfu by using these ble read/write and notifications only
or if someone can list setps like
write command 0x0...  to enter in Bootloader
then when device is in bootloader
set notification for 0x0.... characteristics
and and send zip file to .... this char.
something like this ,it would be really helpfull

A: Entering the bootloader
To enter the bootloader using the Nordic Buttonless DFU you need to write to a characteristic of the Buttonless Secure DFU Service which uses the 16-bit UUID 0xFE59. The actual characteristic depends on your settings. The Buttonless DFU can be used with or without bonds and would show a different characteristic for either one. Take a look at the documentation for more information about that.
The protocol to enter the bootloader is super simple:

To enter the bootloader, you need to send 0x01 to the characteristic. You will receive a response telling you the result of the operation. The message sequence diagram shows a successful response which is made of
0x20 -> defines this message as response
0x01 -> the command you requested (enter bootloader)
0x01 -> Success
Take a look the the documentation for more response codes.
Sending the firmware update
There is a very detailed page about the DFU protocol including a part especially about using BLE. It includes a message sequence chart describing the actual protocol where you can easily see in which order your messages need to be sent and to which characteristic.


text:
Q: ThinkPad T410 buttons I bought a T410 to use as an Ubuntu laptop for robotics work.
I can't find any info on what the buttons above the trackpad are for, and the online user manuals I've found can only be used in Windows, as part of the help system!
Could someone tell me what the upper buttons are for?
I really can't believe there's no PDF online for a user manual, but after some hours all I've found is a hardware service manual, which doesn't seem to have any clues.
Trial and error tells me what the two lower buttons do, and the red joystick.
A manual would be nice to help with BIOS fiddling, too. Sigh.

A: The buttons do exactly the same as the buttons below the track pad.
They are located so you can use them easily when you use the red 'joystick' instead of the track pad.


text:
Q: Update minicart.phtml when I update my product quantity I have made a pair of modifications in "/app/design/frontend/Venustheme/mohawk/Magento_Checkout/templates/cart", a pair of lines that calculates number of carries through the price (If price is 300€, it´s a carry).
Well, my problem is that I buy a product with price 8.20€ and my minicart shows this:

It´s correct, but if I modify the quantity, it doesn´t change until I refresh de page:
WRONG:

CORRECT: (AFTER REFRESH THE PAGE)

The web only update the price, but no my lines...
Any solution to this? It´s going me crazy.
Thank you for your answers.

A: I cannot speak to your specific theme that you've installed. However, I can tell you that I have modified the minicart many times. The data for the minicart is supplied from a specific data provider class \Magento\Checkout\CustomerData\Cart.
Natively, when Magento loads/reloads the minicart, the source data comes from that class. You mentioned that you put this logic into a phtml template. Generally, the minicart data is rendered through the use of an html template containing knockout js such as
    vendor/magento/module-tax/view/frontend/web/template/checkout/minicart/subtotal/totals.html
OR one of the files located inside this directory
    vendor/magento/module-checkout/view/frontend/web/template/minicart
Your best bet will be to create a plugin containing an afterGetSectionData() method and add your new data to the array in order to provide it to whatever template you are using. This SHOULD work but because it sounds like your theme is doing something a bit different from native Magento, it's difficult to guarantee.


text:
Q: Angular 2 routing issue I am using dropwizard for my back end services and angular 2 for my webapp.
I am currently facing an issue with angular routing while trying to bring up the details page.
I am able to bring up the main page (which is the MasterComponent page).
From the MasterComponent page, the user can click onto a row that will invoke the DetailsComponent page. When I click on the row to go the the details I get a HTTP 404 for this issue .
I am not clear how the angular URL should look so that it is able to invoke the details page?
HTTP Error I get
GET http://localhost:8199/detail 404 (Not Found)

In my dropwizard application I am serving the static assets as below
bootstrap.addBundle(new AssetsBundle("/static", "/dashboard", "index.html", "static-assets"));

These are my angular routes
const routes: Routes = [
  {path: '', redirectTo: '/dashboard', pathMatch: 'full'},
  {path: 'dashboard', component: DashboardComponent},
  {path: 'master', component: MasterComponent},
  {path: 'detail', component: DetailComponent}
  ];

From my master component, I specify the below to navigate to the details page
onRowClick(event) {
    window.open('./detail','_self' );
  }

Below is my index.html
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Web</title>
  <base href="/">

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
<dashboard-app></dashboard-app>
<script type="text/javascript" src="dashboard/inline.bundle.js"></script>
<script type="text/javascript" src="dashboard/polyfills.bundle.js"></script>
<script type="text/javascript" src="dashboard/styles.bundle.js">/script>
<script type="text/javascript" src="dashboard/vendor.bundle.js">/script>
<script type="text/javascript" src="dashboard/main.bundle.js"></script>
</body>
</html>

In my angular-cli.json file I specified the deployUrl": "dashboard/" attribute that maps the path in  index.html when I run ng build command.

A: You shouldn't be using window.open to navigate in SPA.
this.router.navigate(['detail'])
//OR
this.router.navigateByUrl('/detail')

Why you want to move user away from screen? You either navigate user to detail  page directly or open modal window.
If you still want to move user to next window you could use
window.open('/detail', '_blank')

A: If you need to use a modal "pop-up" try implementing a Bootstrap modal... link below.
https://www.w3schools.com/bootstrap/bootstrap_modal.asp


text:
Q: Access dynamically created objects in Javascript I am attempting to dynamically create an object with name-value pairs using html input fields. This is what i have so far:
var taskComplete = {
  newTask: function(arg) {
    var fieldObj = {},
        selector = arg,
        inputFields = document.getElementsByClassName(selector);
    for (var i=0;i<inputFields.length;i++) {
      var attrValue = inputFields[i].getAttribute("name"),
          value = inputFields[i].value,
          newFieldObj = fieldObj[i] = {[attrValue]: value };
      console.log(newFieldObj);
    }
  }
}
taskComplete.newTask('input');

The console log outputs:
Object {title: ""}
Object {description: ""}
Object {date: ""}

Question1:
How do i access these objects? they all share the same name eg. 'Object' so 'object.title' does not work.
Question2:
Is there a way to combine these objects into a single object?
eg.
var obj = {
  title: "",
  description: "",
  date: "",
}

code example with html: codepen.io
Hope this make sense. Thank you for any and all assistance.

A: Not super clear on what you are trying to do here.
Instead of creating a new object for each iteration of your loop, why not just assign those properties to the fieldObj you already have?
Then you can just return that object and do whatever you want with it in the calling code:
'use strict';

// ** TASK OBJECT ** //
var taskComplete = {
  newTask: function(selector) {
    var fieldObj = {},
        inputFields = document.getElementsByClassName(selector);

    for (var i = 0; i < inputFields.length; i++) {
      var attrKey = inputFields[i].getAttribute("name"),
          value = inputFields[i].value;

      fieldObj[attrKey] = value;
    }

    return fieldObj;
  }
}
var o = taskComplete.newTask('input');
console.dir(o);

http://codepen.io/anon/pen/reMLPB?editors=0010

A: I will answer your questions in the reverse order, makes more sense, you will see.

Question2: Is there a way to combine these objects into a single object?

Yes, I am happy to inform you that you absolutely can. Where you do
newFieldObj = fieldObj[i] = {[attrValue]: value };

simply do
fieldObj[attrValue] = value;

What this does, is the following: On the  fieldObj, which is a plain {} set a key named after the value of attrValue and pair that key with the value value

Question1: How do i access these objects? they all share the same name eg. 'Object' so 'object.title' does not work.

In order to be able to access these objects, your newTask method should be returning them. So, at the end of your newTask method, simply do return fieldObj; like so
var taskComplete = {
  newTask: function(arg) {
    var fieldObj = {},
        selector = arg,
        inputFields = document.getElementsByClassName(selector),
        attrValue,
        value;

    for (var i=0;i<inputFields.length;i++) {
      attrValue = inputFields[i].getAttribute("name");
      value = inputFields[i].value;
      fieldObj[attrValue] = value;
    }
    return fieldObj;
  }
}

and then store the returned value to a new variable like so:
var aFancyName = taskComplete.newTask('input');

Here's the modified pen: http://codepen.io/anon/pen/XdjKQJ


text:
Q: Registration Form Checking The Two Password Are Matching I want to make this registration script tell the user when the passwords they have entered are not matching.
and i use this code:
 if ($_POST['pass' != 'pass2'])
 {
  echo
   ("Oops! Password did not match! Try again. ");
 }

please help me to correct my coding. :-(
thanks so much!

A: if ($_POST['pass']!= $_POST['pass2'])
 {
     echo("Oops! Password did not match! Try again. ");
 }

.. i will use this code. and it also works. :-)
.. thanks for helping.

A: You should also check if the passwords were not left empty or if they are not just blank spaces. Otherwise, two uncompleted fields are valid.
if(trim($_POST['pass'])=='' || trim($_POST['pass2'])=='')
{
    echo('All fields are required!');
}
else if($_POST['pass'] != $_POST['pass2'])
{
    echo('Passwords do not match!');
}

A: You can't reference both the variables inside the same $_POST
if ($_POST['pass']!= $_POST['pass2'])
 {
     echo("Oops! Password did not match! Try again. ");
 }

A: if ($_POST['pass'] != $_POST['pass2'])

A: Inside the post you cannot reference both. So try this:
if(($_POST["pass"])!=($_POST["pass2"])){
    echo"Oops! Password did not match! Try again.";
}


text:
Q: C++ date output If i ask the user to input a date
and he entered "16 then 5 then 2010"
how can I display it this way
16/5/10

I only did it this way
cout<<day<<"/"<<month<<"/"<<year<<endl;

but the output appears this way

16/5/2010

A: You could just print the year modulo 100. For example,
int yr1 = 1973;
int yr2 = 2010;
std::cout << (yr1%100) << std::endl; // prints 73
std::cout << (yr2%100) << std::endl; // prints 10


text:
Q: How to do filter in the new Ember Data? Also how does filter compare to find in the new Ember Data What's the equivalent of
App.Person.filter(function(e){return e.get('age') == 30})

in the new Ember Data?

In the old Ember Data, App.Model.filter produced a different type of object versus App.Model.find (see this question). I discovered the type difference because if I wanted the record itself and make changes, I had to use filter. So find was kind of like read-only. (Correct me if I'm wrong.)
Is it the case in the new Ember Data?

A: In the new Ember Data (Beta 1.0.0) you can use the filter function from the DS.Store class. Unlike the previous filter function of the Model, you have to specify the type of Model you want:
this.get('store').filter('person', function(record){return record.get('age') == 30});


text:
Q: How can I cleanly express these dependencies? Consider this hypothetical scenario. I have a user form that has a collection of controls that are made available/unavailable based on certain criteria. One important criterion is product type. On selecting a product type, certain features on the form are made available. These features are also dependent on other criteria.
What is the clearest way I can represent this in OOP code? I'd like to be able to express this in such a way that an engineer can see a clear definition of which features are available per product type. I'd also like the ability to show, per feature, what criteria must be met to make that feature available. I'm torn between the following two options, represented as classes with collections of classes/an enum:
Option 1

*

*Product type A

*

*Feature 1

*Feature 2

*Product type B

*

*Feature 1

*Feature 3

*Feature 4

*Product type C

*

*Feature 2

*Product type D

*

*Feature 1

*Feature 4

Option 2

*

*Feature 1

*

*Product type A

*Product type B

*Product type D

*Additional criterion X

*Feature 2

*

*Product type A

*Product type C

*Additional criterion X

*Additional criterion Y

*Feature 3

*

*Product type B

*Feature 4

*

*Product type B

*Product type D

*Additional criterion Y

*Additional criterion Z

I'd also like to design this to conform as closely as possible to the open-closed principle. It should be easy to add either a new product type or a new feature without modifying the existing code.
Since each concept (feature/product) has a dependency on the other, I'm struggling to figure out the best way to accomplish this.

A: It's difficult to say without knowing what different type of criteria could be, but this is an aproximation.

*

*Have Feature implement ConditionalFeature interface

*ConditionalFeatures have Criteria

*ConditionalFeatures have UIElements

*A Criterion have CriterionComponents

*A CriterionComponent can be inspected to find out if it meets the criteria

*Product implements CriterionComponent interface

*Implementors of ConditionalFeature chek if all Criteria are met and toggle the UIElements

*CriterionComponents can be added to Criteria

*Criteria can be added to ConditionalFeature etc.


text:
Q: Problems with xampp server I work with xampp for localhost wordpress web page, but xampp is getting lower and lower.
There are something I would do to fix it? Or you can say other program to work in local with wordpress?
Thanks you. :)

A: Please use updated version of xammp:https://www.apachefriends.org/download.html


text:
Q: SQL Server bulk insert error while inserting .txt file I'm using SQL Server 2012 and when using bulk insert, the following error occurs:

Msg 4832, Level 16, State 1, Line 1
  Bulk load: An unexpected end of file was encountered in the data file.
  Msg 7399, Level 16, State 1, Line 1
  The OLE DB provider "BULK" for linked server "(null)" reported an error. The provider did not give any information about the error.
  Msg 7330, Level 16, State 2, Line 1
  Cannot fetch a row from OLE DB provider "BULK" for linked server "(null)".

My query is:
BULK INSERT _bulk
FROM 'D:\Twilight\Personal\Alexander\result.txt'
WITH (FIELDTERMINATOR = ',', ROWTERMINATOR = '\n')

The data contained in my .txt file is:
1,alex,trichy
2,arun,namakkal
3,shiva,chennai

A: Most likely your rows are terminated by \r\n instead of \n.
You can check this in text editors like Notepad++ or Sublime.
If the command below works, the line-endings were the issue:
BULK INSERT _bulk
FROM 'D:\Twilight\Personal\Alexander\result.txt'
WITH (FIELDTERMINATOR = ',', ROWTERMINATOR = '\r\n')


text:
Q: How to implement Web Worker using React, Typescript and Mobx? I have a mobx store (admisionStore) which contain actions and observables, some of the actions load data from the API using Axios, but it is a long running task that slow the UI, I read about web worker and they may be helpful in this scenario.
I follwed the guidelines in this article: https://dev.to/nicolasrannou/web-workers-in-create-react-app-cra-without-unmounting-4865 and this is what I have:
//typings-custom/custom.d.ts

declare module 'worker-loader!*' {
  class WebpackWorker extends Worker {
    constructor();
  }

  export default WebpackWorker;
}

//worker.ts

import {expose} from 'comlink';
export interface WorkerType {
  busy(value: number): number;
}

const obj: WorkerType = {
  busy(value: number) {
    let j = 0;
    const start = Date.now();

    for (let i = 0; i < value; i++) {
      //
      j++;
      const end = Date.now();
      // if it has been busy for more than 10s return
      if (end - start > 10000) {
        return i;
      }
    }
    return j;
  },
};

expose(obj);

//App.tsx

import React from 'react';
import {wrap} from 'comlink';
/* eslint-disable import/no-webpack-loader-syntax */
import Worker from 'worker-loader!./worker';
import { WorkerType } from './worker';

const handle = async () => {
startDummyWorker()
};

async function startDummyWorker() {
  const worker = new Worker();
  const obj = wrap<WorkerType>(worker);
  const finished = await obj.busy(10000000000000000000);
  console.log(finished);
}

const App = () => {
  return (
    <div>
      <button onClick={handle}>Press</button>
      <button onClick={() => console.log('HOLA')}>press2</button>
    </div>
  );
};

export default App;

//webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /\.worker\.(js|ts)$/i,
        use: [
          {
            loader: 'worker-loader',
          },
        ],
      },
    ],
  },
};

As you can see I had to create a type declaration file for typescript as well as an interface WorkerType otherwise typescript will complain, I also created a webpack.config.js file in order to cofigure worker-loader: https://webpack.js.org/loaders/worker-loader/#config
Everything works fine, but when I tried to implement this approach in React, using mobx as my state management, it didn't work. This is my code:
//worker.ts

import { expose } from 'comlink';
import { useContext } from 'react';
import { RootStoreContext } from '../app/stores/rootStore';
export interface WorkerType {
  load(): void;
}

const rootStore = useContext(RootStoreContext);
const { loadAsegurado } = rootStore.admisionStore;

const admisionWorker: WorkerType = {
  load() {
    loadAsegurado; //mobx action loadAsegurado: () => Promise<void>
  },
};
expose(admisionWorker);

//AdmisionDashboard.tsx
import React, { useContext, useEffect} from 'react';
import { observer } from 'mobx-react-lite';
import { RootStoreContext } from '../../../../app/stores/rootStore';
import { wrap } from 'comlink';
/* eslint-disable import/no-webpack-loader-syntax */
import Worker from 'worker-loader!../../../../my-first-worker/worker';
import { WorkerType } from '../../../../my-first-worker/worker';

function startAdmisionWorker() {
  const worker = new Worker();
  const workerApi = wrap<WorkerType>(worker);
  workerApi.load();
}

const AdmisionDashboard=()=>{
const rootStore = useContext(RootStoreContext);
const {loadAsegurado, setOperacion} = rootStore.admisionStore
const { token } = rootStore.commonStore;

useEffect(() => {
    if (token === null) {
      history.push('/');
    } else {
      setOperacion('buscar');
      startAdmisionWorker();//Here I start my web worker
    }
  }, [setOperacion, token]);

[...] // rest of the code
}
export default observer(AdmisionDashboard);

When I start the application I get this log:
Microsoft Windows [Version 6.3.9600]
(c) 2013 Microsoft Corporation. All rights reserved.

C:\Users\Desarrollo\Desktop\NHME-app>npm start

> admision-app@0.1.0 start C:\Users\Desarrollo\Desktop\NHME-app
> react-scripts start

Starting the development server...

<--- Last few GCs --->

[12160:0000007516C6E060]   265687 ms: Scavenge 2006.3 (2067.4) -> 1992.7 (2068.2) MB, 38.8 / 0.1 ms  (average mu = 0.260, current mu = 0.315) allocation failure
[12160:0000007516C6E060]   268205 ms: Mark-sweep 2010.8 (2071.5) -> 1993.4 (2068.1) MB, 2315.7 / 0.4 ms  (average mu = 0.224, current mu = 0.184) allocation failure scavenge might not succeed

<--- JS stacktrace --->

==== JS stack trace =========================================

    0: ExitFrame [pc: 00007FF69AC6463D]
Security context: 0x02baba3008a1 <JSObject>
    1: /* anonymous */ [000002B6DF429F31] [C:\Users\Desarrollo\Desktop\NHME-app\node_modules\webpack\node_modules\acorn\dist\acorn.js:~2945] [pc=0000017352FE77BB](this=0x0282de28a389 <Parser map = 0000010C5D327E41>)
    2: /* anonymous */ [000002B6DF428BB1] [C:\Users\Desarrollo\Desktop\NHME-app\node_modules\webpack\node_modules\acorn\dist\acorn.js:1155] [b...

FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory

Writing Node.js report to file: report.20200828.085936.12160.0.001.json
Node.js report completed
 1: 00007FF69A09232F napi_wrap+124543
 2: 00007FF69A0336A6 public: bool __cdecl v8::base::CPU::has_sse(void)const __ptr64+34502
 3: 00007FF69A034366 public: bool __cdecl v8::base::CPU::has_sse(void)const __ptr64+37766
 4: 00007FF69A838C5E private: void __cdecl v8::Isolate::ReportExternalAllocationLimitReached(void) __ptr64+94
 5: 00007FF69A820CA1 public: class v8::SharedArrayBuffer::Contents __cdecl v8::SharedArrayBuffer::Externalize(void) __ptr64+833
 6: 00007FF69A6EE56C public: static void __cdecl v8::internal::Heap::EphemeronKeyWriteBarrierFromCode(unsigned __int64,unsigned __int64,class v8::internal::Isolate * __ptr64)+1436
 7: 00007FF69A6F9910 public: void __cdecl v8::internal::Heap::ProtectUnprotectedMemoryChunks(void) __ptr64+1312
 8: 00007FF69A6F6444 public: static bool __cdecl v8::internal::Heap::PageFlagsAreConsistent(class v8::internal::HeapObject)+3204
 9: 00007FF69A6EBCD3 public: bool __cdecl v8::internal::Heap::CollectGarbage(enum v8::internal::AllocationSpace,enum v8::internal::GarbageCollectionReason,enum v8::GCCallbackFlags) __ptr64+1283
10: 00007FF69A6EA4A4 public: void __cdecl v8::internal::Heap::AddRetainedMap(class v8::internal::Handle<class v8::internal::Map>) __ptr64+2356
11: 00007FF69A70B775 public: class v8::internal::Handle<class v8::internal::HeapObject> __cdecl v8::internal::Factory::NewFillerObject(int,bool,enum v8::internal::AllocationType) __ptr64+53
12: 00007FF69A477A49 ??4iterator@JumpTableTargetOffsets@interpreter@internal@v8@@QEAAAEAV01234@$$QEAV01234@@Z+4057
13: 00007FF69AC6463D public: virtual bool __cdecl v8::internal::SetupIsolateDelegate::SetupHeap(class v8::internal::Heap * __ptr64) __ptr64+567949
14: 0000017352FE77BB
npm ERR! code ELIFECYCLE
npm ERR! errno 134
npm ERR! admision-app@0.1.0 start: `react-scripts start`
npm ERR! Exit status 134
npm ERR!
npm ERR! Failed at the admision-app@0.1.0 start script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\Desarrollo\AppData\Roaming\npm-cache\_logs\2020-08-28T14_59_37_653Z-debug.log

C:\Users\Desarrollo\Desktop\NHME-app>

Any suggestion would be greatly appreciated. Thanks in advance.


text:
Q: powershell set variable then pass to filter? I need to filter 30 types of file from 2T of data, i want to set a variable for get-childitem then pass to -filter for different type of files, but it doesn't work.....any idea why? The idea was if I use get-childitem 30 times it will slow down the system, so I only want to do it once and set the output as a variable and use it for filtering different types of files.
$a = Get-ChildItem -Recurse c:\work
$a -filter .prt | .............

Any suggestion please!

A: You can use Where-Object and filter off of the Name parameter. You can't use -filter on a variable.
Also, you need a wildcard to filter all files ending with ".prt" (if that's what you're trying to do).
$a = Get-ChildItem -Recurse c:\work
$a | Where-Object {$_.Name -like '*.prt'} | ...

A: It is usually best to include only the data you're after rather than filtering it from a larger collection; consider using the -include parameter to achieve this.  For example:
#Non-recursive
$fileTypes = @("*.prt","*.doc")
$a = Get-ChildItem c:\work\* -include $fileTypes

#Recursive
$fileTypes = @("*.prt","*.doc")
$a = Get-ChildItem c:\work\* -include $fileTypes -recurse


text:
Q: Why content of folder deleted while restarting tomcat ? How to fix it Thanks in advance.
I created a web application that upload photo dynamically and I stored them locally at deployment path.
But while starting tomcat again it delete that folder and its content.
Is there any way to restore that content before restarting tomcat.


text:
Q: Can I install the disc-based DLC for my digital copy of Skyrim? I have a digital copy of Spirit on my Xbox 360 and I'm thinking about getting a disc copy that has the dlc's to put on my Xbox. Is that possible?

A: Yes, The Elder Scrolls V Skyrim: Legendary Edition is a 2-disk edition of the game, which includes all dlc packs.
The first disk contains the game as normal. The second disk contains the dlc packs, which you must install to your consoles HDD to use. You will need sufficient space on your HDD to install the content as it won't run from disk.


text:
Q: GGPlots legend colors more clear Is there any way  I can make these colour more obvious in my geom_bar ggplot graph? In particular the blue / green ones. Also is there a way to have a white line/space between the colors as the top and bottom ones do?

A: colour = "white" should help you differentiate the colours. If not, then increase size=2. For example:
library(vcd)
data(Arthritis)
ggplot(Arthritis, aes(x = Treatment, fill = Improved)) +
  geom_bar(colour = "white", size=2)


text:
Q: Dispatcher failed to deliver Message (Spring Integration) I'm developing my first flow app with Spring Integration. Shortly, my goal is to obtain files json from a tar.gz. I finished and it work well but at the end, the gateway send an exception instead to end.
The context is this:
<int:poller default="true" fixed-delay="0" />

<int:gateway id="extractedFolderProcess" default-reply-channel="endFlow"
    default-request-channel="inputChannelDatasetPath"
    error-channel="error_channel"
    service-interface="com.javarticles.spring.integration.utilities.ExtractedFolderProcess">
</int:gateway>

<int:channel id="error_channel"/>

<int:filter id="nullMessage" input-channel="error_channel" ref="errorFlow" />

<int:channel id="inputChannelDatasetPath"/>

<int:channel id="endFlow" />

<int:channel id="filesIn" >
    <int:queue />
</int:channel>

<int:channel id="jsonChannel">
    <int:queue />
</int:channel>

<int:channel id="extractedJsonChannel">
    <int:queue />
</int:channel>

<task:executor id="executor" pool-size="2" />

<int:splitter id="unzipSplitter" input-channel="inputChannelDatasetPath"  ref="unziperDataset" output-channel="filesIn"/>

<int:splitter id="testSplitter" input-channel="filesIn" ref="jsonSplitter" output-channel="jsonChannel">
    <int:poller task-executor="executor" fixed-delay="1000" />
</int:splitter>

<int:aggregator input-channel="jsonChannel" ref="jsonAggregator" output-channel="extractedJsonChannel" method="add"/>

<int:aggregator input-channel="extractedJsonChannel"
ref="sumAggregator" output-channel="endFlow"
method="add"
release-strategy="releaseStrategySumAggregator"
correlation-strategy="correlationIdStrategySumAggregator" />

<bean id="errorFlow" class="com.javarticles.spring.integration.endPoints.ErrorFlow" />
<bean id="releaseStrategySumAggregator" class="com.javarticles.spring.integration.utilities.ReleaseStrategySumAggregator" />
<bean id="correlationIdStrategySumAggregator" class="com.javarticles.spring.integration.utilities.CorrelationIdStrategySumAggregator" />
<bean id="jsonSplitter" class="com.javarticles.spring.integration.endPoints.JsonSplitter" />
<bean id="unziperDataset" class="com.javarticles.spring.integration.endPoints.UnzipDataset" />
<bean id="jsonAggregator" class="com.javarticles.spring.integration.endPoints.JsonAggregator"/>
<bean id="sumAggregator" class="com.javarticles.spring.integration.endPoints.SumAggregator" />

and stackstrace shows this:
2018-09-10 14:28:36 ERROR LoggingHandler:192 - org.springframework.messaging.MessagingException: Dispatcher failed to deliver Message; nested exception is org.springframework.messaging.core.DestinationResolutionException: no output-channel or replyChannel header available, failedMessage=GenericMessage [payload=15878, headers={sequenceNumber=5875, correlationId=0, check=0, id=06f00498-e3ea-2dd0-e5e0-5663974e0e45, sequenceSize=5875, timestamp=1536582516348}]
at org.springframework.integration.dispatcher.AbstractDispatcher.wrapExceptionIfNecessary(AbstractDispatcher.java:133)
at org.springframework.integration.dispatcher.AbstractDispatcher.tryOptimizedDispatch(AbstractDispatcher.java:120)
at org.springframework.integration.dispatcher.UnicastingDispatcher.doDispatch(UnicastingDispatcher.java:148)
at org.springframework.integration.dispatcher.UnicastingDispatcher.dispatch(UnicastingDispatcher.java:121)
at org.springframework.integration.channel.AbstractSubscribableChannel.doSend(AbstractSubscribableChannel.java:89)
at org.springframework.integration.channel.AbstractMessageChannel.send(AbstractMessageChannel.java:423)
at org.springframework.integration.channel.AbstractMessageChannel.send(AbstractMessageChannel.java:373)
at org.springframework.messaging.core.GenericMessagingTemplate.doSend(GenericMessagingTemplate.java:115)
at org.springframework.messaging.core.GenericMessagingTemplate.doSend(GenericMessagingTemplate.java:45)
at org.springframework.messaging.core.AbstractMessageSendingTemplate.send(AbstractMessageSendingTemplate.java:105)
at org.springframework.integration.handler.AbstractMessageProducingHandler.sendOutput(AbstractMessageProducingHandler.java:292)
at org.springframework.integration.handler.AbstractMessageProducingHandler.produceOutput(AbstractMessageProducingHandler.java:212)
at org.springframework.integration.handler.AbstractMessageProducingHandler.sendOutputs(AbstractMessageProducingHandler.java:129)
at org.springframework.integration.aggregator.AbstractCorrelatingMessageHandler.completeGroup(AbstractCorrelatingMessageHandler.java:671)
at org.springframework.integration.aggregator.AbstractCorrelatingMessageHandler.handleMessageInternal(AbstractCorrelatingMessageHandler.java:418)
at org.springframework.integration.handler.AbstractMessageHandler.handleMessage(AbstractMessageHandler.java:127)
at org.springframework.integration.endpoint.PollingConsumer.handleMessage(PollingConsumer.java:129)
at org.springframework.integration.endpoint.AbstractPollingEndpoint.doPoll(AbstractPollingEndpoint.java:272)
at org.springframework.integration.endpoint.AbstractPollingEndpoint.access$000(AbstractPollingEndpoint.java:58)
at org.springframework.integration.endpoint.AbstractPollingEndpoint$1.call(AbstractPollingEndpoint.java:190)
at org.springframework.integration.endpoint.AbstractPollingEndpoint$1.call(AbstractPollingEndpoint.java:186)
at org.springframework.integration.endpoint.AbstractPollingEndpoint$Poller$1.run(AbstractPollingEndpoint.java:353)
at org.springframework.integration.util.ErrorHandlingTaskExecutor$1.run(ErrorHandlingTaskExecutor.java:55)
at org.springframework.core.task.SyncTaskExecutor.execute(SyncTaskExecutor.java:50)
at org.springframework.integration.util.ErrorHandlingTaskExecutor.execute(ErrorHandlingTaskExecutor.java:51)
at org.springframework.integration.endpoint.AbstractPollingEndpoint$Poller.run(AbstractPollingEndpoint.java:344)
at org.springframework.scheduling.support.DelegatingErrorHandlingRunnable.run(DelegatingErrorHandlingRunnable.java:54)
at org.springframework.scheduling.concurrent.ReschedulingRunnable.run(ReschedulingRunnable.java:81)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:180)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:293)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Caused by: org.springframework.messaging.core.DestinationResolutionException: no output-channel or replyChannel header available
at org.springframework.integration.handler.AbstractMessageProducingHandler.sendOutput(AbstractMessageProducingHandler.java:287)
at org.springframework.integration.handler.AbstractMessageProducingHandler.produceOutput(AbstractMessageProducingHandler.java:212)
at org.springframework.integration.handler.AbstractMessageProducingHandler.sendOutputs(AbstractMessageProducingHandler.java:129)
at org.springframework.integration.handler.AbstractReplyProducingMessageHandler.handleMessageInternal(AbstractReplyProducingMessageHandler.java:115)
at org.springframework.integration.handler.AbstractMessageHandler.handleMessage(AbstractMessageHandler.java:127)
at org.springframework.integration.dispatcher.AbstractDispatcher.tryOptimizedDispatch(AbstractDispatcher.java:116)
... 33 more

Probably the message sended by second Aggregator has a bad headers, but I'm not sure. How can I resolve?

A: There are multiple problems with your configuration.
Your filesIn, jsonChannel, extractedJsonChannel are all pollable channels, however, the only polling consumer I see is testSplitter. So I don't really see how any of the aggregators getting messages.
I would suggest to change those channels to DirectChannels (remove <queue>) as a starting point.


text:
Q: Dragged out, left it hanging
I've let this chapter hang for two days now.

I've left this chapter hanging for two days now.

This chapter has been hanging for two days now.

I've dragged this chapter out for two days now.

Do all these sentences sound natural?
Like if something is left hanging it's left unresolved or unaddressed. So if you're reading a book, but if you're not ready for the second hand embarrassment, you put it away for a while. This is what this question is basically about. Like you haven't been able to finish reading a chapter, cause you always end up putting the book away for a couple hours.
Someone was reading a book. And a particular chapter was too cliched and cringey. So that person was reading it on and off for two days.
Second context: Someone's writing a book and has hit a writer's block and is having trouble finishing this chapter.
The context I had in my mind was former.

A: Sorry to say that none of these sound to me like you are describing writer's block.
When you say that you "let" or "left" the chapter hanging, it sounds like a deliberate thing you are doing.
Also, to "drag something out" means to unnecessarily elongate something. Again, it sounds partially deliberate, that you've taken your time. It could also be taken to mean that you completed it after 2 days.
As you appear to be anthropomorphising the chapter, speaking as if it already exists when you are actually still trying to write it, I would try to word it so that the blame is on the chapter, not you. You want the chapter to come out, but it won't.
How about:

I've been wrestling with this chapter for 2 days now.

or

This chapter has been stuck in my mind for 2 days now and won't come out.

A: If you want to be clear on your intended meaning, which involves reading rather than writing, say so. And if your focus is your reason for delay, avoid a construction that implies double agency.

I have dilly-dallied over reading this chapter for days because …

or

For days, I have fruitlessly tried to read this chapter all the way through because …

or

I cannot seem to read all the way through this chapter because …

or

This chapter is hard reading for me because …

There must be hundreds of ways to express this thought. None of yours seems particularly apt because none mentions reading.


text:
Q: Работа с UART на Arduino и atmega328p Я написал скрипт для управления шимом на пяти выходах микроконтроллера по COM-порту: посылаешь с компьютера строку вида "1;1;1;1;1\n", где число между разделителями в пределах [0,2] пересчитывается на мк в шим от 0 до 255 соответственно. На микроконтроллере по приходу данных срабатывает прерывание, которое читает из порта до '\n' и выставляет флаг, что данные получены. По этому флагу в основном цикле программы включаются функции, которые разбирают строку на числа, пересчитывают и кладут в регистры OCRхх соответствующих таймеров.
Ниже основная часть кода:
#define BAUD 9600
#define FOSC 16000000
#define MYUBRR FOSC/16/BAUD -1

#define T1_PB1 1
#define T1_PB2 2
#define T0_PD1 5
#define T0_PD2 6
#define T2_PD3 3

#define num_of_leds 5

float leds[num_of_leds];
int out_p[num_of_leds] = {1, 2, 5, 6, 3};

volatile unsigned char data_in[22];
volatile unsigned char *command_in;

volatile unsigned char data_count;
volatile unsigned char ready;

void set_pwm(int i, int pwm) {
switch(i) {
  case 1:
      OCR1A = pwm;
      break;
  case 2:
      OCR1B = pwm;
      break;
  case 5:
      OCR0A = pwm;
      break;
  case 6:
      OCR0B = pwm;
      break;
  case 3:
      OCR2B = pwm;
      break;
  default:
      break;
  }
}

void uart_init(void) {
      UBRR0H = (MYUBRR >> 8);
      UBRR0L = MYUBRR;

      UCSR0B |= (1 << RXEN0) | (1 << TXEN0);
      UCSR0B |= (1 << RXCIE0);
      UCSR0C |= (1 << UCSZ01) | (1 << UCSZ00);
}

// главная функция
void process() {
      // разбивает строку на числа
      char* pch = strtok(command_in, ";");
      int i = 0;
      while (pch != NULL) {
            leds[i] = char_to_float(pch);
            pch = strtok(NULL, ";");
            i++;
      }

      // присваивает значения шима регистрам
      int pwm;
      for(int i = 0; i < num_of_leds; i++) {
      pwm = (led[i]*255)/2;
      set_pwm(out_p[i], pwm);
      }
}

int main(void) {
      pin_init();
      timer_init();
      uart_init();
      sei();

      while(1) {
            if (ready == TRUE) {
                  command();
                  ready = FALSE;
            }
    }
 }

 ISR (USART_RX_vect) {
       data_in[data_count] = UDR0;
       if (data_in[data_count] == '\n') {
             ready = TRUE;
             data_count = 0;
       } else {
             data_count++;
       }
 }

В итоге работает так: я посылаю "1;1;1;1;1\n" - 5 диодов горят с 127 шим. Посылаю следом "0.5;1;1;1;1\n" - первый диод притухает до ~64, а остальные продолжают гореть, как раньше.
Я тестировал на Arduino Nano - все работает так, как описано выше. А на голой atmega328p ведет себя следующим образом: когда приходит строка, зажигается (вспыхивает на миг) только один диод (тот, чей регистр в массиве out_p с нулевым индексом). Если в этот цикл дописать вывод в ком-порт, то можно увидеть, что цикл работает только одну итерацию (i = 0), и присваивает значение шим только первому регистру.
for(int i = 0; i < num_of_motors; i++) {
    pwm = (leds[i]*255)/period;
    print(pwm);                       // вывод: b'127\n'
    set_pwm(out_p[i], pwm);
}

Я понимаю, что дело тут как-то связано с прерыванием, но не понимаю, что я должен исправить. Почему в ардуино все отрабатывает корректно, а здесь значения в регистрах сбрасываются?
И еще один вопрос: каждый раз при инициализации порта ардуино перезагружается(?) - по крайней мере кат это выглядит. Как мне сделать то же самое с голой атмегой?
UPD:  Микроконтроллер Atmega328p, тактируется от внешнего кварца на 16 МГц, фьюзы: high 0xdf, low 0xff


text:
Q: OpenCV: declaring GPU matrix In OpenCV 2.4.3, I am trying to delcare one GPU matrix in this way:
cv::VideoCapture video;
video.open("sample.avi");
cv::Mat source;
for ( int n = 0; n < 500; n ++ )
{
    video >> source;
    cv::gpu::GpuMat gpuMat ( source );
}

Then I got the following error for the gpu matrix declaration:
Error: incomplete type is not allowed

What mistake did I make here? Thanks.

A: Usually this is associated with missing an include statement. Double check all the necessary includes are present.

A: For opencv4, try this
#include <opencv2/cudaarithm.hpp>

fixed problem for me


text:
Q: Playstation Online Store & D.M.R.ights DMR. Digital Media Rights - correct?
If you own a PS4 and download full games on the PS.Store, like I have for at least three games I've purchased. When does that ownership expire? The answer should be never, since I paid for them. But I want to know the details...
Are they locked to the Playstation Network ID? If I sell my Ps4 in 10 years. And buy another 10 years later. Can I simply login on a new Ps4, and have my games?
10 years is long. By then something like Witcher 3 will be a full remake remodel hologram made out of chrome by then. So lets say 3 years.

A: Games you buy through PSN are locked to your account. They're yours forever to keep and download on any Playstation where you're logged in, as long as your account is in good standing and PSN exists. However, Sony reserves the right to remove your access to a game you bought if they deem it necessary. They also won't issue a refund if that happens.


text:
Q: How to get Jquery to work in Docpad in the boilplate skeletion with grunt This is my grunt configuration file. Jquery is not rendered into the all.min.js, there also is no vendor directory in my out directory, I would assume that docpad is supposed to gernerate teh vendor directory inside of the out directory but it doesnt, why might this be?
{
  "min": {
    "js": {
      "src": ["out/vendor/jquery.js", "out/vendor/log.js", "out/vendor/modernizr.js", "out/scripts/script.js"],
      "dest": "out/scripts/all.min.js"
    }
  },
  "concat": {
    "css": {
      "src": ["out/vendor/normalize.css","out/styles/style.css","out/styles/animate.css"],
      "dest": "out/styles/all.css"
    }
  },
  "cssmin": {
    "all": {
      "src": ["out/styles/all.css"],
      "dest": "out/styles/all.min.css"
    }
  }
}

A: I'm having a similar yet seemingly different issue @ How to have a the docpad grunt skeleton min vendor js files with live reload
If you wanted CDN caching advantage for jQuery you'd want to call it directly on a template instead of through grunt (then you're dealing with caching 24k vs another httprequest). There are other vendor scripts one might want to be able to use with this skeleton however. :)
not allowed to comment yet, but I felt this might be of some use. not an answer. aside from copying out /src/ dir out and just reinstalling the skeleton again. :p sometimes docpad gets a little wonky.


text:
Q: Change the color of instantited prefabs i want to change the color of instantiated prefabs
i was able to get to this point but the instantiated prefabs color stays the same , but the materiel colors changed
here is the code
public class InstantiatePrefabs : MonoBehaviour
{
    public GameObject cube;
    Renderer rend;

    Color[] colors = new Color[6];
    // Start is called before the first frame update
    void Start()
    {
        rend = GetComponent<Renderer>();
        InvokeRepeating("Spawn", 0, 3);

    }

    public void Spawn()
    {

        float x = Random.Range(-2, 2);

        GameObject newCube = (GameObject)Instantiate(cube) as GameObject;
        newCube.transform.position = new Vector2(x,6);
        int randcol = Random.Range(1, 6);
        if (randcol == 1)
        {
            rend.material.color = Color.red;

            // print("red");
        }
        if (randcol == 2)
        {
            //  print("green");
            rend.material.color = Color.green;
        }
        if (randcol == 3)
        {
            rend.material.color = Color.blue;
        }
        if (randcol == 4)
        {
            rend.material.color = Color.yellow;
        }

    }

A: Your issue is that you were gettiing the Renderer of the GameObject instantiating the Cubes not the Renderer of the Cubes.
public class InstantiatePrefabs : MonoBehaviour
{
    public GameObject cube;
    public Color[] colors;

    void Start()
    {
        InvokeRepeating("Spawn", 0, 3);
    }

    public void Spawn()
    {
        float x = Random.Range(-2, 2);

        GameObject newCube = (GameObject)Instantiate(cube) as GameObject;
        newCube.transform.position = new Vector2(x,6);

        // Get the Cubes Renderer
        Renderer rend = newCube.GetComponent<Renderer>();

        //Select a random Color from the Colors set in the inspector
        //Making this dynamic you can change the colors and this will select a random color within the range of colors.
        Color randcol = colors[Random.Range(0, colors.Length)]

        //Set color to the cubes Renderer
        rend.material.color = randcol;

         //OR use the if statements like you were (not the best way!)
        /*
        int rand = Random.Range(1, 5)
        if (rand == 1)
        {
            rend.material.color = Color.red;
            // print("red");
        }
        if (rand == 2)
        {
            //  print("green");
            rend.material.color = Color.green;
        }
        if (rand == 3)
        {
            rend.material.color = Color.blue;
        }
        if (rand == 4)
        {
            rend.material.color = Color.yellow;
        }
        */
    }
}

If you have any questions about my changes don't hesitate to ask.


text:
Q: Show that $k[x]/(x^{2})$ is an indecomposable (1), but not irreducible (2) $k[x]$-module. Exercise: Show that $k[x]/(x^{2})$ is an indecomposable (1), but not irreducible (2) $k[x]$-module.

I'm not sure about all different kind of modules, but this is a question of a book about associative algebras. It is not really exercise, it is just stated in the text, so  I guess it must be rather trivial, but I'm not getting it. I think it may be I forgot some old ring theory/linear algebra stuff.
If I understand correctly: $k[x]/(x^{2})$ can be seen as $\{a+bx: a,b \in k\}$.
So for (1), I must show that there don't exist two non-zero representation $V_{1},V_{2}$ of $k[x]$so that $k[x]/(x^{2})$ is isomorphic to $V_{1}\oplus V_{2}$. Well as $k[x]/(x^{2})$ is 2 dimensional. $V_{1},V_{2}$ have to be $1$ dimensional. But I'm not sure how the 1-dimensional subrepresentation look like. Are they just isomorphic to $k$ ?
For (2), I need to show there exist an non-trivial subrepresention. So I have to show there exists a subspace $W$ of $\{a+bx: a,b \in k\}$ such that $fW \subset W$ for any polynomial $f$. Well, that seems impossible to me. I can't think of any if $W=k$, then $x\cdot \alpha$ is not in $W$. If $W=\{bx:b\in k\}$ then $bx bx$ is not in $W$.

I feel like I look at this the complete wrong way, feel free to ignore all my stuff above, and show me a way how to look at this. :)

A: 1) A one-dimensional space over $k$ always looks like $k$.  Think about what copies of $k$ there are, and which ones are invariant.
2) Why do you say that $bxbx\notin W$?  $bxbx = b^2 x^2 = 0 \in W$.

A: For a field $k$, $k[x]$ is a principal ideal ring. By the correspondence theorem, the only ideals of $k[x]/(x^2)$ are those generated by divisors of $x^2$. Thus $k[x]/(x^2)$ has exactly three submodules: $(x^2)/(x^2),(x)/(x^2)$ and $k[x]/(x^2)$.
So the existence of $(x)/(x^2)$ immediately tells you why $k[x]/(x^2)$ isn't irreducible. And how could it be directly decomposable? There is only one proper ideal, so there isn't a second proper ideal to complement the first. So, there isn't a nontrivial decomposition of $k[x]/(x^2)$


text:
Q: Can you delay the loading of an element using jQuery? I have an accordion with an image that loads over the accordion. The image disappears when clicked revealing the accordion. This works correctly but as the page loads there is a moment when you can see the raw contents of the accordion before the image appears.
My script, hides the accordion, shows the image and then hides the image on click thus:
jQuery(document).ready(function($) {
    $("#theBomb").show();
    $("div#accordion").hide();
    $("#theBomb").click(function() {
        $(this).hide("explode", {pieces:100}, 1000,
          function(){
            $("div#accordion").show("blind");
            });
       });
     });

Is there any way I can stop the raw contents of the accordion appearing before the image loads?
I don't want to hide the contents of the accordion using css because if there is no Javascript active in the browser I want the reader to not see the image but see the contents of the accordion.

A: $('yourElement').delay(500).queue(function( nxt ) {
    $(this).load('yourpage');
    nxt();
});


text:
Q: python how to link sublist together in a list which describe a tree For example list =[[1,0],[2,1],[6,2],[7,6],[7,8],[15,13],[8,15]]
shows tree
     _7_
   _6   8_
 _2      _15

how to get a new list contain all these number.
like the example list =

[[1,0],[2,1],[6,2],[7,6],[7,8],[15,13],[8,15]]

the output will be new_list=[0,1,2,6,7,8,15,13] (order not important)
My biggest problem is to link [6,2],[7,6],[7,8],[8,15] together

A: simple, if order doesn't matter:
 l =[[1,0],[2,1],[6,2],[7,6],[7,8],[15,13],[8,15]]
 # flatten list
 t = sum(l,[])
 # transform in a set removing duplicate values
 # otherwise if u want to keep the order you have to use an OrderedDict
 list(set(t)) # [0, 1, 2, 6, 7, 8, 13, 15]

A: Leaving Tree and Graph Theory aside:
list =[[1,0],[2,1],[6,2],[7,6],[7,8],[15,13],[8,15]]

uniq = {}

for i in list:
  uniq.update({i[0]: True, i[1]: True})

print(uniq.keys())

>>> [0, 1, 2, 6, 7, 8, 13, 15]

Using python set:
list =[[1,0],[2,1],[6,2],[7,6],[7,8],[15,13],[8,15]]

uniq = set()

for i in list:
  uniq.add(i[0])
  uniq.add(i[1])

print uniq

A: if the order is not important, you can loop through the list and sub-list and check if element is not in new_list:
list = [[1, 0], [2, 1], [6, 2], [7, 6], [7, 8], [15, 13], [8, 15]]
    new_list = []
    for sub in list:
        for elem in sub:
            if elem not in new_list:
                new_list.append(elem)
    print new_list

output:
[1, 0, 2, 6, 7, 8, 15, 13]


text:
Q: SQL Match Contact Ids with Many Tag Ids I seem to have got myself in a pickle, One table three columns, forget the Id column. I add a tagId to a contactId, so one contactId can have many TagId's
I need to select just contactId's that match my IN TagId's e.g.
-- The Table --
Id    ContactId    TagId
3136    2562    4
3137    2585    4
3139    2772    4
4543    2117    150
4882    2562    150
4903    2585    150
5067    2772    150
5229    2804    150
5241    2808    150
5244    2809    150
5247    2810    150
5250    2811    150
5457    2085    4
-- The SQL MSSQL 2005 --
SELECT [Id],[ContactId],[TagId]
FROM [search-contacts].[dbo].[ContactTagsGrouping]
WHERE ContactId IN (2085,2804,2808,2809,2810,2117,2811,2772,2562,2585)
  AND TagId IN (150,4)

Thanks in advance, this is only a small sample of data, I have a couple of hundred rows, and the TagId IN () can have many TagId's selected.
In the above SQL, I should only see three ContactId records that match both 150 and 4 e.g.
ContactId
2772
2562
2585

A: Using aggregation to match a given ContactId to a set of TagId:
SELECT [ContactId]
  FROM [search-contacts].[dbo].[ContactTagsGrouping]
  WHERE ContactId IN (2085,2804,2808,2809,2810,2117,2811,2772,2562,2585)
    AND TagId IN (150,4)
group by ContactId
having count(distinct TagId)=2 /* 2 is the number of tags in the TagId in() */

If you have a unique index/constraint on ContactId, TagId then you can skip the distinct in count(distinct TagId) to remove any overhead incurred from a sort operator.
rextester demo: http://rextester.com/RUF13404
returns:
+-----------+
| ContactId |
+-----------+
|      2562 |
|      2585 |
|      2772 |
+-----------+


text:
Q: How to convert JSON data to XML format data and download the file in React JS I am fetching the data from API which I am getting in JSON format, I want this data to download in XML format. This functionality will be like if anyone clicks on the button on UI the xml file will get downloaded with the data.
I have searched for some resolution over that but not able to find something firm.
The following link could be useful but not know how to use that properly.
https://www.npmjs.com/package/export-from-json
Initiatives will be appreciated. Many Thanks.

A: That package you found is actually the solution to your problem (I actually used it myself and I can confirm it's nice).
Basically, all you have to do is to call the exportFromJSON function with the right arguments and the download will start:
Sample data
  const dataForXml = [
    {
      "Name": "aaaaa",
      "Author": "aaaaaaaa",
      "Subject": "History",
      "Publication Date": 1981,
      "additional data": {
        "rating": 9.9,
        "opinion": "Nice to have"
      }
    },
    {
      "Name": "L'Ancien Régime et la Révolution",
      "Author": "Alexis de Tocqueville",
      "Subject": "History",
      "Publication Date": 1866
    },
    {
      "Name": "A Brief History of Time",
      "Author": "Stephen Hawking",
      "Subject": "Cosmology",
      "Publication Date": 1988
    },
    {
      "Name": "ooooo",
      "Author": "ooooooooo",
      "Subject": "Novel",
      "Publication Date": 1995
    }
  ];

Adjusting used fields and their tags in the file:
  const fieldsAsObjects = {
    "Name": "Name column header",
    "Author": "Author column header",
    "Subject": "Subject column header",
    "Publication Date": "Publication Date column header",
    "additional data": "additional data column header"
  };

This mapping allows you to change tags in the file. Field names are corresponding to the field names in the data, while values will be used as tags, hyphen-joined, eg <additional-data-column-header>.
Alternatively this way you can just pick fields that are supposed to be included in the file:
  const fieldsAsStrings = [
    "Name",
    "Author",
    "Subject",
    "Publication Date",
    "additional data"
  ];

And here's the closure; how to use it:
import React from "react";

import Button         from "@material-ui/core/Button";
import exportFromJSON from "export-from-json";

export default function XMLExport(props) {

  function onClick() {
    const data = props.data;   //dataForXml
    const fileName = props.fileName ? props.fileName : "exported";
    let fields = props.fields ? props.fields : [];  //fieldsAsObjects or fieldsAsStrings, empty list means "use all"
    const exportType = 'xml';
    exportFromJSON({data, fileName, fields, exportType})
  }

  return (
    <Button onClick={onClick}>
      download
    </Button>
  )

}

Output for the sample data:
<?xml version="1.0" encoding="utf-8"?><!DOCTYPE base>
<base>
  <element>
    <Name-column-header>
      aaaaa
    </Name-column-header>
    <Author-column-header>
      aaaaaaaa
    </Author-column-header>
    <Subject-column-header>
      History
    </Subject-column-header>
    <Publication-Date-column-header>
      1981
    </Publication-Date-column-header>
    <additional-data-column-header>
      <rating>
        9.9
      </rating>
      <opinion>
        Nice to have
      </opinion>
    </additional-data-column-header>
  </element>
  <element>
    <Name-column-header>
      L'Ancien Régime et la Révolution
    </Name-column-header>
    <Author-column-header>
      Alexis de Tocqueville
    </Author-column-header>
    <Subject-column-header>
      History
    </Subject-column-header>
    <Publication-Date-column-header>
      1866
    </Publication-Date-column-header>
  </element>
  <element>
    <Name-column-header>
      A Brief History of Time
    </Name-column-header>
    <Author-column-header>
      Stephen Hawking
    </Author-column-header>
    <Subject-column-header>
      Cosmology
    </Subject-column-header>
    <Publication-Date-column-header>
      1988
    </Publication-Date-column-header>
  </element>
  <element>
    <Name-column-header>
      ooooo
    </Name-column-header>
    <Author-column-header>
      ooooooooo
    </Author-column-header>
    <Subject-column-header>
      Novel
    </Subject-column-header>
    <Publication-Date-column-header>
      1995
    </Publication-Date-column-header>
  </element>
</base>

I've created this sandbox sandbox  for you. Unfortunately the download itself doesn't work in the sandbox.

A: I have found one solution without any npm package library:
const xmlData = [
{
    color: "red",
    value: "#f00"
},
{
    color: "green",
    value: "#0f0"
},
{
    color: "blue",
    value: "#00f"
},
{
    color: "cyan",
    value: "#0ff"
},
{
    color: "magenta",
    value: "#f0f"
},
{
    color: "yellow",
    value: "#ff0"
},
{
    color: "black",
    value: "#000"
}];

And this will be your component; how to use it:
import React from "react";

export default function XMLExport(props) {

  function convertXML(data, tagName, arrayElementTag = "element", spaces = 0) {
    const tag = tagName
      .replace(/[^_a-zA-Z 0-9:\-\.]/g, "")
      .replace(/^([ 0-9-:\-\.]|(xml))+/i, "")
      .replace(/ +/g, "-");

    const indentSpaces = Array(spaces + 1).join(" ");

    if (data === null || data === undefined) {
      return `${indentSpaces}<${tag} />`;
    }

    const content =
      Object.prototype.toString.call(data) === "[object Array]"
        ? data
            .map((item) =>
              convertXML(item, arrayElementTag, arrayElementTag, spaces + 2)
            )
            .join("\n")
        : typeof data === "object"
        ? Object.keys(data)
            .map((key) => [key, data[key]])
            .map(([key, value]) =>
              convertXML(value, key, arrayElementTag, spaces + 2)
            )
            .join("\n")
        : indentSpaces +
          "  " +
          String(data).replace(/([<>&])/g, (_, $1) => {
            switch ($1) {
              case "<":
                return "<";
              case ">":
                return ">";
              case "&":
                return "&";
              default:
                return "";
            }
          });

    const contentWithWrapper = `${indentSpaces}<${tag}>
            ${content}
            ${indentSpaces}</${tag}>`;

    return contentWithWrapper;
  }

  function createXMLData(data) {
    const content = `<?xml version="1.0" encoding="utf-8"?><!DOCTYPE root>
    ${convertXML(data, "root")}
    `;

    const dataStr =
      "data:text/application/xml;charset=utf-8," + encodeURIComponent(content);
    let downloadData = document.getElementById("downloadData");
    downloadData.setAttribute("href", dataStr);
    downloadData.setAttribute("download", "xmlData.xml");
    downloadData.click();
  }

  return (
    <>

      <button
        onClick={() => {
          createXMLData(props.data);
        }}
      >
        download
      </button>
    </>
  );
}

Output for the data:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE root>
 <root>
  <element>
    <color>red</color>
    <value>#f00</value>
  </element>
  <element>
    <color>green</color>
    <value>#0f0</value>
  </element>
  <element>
    <color>blue</color>
    <value>#00f</value>
  </element>
  <element>
    <color>cyan</color>
    <value>#0ff</value>
  </element>
  <element>
    <color>magenta</color>
    <value>#f0f</value>
  </element>
  <element>
    <color>yellow</color>
    <value>#ff0</value>
  </element>
  <element>
    <color>black</color>
    <value>#000</value>
  </element>
</root>


text:
Q: Are large prime numbers kept secret? I've read several times that modern cryptography is based on the fact that multiplying two primes is easy, whereas getting the prime factorization of a random big integer is very hard. (see here)
Does it mean that the largest prime numbers known are kept secret, for cryptography purposes ?
If they were not, one could compute the product of every pair of known prime numbers and decode the public keys ?


text:
Q: Javascript Canvas and UNICODE I have a Unicode font using 5 digits for its characters set. Problem is that they don't print in canvases. I want to display character, say, \u1302b:
ctx.fillText('\u1302b',10,50);

displays a square and a 'b'.
ctx.fillText(String.fromCharCode(parseInt('\u1302b',16)),10,50);

has no effect either, nothing displayed.
Are canvases limited to 4 digits UNICODE chars?
Edit: sure, there is a similar question here: Unicode characters not rendering properly in HTML5 canvas. Apparently, I need to break that 5 digit character code in two 4 digit character codes, using the toUTF16() function provided. OK, but then, how to render them on the canvas? There is no working example given and all I try fails.

A: Enclose the hex value inside {}, like so:
ctx.fillText('\u{1302b}',10,50);


text:
Q: Keep file after wipe data in Android 10 The application I'm currently working on requires a manual setup (entering some information) on device provisioning. This information needs to be written to a file that should not be deleted when the application is uninstall or the application data is wiped (user support requirement, as they can direct users to do this in some cases)
There was a very similar old question, but the answer is now deprecated and no up-to-date answer has been posted
Keep files after uninstallation of android app
So the question is, given the deprecation of Environment.getExternalStorageDirectory() on Android 10, how do we programmatically write/read a file that will not be deleted when the application is uninstalled or the data is wiped?
For what is worth, we can not rely on app auto backup, as the users don't have google accounts configured.
Thanks

A: To summarize while targetting 30.
For Android 10 device: Request legacy external storage to get external storage access as usual.
And Googles step back for Android 11 devices: use directories like Download, Pictures, Movies, Documents, DCIM and so on. Read and write access for all. Android OS is very picky to use the right extensions for files to be created in those folders.


text:
Q: C++ thread error: no type named 'type' MINGW I'm currently doing a project for my operational systems class and I have to make a program to find prime numbers to run in threads.
So I did this:
#include <iostream>
#include <cmath>
#include <thread>
#define THREADNUMBER 100
using namespace std;

int CONTADOR = 0;
int CONTADORTHREADEXECUTADA = 0;
int primeRange(int v1, int v2) {
int a, limit;
bool isprime;

for (int i = v1; i <= v2; i++) {
    if (i % 2 != 0 && i % 3 != 0) {
        isprime = true;
        limit = i / 2;
        if(i == 1) isprime =false;

        limit = (int)sqrt(i); //General case

        for(a=2; a <= limit; a++){
            if(i % i == 0 && i != 2){
                isprime = false;
                break;
            }
        }
        if (isprime) {
            CONTADOR++;
        }

    }
}
CONTADORTHREADEXECUTADA++;
return 1;
}
int main(int argc, char *argv[ ] ) {
int number1 =  atoi(argv[1]);
int number2 = atoi(argv[2]);
int dif = number2-number1;
thread** vec = new thread*[THREADNUMBER];
cout<< "criando threads" <<endl;
int contadorthread = 0;
if (dif <= THREADNUMBER) {
    for(int i = number1; i <= number2; i++) {
        thread* t = new thread(primeRange(i,i));
        vec[contadorthread] = t;
        contadorthread++;
    }
} else {
    int c = dif / THREADNUMBER;

    for(int i = number1; i <= number2; i+=(c+1)) {
        if (contadorthread==THREADNUMBER-1) {
            thread* t = new thread(primeRange(i,number2));
            vec[contadorthread] = t;
            contadorthread++;
            break;
        }
        thread* t = new thread(primeRange(i,i+c));
        vec[contadorthread] = t;
        contadorthread++;

    }
cout<<contadorthread << " threads criadas"<<endl;
cout<<"inicializando threads" <<endl;

while (CONTADORTHREADEXECUTADA < contadorthread) {
    cout<<contadorthread - CONTADORTHREADEXECUTADA << endl;
}
cout<< CONTADOR << "primos encontrados" <<endl;
}
}

But everytime I try to compile on 64 windows GCC I get this error message saying that there is not type named 'type'
I compile with this
g++ -Wall -g -std=c++11 -pthread codigo.cpp -o exe -Wall

What can I do?
I already downloaded the version of mingw they say is thread safe.

A: The statement
thread* t = new thread(primeRange(i,i));

call function primeRange and pass result(int) to thread constructor which is obviously not the way to call. Instead use:
thread* t = new thread(primeRange, i, i);

It will pass function pointer as well as arguments to thread constructor.


text:
Q: Fixed gradient with a moving rectangle? I have a WPF 'monitor widget' that displays CPU, RAM and disk performance as small percentage bars. I use the following gradient as a resource to divide the bars into 4 sections (ie. 0% - 25%, 25% - 50%, etc.)
<LinearGradientBrush x:Key="Quarters" StartPoint="0,0" EndPoint="0,15" MappingMode="Absolute">
    <GradientStop Color="LightGreen" Offset="0.0" />
    <GradientStop Color="LightGreen" Offset="0.24" />
    <GradientStop Color="Yellow" Offset="0.25" />
    <GradientStop Color="Yellow" Offset="0.49" />
    <GradientStop Color="Orange" Offset="0.5" />
    <GradientStop Color="Orange" Offset="0.74" />
    <GradientStop Color="Red" Offset="0.75" />
    <GradientStop Color="Red" Offset="1.0" />
</LinearGradientBrush>

Originally, the bars' 0% position was at the top (bar.Height = 0) and 100% was at the bottom (bar.Height = 15). The bar size would change by simply adjusting its Height property. Everything worked fine, but I would prefer the bars' 0% position to be at the bottom instead, ie. the bars will 'grow' upward.
Making the bars grow upward was no problem, but the problem I do have is that the gradient now moves with the rectangle, so that the top of the rectangle is always green, no matter how small it is. I understand that this is because I am now using Canvas.SetTop to move the top of the rectangles (bars) as well as change their height. How can I force the gradient to an absolute position, regardless of the position of the rectangle?
  (background opacity)
Sorry, I know the image is small, but you should just be able to make out that the middle bar starts from the top (green) and grows downward, ending in orange (50% -75% value). The left bar starts at the bottom (this is what I want), but the gradient in this bar moves with the height... this is the problem. Note that I'll reverse the gradient when I can fix this problem, so that red will represent the top 25%. In this example, the bottom quarter should be red, the next quarter orange and the remainder yellow.
I can't believe that there is no simple solution for this... come on brain-boxes. :) How about moving the absolute position of the gradient with the rectangle... is this possible???
(Relating post: Determining a computer's maximum hard drive data transfer rate programmatically with C#)

A: I solved a similar issue using clipping. Create rectangles for 100% and fill with the brush. Then use clipping to only show part of the rectangle, see sample code below which shows two rectangles:
<Window x:Class="GradientTest.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Height="300" Width="300">

    <Window.Resources>

        <LinearGradientBrush x:Key="Quarters" StartPoint="0,1" EndPoint="0,0">
            <GradientStop Color="LightGreen" Offset="0.0" />
            <GradientStop Color="Yellow" Offset="0.25" />
            <GradientStop Color="Orange" Offset="0.5" />
            <GradientStop Color="Red" Offset="0.75" />
        </LinearGradientBrush>

    </Window.Resources>

    <Canvas Height="100">

        <!--21%-->
        <Rectangle Fill="{StaticResource Quarters}" Width="30" Height="100" Canvas.Bottom="0" Canvas.Left="0">
            <Rectangle.Clip>
                <RectangleGeometry Rect="0, 79, 30, 100" />
            </Rectangle.Clip>
        </Rectangle>

        <!--68%-->
        <Rectangle Fill="{StaticResource Quarters}" Width="30" Height="100" Canvas.Bottom="0" Canvas.Left="40">
            <Rectangle.Clip>
                <RectangleGeometry Rect="0, 32, 30, 100" />
            </Rectangle.Clip>
        </Rectangle>

    </Canvas>

</Window>

A: Update
Clip the rectangle with values set at runtime.
    <Window.Resources>
        <LinearGradientBrush x:Key="Quarters" StartPoint="0,0" EndPoint="0,1" >
            <GradientStop Color="LightGreen" Offset="0.0" />
            <GradientStop Color="LightGreen" Offset="0.24" />
            <GradientStop Color="Yellow" Offset="0.25" />
            <GradientStop Color="Yellow" Offset="0.49" />
            <GradientStop Color="Orange" Offset="0.5" />
            <GradientStop Color="Orange" Offset="0.74" />
            <GradientStop Color="Red" Offset="0.75" />
            <GradientStop Color="Red" Offset="1.0" />
        </LinearGradientBrush>
    </Window.Resources>

    <Canvas Height="100">
        <Rectangle Fill="{StaticResource Quarters}" Width="30" Height="100" Canvas.Bottom="0" Canvas.Left="0">
            <Rectangle.Clip>
                <RectangleGeometry x:Name="ClipRect" Rect="0, 100, 30, 100" />
            </Rectangle.Clip>
        </Rectangle>
     </Canvas>

Code:
ClipRect.Rect = new Rect(0, 20, 30, 100); //80%
ClipRect.Rect = new Rect(0, 70, 30, 100); //30%

Original Solution
Use 2 rectangles for each bar.
One rectangle with 100% height and the colored gradient. Then overlay a black rectangle over the first rectangle. Adjust the black rectangles height(as you were before) to expose the gradient below.
eg If the value is 25% set the overlay height to 75%

A: Yes, the 0,0 point of gradient fill's StartPoint/EndPoint always seems to be the top left of the object.
So one way around that is to rotate the object 180 degrees using a RenderTransform.
Then you can just set the height of the rectangle, but the gradient fill will stay anchored to the bottom.