text:
Q: Another void* topic; I just have to ask because I am confused Ok, muddling though Stack on the particulars about void*, books like The C Programming Language (K&R) and The C++ Programming Language (Stroustrup).  What have I learned?  That void* is a generic pointer with no type inferred.  It requires a cast to any defined type and printing void* just yields the address.
What else do I know?  void* can't be dereferenced and thus far remains the one item in C/C++ from which I have discovered much written about but little understanding imparted.
I understand that it must be cast such as *(char*)void* but what makes no sense to me for a generic pointer is that I must somehow already know what type I need in order to grab a value. I'm a Java programmer; I understand generic types but this is something I struggle with.
So I wrote some code
typedef struct node
{
  void* data;
  node* link;
}Node;

typedef struct list
{
   Node* head;
}List;

Node* add_new(void* data, Node* link);

void show(Node* head);

Node* add_new(void* data, Node* link)
{
  Node* newNode = new Node();
  newNode->data = data;
  newNode->link = link;

  return newNode;
}

void show(Node* head)
{
  while (head != nullptr)
  {
      std::cout << head->data;
      head = head->link;
  }
}

int main()
{
  List list;

  list.head = nullptr;

  list.head = add_new("My Name", list.head);

  list.head = add_new("Your Name", list.head);

  list.head = add_new("Our Name", list.head);

  show(list.head);

  fgetc(stdin);

  return 0;
}

I'll handle the memory deallocation later. Assuming I have no understanding of the type stored in void*, how do I get the value out?  This implies I already need to know the type, and this reveals nothing about the generic nature of void* while I follow what is here although still no understanding.
Why am I expecting void* to cooperate and the compiler to automatically cast out the type that is hidden internally in some register on the heap or stack?

A:
I'll handle the memory deallocation later. Assuming I have no understanding of the type stored in void*, how do I get the value out?

You can't. You must know the valid types that the pointer can be cast to before you can dereference it.
Here are couple of options for using a generic type:

*

*If you are able to use a C++17 compiler, you may use std::any.

*If you are able to use the boost libraries, you may use boost::any.

A: Unlike Java, you are working with memory pointers in C/C++. There is no encapsulation whatsoever. The void * type means the variable is an address in memory. Anything can be stored there. With a type like int * you tell the compiler what you are referring to. Besides the compiler knows the size of the type (say 4 bytes for int) and the address will be a multiple of 4 in that case (granularity/memory alignment). On top, if you give the compiler the type it will perform consistency checks at compilation time. Not after. This is not happening with void *.
In a nutshell, you are working bare metal. The types are compiler directives and do not hold runtime information.  Nor does it track the objects you are dynamically creating. It is merely a segment in memory that is allocated where you can eventually store anything.

A: The main reason to use void* is that different things may be pointed at. Thus, I may pass in an int* or Node* or anything else. But unless you know either the type or the length, you can't do anything with it.
But if you know the length, you can handle the memory pointed at without knowing the type. Casting it as a char* is used because it is a single byte, so if I have a void* and a number of bytes, I can copy the memory somewhere else, or zero it out.
Additionally, if it is a pointer to a class, but you don't know if it is a parent or inherited class, you may be able to assume one and find out a flag inside the data which tells you which one. But no matter what, when you want to do much beyond passing it to another function, you need to cast it as something. char* is just the easiest single byte value to use.

A: Your confusion derived from habit to deal with Java programs. Java code  is set of instruction for a virtual machine, where function of RAM is given to a sort of database, which stores  name, type, size  and data of each object. Programming language you're learning now  is meant to be compiled into instruction for CPU, with same organization of memory as underlying OS have. Existing model used by C and C++ languages is some abstract built on top of most of popular OSes in way that code would work effectively after being compiled for that platform and OS. Naturally that organization doesn't involve string data about type, except for famous RTTI in C++.
For your case RTTI cannot be used directly, unless you would create a wrapper around your naked pointer, which would store the data.
In fact C++ library contains a vast collection of container class templates that are useable and portable, if they are defined by ISO standard. 3/4 of standard is just description of library often referred as STL. Use of them is preferable over working with naked pointers, unless you mean to create own container for some reason. For particular task only C++17 standard offered std::any class, previously present in boost library. Naturally, it is possible to reimplement it, or, in some cases, to replace by std::variant.

A:
Assuming I have no understanding of the type stored in void*, how do I get the value out

You don't.
What you can do is record the type stored in the void*.
In c, void* is used to pass around a binary chunk of data that points at something through one layer of abstraction, and recieve it at the other end, casting it back to the type that the code knows it will be passed.
void do_callback( void(*pfun)(void*), void* pdata ) {
  pfun(pdata);
}

void print_int( void* pint ) {
  printf( "%d", *(int*)pint );
}

int main() {
  int x = 7;
  do_callback( print_int, &x );
}

here, we forget thet ype of &x, pass it through do_callback.
It is later passed to code inside do_callback or elsewhere that knows that the void* is actually an int*.  So it casts it back and uses it as an int.
The void* and the consumer void(*)(void*) are coupled.  The above code is "provably correct", but the proof does not lie in the type system; instead, it depends on the fact we only use that void* in a context that knows it is an int*.

In C++ you can use void* similarly.  But you can also get fancy.
Suppose you want a pointer to anything printable.  Something is printable if it can be << to a std::ostream.
struct printable {
  void const* ptr = 0;
  void(*print_f)(std::ostream&, void const*) = 0;

  printable() {}
  printable(printable&&)=default;
  printable(printable const&)=default;
  printable& operator=(printable&&)=default;
  printable& operator=(printable const&)=default;

  template<class T,std::size_t N>
  printable( T(&t)[N] ):
    ptr( t ),
    print_f( []( std::ostream& os, void const* pt) {
      T* ptr = (T*)pt;
      for (std::size_t i = 0; i < N; ++i)
        os << ptr[i];
    })
  {}
  template<std::size_t N>
  printable( char(&t)[N] ):
    ptr( t ),
    print_f( []( std::ostream& os, void const* pt) {
      os << (char const*)pt;
    })
  {}
  template<class T,
    std::enable_if_t<!std::is_same<std::decay_t<T>, printable>{}, int> =0
  >
  printable( T&& t ):
    ptr( std::addressof(t) ),
    print_f( []( std::ostream& os, void const* pt) {
      os << *(std::remove_reference_t<T>*)pt;
    })
  {}
  friend
  std::ostream& operator<<( std::ostream& os, printable self ) {
    self.print_f( os, self.ptr );
    return os;
  }
  explicit operator bool()const{ return print_f; }
};

what I just did is a technique called "type erasure" in C++ (vaguely similar to Java type erasure).
void send_to_log( printable p ) {
  std::cerr << p;
}

Live example.
Here we created an ad-hoc "virtual" interface to the concept of printing on a type.
The type need not support any actual interface (no binary layout requirements), it just has to support a certain syntax.
We create our own virtual dispatch table system for an arbitrary type.
This is used in the C++ standard library.  In c++11 there is std::function<Signature>, and in c++17 there is std::any.
std::any is void* that knows how to destroy and copy its contents, and if you know the type you can cast it back to the original type.  You can also query it and ask it if it a specific type.
Mixing std::any with the above type-erasure techinque lets you create regular types (that behave like values, not references) with arbitrary duck-typed interfaces.


text:
Q: Azure Devops resource names versus id's In Azure Devops, it would be helpful if we could refactor names of resources as our systems grow. We tend to leave things named as-is because of fear of breaking things. Behind the scenes, some things are referenced by ID value instead of by Name, even though Name is shown in the interface. It would be helpful to know which names can be changed that don't break things, or at least how references are done so that we can understand potential repercussions of renames.
For example, we can easily rename a pipeline's folder in Azure Pipelines because it has no effect at all on behavior. However, renaming an Azure Devops project can cause references to need to change both for URLs and for pipeline references.
Does a catalog of resources exist that describes the effects of name changes on each resource?
Specific resources include:

*

*Organization

*Project

*Team

*Group

*YAML Pipeline

*Classic Build Pipeline

*Classic Release Pipeline

*Repository

*Artifact

*Library

*Task Group

*Area Path

*Iteration Path

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to throw `InterruptedException` while junit testing my class? I am trying to write some junit for a class which is using CountDownLatch and I am using jmockit library for junit testing.
public class MappedData {

    private static final AtomicReference<Map<String, Map<Integer, String>>> mapped1 = new AtomicReference<Map<String, Map<Integer, String>>>();
    private static final AtomicReference<Map<String, Map<Integer, String>>> mapped2 = new AtomicReference<Map<String, Map<Integer, String>>>();
    private static final CountDownLatch firstSet = new CountDownLatch(1);

    public static Map<String, Map<Integer, String>> getMapped1Table() {
    try {
        firstSet.await();
    } catch (InterruptedException e) {
        throw new IllegalStateException(e);
    }
    return mapped1.get();
    }

    public static Map<String, Map<Integer, String>> getMapped2Table() {
    try {
        firstSet.await();
    } catch (InterruptedException e) {
        throw new IllegalStateException(e);
    }
    return mapped2.get();
    }
}

What is the easiest way to make sure that in the getMapped1Table and getMapped2Table method - I am able to throw an InterruptedException so that I can cover that scenario as well. If you take a look into those two methods, I have a catch block which I am not able to cover.
MappedData.getMapped1Table()

Is there any way I can make sure that my above two methods are throwing InterruptedException?
Update:-
What I am trying to do is - how to get firstSet.await() to throw an InterruptedException when I am junit testing.

A: Call the method in a sperate thread, then interrupt that thread:
Thread t = new Thread(new Runnable(){
   public void run(){
      MappedData.getMappedTable();
    }
});

t.start();

t.interrupt();

A: Here is the simplest way to write the test with JMockit:
public class MappedDataTest
{
    @Test
    public void getMappedTableHandlesInterruptedException(
        @Mocked final CountDownLatch anyLatch) throws Exception
    {
        final InterruptedException interrupt = new InterruptedException();
        new NonStrictExpectations() {{ anyLatch.await(); result = interrupt; }};

        try {
            MappedData.getMapped1Table();
            fail();
        }
        catch (IllegalStateException e) {
            assertSame(interrupt, e.getCause());
        }
    }
}

A: You can do it with a mocking library such as Mockito or EasyMock. You will need a way to inject the mock dependency. Generally this is done through a constructor, but since your field is static you'll probably want to add a setter.
public static void setFirstSet(CountDownLatch latch)
{
    firstSet = latch;
}

The rest of this example is for Mockito.
In your test, create a mock CountDownLatch:
CountDownLatch mockLatch = mock(CountDownLatch.class);

Then stub the method to throw the exception:
when(mockLatch.await()).thenThrow(new InterruptedException());

Next inject the mock:
MappedData.setFirstSet(mockLatch);

Finally call the method under test:
Map<String, Map<Integer, String>> result = MappedData.getMapped1Table();

I've never used jmockit, but from a quick a quick google search suggests this is the way to do it:
final CountDownLatch mockLatch = new CountDownLatch();
new Expectations(mockLatch){
    {
        mockLatch.await();
        result = new InterruptedException();
    }
};
MappedData.setFirstSet(mockLatch);
Map<String, Map<Integer, String>> result = MappedData.getMapped1Table();


text:
Q: DOM nodes generate HTML5 Possible? I want to generate a html5 file using DOM node methods, is it possible ?
I already tried making but, i can't find the right code to generate with the
"!DOCTYPE" template.
I want like this structure :
<!DOCTYPE html>
........
.......
.....
...
..
</html>

A: Sure you can generate a <doctype> node, you'll just have to use document.implementation.createDocumentType() method.
However, to generate an HTML5 document is quite a burden (at least when it comes to stringification). Indeed, there is no HTML5 namespace, and your HTML5 document is actually XHTML once parsed in the DOM:

console.log(document.documentElement.namespaceURI);

So when you'll stringify this document, you'll have the xmlns="http://www.w3.org/1999/xhtml" attributes all over your elements.
To avoid that, you actually need to generate all your elements with a null namespace:

// Our <!DOCTYPE html> node
const doctype = document.implementation.createDocumentType('html', '', '');
// A new HTML5 document
const doc = document.implementation.createDocument("", 'html', doctype);

// We need to force null NS
const body = doc.createElementNS(null, 'body');
body.appendChild(doc.createTextNode('hello'));

doc.documentElement.appendChild(body);

const str = (new XMLSerializer).serializeToString(doc);

console.log(str);


text:
Q: Mongoose Find not working This is my first time writing a MVC app in Node/Express/Mongoose so I could really use some help. My .find() command just doesn't find anything! :(
Structure is that I have a an /app folder in the root. /app folder contains /models (schemas), /controllers and /views in it. And I have app.js outside in the root.
Somewhere in app.js:
// all necessary config/setup stuff..
var mongoose = require('mongoose');
mongoose.connect(config.db);
var app = express();
require('./config/routes')(app)

In my routes.js file:
var skills = require('../app/controllers/skills');
app.get('/', skills.showall);

My controller skills.js contains:
var Skill = require('../models/skill');

exports.showall = function(req, res) {
    Skill.find({}, function(err, docs){
        if (!err) {
            res.render('index', {title: 'Skilldom', skills: docs});
        }
        else {
            throw err;
        }
    });
}

Finally my Model skill.js contains:
var mongoose = require('mongoose');

//Skill schema definition
var skillSchema = new mongoose.Schema({
    name: String,
    length: String,
});

var Skill = mongoose.model('Skill', skillSchema);

module.exports = Skill;

My index view renders, so I see the content from my index.jade template, but for some reason the find command in the model is not fetching anything. I can confirm that my database (in MongoHQ) has real data.
Any thoughts?

A: I was in the same situation as you describe and it turns out I didn't understand the magic of mongoose collection naming, in your code it will try to load the "skills" and if that's not what it's named in your mongo nothing will be returned. Should really toss a "so such collection" error instead imho.

A: Change your Skill.js for this
var mongoose = require('mongoose');
mongoose.set('debug', true);

//Skill schema definition

var skillSchema = new mongoose.Schema({
  name: String,
  length: String,
});

var Skill = mongoose.model('Skill', skillSchema);
module.exports = Skill;

After that, you can see at the console if mongoose is doing your queries.

A: This below method gives an alternate name for your collection
var skillSchema = new mongoose.Schema({
  name: String,
  length: String,
},{collection : 'Skill'});

or

var Skill = mongoose.model('Skill', skillSchema,''Skill);


text:
Q: Cannot add Contour to layers I am brand new to QGIS as my uni has shut down but we still need to do our coursework they have asked up to make a bathymetry map on QGIS. It is a very simple map of sounding data we have taken and all I am trying to do is add a contour and a grid and I keep getting error messages, can anyone help? Code below:
QGIS version: 3.8.3-Zanzibar
Qt version: 5.11.2
GDAL version: 2.4.2
GEOS version: 3.7.2-CAPI-1.11.2 b55d2125
PROJ version: Rel. 5.2.0, September 15th, 2018
Processing algorithm…
Algorithm 'Contour' starting…
Input parameters:
{ 'BAND' : 1, 'CREATE_3D' : False, 'FIELD_NAME' : 'ELEV', 'IGNORE_NODATA' : False, 'INPUT' : '/Users/Mim/Desktop/OS203/CW2/Bathymetric Survey Coursework-20200327/Final Bathymetry GeoTiff/PlymouthSound_1m_final.tif', 'INTERVAL' : 10, 'NODATA' : None, 'OFFSET' : 0, 'OPTIONS' : '', 'OUTPUT' : 'TEMPORARY_OUTPUT' }

GDAL command:
gdal_contour -b 1 -a ELEV -i 10.0 -f "ESRI Shapefile" "/Users/Mim/Desktop/OS203/CW2/Bathymetric Survey Coursework-20200327/Final Bathymetry GeoTiff/PlymouthSound_1m_final.tif" /var/folders/81/njbhr3dn3556brkh725_7_fm0000gn/T/processing_1b3ff932a52446e38b6da3b9147e595c/ec4a71fdc1d44220b082c3a61362c3b1/OUTPUT.shp
GDAL command output:
/bin/sh: gdal_contour: command not found

Execution completed in 0.10 seconds
Results:
{'OUTPUT': '/var/folders/81/njbhr3dn3556brkh725_7_fm0000gn/T/processing_1b3ff932a52446e38b6da3b9147e595c/ec4a71fdc1d44220b082c3a61362c3b1/OUTPUT.shp'}

Loading resulting layers
The following layers were not correctly generated.

/var/folders/81/njbhr3dn3556brkh725_7_fm0000gn/T/processing_1b3ff932a52446e38b6da3b9147e595c/ec4a71fdc1d44220b082c3a61362c3b1/OUTPUT.shp

You can check the 'Log Messages Panel' in QGIS main window to find more information about the execution of the algorithm.


text:
Q: Merge nested object using Lodash I have an object, which look like this,
{"basket":
    [
        {
            "firmId":"27150190-3aa0-4740-a859-3e215d338a2b",
            "adisyonId":"35dca2a0-2c9a-4d8d-9b0e-1e146f7b900a","productId":"de37dce5-f8f9-4f54-900f-fbc90659b37d",
            "product":
                {
                    "productId":"de37dce5-f8f9-4f54-900f-fbc90659b37d",
                    "productCategoryId":"8ac4cb8c-86cb-4d23-8f01-639a7f6ac1be",
                    "productCategory":null,
                    "productName":"cola",
                    "price":8.00,
                    "st":true}},

        {
            "firmId":"4ac6dd14-798a-422f-8f3e-1ed06f5e8fb7",
            "adisyonId":"35dca2a0-2c9a-4d8d-9b0e-1e146f7b900a",
            "productId":"de37dce5-f8f9-4f54-900f-fbc90659b37d",
            "product":
                {
                    "productId":"de37dce5-f8f9-4f54-900f-fbc90659b37d",
                    "productCategoryId":"8ac4cb8c-86cb-4d23-8f01-639a7f6ac1be",
                    "productCategory":null,
                    "productName":"tea",
                    "price":1.00,
                    "st":true}}]};

I use that lodash.js then I want it as I want it to be in the example below.
{"basket":
    [
        {
            "product":
                {
                    "firmId":"27150190-3aa0-4740-a859-3e215d338a2b",
                    "productId":"de37dce5-f8f9-4f54-900f-fbc90659b37d",
                    "productCategoryId":"8ac4cb8c-86cb-4d23-8f01-639a7f6ac1be",
                    "productCategory":null,
                    "productName":"cola",
                    "price":8.00,
                    "st":true}},

        {
            "product":
                {
                    "firmId":"4ac6dd14-798a-422f-8f3e-1ed06f5e8fb7",
                    "productId":"de37dce5-f8f9-4f54-900f-fbc90659b37d",
                    "productCategoryId":"8ac4cb8c-86cb-4d23-8f01-639a7f6ac1be",
                    "productCategory":null,
                    "productName":"tea",
                    "price":1.00,
                    "st":true}}]};

I tried this,
var list = [];
_.each(this.props.basket, function (item) {
    list.push(_.omit(item, 'firmId'));
    list.push(_.flatten(_.pick(item, 'product')));
});
var result = _.flatten(list);
console.log(result);

Its above code only give that first version, so I want to merge firmId and products on one object.
Thanks,

A: Can do this as a simple map()
const list = this.props.basket.map(({firmId, product}) => {
   product.firmId = firmId;
   return {product};
})


text:
Q: Cómo acceder a una API key del archivo .env desde javascript con laravel mix tengo una api key que según la documentación oficial debo guardar con el siguiente nombre
MIX_GOOGLE_GEOCODER_API_KEY=

en mi archivo .env para luego acceder a ella mediante
let googleGeoCoderApiKey = process.env.MIX_GOOGLE_GEOCODER_API_KEY;

lo cual estoy haciendo, el mismo IDE me da la sugerencia ya incluso mostrando la API key, esa variable está incluida en un archivo javascript que está minificado por mix de la siguiente manera
<script src="{{asset(mix('js/maps/franchise-map.min.js'))}}"></script>

y en mi webpack.mix.js lo estoy llamando de la siguiente forma
mix.minify([
    'public/js/maps/franchise-map.js',
])
    .version();

luego de tener todo esto, hago limpieza de la cache de config y ejecuto el comando npm run production, sin embargo, en el navegador obtengo el siguiente error:

franchise-map.min.js?id=1ed23d100abe226aaceb:1 Uncaught
ReferenceError: process is not defined
at franchise-map.min.js?id=1ed23d100abe226aaceb:1:227

cómo puedo corregir este problema?

A: La documentación oficial que linkeas menciona dos convenciones que aplican:

*

*manejar las variables de entorno en un archivo .env

*de entre las definidas en aquel archivo, solamente tomar en cuenta aquellas con prefijo MIX_
Los demás supuestos que hiciste no dices de dónde vienen, pero pienso que son erróneos.
Primero, mix procesa (en el sentido de transpilar-concatenar-minificar y hacer la sustitución de variables de entorno) desde resources y hacia public. Esto no está escrito a fuego, pero es la práctica recomendada:
let mix = require('laravel-mix');

mix.js('resources/js/app.js', 'js')
   .sass('resources/sass/app.scss', 'css');

Lo que estás haciendo hoy funciona, anecdóticamente, porque al sufijar (via .version()) y usar minify (lo cual pone el sufijo .min) en rigor la fuente y la salida de la compilación son distintas.   Tienes que pensar que lo que esté en public tus visitantes lo pueden abrir via browser. Si necesitas pasar esos scripts por laravel mix significa que no se trata de la salida final, y por tanto no tienen nada que hacer en public.
Segundo, comandos como minify o combine están pensados para cuando tienes un script, plugin, dependencia, etc legacy que es inviable de incorporar a la lógica principal. Por ejemplo, cuando se trata de un montón de globales en un script que no tiene exports de ninguna clase, así que no puedes requerirlo o importar de él.
Mix no intentará procesar ese archivo. Nada de sustitución de variables de entorno, transpilación, tree shaking. Se limita a operaciones que no conllevan parsear el contenido.
En cualquier otro caso, se usa .js(), y con ese comando le dejas a mix la responsabilidad de generar un build óptimo. Algo que sabe hacer de sobra.


text:
Q: Transparent background in Flex Air For Android? Can a Flex Air Android app have transparent background, like the Android Theme.Transluscent? I've tried adding:
    <systemChrome>none</systemChrome>
    <transparent>true</transparent>

to the -app file but that just makes the background white. Any suggestions?

A: Answering own question: It's not possible. The transparent theme has to be set in the main activity's theme tag in the android manifest. But the theme tag in the android manifest can not be overridden via the Flex mobile android manifest.

A: If you can use fill:
      <fill>
           <SolidColor color="#000000" alpha="0"/>
      </fill>

Not sure which file that code is in.
Also, this may be useful to read through: http://oreilly.com/flex/excerpts/flex-4-cookbook/graphics.html

A: I tried @Gunnar idea, by decompiling the apk with apk-tools, changing the activity theme and rebuilding it. Doesn't work. At least by only doing this. I'll try other combinations of things and if I succeed, I'll post here.


text:
Q: Remove third input from GCD calculation if left blank I am using the following code to calculate the GCD of three numbers supplied by a user:
$('#calc').click(function(){

Math.GCD = function(numbers) {
  for (var i = 1 ; i < numbers.length ; i++){
    numbers[0] = twogcd(numbers[0], numbers[i]);
  }
  return numbers[0];

  function twogcd(first, second) {
    if (first < 0) first = -first;
    if (second < 0) second = -second;
    if (second > first) {var temp = first; first = second; second = temp;}
    while (true) {
        first %= second;
        if (first == 0) return second;
        second %= first;
        if (second == 0) return first;
    }
   }
};

Math.LCM = function(first,second) {
    return first * (second / this.GCD(first, second));
};

var first   = document.getElementById("first").value;
var second   = document.getElementById("second").value;
var third = document.getElementById("third").value;

var numbers = [first,second,third];

var GCDresult = Math.GCD(numbers);

alert(GCDresult);
});

with HTML:
<FORM NAME="calc" method="POST">

<button TYPE="button" ID="calc">CALC</button>
<input type="text" name="stuff[]" class="input-field" id="first"/>
<input type="text" name="stuff[]" class="input-field" id="second"/>
<input type="text" name="stuff[]" class="input-field" id="third"/>

</FORM>

However, I would like for this form to calculate the GCD of both 2 and 3 numbers depending on what the user inputs. Thus, if a field is left blank, the null field will be ignored and the GCD calculation will proceed with the two inputs. However, I cannot, being relatively new to JavaScript, figure out how to exclude an empty field.
Fiddle: https://jsfiddle.net/tjj7won4/40/
How might I alter the code to account for this?

A: Updated your code. Added a check for first input field isEmpty. If yes then assigned it a value of next nonEmpty input field.
updated JS :
$('#calc').click(function(){

Math.GCD = function(numbers) {
  for (var i = 1 ; i < numbers.length ; i++){
    if(numbers[0]==""){
            $.each($('.inputField'),function(){
          if($(this).val()!=""){
               numbers[0] = $(this).val();
               return false;
          }
        });
    }
    if(numbers[0]!="" && numbers[i]!=""){
        numbers[0] = twogcd(numbers[0], numbers[i])
    }
  }
  return numbers[0];

 if (numbers[i] === '' || numbers[i] === 0) {
    numbers[0] = twogcd(numbers[0], numbers[i])
    };
  function twogcd(first, second) {
    if (first < 0) first = -first;
    if (second < 0) second = -second;
    if (second > first) {var temp = first; first = second; second = temp;}
    while (true) {
        first %= second;
        if (first == 0) return second;
        second %= first;
        if (second == 0) return first;
    }
   }
};

Math.LCM = function(first,second) {
    return first * (second / this.GCD(first, second));
};

var first   = $("#first").val();
var second   = $("#second").val();
var third = $("#third").val();

var numbers = [first,second,third];

var GCDresult = Math.GCD(numbers);

alert(GCDresult);
});

update fiddle link

A: Filter out non-numeric values before sending it to the GCD function, something like
/* Filter out things that don't look like numbers */
var numbers = [first,second,third].filter(function (e, i, a) { /* e = element, i = index, a = array */
    return parseFloat(e); /* Is it numeric? */
});

Demo

$('#calc').click(function(){

Math.GCD = function(numbers) {
  for (var i = 1 ; i < numbers.length ; i++){
    numbers[0] = twogcd(numbers[0], numbers[i]);
  }
  return numbers[0];

  function twogcd(first, second) {
    if (first < 0) first = -first;
    if (second < 0) second = -second;
    if (second > first) {var temp = first; first = second; second = temp;}
    while (true) {
        first %= second;
        if (first == 0) return second;
        second %= first;
        if (second == 0) return first;
    }
   }
};

Math.LCM = function(first,second) {
    return first * (second / this.GCD(first, second));
};

var first   = document.getElementById("first").value;
var second   = document.getElementById("second").value;
var third = document.getElementById("third").value;

/* Filter out things that don't look like numbers */
var numbers = [first,second,third].filter(function (e, i, a) { /* e = element, i = index, a = array */
 return parseFloat(e); /* Is it numeric? */
});

var GCDresult = Math.GCD(numbers);

alert(GCDresult);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<FORM NAME="calc" method="POST">

<button TYPE="button" ID="calc">CALC</button>
<input type="text" name="stuff[]" class="input-field" id="first"/>
<input type="text" name="stuff[]" class="input-field" id="second"/>
<input type="text" name="stuff[]" class="input-field" id="third"/>

</FORM>


text:
Q: Посоветуйте модуль для реагирования на нажатие клавиш посоветуйте модуль для реагирования на нажатие клавиш. Я работал с модулем от tkinter (Canvas):
from tkinter import *
window = Tk()
c = Canvas(window)
c.pack()
def a():
    key = event.keysym
    if key == 'w':
        КАКОЙ-ТО КОД
c.bind_all("<KeyPress>", a)
window.mainloop()

Но он не может реагировать на нажатие нескольких клавиш одновременно, посоветуйте модуль, который может реагировать на нажатие нескольких клавиш одновременно, спасибо.

A: Если вам нужно реагировать на нажатия кнопок клавиатуры, вам может подойти модуль keyboard
Устанавливается через pip (pip install keyboard)
Примеры работы модуля: Пример 1, Пример 2


text:
Q: Moving from Gnome to XFCE I'm using Gnome now and want to install XFCE. Nothing complicated but just curious - do all applications, installed previously on Gnome will be also removed or they would work on XFCE properly after installing XFCE and removing Gnome ?
OS: Linux Mint 7

A: Don't uninstall Gnome, just select XFCE in the graphical login screen

A: You might lose functionality in any desktop widgets that were using Gnome, but in general, all of your application using GTK should not in any way be affected by what desktop environment you are using.
At least under Ubuntu, I am fairly sure that uninstalling Gnome should only affect the desktop environment, it should not remove any applications that are not explicitly tied to the Gnome desktop.

A: Installing XFCE is easy : as root, run:
yum groupinstall XFCE

In my experience, all gnome applications will work with XFCE. However, you should make sure that XFCE launches the appropriate services for these at startup. Navigate to Menu –> Settings –> Sessions & Startup. On the "Advanced" tab, select the appropriate checkbox.
There is no need to uninstall GNOME. The login screen will allow you to select one or the other.


text:
Q: Sapui5 table column with various control template I implemented a table which bound to a json model.
I want to manipulate it such as one of the column be with various control types depend on the row value.
For example with some condition some rows of same column has text view control and other has dropdown list control.
I attached a sample image:

Thanks in advance!

A: You could also just create your custom control that renders the control you want based on a property value.
I created a simple example for you: http://jsbin.com/cafumivuco/13/edit?js,output
This has the advantage that only one control is rendered per row and not both while one is invisible.


text:
Q: Extra padding with @font-face in Windows? I have come across an issue with Windows rendering of an Font Squirrel @fontface font (Lekton Regular).
In Chrome and Firefox it renders perfectly:

But in the same browsers in Windows (XP and 8 tested), it adds top and bottom padding:

The computed styles for both elements are the same across both browsers, on both operating systems.
Is this a known issue and is there a work around?

A: The problem was with the font file. The problem disappeared when I loaded an alterative (from Google Fonts)


text:
Q: I2C Mux on Linux I am trying to understand how to address devices behind I2C Mux like PCA9548 in linux.
If the topology is something like
CPU->I2C_A Controller->PCA9548->Channel 0->RTC
CPU->I2C_A Controller->PCA9548->Channel 1->Temp Sensor

CPU->I2C_B Controller->PCA9548->Channel 0->Voltage Sensor
CPU->I2C_B Controller->PCA9548->Channel 1->Speed Sensor

I want to know the representation of these devices in user space? What are the associated sysfs entries?
I also want to know if pc9548 is the only driver required in kernel and i2c-dev and i2c-core are already available? Or driver for RTC/sensors is also required?
I have tried to read this, but could not follow it much.
My requirement is to read/write to those devices from user space. Do I have to  instantiate devices and assign addresses to it in startup script?
Thanks,
Hemant

A: You could use i2c-tools for manipulation at user space, if the driver has some problem.
Also you'll need enable the kernel module "i2c-dev" for the char device.
Like /dev/i2c-0
link here.
The necessary driver are i2c-mux, pca954x, I believe you already have i2c-core.
Also you should describe all the I2C devices in device tree or other files.
If the driver is prepared, you may see 8 i2c adapters under /dev, and their salve device is under /sys/bus/i2c.


text:
Q: referencing jquery global variables inside html? I am new to jquery.
I have below line of code: i just need to refer the variable inside html () function.
$('#myform #formProgress').html(' Saving…');

Now img src i have in a variable as below.
var url = document.location.host;
var url2 = url.concat("/MyApp/public/images/ajax-loader.gif");

Now inside i need to pass url2 as img src tag.  how can i do that?
Thanks!

A: Two ways:
$(...).html('Saving...')

Or:
$(...).append($('').attr('src', url2))

The second method is cleaner/better IMHO.

A: Use string concatenation (the + operator with strings).  This has nothing to do with jQuery specifically and is a very simple JavaScript (and general string handling) concept.
.html(' Saving&helliop;');


text:
Q: Resize an image with height/width constraints and constant ratio I want to insert an image in a webpage and I want it to fit in a 120*40 space.
The problem is, original images can have about any size (400*40, 30*220, etc.)
so if I set height attribute to 40, I might find myself with images larger than 120 width. The same goes if I set a 120px width.
If I set both width to 120 and height to 40, well it fits, but the original ratio is lost, and I don't want that.
What would you suggest ?
Get the original properties of the image in javascript and then set one of them (either to 120 width or 40 height) so that the other fits in 120*40 ?
There are a lot images like that in one page so I think this method is a bit heavy...
PHP solution :
    <?php
list($width, $height, $type, $attr) = getimagesize($image);
        if($width/$height>3)
            $height *= 120/$width;
        else
            $height = 40;
?>
<img src="<?=$image?>" height=<?=$height?>>

see below for a javascript solution and a CSS solution

A: css properties max-width and max-height are what you need.
My guess is that it will resize itself if it reaches one of these.
I have used this alot in previous web projects.
But i havent used the combination of both yet.
EDIT: I've sais this in a comment, but setting both those properties does work in my tests. It keeps the ratio and resizes by the limit it reaches first. Do not set any width or height properties, these might cause problems

A: JavaScript is quite fast, so why not try it?
I'd just stick to finding the aspect ratio and adding some checks:
var width = image.width;
var height = image.height;
var ratio = width / height;

if (width > 120) {
  width = 120;
  height = 120 * ratio;
} else if (height > 80) {
  height = 80;
  width = 80 * ratio;
}

image.width = width + 'px';
image.height = height + 'px';

As you seem to be using PHP, ImageMagick can resize an image to fit inside of a predefined box. I only know how to do it via CLI, as I don't use PHP, but I bet the PHP code would be simple.

A: I was actually searching for an answer to a different query but came across yours.
I use this to resize images which I am finding is very handy in a number of my scripts, but what I would suggest is that you resize the image to a little bigger than the longest side of the container and then use css to center the image both horizontally and vertically and set the container with overflow:hidden;
You lose a small bit of the image around the edges but at least they are all inserted without any stretching or squashing.
Hope that helps you or anyone else trying something similar.


text:
Q: Return string using Keras OCR I am using an example of Keras OCR to detect text from image. Using the example code provided in the official documentation I received a good accuracy using the pretrained weights.
I intent to use the OCR string for comparing some patterns detected in the text. To be able to create an app, I am using Flask.
I would like to print the string received from the OCR line wise. At the moment the output returns an image with the text (individual words). I want to be only able to print the string received from the OCR line wise. How can I achieve this?
Code:
import matplotlib.pyplot as plt

import keras_ocr

# keras-ocr will automatically download pretrained
# weights for the detector and recognizer.
pipeline = keras_ocr.pipeline.Pipeline()

# Get a set of three example images
images = [
    keras_ocr.tools.read(url) for url in [
        'https://upload.wikimedia.org/wikipedia/commons/b/b4/EUBanana-500x112.jpg',
         'abc.jpg'
    ]
]

# Each list of predictions in prediction_groups is a list of
# (word, box) tuples.
prediction_groups = pipeline.recognize(images)

# Plot the predictions
fig, axs = plt.subplots(nrows=len(images), figsize=(90, 90))
for ax, image, predictions in zip(axs, images, prediction_groups):
    keras_ocr.tools.drawAnnotations(image=image, predictions=predictions, ax=ax)

A: I dont know you have solved it or not. But after struggling for hours I have come up with following solution. I ran into your question while searching the answer for same issue.
for i in prediction_groups:
    for y in i:
        print(y[0])


text:
Q: I can list th database record, but i cannot update the record(MYSQL,XAMPP,PHP) I don't know the problem whether it is about my.ini. Can somebody can help me?? I can list the record, but i cannot update the record.
list_property.php
<title>List Property</title>

<?php

// Connect to server and select database.
mysql_connect("localhost", "root", "123456")or die("cannot connect");
mysql_select_db("album")or die("cannot select DB");

$sql="SELECT * FROM property";
$result=mysql_query($sql);

?>

List the property

Update_date
Usage
Region
Street
Building
Layers
Unit
Construction_area
Saleable_area
Price
Rent
Contant_person
Contant_Num
Layout
Decoration

<?php
while($rows=mysql_fetch_array($result)){
?>

<?php echo $rows['Update_date']; ?>
<?php echo $rows['Usage']; ?>
<?php echo $rows['Region']; ?>
<?php echo $rows['Street']; ?>
<?php echo $rows['Building']; ?>
<?php echo $rows['Layers']; ?>
<?php echo $rows['Unit']; ?>
<?php echo $rows['Construction_area']; ?>
<?php echo $rows['Saleable_area']; ?>
<?php echo $rows['Price']; ?>
<?php echo $rows['Rent']; ?>
<?php echo $rows['Contant_person']; ?>
<?php echo $rows['Contant_Num']; ?>
<?php echo $rows['Layout']; ?>
<?php echo $rows['Decoration']; ?>
<a href="update.php?P_ID=<?php echo $rows['P_ID']; ?>">update

<?php
}
?>

update.php
<title>Update Property</title>

<?php
// Connect to server and select database.
mysql_connect("localhost", "root", "123456")or die("cannot connect");
mysql_select_db("album") or die("cannot select DB");

// get value of id that sent from address bar
$P_ID=$_GET['P_ID'];

// Retrieve data from database
$sql="SELECT * FROM album.property WHERE P_ID = '$P_ID'";
$result=mysql_query($sql);
$rows=mysql_fetch_array($result);
?>

<form name="form1" method="post" action="update_ac.php">

Update Property Details

Usage
Region
Street
Building
Layers
Unit
Construction_area
Saleable_area
Price
Rent
Contant_person
Contant_Num
Layout
Decoration

<input name="Usage" type="text" P_ID="Usage" value="<?php echo $rows['Usage']; ?>"size= "15"/>

<input name="Region" type="text" P_ID="Region" value="<?php echo $rows['Region']; ?>" size="15"/>

<input name="Street" type="text" P_ID="Street" value="<?php echo $rows['Street']; ?>" size="15"/>

<input name="Building" type="text" P_ID="Building" value="<?php echo $rows['Building']; ?>" size="15"/>

<input name="Layers" type="text" P_ID="Layers" value="<?php echo $rows['Layers']; ?>" size="15"/>

<input name="Unit" type="text" P_ID="Unit" value="<?php echo $rows['Unit']; ?>" size="15"/>

<input name="Construction_area" type="text" P_ID="Construction_area" value="<?php echo $rows['Construction_area']; ?>" size="15"/>

<input name="Saleable_area" type="text" P_ID="Saleable_area" value="<?php echo $rows['Saleable_area']; ?>" size="15"/>

<input name="Price" type="text" P_ID="Price" value="<?php echo $rows['Price']; ?>" size="15"/>

<input name="Rent" type="text" P_ID="Rent" value="<?php echo $rows['Rent']; ?>" size="15"/>

<input name="Contant_person" type="text" P_ID="Contant_person" value="<?php echo $rows['Contant_person']; ?>" size="15"/>

<input name="Contant_Num" type="text" P_ID="Contant_Num" value="<?php echo $rows['Contant_Num']; ?>" size="15"/>

<input name="Layout" type="text" P_ID="Layout" value="<?php echo $rows['Layout']; ?>" size="15"/>

<input name="Decoration" type="text" P_ID="Decoration" value="<?php echo $rows['Decoration']; ?>" size="15"/>

<input name="P_ID" type="hidden" P_ID="P_ID" value="<?php echo $rows['P_ID']; ?>"/>
<input type="submit" name="Submit" value="Submit" />

</form>

update_ac.php
<?php
// Connect to server and select database.
mysql_connect("localhost", "root", "123456")or die("cannot connect");
mysql_select_db("album")or die("cannot select DB");

// update data in mysql database
$sql="UPDATE property SET Usage='".$_POST['Usage']."', Region='".$_POST['Region']."' , Street='".$_POST['Street']."' , Building='".$_POST['Building']."' , Layers='".$_POST['Layers']."' , Unit='".$_POST['Unit']."' , Construction_area='".$_POST['Construction_area']."' , Saleable_area='".$_POST['Saleable_area']."' , Price='".$_POST['Price']."' , Rent='".$_POST['Rent']."' , Contant_person='".$_POST['Contant_person']."' , Contant_Num='".$_POST['Contant_Num']."' , Layout='".$_POST['Layout']."' , Decoration='".$_POST['Decoration']."' WHERE P_ID='".$_POST['P_ID']."'";
$result=mysql_query($sql) or die ("Cannot Update Property......");

// if successfully updated.
if($result){
echo "Successful";
echo "
";
echo "View Property";
}

else {
echo "ERROR";
}

?>

After changing the error processing as suggested: The query is:
UPDATE property SET Usage='0', Region='Wah Chai' , Street='Tai Hang Road' , Building='Happy Valley' , Layers='a' , Unit='A' , Construction_area='1085 square feet' , Saleable_area='872 square feet' , Price='16800000' , Rent='48000' , Contant_person='Mr Yu' , Contant_Num='99968977' , Layout='3 bedrooms, including one suit' , Decoration='Yes' WHERE P_ID='1'

And the error is
You have an error in your SQL syntax;
check the manual that corresponds to your MySQL server version
for the right syntax to use near
'Usage='0', Region='Wah Chai' , Street='Tai Hang Road' , Building='Happy Valley'
 at line 1

A: It would help if you processed the error correctly. Then you would know what the error was rather than just that an error happened.
// update data in mysql database
$sql="UPDATE property SET Usage='".$_POST['Usage'].
                      "', Region='".$_POST['Region'].
                      "' , Street='".$_POST['Street'].
                      "' , Building='".$_POST['Building'].
                      "' , Layers='".$_POST['Layers'].
                      "' , Unit='".$_POST['Unit'].
                      "' , Construction_area='".$_POST['Construction_area'].
                      "' , Saleable_area='".$_POST['Saleable_area'].
                      "' , Price='".$_POST['Price'].
                      "' , Rent='".$_POST['Rent'].
                      "' , Contant_person='".$_POST['Contant_person'].
                      "' , Contant_Num='".$_POST['Contant_Num'].
                      "' , Layout='".$_POST['Layout'].
                      "' , Decoration='".$_POST['Decoration'].
                      "' WHERE P_ID='".$_POST['P_ID'].
                      "'";
$result=mysql_query($sql);

if ( ! $result ) {
    echo "SQL\n $sql\nGenerated this error\n";
    echo 'Database error: ' . mysql_errno() . ' : ' . mysql_error();
}

This mysql_* extension has been deprecated and therefore any code you write with it will at some point in time no longer work as the extension will soon be removed from new releases of PHP.


text:
Q: Parabolic filtration of data in C I want to create a filtration of a value in order to prevent it from instant changes. I have a task which is executed on 20ms. The final aim is to create a filter which to receive time constant which to show what time should be elapsed to reach the aim value with parabolic change of the delta(data change step). For example to configure the filtration to reach value 10 with initial value of 0 for 8 seconds.
I have implemented PT1 filtration, but it has only decreasing delta changes(in the beginning the delta is bigger with big data change step and as close as it reaches the aim value the delta is getting smaller and smaller). The filtration that i want to reach is to have small delta in the beginning and in the end of the filtration time and biggest delta in the middle of the filtration time.
My question is if there is such an algorithm already? Or could you give me any advices how to handle the problem.
The target delta changes in time:

A: Your filtration rate f′(t) is a quadratic function with value 0 at time 0 and at time T (8 seconds) and the area under the curve between time 0 and time T is F (8 units). So the filtration rate function has the form:

f′(t) = K·t·(T − t)

where the constant K is to be determined.  Expanding the above gives:

f′(t) = K·T·t − K·t2

Integrating f′(t) with respect to t gives:

∫f′(t)·dt = (K·T/2)·t2 − (K/3)·t3 + c

F is the integral of f(t) from 0 to T with respect to t, so since the lower bound is 0, we can substitute T for t in the above and drop the constant of integration c, giving:

F = (K·T/2)·T2 − (K/3)·T3

which simplifies to:

F = K·T3/6

Rearranging the above gives:

K = 6·F/T3

So we can substitute that into the original f′(t), giving:

f′(t) = (6·F/T3)·t·(T − t)

The above only applies for a continuous function f′(t), so you may need some minor adjustments because your real f′(t) only changes at 20 ms intervals. Taking the average between f′(t) and f′(t + .02) might be close enough. Another option is to use f'(t+.01) at each step. The most accurate option is to integrate from t to t+.02 at each step using the formula for the integral above and divide by .02.
For T = 8, F = 10, the filtration rate is given by:

f′(t) = 0.1171075·t·(8 − t)

A: Your question is kinda hard to understand... but if you want an output that has has S-shaped response to a step change in the input, with the S-shape made from parabolic arcs, then it's very easy to do -- just apply a moving average filter twice.
In digital signal processing, this technique is common, and is known as a cascaded integrator-comb (CIC) filter.  You can google that and get lots of hits, but I'm afraid I couldn't find one suitable for someone with no DSP experience.   No matter -- it's just a simple moving average applied multiple times.
If you want the output to take 6 seconds to reach the final value after a step change in the input, then apply a 3-second moving average twice, or a 2-second moving average 3 times.  The latter will have a piecewise cubic shape instead of a parabolic shape, which you might like better.


text:
Q: Run intellij idea project from command line I have quite massive project which was developed in intellij Idea. Now I have to be able to run it from command line, but there are too many libraries including maven dependencies are used.Is there a way to get command line that is used by intellij idea when it runs a project?

A: If you use maven you can do this:
mvn install
mvn exec:java -Dexec.mainClass="com.module.Main" -Dexec.classpathScope=runtime


text:
Q: Processing JSON data in angular 7 So I'm very new to Angular, html, and Typescript...
With that said I'm following this tutorial https://www.youtube.com/watch?v=f7w5c6IlmaA
I've got the JSON data to show in the console just fine. However at 24:12 in his video I get the same error as him, except it doesn't work.
I've tried to push the city name to the console from home.component.ts and still getting the same error.
Here's some code that may explain my stupidity, thanks!
home.component.ts file
import { Component, OnInit } from '@angular/core';
import {WeatherService} from '../weather.service';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {

  location = {
    city: 'orlando',
    code: 'us'

  };

  weather: any;

  constructor(private weatherService: WeatherService) {

  }

  ngOnInit() {
    this.weatherService.getWeather(this.location.city, this.location.code).subscribe(result => {
      console.log(result);

      this.weather = result;
      // console.log(this.weather.city.name);
    });
  }

}

weather.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

import { map } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class WeatherService {

  apiKey = 'Promise I didn't mess this part up';
  url;

  constructor(private http: HttpClient) {

    this.url = 'http://api.openweathermap.org/data/2.5/forecast?q=';
  }

  getWeather(city, code) {

    return this.http.get(this.url + city + ',' + code + '&APPID=' + this.apiKey).pipe(map(result => {
      console.log(result);
    }));
  }

}

A: You are not returning anything from your service, you should return it as,
getWeather(city, code)
      return this.http.get(this.url + city + ',' + code + '&APPID=' + this.apiKey).pipe(map(result => {
          console.log(result);
          return result;
        }));
 }

A: You forgot to return restult after console log replace below method
getWeather(city, code) {

    return this.http.get(this.url + city + ',' + code + '&APPID=' + this.apiKey).pipe(map(result => {
      console.log(result);
      return result;
    }));
  }

Hope this help! :)


text:
Q: How to send file through http post method without additional info? I am sending a file from sd card by using the following code.
 HttpURLConnection conn = null;
         DataOutputStream dos = null;
         DataInputStream inStream = null;
         String existingFileName = Environment.getExternalStorageDirectory().getAbsolutePath()
                 + "/111";

     File f = new File(existingFileName);
     String lineEnd = "\r\n";
     String twoHyphens = "--";
     String boundary =  "*****";
     int bytesRead, bytesAvailable, bufferSize;
     byte[] buffer;
     int maxBufferSize = 1*1024*1024;
     String responseFromServer = "";
     String urlString = "http://192.178.1.7/Geo/Prodect(filename)";
     try
     {
      //------------------ CLIENT REQUEST
     FileInputStream fileInputStream = new FileInputStream(f);
      // open a URL connection to the Servlet
      URL url = new URL(urlString);
      // Open a HTTP connection to the URL
      conn = (HttpURLConnection) url.openConnection();
      // Allow Inputs
      conn.setDoInput(true);
      // Allow Outputs
      conn.setDoOutput(true);
      // Don't use a cached copy.
      conn.setUseCaches(false);
      // Use a post method.
      conn.setRequestMethod("POST");
      conn.setRequestProperty("Connection", "Keep-Alive");
      conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);
      dos = new DataOutputStream( conn.getOutputStream() );
      dos.writeBytes(twoHyphens + boundary + lineEnd);
      dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + existingFileName + "\"" + lineEnd);
      dos.writeBytes(lineEnd);
      // create a buffer of maximum size
      bytesAvailable = fileInputStream.available();
      bufferSize = Math.min(bytesAvailable, maxBufferSize);
      buffer = new byte[bufferSize];
      // read file and write it into form...
      bytesRead = fileInputStream.read(buffer, 0, bufferSize);
      //while (bytesRead > 0)
      Log.v("info",".size."+bytesRead);
      for(int n1=0;n1<bytesRead;n1++)
      {

       dos.write(buffer, 0, bufferSize);
       bytesAvailable = fileInputStream.available();
       bufferSize = Math.min(bytesAvailable, maxBufferSize);
       bytesRead = fileInputStream.read(buffer, 0, bufferSize);

      }

      dos.writeBytes(lineEnd);
      dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
      // close streams
      Log.v("info","File is written");
      fileInputStream.close();
      dos.flush();
      dos.close();
     }
     catch (MalformedURLException ex)
     {
          Log.v("info", "error: " + ex.getMessage(), ex);
     }
     catch (IOException ioe)
     {
          Log.v("info", "error: " + ioe.getMessage(), ioe);
     }
     //------------------ read the SERVER RESPONSE
     try {
           inStream = new DataInputStream ( conn.getInputStream() );
           String str;

           while (( str = inStream.readLine()) != null)
           {
                Log.v("info","Server Response "+str);
           }
           inStream.close();

     }
     catch (IOException ioex)
     {
          Log.v("info", "error: " + ioex.getMessage(), ioex);
     }

It works fine but,the file contains 20 lines it saved in the sever with 22 lines.
My actual file  looks like as follows.
android app info
app name
app time
when i will send the flle to server from sd card the file look like as follows
1)**mnt/sdcard/111**
android app info
app name
app time
2)**
1 and 2 lines are added.
How i can send a file without those two lines .
If any one know the solution please help me .
Thanks in advance..

A: Try commenting the following
  dos.writeBytes(twoHyphens + boundary + lineEnd);
      dos.writeBytes(lineEnd);

A: public static StringBuffer post(String url,InputStream in) throws IOException {
        InputStream bufferInputStream = null;
        InputStreamReader responseInputStream = null;
        HttpURLConnection conn = null;
        OutputStream requestOutputStream = null;
        StringBuffer responseString = new StringBuffer();
        int bufferSize = 8192;
        byte[] byteBuffer  = new byte[bufferSize];
        int postDataSize = 0;
        try {
            if (in != null) {
                bufferInputStream = new BufferedInputStream(in);
            }
            if (bufferInputStream != null) {
                postDataSize = bufferInputStream.available();
            }
            //send request
            conn = getConnecttion(url);
            if (postDataSize > 0) {
                requestOutputStream = conn.getOutputStream();
                int position = 0;

                while ((position = bufferInputStream.read(byteBuffer)) > -1) {
                    requestOutputStream.write(byteBuffer, 0, position);
                }
                requestOutputStream.flush();
                requestOutputStream.close();
                requestOutputStream = null;
                byteBuffer = null;
            }
            // get response
            int responseCode = conn.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                responseInputStream = new InputStreamReader(conn.getInputStream(),"UTF-8");

                char[] charBuffer = new char[bufferSize];
                int _postion = 0;
                while ((_postion=responseInputStream.read(charBuffer)) > -1) {
                    responseString.append(charBuffer,0,_postion);
                }
                responseInputStream.close();
                responseInputStream = null;
                charBuffer = null;
            }else{
                throw new IOException("Respsone code:"+responseCode);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new IOException(e.getMessage());
        } finally {
            byteBuffer = null;

            if (responseInputStream != null) {
                responseInputStream.close();
                responseInputStream = null;
            }
            if (conn != null) {
                conn.disconnect();
                conn = null;
            }
            if (requestOutputStream != null) {
                requestOutputStream.close();
                requestOutputStream = null;
            }
            if (bufferInputStream != null) {
                bufferInputStream.close();
                bufferInputStream = null;
            }
        }
        return responseString;
    }

Please reference to above simple code,
send file like this:post("http://youurl.com",new FileInputStream(" you file path"))


text:
Q: Trouble passing arguments into os.system() I want to run a python script 5 times. The output from each run is an image, and I want 5 images saved at the end. To do this I am using the os.system() command, and I end up with the following error:
TypeError: system() takes at most 1 argument (3 given)

Here is my code:
import os
i = 1

    while i < 6:
        run = os.system ('python main.py', 'input laska.png', 'output laska_save' + str(i) + '.png')
        i = i + 1

Not sure what the problem here might be. I essentially want the output argument to be laska_save1, laske_save2 ... laska_save5. The increment happens 5, once everytime after the called script runs.
Any guidance is appreciated.

A: You should call it with just one string as follows:
os.system('python main.py input laska.png output laska_save{}.png'.format(i))

The os.system documentation says it just take an string as argument, so you must create that full string with the command before passing it to the function.

A: just format the string as the command you type in cmd prompt.
for example:
if test.py is a script which takes input file file.csv then the code will be
os.system("python {0} {1}".format(test_filepath,file.csv_filepath))

A: If your main.py is taking two arguments input file(laska.png) and the name of output file then your while loop will contain:-
os.system('python main.py laska.png laska_save{}.png'.format(i))


text:
Q: Add a column to a dataset whose values are filled by groups I have a dataset, which contains columns: week, shop, Item number and price. Also I have an array of unique numbers, which are equal to Item Numbers, but in different order.
I want to add new columns to this dataset based on these unique numbers. First of all, I need to group this dataset by week and shop. Then in particular week and particular shop I need to find an Item number which is equal to new column name (Element from array of unique numbers). If there is no such field fill with null.
Then i should fill all fields in a particular week and particular shop with price of this Item number.
Here some code that I've tried, but it works very slow, because the amount of rows is very big.
#real dataset
data2
weeks = data2['Week'].unique()

for k in range(len(Unique_number)):
    for i in range(len(weeks)):
        temp_array = data2.loc[data2["Week"] == weeks[i]]
        stores = temp_array['Shop'].unique()
        for j in range(len(stores)):
            temp_array2 = temp_array.loc[data2["Shop"] == stores[j]]
            price = temp_array2.loc[temp_array2["Item number"] == Unique_number[k], "Price"]
            if (price.empty):
                price = 0
            else:
                price = price.values[0]
            data2.loc[(data2["Week"] == weeks[i]) & (data2["Shop"] == stores[j]),Unique_number[k]] = price

I want something like this
Unique_numbers = [0,1,2,3]

dataframe before
week; shop; Item number; price
1     1     0            2
1     2     1            3
2     1     3            4
2     1     2            5
3     4     1            6
3     1     2            7

dataframe after
week; shop; Item number; price; 0; 1; 2; 3
1     1     0            2      2  0  0  0
1     2     1            3      0  3  0  0
2     1     3            4      0  0  5  4
2     1     2            5      0  0  5  4
3     4     1            6      0  6  0  0
3     1     2            7      0  0  7  0

A: Setup
u = df['Item number'].to_numpy()
w = np.asarray(Unique_numbers)
g = [df.week, df.shop]

Using some broadcasted comparison here (assumes that all of your price values are greater than 0).

pd.DataFrame(
  np.equal.outer(u, w) * df['price'].to_numpy()[:, None]).groupby(g).transform('max')

   0  1  2  3
0  2  0  0  0
1  0  3  0  0
2  0  0  5  4
3  0  0  5  4
4  0  6  0  0
5  0  0  7  0

A: This turns out a combination of pivot and merge:
df.merge(df.pivot_table(index=['week', 'shop'],
                       columns='Item number',
                       values='price',
                       fill_value=0)
           .reindex(Unique_numbers, axis=1),
         left_on=['week', 'shop'],
         right_index=True,
         how='left'
        )

Output:
   week  shop  Item number  price  0  1  2  3
0     1     1            0      2  2  0  0  0
1     1     2            1      3  0  3  0  0
2     2     1            3      4  0  0  5  4
3     2     1            2      5  0  0  5  4
4     3     4            1      6  0  6  0  0
5     3     1            2      7  0  0  7  0


text:
Q: mysql connection driver to dockerize the cakephp 1.3 application .env file
export MYSQL_URL='mysql'
export MYSQL_USERNAME='root'
export MYSQL_PASSWORD=''

database.php file
class DATABASE_CONFIG {

public function __construct(){
 $this->default['host'] = getenv('MYSQL_URL');
 $this->default['login'] = getenv('MYSQL_USERNAME');
 $this->default['password'] = getenv('MYSQL_PASSWORD');
}

var $default = array(
 'driver' => 'Cake\Database\Driver\Mysql',  // incompatible driver for cakephp 1.3
 'persistent' => false,
 'host' => '',
 'login' => '',
 'password' => '',
 'database' => 'RP',
 'prefix' => '',
 //'encoding' => 'utf8',
);
}

Unable to import DataSource class due to incompatible driver for the cake version used

please suggest a compatible mysql connection driver for cakephp 1.3 on docker

A: CakePHP 1.3 didn't use namespaces. I think you just want 'driver' => 'mysql'.


text:
Q: Java - send signal from Thread to Swing component I would like to ask, if I can run Thread and if some event happened, send signal and some swing components will catching signals.
Something like this:
public class MyThread extends Thread {
  String today = "???";

  @Override
  public void run() {
    if (today.equals("monday")) {
        // send signal
    }
  }
}

public class MyPanel extends JPanel {
  // catching signals and if signal is catched change background color
}

EDIT:
I tried this, but it do not work.
public class MyThread extends Thread {
@Override
public void run() {
    SwingWorker worker = new SwingWorker<String, String>() {
        @Override
        protected String doInBackground() throws Exception {
            System.out.println("doInBackground");
            publish("doInBackgroundPublish");
            firePropertyChange("firePropertyChange1", "oldValue1", "newValue1");
            return "doInBackground return";
        }
        @Override
        protected void process(List<String> chunks) {
            super.process(chunks);
            firePropertyChange("firePropertyChange2", "oldValue2", "newValue2");
        }
    };
    worker.execute();
}

}
public class MyPanel extends JPanel {
public class SWListen implements PropertyChangeListener, Observer {
    @Override
    public void update(Observable o, Object arg) {
        System.out.println("SWListen update");
    }
    @Override
    public void propertyChange(PropertyChangeEvent evt) {
        System.out.println("SWListen propertyChange");
    }
}
public MyPanel {
    addPropertyChangeListener(new SWListen());
}

}

A: A SwingWorker is a self contained "thread" (for argument sake), this means that it will create and launch it's own Thread from which doInBackground will be called.
doInBackground should then "do something" and call publish with the intermediate value (assuming your want to produce an overall value at the end, otherwise, it just generates a value)
At some point in the future process is called.  This method is called from within the context of the EDT, making it safe to update the UI from within.
There are a number of ways you could then "notify" the UI of the changes, most will fall under the category of an "observer pattern".
For example...
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridBagLayout;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingWorker;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class Test {

    public static void main(String[] args) {
        new Test();
    }

    public Test() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        public TestPane() {
            setLayout(new GridBagLayout());
            JLabel label = new JLabel("...");
            add(label);

            TickerWorker worker = new TickerWorker();
            worker.addPropertyChangeListener(new PropertyChangeListener() {
                @Override
                public void propertyChange(PropertyChangeEvent evt) {
                    System.out.println(evt.getPropertyName());
                    if ("counter".equals(evt.getPropertyName())) {
                        long value = (long) evt.getNewValue();
                        label.setText(Long.toString(value));
                    }
                }
            });
            worker.execute();
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(200, 200);
        }

    }

    public class TickerWorker extends SwingWorker<Void, Long> {

        @Override
        protected Void doInBackground() throws Exception {
            long counter = 0;
            while (true) {
                Thread.sleep(1000);
                publish(++counter);
            }
        }

        @Override
        protected void process(List<Long> chunks) {
            // Since we're in the EDT, it's probably pointless do announce ALL the
            // values, we're probably only interested in the last one
            for (long value : chunks) {
                firePropertyChange("counter", value - 1, value);
            }
        }
    }

}

Now, this notifies a single component, if you need to notify a number of components, then it becomes an order of magnitude more difficult.
You could have each component create it's own SwingWorker, which monitors some global monitor lock, allowing the "main" worker to trigger a notifyAll, which would then allow the "component workers" to publish some result ... but how do you get the value!?
At this point I'd probably just consider using some kind of event bus


text:
Q: Calculation wrong after multiple create class I have used the code below to calculate the value of linear weighted moving average but when I tried to recalculate for a new set of data by create a new class the result was wrong.
The first call I got value correctly but for the second call it was wrong.
public class LWMA
{
BarChart barChart;
int maPeriod;
public double value[];

public LWMA(int mp,BarChart bc){
    barChart = bc;
    maPeriod = mp;

    value = new double[barChart.barCount];
    for (int i = 0; i < barChart.barCount - 1; i++){
        value[i] = 0;
    }
    calculateIndicator();
}   // Ending L

public boolean calculateIndicator(){
    double sumPrice;
    double sumDivider;
    sumPrice = 0;
    sumDivider = 0;

    for ( int i = 1; i <= maPeriod; i++)
        sumDivider += i;

    for (int i = 0; i < barChart.barCount; i++){
        value[i] = 0f;
        if (i >= maPeriod){
            sumPrice = 0f;
            for (int j = 0; j < maPeriod; j++){
                sumPrice += (barChart.barChartItem[i-j].getClosePrice()*(maPeriod-j));
            }   // loop j
            value[i] = sumPrice/sumDivider;
        }
        else{
            value[i] = 0f;
        }
    }   //loop i
    return true;
}


text:
Q: I want to convert input object data to this below output in JavaScript es6 by add some null values logic is when first batch this is my input data

`let Input = {
    labels: [10, 20, 20, 10, 10, 10, 2, 2, 12, 12, 12, 4, 4, 8, 89],
    datasets: [
        {
            label: "One",
            data: [5, 4, 3, 2, 1],
        },
        {
            label: "Two",
            data: [7, 8, 9, 3, 1,3,2,1,],
        },
        {
            label: "Three",
            data: [10, 15, 19, 21],
        },
    ],
};`

let output = {
    labels:[10,20,20,10,10,10,2,2,12,12,12,4,4,8,89,32,40],
    datasets:[
        {
            label: "One",
            data: [5, 4, 3, 2, 1, null, null, null, null, null, null, null, null, null, null, null, null]
        },
        {
            label: "Two",
            data: [null, null, null, null, null, 7, 8, 9, 3, 1, 3,2,1,null, null, null, null]
        },
        {
            label: "Three",
            data: [null, null, null, null, null, null, null, null, null, null, null, null, null, 10, 15, 19, 21]
        }
    ]
}

I have input I have to convert the input data into output data as show in the code below example using JavaScript es6
logic is like in first array add label one value and rest with nulls and second array add values to second array rest all null same with three insert three array values and rest all null


text:
Q: adding .className to object is not working I am attempting to set a className to my nav element and it isn't working as intended. When I manually add the class to my HTML it puts a border around the unordered list items and the buttons. When I use js to add it, it shows that the nav tag has the attribute in the inspector but it does not add the border so I do not believe it is working. What am I doing wrong? I have linked to the bootstrap cdn and jquery cdn in the file.
HTML
<!doctype html>

      <title>Exercise 5.9</title>
      <meta charset="UTF-8">
      <meta equiv="X-UA-Compatible" content="IE=Edge">

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">

Home

Our Policies

How you can help

What we have accomplished

          <button type="button">Donate $10.00</button>
          <button type="button">Donate $50.00</button>
          <button type="button">Donate $100.00</button>

If you would to offer financial support, please choose the buttons above

JS
var nav = document.getElementsByTagName("nav");
nav.className = "navbar navbar-default";
console.log(nav);

A: Instead of using .className = try just setting the attribute of class to whatever you want. The main reason why it's not working, however, is because .getElementsByTagName() returns an array (nodeList) so you need to make sure when you set the class, it's properly indexed.
Using .setAttribute("atr", "value")
var button = document.getElementById("btnGo");

button.onclick = function () {
    var nav = document.getElementsByTagName("nav");

    for (var i = 0; i < nav.length; i++) {
        nav[i].setAttribute("class", "myClassName");
    }

};

Using .className
var button = document.getElementById("btnGo");

button.onclick = function () {
    var nav = document.getElementsByTagName("nav");

    for (var i = 0; i < nav.length; i++) {
        nav[i].className = "myClass";
    }

};

A: getElementsByTagName() return an array, you should write document.getElementsByTagName('nav')[0];


text:
Q: Conditions for convergence to 0 of 1/n^a Apologies if this has already been asked and answered, I could not find anything explicit on it.
I'm trying to find the range of $\alpha$ such that $$ \lim_{n\to\infty} \frac{k}{n^\alpha} = 0 $$
with $k>0$.
Now obviously $ \alpha \ge 1 $ is fine, but intuitively I believe $\alpha > 0$ is sufficient. Is this correct and if so, why?
I have considered thinking of it as a sequence so
$$x_n = \frac{k}{n^\alpha}$$
Then for $ M>n$,
$$ \vert x_M - L \vert <\epsilon $$
$$ \therefore \vert \frac{k}{M^\alpha}-0 \vert < \epsilon $$
$$ \therefore \frac{k}{M^\alpha} < \epsilon $$
But I can get no closer to a definitive answer.
Thanks in advance to whomever can help here!

A: Suppose $\alpha > 0$, then let $\epsilon > 0$. Note that: $\frac{k}{n^\alpha} = \exp (\log \frac{k}{n^\alpha}) = \exp(\log k - \alpha \log n)$.
Now, if $n$ increases to infinity, then $\log n$ also increases to infinity. So the whole thing hinges on $\alpha$.
If $\alpha$ is positive, then $\log k - \alpha \log n$ will keep decreasing, then it will go to $- \infty$ (roughly, you need to make this rigorous), and $e^{-\infty} = 0$ (once again, roughly), therefore the limit is zero.
On the other hand, if $\alpha$ is negative, then $\log k - \alpha \log n$ will keep increasing, so that it goes to $+\infty$, and $e^{+\infty} = +\infty$, so convergence doesn't happen.
Of course, if $\alpha = 0$, then the limit is $k$.
This answer is not rigorous, however it wishes to point out the power of rewriting the given expression in a form where it is almost immediately obvious  that the values of $\alpha$ convergence occurs are only the non-negative ones.
(By roughly, I mean to say that the understanding of the statement should be clear, along with a rigorous proof, but the statement itself is purely indicative, and in fact incorrect as a mathematical statement).

A: Let $f(x)=k/x^\alpha.$ Note that if we put $u=1/x$ then as $x \to +\infty,$ we have $u \to 0^+,$ and that in terms of $u$ we have $f=ku^\alpha.$ Since for $\alpha>0$ the latter function is continuous from the right at $0,$ your statement is right about the limit of $f$ at infinity.
Some of this conclusion depends on verifying the limits may be substituted in as suggested, and in showing $x^\alpha$ continuous from the right at $0.$


text:
Q: Profile picture from cloud storage to database - Android I would like to save a profile picture of a user in my database and to use it later.
I saved it to my firebase cloud storage with this code :
    private void uploadImage() {

    if(picture != null)
    {
        final ProgressDialog progressDialog = new ProgressDialog(this);
        progressDialog.setTitle("Uploading...");
        progressDialog.show();

        StorageReference ref = storageReference.child("images"+ UUID.randomUUID().toString());
        ref.putFile(picture)
                .addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                    @Override
                    public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                        progressDialog.dismiss();

                        Toast.makeText(MainActivity.this, "Uploaded", Toast.LENGTH_SHORT).show();
                    }
                })
                .addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        progressDialog.dismiss();
                        Toast.makeText(MainActivity.this, "Failed "+e.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                })
                .addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
                    @Override
                    public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
                        double progress = (100.0*taskSnapshot.getBytesTransferred()/taskSnapshot
                                .getTotalByteCount());
                        progressDialog.setMessage("Uploaded "+(int)progress+"%");
                    }
                });
    }
}

Now, I want to save it as a child in my Database...
I have this code to save all the datas (Name, email, phone, password...)
mAuth.createUserWithEmailAndPassword(edtEmail.getText().toString(), edtPassword.getText().toString())
                    .addOnSuccessListener(new OnSuccessListener<AuthResult>() {
                        @Override
                        public void onSuccess(AuthResult authResult) {
                            User user = new User();
                            user.setEmail(edtEmail.getText().toString());
                            user.setPhone(edtPhone.getText().toString());
                            user.setPassword(edtPassword.getText().toString());
                            user.setName(edtName.getText().toString());
                            user.setId(mAuth.getCurrentUser().getUid());
                            user.setProfilePic(picture);

But the "user.setProfilePic(picture)" doesn't work...
What could be the best way to save the profile picture of the user on my database ?
Thank you

A: Thats not the right way of doing it. What you should do is,
1) Store images in storage it self, with some UUID.
2) Store that reference of image in the storage.
3) Get the data from database use libraries like Glide or Picasso to load the images to avoid OutOfMemory Exception.
Here is the example
 StorageReference ref = storageReference.child("images"+ UUID.randomUUID().toString());
    ref.putFile(picture)
            .addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                @Override
                public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                    progressDialog.dismiss();
               Uri downloadUri = taskSnapshot.getMetadata().getDownloadUrl();
               String downloadurl = mDownloadUrl.toString();

                }
            })

           );

And now
  User user = new User();
  user.setEmail(edtEmail.getText().toString());
  user.setPhone(edtPhone.getText().toString());
  user.setPassword(edtPassword.getText().toString());
  user.setName(edtName.getText().toString());
  user.setId(mAuth.getCurrentUser().getUid());
  user.setProfilePic(downloadurl);  //here picture URL

And final Step just to push the data to DataBase
String key = mDatabase.child("YourNodeHere").push().getKey();
mDatabase.child("YourNodeHere").child(key).setValue(user);

A: To save the profile picture in the database try this:
         ref=db.child(mCurrentUser.getUid());
         StorageReference filepath=mStorage.child(uri.getLastPathSegment());
          filepath.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
             @Override
           public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
           String downloadurl = taskSnapshot.getDownloadUrl().toString();
           ref.child("image").setValue(downloadurl);
           //can save other data also

            }
      });

First add the url of the image in the firebase storage, then if added successfully, you will be able to retrieve the url String downloadurl = taskSnapshot.getDownloadUrl().toString(); and add it to the database child("image").setValue(downloadurl);
more info here:
https://firebase.google.com/docs/storage/android/download-files


text:
Q: Generate javax.wsdl.Definition from a String or byte array I have a wsdl stored in a string/byte array. Is there a way to generate  javax.wsdl.Definition from a String or byte array ? I checked the documentation here but couldn't find a way to do this.
Any samples or pointers ?

A: Found the answer:
public void getWSDLDefinition(byte[] wsdl) {
        try {
            WSDLReader wsdlReader = javax.wsdl.factory.WSDLFactory.newInstance().newWSDLReader();
            // switch off the verbose mode
            wsdlReader.setFeature(JAVAX_WSDL_VERBOSE_MODE, false);
            wsdlReader.setFeature("javax.wsdl.importDocuments", false);
            Definition wsdlDefinition = wsdlReader.readWSDL(null, new InputSource(new ByteArrayInputStream(wsdl)));
        } catch (Exception e) {}
    }


text:
Q: How to base64url Encode Strings in Cocoa Touch Is there a library function/method/class in Cocoa Touch for base64url encoding strings?

A: While there isn't a standard way to do this with the Apple frameworks, you should certainly check out CocoaDev's entry and discussion on the topic: BaseSixtyFour. They have plenty of ways to work this out, and the last comment there doesn't require libcrypto, or any external frameworks (which, on iOS, is a good start). It's definitely worth a look.
Update: Or even better, check out Base64 encoding options on Mac and iPhone on CocoaWithLove, as it includes excellent source code.


text:
Q: Populating Wix Combo Box Im using the code from from this link
and my Wix Dialogs looks like this
   <Control Id="DummyComboBox" Hidden="yes" Type="ComboBox" Sorted="yes" ComboList="yes" Property="DUMMYPROPERTY" X="65" Y="60" Width="150" Height="18">
      <ComboBox Property="DUMMYPROPERTY">
        <ListItem Text="Dummy" Value="Dummy"/>
      </ComboBox>
    </Control>
    <Control Id="SQLServer" Type="ComboBox" Sorted="yes" ComboList="yes"  X="150" Y="100" Width="110" Height="18" Property="DBSERVER"/>
    <Control Id="SQLServerLabel"  Type="Text" X="25" Y="100" Width="90" Height="18" NoPrefix="yes" Text="!(loc.SQLServerLabel)"/>

    <Control Id="SQLDatabaseName" Type="Edit" X="150" Y="120" Width="110" Height="18" Property="SQLDBNAME"/>
    <Control Id="SQLDBServerLabel" Type="Text" X="25" Y="120" Width="90" Height="18" NoPrefix="yes" Text="!(loc.SQLDatabaseLabel)"/>

    <Control Id="SQLUser"         Type="Edit" X="150" Y="140" Width="110" Height="18" Property="SQLUSER"/>
    <Control Id="SQLUServerLabel" Type="Text" X="25" Y="140" Width="90" Height="18" NoPrefix="yes" Text="!(loc.SQLUserLabel)"/>

    <Control Id="SQLPassword"     Type="Edit" X="150" Y="160" Width="110" Height="18" Property="SQLPASSWORD" Password="yes"/>
    <Control Id="SQLPServerLabel" Type="Text" X="25" Y="160" Width="90" Height="18" NoPrefix="yes" Text="!(loc.SQLPasswordLabel)"/>

I have walked through the code and it's functioning properly. However when I display the Wix Dialog the combo box is empty. Any idea as to what I'm doing wrong

A: Quite simple ...
Hidden="yes"

Hidden="no"

You are hiding it.

A: You need to write custom actions to fill the combo boxes  for e.g. for filling Server Instance combo box u may be write some thing like given below:-
public static ActionResult FillServerInstances(Session xiSession)
{
    xiSession.Log("Begin CustomAction");

    xiSession.Log("Opening view");
    View lView = xiSession.Database.OpenView(
        "DELETE FROM ComboBox WHERE ComboBox.Property='DBSRVR'");
    lView.Execute();

    lView = xiSession.Database.OpenView("SELECT * FROM ComboBox");
    lView.Execute();

    int Index = 1;
    bool flag = false;
    try
    {
        foreach (DataRow dr in Microsoft.SqlServer.Management.Smo.SmoApplication
                                        .EnumAvailableSqlServers(false).Rows)
        {
            String InstanceName = dr["Name"].ToString();

            if (InstanceName.Equals(xiSession["ComputerName"]
                + @"\"
                + xiSession["SQLINSTANCENAME"],
                StringComparison.InvariantCultureIgnoreCase))
            { flag = true; }

            Record lRecord = xiSession.Database.CreateRecord(4);
            xiSession.Log("Setting record details");
            lRecord.SetString(1, "DBSRVR");
            lRecord.SetInteger(2, Index);
            lRecord.SetString(3, InstanceName);
            lRecord.SetString(4, InstanceName);

            xiSession.Log("Adding record");
            lView.Modify(ViewModifyMode.InsertTemporary, lRecord);

            ++Index;
        }
    }
    catch (Exception ex)
    {
        logException(xiSession, ex);
    }
    if (flag)
    {
        xiSession["DBSRVR"] = xiSession["ComputerName"].ToString()
            + @"\" + xiSession["SQLINSTANCENAME"].ToString();
    }

    lView.Close();

    xiSession.Log("Closing view");
    lView.Close();
    return ActionResult.Success;
}


text:
Q: Uncaught TypeError: Cannot read property 'length' of undefined, web SQL I had created a database using web SQL that contains 2 columns username and password. To log in the application, I need to check wether the user exist or not. So I wrote this function:
html5rocks.webdb.Search = function(user,password){
       var db = html5rocks.webdb.db;
       db.transaction(function(tx){
          tx.executeSql("SELECT * FROM users WHERE username=? AND password=?",
          [username,password],
          function(rs){
              var verif =false;
                 for(var i=0; i<rs.rows.length; i++)
                     if((rs.rows.item(i).username == username) && (rs.rows.item(i).password == password))
                       verif =true;
                 if(verif == true)
                 {
                        alert("logged in");
                        self.location.href = "login.html";
                  }
                else
                         alert("access denied");
             },
          html5rocks.webdb.onSuccess,
          html5rocks.webdb.onError)
       });
   }

But when I run the application I get this error:
Uncaught TypeError: Cannot read property 'length' of undefined
Can any of you tell me what is wrong in this code?
Thanks


text:
Q: Вывести из текстового файла "input.txt" в файл "output.txt" только четные по счету строки     #include <iostream>
#include <fstream>
#include <string.h>

using namespace std;

int main()
{
int fl = 1;
FILE* f1;

fopen_s(&f1, "input.txt", "r");

char* str = new char[255];
FILE* f2;
fopen_s(&f2, "output.txt", "w");

if (!f2) {
    cout << "error 2" << endl;
    return 0;
}

if (!f1) {
    cout << "error 1" << endl;
    return 0;
}

while (!feof(f1)) {
    fgets(str,255,f1);
    for(int i = 0; i < strlen(str); i++)
        if (str[i] == '\0') {
            fl++;
            if (fl % 2==0) {
                fputs(str, f2);
            }
        }
}
fclose(f1);

return 0;}

не знаю как поделить строки на четные и нечетные

A: Раз у вас С++, то и используйте средства С++.
int main()
{
    ifstream in("input.txt");
    ofstream out("output.txt");
    in >> noskipws;
    for(char c, even = 0; in >> c; )
    {
        if (even) out << c;
        if (c == '\n') even = 1 - even;
    }
}

Проверки, что файлы открыты, допишите сами.


text:
Q: Linq To Sql compare Time only How do I compare time only of DateTime Object without getting the following
Error:
An exception of type 'System.NotSupportedException' occurred in mscorlib.dll but was not handled in user code Additional information: The specified type member 'TimeOfDay' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported.

My code:
var date = DateTime.Parse(query.DueTime);
entities = entities.Where(r => r.DueTime.TimeOfDay.Equals(date.TimeOfDay));

A: This is the answer!
var date = DateTime.Parse(query.DueTime);
var time = date.TimeOfDay;
entities = entities.Where(r => DbFunctions.CreateTime(r.DueTime.Hour, r.DueTime.Minute,  r.DueTime.Second) == time);

A: Have you tried using the function EntityFunctions.TruncateTime(TIME) ?
it would go as follows:
var date = DateTime.Parse(query.DueTime);
entities = entities.Where(r => EntityFunctions.TruncateTime(r.DueTime) == EntityFunctions.TruncateTime(date));

Hope this helps!


text:
Q: How to properly decode .wav with Python I am coding a basic frequency analisys of WAVE audio files, but I have trouble when it comes to convertion from WAVE frames to integer.
Here is the relevant part of my code:
import wave
track = wave.open('/some_path/my_audio.wav', 'r')

byt_depth = track.getsampwidth() #Byte depth of the file in BYTES
frame_rate = track.getframerate()
buf_size = 512

def byt_sum (word):
#convert a string of n bytes into an int in [0;8**n-1]
    return sum( (256**k)*word[k] for k in range(len(word)) )

raw_buf = track.readframes(buf_size)
'''
One frame is a string of n bytes, where n = byt_depth.
For instance, with a 24bits-encoded file, track.readframe(1) could be:
b'\xff\xfe\xfe'.
raw_buf[n] returns an int in [0;255]
'''

sample_buf = [byt_sum(raw_buf[byt_depth*k:byt_depth*(k+1)])
              - 2**(8*byt_depth-1) for k in range(buf_size)]

Problem is: when I plot sample_buf for a single sine signal, I get
an alternative, wrecked sine signal.
I can't figure out why the signal overlaps udpside-down.
Any idea?
P.S.: Since I'm French, my English is quite hesitating. Feel free to edit if there are ugly mistakes.

A: It might be because you need to use an unsigned value for representing the 16bit samples. See https://en.wikipedia.org/wiki/Pulse-code_modulation
Try to add 32767 to each sample.
Also you should use the python struct module  to decode the buffer.
import struct
buff_size = 512
# 'H' is for unsigned 16 bit integer, try 'h' also
sample_buff = struct.unpack('H'*buf_size, raw_buf)

A: The easiest way is to use a library that does the decoding for you. There are several Python libraries available, my favorite is the soundfile module:
import soundfile as sf
signal, samplerate = sf.read('/some_path/my_audio.wav')


text:
Q: I'm trying to count the number of words in a text but the count function is throwing an error message. I will be grateful for any help. Thanks library(tidytext)
library (dplyr)
anfarm %>%
    unnest_tokens(output = "word",
                  input = "text_column",
                  token = "words") %>%
    count(word, sort = TRUE)

#> Error in UseMethod("count") :
#>   no applicable method for 'count' applied to an object of class "c('tbl_df', 'tbl', 'data.frame')"

I expanded the tidytext function by adding the count function. I was expecting the tokenization of words, and the the number of occurences for each word.


text:
Q: Placement of scale tick labels in pgfplots When i use scale ticks in my plots i can't get those multiplicators to move anywhere. So basically i use plots like:
\documentclass[border=5mm]{standalone}
\usepackage{pgfplots}
 \begin{document}
  \begin{tikzpicture}
    \begin{axis}[scaled ticks=true]
    \addplot coordinates { (20000,0.0005) (40000,0.0010) (60000,0.0020)};
    \end{axis}
  \end{tikzpicture}%
 \end{document}

which gives:

So my Question is: How can i get this x tick scale label to move onto the right side of the right y-axis? So that it is above the x-axis?
(The mind behind this question is, that i sometimes have large x-labels, which then are very close to the scale label)

A: You should use the key: every x tick scale label which lets you overwrite the default placements. Notice that the keyword at within this style refers to the absolute size of the axis environment and are not in cm or pt.
So:
every x tick scale label/.style={
    at={(1,0)},xshift=1pt,anchor=south west,inner sep=0pt
}

will make the x tick scale be at the graph south east corner, shifted 1 pt to the right and anchored at south west (making sure that it is not overlapping with the graph).
Inserting this in your code yields:

You can always play with the yshift etc. as well.
For reference, the default option for x-tick scale placement is:
every x tick scale label/.style={at={(xticklabel cs:0.9,5pt)},yshift=-2em,left,inner sep=0pt}

where you should notice that the xticklabel cs is the coordinate system in the x-axis. Thus you can use this to manually place it according to the x-tick labels. Try for instance:
every x tick scale label/.style={at={(xticklabel cs:1)},anchor=south west}


text:
Q: How to create different post layout for different categories and subcategories in wordpress I've modified the single.php file in order to change layout for each category. In single.php I have this code
<?php
$post = $wp_query->post;
if ( in_category( '26') ||  get_term_children('26') {
include(TEMPLATEPATH . '/single-ric.php');
}
elseif ( in_category( '36') ||  get_term_children('36') {
include(TEMPLATEPATH . '/single-parl.php');
}
else {
include(TEMPLATEPATH . '/single-all.php');
}
?>

Is there something wrong in this code?
Each post article is shown with single-ric.php layout

A: Your question address few issues. First, as Pieter stated, you should use get_template_part instead of TEMPLATEPATH as it is deprecated.
What you need to do is to rename your templates to something like singlepost-ric.php, singlepost-parl.php and singlepost.php (instead of singlepost-all.php - that will be your fallback), this to prevent any fallback loop conflict - you need to place them at the same level as single.php to make this work. Then, use get_template_part in this way:
get_template_part('singlepost', 'ric');

If this doesn't work, use this to get the possible error messages:
assert("locate_template( array('singlepost-ric.php', 'singlepost.php'), false, false )");

The other issue is, and why your first condition is always true, is that you don't use right get_term_children. This function is used to get all the childrens of a term in a single array. If it don't find any, it will return an empty array, not false. This is why this (in_category( '26') ||  get_term_children('26')) is always true. By the way, you're missing a closing parenthesis in all your conditions.
I assume that what you want to do, is to know if the current post is in the category 26. Just remove the get_term_children part - it address something else. You probably added this because a category is a taxonomy, which would be valid then, but in_category is enough.
Last thing, you don't need this:
$post = $wp_query->post;

It is redundant. As you're within a template, the global var $post already contains the post you query.


text:
Q: Plotting Two Components of NDSolve using Parametric Plot Right now, I'm using this set-up to calculate one part of my differential equation function.
Manipulate[
 s = NDSolve[{p''[t] - 3 Sqrt[8*Pi*(p[t]*p[t] + p'[t]*p'[t])/6.0]*p'[t]
 - p[t]*p[t] == 0, p[0] == po, p'[0] == ppo}, p, {t, 0, ttop}];
 Plot[Evaluate[p'[t] /. s], {t, 0, ttop}], {{po, 0},0, .1},
 {{ppo, 0}, 0, .001}, {{ttop, 1}, 0, 3}]

And that works fine, however I want to use parametric plot to plot
    $p'[t]$ against $p[t]$ over {t,0,ttop}. Or really I wouldn't mind specifying the range as {t,0,3} and removing the variable.
However, I can't figure out how to plot two functions from the NDSolve on the parametric plot.
Currently, I'm trying this:
Manipulate[
  s = NDSolve[{p''[t] -
  3 Sqrt[8*Pi*(p[t]*p[t] + p'[t]*p'[t])/6.0]*p'[t] - p[t]*p[t] ==
 0, p[0] == po, p'[0] == ppo}, p, {t, 0, ttop}];
 ParametricPlot[Evaluate[{p'[t], p[t]} /. s], {t, 0, ttop}], {{po, 0},
 0, .1}, {{ppo, 0}, 0, .001}, {{ttop, 1}, 0, 3}]

But this isn't working. Does anyone know how I could use parametric plot  to plot $p'[t]$ against $p[t]$ for a given range of $t$ $(0,3)$?

A: Change this
s=NDSolve[{p''[t]-3 Sqrt[8*Pi*(p[t]*p[t]+p'[t]*p'[t])/6.0]*p'[t]-p[t]*p[t]==0,
  p[0]==po, p'[0]==ppo}, p, {t,0,ttop}];

to this
s=NDSolve[{p''[t]-3 Sqrt[8*Pi*(p[t]*p[t]+p'[t]*p'[t])/6.0]*p'[t]-p[t]*p[t]==0,
  p[0]==po, p'[0]==ppo}, p, {t,0,ttop}][[1]];

And I believe you will get your desired ParametricPlot.
Look carefully, the change might be easily missed, perhaps look at the value of s from each of those to more easily spot it. Once you find it then study why this makes the difference and why the original version worked with Plot, but not with ParametricPlot.


text:
Q: How to resize textarea based on its value? I want to scale a textarea based on its content, for example:

textarea {
  height: auto;
}
<textarea>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Commodi illum obcaecati alias, quaerat enim eos esse corrupti ducimus eius saepe, odio dignissimos nihil dicta sunt cum voluptas quae magni reiciendis labore velit aliquid asperiores iure? Non laboriosam eaque quis voluptatibus recusandae doloribus, suscipit, at dignissimos, dicta voluptates corporis nisi! Voluptatem?
</textarea>

Hopefully you can find a solution

A: Unfortunately, there is no great way to do it with raw HTML or CSS, JavaScript is typically the solution especially with using the textarea element. However, you can use the contentEditable feature on a div, which will make it so the textbox automatically resizes based on content.

div {
  outline: solid 1px;
  width: 120px;
}
<div contentEditable></div>


text:
Q: File never gets created Im trying to write and execute a .vbs file with python. When I run the program, the IDE shows an error that the file I tried to make isn't there, so therefore it couldn't be executed. I followed exactly the documentation in python.org and other similar questions in stack overflow but they didn't give a good answer to my problem. Here is the code I tried to run:
import os
a = open('draw.vbs','w+')
a.write('do\nSet oWMP = CreateObject(\"WMPlayer.OCX.7\")\nSet colCDROMs             oWMP.cdromCollection\nif colCDROMs.count >= 1\ncolCDROMs.Item(i).eject\nNext  cdrom\nEnd If\nloop')
b = os.system('draw.vbs')

A: Try using a with statement.
with open('draw.vbs', 'w+') as a:
    a.write('do\nSet oWMP = CreateObject(\"WMPlayer.OCX.7\")\nSet colCDROMs
b = os.system('draw.vbs')


text:
Q: how to show eclipse error icons instead of egit icons? egit plug in for eclipse is great.
It's only drawback is that its icons hide eclipse error icons in the navigation tree.
How do you handle this?
see egit icons: