text:
Q: How to implement Modal Dialog in Angular 2 and above I am a newbie to angular.
I have used bootstrap modal using the package ng2-bootstrap.
My View file is

Area Master

        <button type="button" class="close pull-right" (click)="lgModal.hide();" aria-label="Close">
          ×
        </button>

        Modal Content here...

        <button type="submit" class="btn btn-primary">Add</button>

I need to know how to show/hide this modal from the component (type script file).
Type script file is
import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';
import { Router } from '@angular/router';
import { FormGroup, Validators, FormBuilder, FormControl } from '@angular/forms';
import { Area } from './area';
import { AreaService } from './area.service';
@Component({

  moduleId: module.id,
  selector: 'my-areas',
  templateUrl: './areas.component.html',
  styleUrls: ['./areas.component.css']
})

export class AreasComponent implements OnInit {
  area_form: FormGroup;
  new_area: Area;
  areas: Area[];
  @ViewChild('lgModal') lgModal:ElementRef;
  constructor(
    private areaService: AreaService,
    private router: Router,
    private form_builder: FormBuilder) { }

  getAreas(): void {
    this.areaService
      .getAreas()
      .then(areas => this.areas = areas);
  }

  submit(area: Area): void {
    console.log(area);
    this.areaService.create(area)
      .then(area => { this.areas.push(area) })
  }

  ngOnInit(): void {
    this.getAreas();
    this.lgModal.show();
    this.area_form = this.form_builder.group({
      name: ['', Validators.required],
      pincode: ['', Validators.required],
      status: ['Active'],
      type: ['Busines Service Area']
    })
  }
}

A: Your common child modal component will be as below
import {Component,Input, ViewChild} from '@angular/core';
import { ModalDirective } from 'ngx-bootstrap';

@Component({
  selector: 'common-modal',
  template: `

{{title}}

        <button type="button" class="close pull-right" aria-label="Close" (click)="hideChildModal()">
          ×
        </button>

        <ng-content select=".modal-body"> </ng-content>

          <button class="btn btn-default" (click)="hide()"> Cancel </button>

  `,
})
export class CommonModalComponent {
   @ViewChild('childModal') public childModal:ModalDirective;
   @Input() title:string;
  constructor() {
  }
  show(){
    this.childModal.show();
  }
  hide(){
    this.childModal.hide();
  }
}

Using the child component in your parent component will look as below
import {Component, ViewChild, NgModule,ViewContainerRef} from '@angular/core'
import { BrowserModule } from '@angular/platform-browser';
import { ModalDirective,ModalModule } from 'ngx-bootstrap';
import {CommonModalComponent} from './child.modal';
@Component({
  selector: 'my-app',
  template: `
    <button type="button" class="btn btn-primary" (click)="childModal.show()">Open modal</button>
    <common-modal  #childModal [title]="'common modal'">

    Hi heloo

    </common-modal>

  `,
})
export class AppComponent {
  @ViewChild('childModal') childModal :CommonModalComponent;
  constructor(private viewContainerRef: ViewContainerRef) {
  }

}

Using the above code you can have a separate common modal dialog which can be reused, so that your header & footer remains the same and you can use Content-Projection to use change the body of the modal dialog.
LIVE DEMO

A: The below answer is in reference to the latest ng-bootstrap
Component Controller
import { TemplateRef, ViewChild } from '@angular/core';
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';

@Component({
  selector: 'app-app-registration',
  templateUrl: './app-registration.component.html',
  styleUrls: ['./app-registration.component.css']
})

export class AppRegistrationComponent implements OnInit {

  @ViewChild('editModal') editModal : TemplateRef<any>; // Note: TemplateRef

  constructor(private modalService: NgbModal) { }

  openModal(){
    this.modalService.open(this.editModal);
  }

}

Component HTML
<ng-template #editModal let-modal>

Edit Form

  <button type="button" class="close" aria-label="Close" (click)="modal.dismiss()">
    ×
  </button>

  <button type="button" class="btn btn-outline-dark" (click)="modal.close()">Save</button>

</ng-template>

app.module.ts
import {NgbModule} from '@ng-bootstrap/ng-bootstrap';

@NgModule({
  declarations: [
    ...
  ],
  imports: [
    ...

    NgbModule

  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

A: Now (v1.8.1+) you can do it easier by using modal service
you can use templates and components for creating modals
http://valor-software.com/ngx-bootstrap/#/modals#service-section


text:
Q: Yet another ImportError: attempted relative import with no known parent package I have the following directory structure:
py_test
├── __init__.py
├── dir1
│   ├── __init__.py
│   └── script1.py
└── dir2
    ├── __init__.py
    └── script2.py

In script2 I want to "import ..\script1".
What I tried in script2:

*

*Does not work
from ..dir1 import script1
ImportError: attempted relative import with no known parent package`

*Works
import sys, os
path2add = os.path.normpath(os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir, 'dir1')))
if (not (path2add in sys.path)) :
    sys.path.append(path2add)

If I want to go with option 1, what is the simplest (i.e., with the least files) file/dir structure that makes it work?
I am aware of this, but I wonder if creating that directory structure can be avoided, and still use type-1 import.
I am currently using this workaround, which uses type-2 import.
Related:
How to import a Python class that is in a directory above?
Import a module from a directory (package) one level up
Getting "ImportError: attempted relative import with no known parent package" when running from Python Interpreter
Using importlib to dynamically import module(s) containing relative imports
How to import variables in a different python file

A: As mentioned in the comments, attempting to import modules a directory up will not work if script2.py is your entry point.
As mentioned in this link you included:

If the module's __name__ does not contain any package information (e.g., it is set to __main__), then relative imports are resolved as if the module were a top-level module, regardless of where the module is actually located on the file system.

The module's __name__ is set to __main__ if it is the entry point, or the one that you pass to the interpreter with something like python script2.py.
Any python module run as such no longer has the information needed to import files from higher directories.
Therefore you have two options:
Option 1: Keep using the workaround with sys.path.append
This will work how you want it to, but it is rather cumbersome.
Option 2: Make your entry point at the top level
Assuming your package has more than one script that needs to be run, you could create a new file that imports both script1 and script2 and then calls the functionality you want based on a command line argument. Then you will be able to keep your current directory structure and have your relative imports work just fine, without any kind of fiddling with sys.path.

redpajama_set_name: RedPajamaStackExchange


text:
Q: java.io.FileNotFoundException: /storage/6CDB-8541/DCIM/Camera/IMG_20180523_202102.jpg (Permission denied) I have trouble getting the image file path to my FileOutputStream. There is an error related to the permission. How can I fix this?
if (getIntent().getExtras().getString("file_path") != null) {
    Log.d(TAG, "Path is NOT NULL");
    file = new File(getIntent().getExtras().getString("file_path"));

    Bitmap src;
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(file.getPath(), options);

    final int REQUIRED_SIZE = 400;
    int scale = 1;
    while (options.outWidth / scale / 2 >= REQUIRED_SIZE
            && options.outHeight / scale / 2 >= REQUIRED_SIZE)
        scale *= 2;

    options.inSampleSize = scale;
    options.inJustDecodeBounds = false;
    src = BitmapFactory.decodeFile(file.getAbsolutePath(), options);
    FileOutputStream os;

    try{
        ExifInterface exif = null;
        try {
            exif = new ExifInterface(file.getPath());
        } catch (IOException e) {
            e.printStackTrace();
        }
        int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION,
                ExifInterface.ORIENTATION_UNDEFINED);

        Bitmap bmRotated = rotateBitmap(src, orientation);

        os = new FileOutputStream(file.getAbsoluteFile());
        bmRotated.compress(Bitmap.CompressFormat.JPEG, 100, os);
        photoView.setImageBitmap(bmRotated);
        os.flush();
        os.close();
    } catch (Exception e){
        e.printStackTrace();
    }
} else {
    Log.d(TAG, "Path is NULL");
}

I tried to look from other sources but it does not help me to know the answer.

A: Have you ever declared this in manifest? I think you are missing android permission.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

A: With declaring permissions in AndroidManifest, you also need to handle Runtime permissions

A: give below permission into android manifest file..
if you perform read and write then add both ..
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

then in activity when you perform read and write operation that time handle run time permission like below..
 /**
 * this method check permission and return current state of permission need.
 */
private boolean checkPermissions() {
    int permissionState = ActivityCompat.checkSelfPermission(this,
            Manifest.permission.READ_EXTERNAL_STORAGE);
    return permissionState == PackageManager.PERMISSION_GRANTED;
}
  /**
 * this method request to permission asked.
 */

private void requestPermissions() {
    boolean shouldProvideRationale =
            ActivityCompat.shouldShowRequestPermissionRationale(this,
                    Manifest.permission.READ_EXTERNAL_STORAGE);

    if (shouldProvideRationale) {
    } else {
        Log.i("Error", "Requesting permission");
        // previously and checked "Never ask again".
        ActivityCompat.requestPermissions(MainActivity.this,
                new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                REQUEST_PERMISSIONS_REQUEST_CODE);
    }
}

and then perform your operation.
 if (!checkPermissions()) {
        requestPermissions();
    } else {
        // here your operation
        getFileDetails();

    }

and when permission is grant then get call back in below method..
   @Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    if (requestCode == REQUEST_PERMISSIONS_REQUEST_CODE) {
        if (grantResults.length <= 0) {
            // If user interaction was interrupted, the permission request is cancelled and you
            // receive empty arrays.
            Log.i("Error", "User interaction was cancelled.");
        } else if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            // Permission was granted. Kick off the process of building and connecting
            // GoogleApiClient.
        } else {
        }
    }

}


text:
Q: Why rewrite directive causes "301 Moved Permanently" with Nginx? Below is a much simplified version of what I have in the configuration file of a server run by Nginx 1.2.5, yet it causes 301 Moved Permanently with Location: http://example.com/phpmyadmin/ before serving data, which is not what I expected from the default behavior of the rewrite directive.
server {
    listen 80;
    location /pma {
        rewrite ^ /phpmyadmin;
    }
    location /phpmyadmin {
        root /var/www;
        index Documentation.html;
    }
}

When I go to http://example.com/pma in a browser, the data is served but the URL in the address bar changes to http://example.com/phpmyadmin/ while it was supposed to stay http://example.com/pma.
How do I avoid Nginx sending 301 Moved Permanently so that it doesn't expose the actual directory structure on my server?

A: Try alias:
server {
    listen 80;
    location /pma {
        alias /phpmyadmin;
    }
    location /phpmyadmin {
        root /var/www;
        index Documentation.html;
}

A: I think that you need to use alias instead of rewrite. Rewrite creates a "new" URL, so it makes a redirect
server {
    listen 80;
    location /pma {
        alias  /var/www/phpmyadmin;
        index Documentation.html;
    }
    location /phpmyadmin {
        root /var/www;
        index Documentation.html;
    }
}


text:
Q: HTML page not loading using QWebView I am trying to load one HTML file using QWebView, which contains a flash video.
 But my webpage is not getting loaded at all. if I right click on the page , context menu is just displaying
"load" button.
I am using QtSDK5.1 64bit on win7 64 bit machine.
NOTE :-
 1. Same source code when I am compiling using QtSDK 4.8.1 32 bit it is working fine.
 2. I tried to install openssl libraries(copied libeay32.dll and ssleay32.dll in the same application folder) for win64 bit machine as well, but no luck.
Below mention is the code
QWebView m_pWyseWebView;
m_pWyseWebView.settings()->setAttribute(QWebSettings::PluginsEnabled, true);
m_pWyseWebView.settings()->setAttribute(QWebSettings::JavascriptEnabled, true);
m_pWyseWebView.settings()->setAttribute(QWebSettings::JavaEnabled, true);
m_pWyseWebView.settings()->setAttribute(QWebSettings::PrivateBrowsingEnabled, true);
m_pWyseWebView.settings()->setAttribute(QWebSettings::JavascriptCanOpenWindows, true);
m_pWyseWebView.settings()->setAttribute(QWebSettings::WebGLEnabled, true);
QString str = "<embed type=\"application/x-shockwave-flash\"     src=\"http://z.cdn.turner.com/xslo/cvp/assets/container/2.0.4.0/cvp_main_container.swf\"     width=\"100%\"     height=\"100%\"  data=\"http://z.cdn.turner.com/xslo/cvp/assets/container/2.0.4.0/cvp_main_container.swf\"  name=\"cvp_1\"  id=\"cvp_1\"  type=\"application/x-shockwave-flash\"  PARAM=\"\"  quality=\"high\"  bgcolor=\"#000000\"  allowFullScreen=\"true\"  allowScriptAccess=\"always\"  wmode=\"direct\"  flashvars=\"context=vidEx&autostart=true&site=cnn&profile=desktop&domId=cvp_1&cvpSessionToken=KP156PURf6shHZ3PI72XS6ill\">";
m_pWyseWebView.setHtml(str,QUrl("https://edition.cnn.com/video"));
m_pWyseWebView.setGeometry(50,50, 640, 480);
m_pWyseWebView.show();

Please help what needs to be installed extra on 64bit machine.
Any help will be greatly appreciated.

A: Did you copy the openssl libs from a 32bit machine to a 64bit machine? Not quite clear from your wording. This might work if you have a 32bit Qt on your 64bit machine, but using 32bit openssl with a 64bit Qt won't work. You need get 64bit openssl libs.


text:
Q: Generating a web service server implementation using wsdl2java in CXF  Background :
I have prior experience working on consuming Apache CXF web services but I am a bit new to generating a service endpoint interface (SEI) and a service implementation using the wsdl2java tool that comes along with the Apache CXF distribution.
The task :
I am currently working on the implementation of a SOAP based web-service that will be consumed by external systems. I have already defined the messages (XSD) and the WSDL file. I have tried generating the SEI by using the wsdl2java tool from Apache CXF. The SEI gets generated correctly with the JAXB types as the input parameters and return types to the web service methods.
When I take a look at the code generated for the service implementation class, I see that it extends the javax.xml.ws.Service class. Also, a lot of overloaded methods are generated which have the same name as the methods in the service endpoint interface with "Soap12Http" appended to the method name. A few of these methods take the parameter of type WebServiceFeature... features whereas the others don't take any parameters. Example :
public class Query extends Service {

        @WebEndpoint(name = "product_query-soap12-http")
    public IQuery getProductsSoap12Http(WebServiceFeature... features) {
        return super.getPort(getProductsSoap12Http, IQuery.class,features);
    }
}

*where IQuery is the service endpoint interface
The problem :

*

*I was expecting the service implementation class to implement the service endpoint interface instead of extending javax.xml.ws.Service. Is this a valid expectation?

*I was expecting the service implementation class to implement the methods from the service endpoint interface. Is this a valid expectation?

*I would also like to know if the wsdl2java command can be asked to generate a jar for the JAXB POJOS instead of generating them as class files.

A: For 1 and 2, the answer is no.   The generated XXXXService class is pretty much a factory for proxies of the various SEI's in the WSDL.   Each endpoint/binding/portType combination in the wsdl should result in a series of "getXYZPort(...)" calls on the Service object to return an instance of that specific SEI.
For 3, a -clientjar option was added to cxf's tools last week (not released yet, would need the latest snapshots) that may be close to what is needed.


text:
Q: How often should I remind the user on "Rate the app" (iPhone)? I have this application: http://www.youtube.com/watch?v=Tn7_yNt1OaE
I made a mechanism that counts the number of times the app has launched, and measure the playtime duration as well.
I want to remind the user on she/he can support the development, can help others to find my app by dropping a rate in the App Store (I have instant App Store link format as well).
The only thing I want to discuss here: How often/rare should I remind the user?
The first should be about after 15 launch, and 3-6 hours of playtime... ...or not? And the second? Have you any experience on it?

A: I know that I get annoyed as hell about this type of thing. Not pestering me with such a question will actually yield the highest probability that I care to vote.
Make quality content, then people will give you high ratings.
You might keep your first reminder in, but if I haven't voted after the 15th launch, I certainly won't vote after the 100th launch.

A: According to The Business of iPhone and iPad Development, the best time to remind your users to rate your app is when they've accomplished some task, or otherwise have a positive feeling about your app. If you have a game, you may want to remind users to rate when they've beaten a boss or a level. Otherwise, once or twice a month is probably best. Users don't like to be pestered. There are thousands of other apps that say "Rate Me". If they wanted the  " Remind Me to Rate" app, they would've downloaded another one.

A: It really depends on how often your users open your app. If they do it on a daily basis, it might be a good idea to remind them every two weeks or so.
If the use it once a month, I'd say every time they open it, or every seconds time.
The best idea would be to test - start with a low frequency and wait for ratings. Increase the frequency from time to time and try to measure the effect it has on ratings. While some users tend to be annoyed by this kind of feature, from what I hear the overall effect is more ratings and more sales. I think if you're app is useful enough, users won't mind. And if it's not - skipping this feature is not what's going to save you:)
P.S. there's a quick way to integrate this feature into your app, by using this: http://bnpr.es/iuZmsU

A: I'm of the opinion that you should never display an alert that the user is forced to dismiss. Rather, provide a link to the review page in a static, non-intrusive place.
For example, looking at your app you have an alert between puzzles; if you instead modified the finished puzzle view (where you briefly highlight the completed shape) to have both the "Next Puzzle" button as well as a small text link that said "Rate this app on iTunes", you'd effectively remind people all the time and yet never force them to respond to your request.
If you wanted to, every few puzzles you could highlight the text, or briefly highlight it and fade it back to normal, something like that, to help ensure they saw it once in a while. If they ever tap on it then never highlight it again.
I believe that this kind of system is much, much more likely to generate useful reviews, if for no other reason than it seems like nearly every app these days is using the Appirater-style alert and I've gotten to the point where I just always tap "never," even if I would have reviewed it later.

A: I contemplated this myself, and I thought that it should be based on playing time. If you base it level wise, most people will make it a forced-habit to hit the "No Thanks" button. If you base it off playing time that would be better and make it less of a habit for a user to hit "No Thanks"
Also, make sure that it never comes up again after the user does rate it. This way it won't keep annoying them.


text:
Q: GAE NDB Expando Model with dynamic Kind Is it possible to assign a dynamic Entity Kind to an Expando Model? For example, I want to use this model for many types of dynamic entities:
class Dynamic(ndb.Expando):
    """
    Handles all "Post types", such as Pages, Posts, Users, Products, etc...
    """
    col = ndb.StringProperty()
    parent = ndb.IntegerProperty()
    name = ndb.StringProperty()
    slug = ndb.StringProperty()

Right now I use the "col" StringProperty to hold the Kind (like "Pages", "Posts", etc) and query for the "col" every time.
After reading the docs, I stumbled upon this @classmethod:
class MyModel(ndb.Model):
    @classmethod
    def _get_kind(cls):
         return 'AnotherKind'

Does that mean I can do this?
class Dynamic(ndb.Expando):
    """
    Handles all "Post types", such as Pages, Posts, Users, Products, etc...
    """
    col = ndb.StringProperty()
    parent = ndb.IntegerProperty()
    name = ndb.StringProperty()
    slug = ndb.StringProperty()

    @classmethod
    def _get_kind(cls):
        return 'AnotherKind'

But how do I dynamically replace 'AnotherKind'? Can I do something like return col?
Thanks!

A: I don't know if you can do that, but it sounds dangerous, and GAE updates might break your code.
Using subclasses seems like a much safer alternative.  Something like this:
class Dynamic(ndb.Expando):
    parent = ndb.IntegerProperty()
    name = ndb.StringProperty()
    slug = ndb.StringProperty()

class Pages(Dynamic):
    pass

class Posts(Dynamic):
    pass

class Users(Dynamic):
    pass

You could also try using PolyModel.
We need to know more about your application and what you are trying to accomplish to give more specific advice.


text:
Q: Need kcachegrind like profiling tools for mac Need suggestion on tools similar to kcachegrind wingrind valgrind for mac platform.
I don't think these work on mac, I already checked these.

A: Webgrind runs in PHP and can read the cachegrind output of XDebug. It currently doesn't offer all the functionality of KCacheGrind, but it is super simple to install, and seems to have renewed activity.

A: MacCallGrind is a semi-commercial alternative available for the Mac.  I've experimented with the free version which is limited to 3MB grind files.  It's roughly equivalent to WinCacheGrind in terms of functionality.

A: Try the qcachegrind + Graphviz killer combo.
It installs quickly via brew, which is nice.
Check out these instructions, basically install it via:
brew install qcachegrind

which will download other dependencies such as qtand graphviz.

A: You can install KCacheGrind using MacPorts.
There are also some alternatives like:

*

*WebGrind

*qcachegrind (brew install qcachegrind)

*XHProf: A Hierarchical Profiler for PHP (pecl install xhprof)

*MCG premium app can analyse your application profile data natively on your Mac (released to the Mac App Store at $27)

*Profiling Viewer, available on App Store at $25
Older: MacCallGrind (semi-commercial alternative, free version which is limited to 3MB grind files)

Image: Homepage of MCG
See also: Is there any KCacheGrind alternative for Mac Os X outta there?

A: Apple supply Instruments for monitoring runtime allocation of stuff and finding leaks, Shark for explicit profiling and Guard Malloc (directly built into Xcode) for memory allocation debugging. These all come as part of the developer tools.

A: Both valgrind and kcachegrind are available for Mac OS X.
You can install them using MacPorts:
sudo port install valgrind kcachegrind

A: I ended up using qcachegrind on OSX. It can be installed via brew
brew install qcachegrind

or, to enable graphviz support:
brew install qcachegrind --with-graphviz

What's great about this program is that I successfully loaded a 6.1GB cachegrind file on my MacBook Pro! Pretty slick!

A: valgrind is available for the mac. If you are building a cocoa app, you can use the tools that come with XCode such as leaks, they are very good.


text:
Q: Faster Python alternatives to WebDriver's find_elements_by_(class_name | css_selector)? For a typical eBay search results page such as this, I'm using WebDriver in Python to extract the price of each result thus:
PRICEELEMENT = 'ul:nth-child(3) > li:nth-child(1) > span:nth-child(1)'
prices =  driver.find_elements_by_css_selector(PRICEELEMENT)]

Constructing prices sometimes takes up to 10 seconds, with an average of 4 or 5. So does:
PRICEELEMENTCLASS = 'bidsold'
prices driver.find_elements_by_class_name(PRICEELEMENTCLASS)

Of course, then I have to go and get .text for each price, which adds even more time.
What are better options here using BeautifulSoup or lxml (or other)?


text:
Q: I am getting a UWP App Compiler Error ILT0038 in x64 Release mode but not Debug mode I have a UWP app that compiles and runs fine in debug mode, but when I compile in x64 release mode, I get the following error:

Severity  Code    Description Project File    Line    Source
Error       ILT0038: 'Microsoft.CodeAnalysis.Formatting.AutoFormattingOptions' is a value type with a default constructor. Value types with default constructors are not currently supported. Consider using an explicit initialization function instead.

I do have Microsoft.CodeAnalysis analyzers installed, but they should have no effect while compiling, right?
Has anyone seen this before or have any idea how to resolve? Any help appreciated.

EDIT - updated, I originally noted x86, but actually x64.

A: I am unsure if this is the best answer, but it did 'fix the problem'.  I added ExcludeAssets to project folder as such:
<PackageReference Include="Microsoft.CodeAnalysis">
      <Version>4.4.0</Version>
      <ExcludeAssets>All</ExcludeAssets>
</PackageReference>

I am unsure of the long-term consequences to this, but it also removed several warnings and allowed me to remove additional references that were being demanded by Microsoft.CodeAnalysis, but only in Release mode.


text:
Q: Using the universal selector (*) in a click event to select only that clicked and not parents I'm developing a DOM inspector bookmarklet. I need the user to be able to click on anything in the page, therefore I have to use the universal selector (*) to attach a click event to. However, when an item is clicked via this selector, I get returned the selected item plus every parent. How do I get just the selected item so I can work with that?
$(document).on("click", "*", function() {
    alert(this);
});

A: $(document).on("click", "*", function(event) {
    event.stopPropagation();
});

jQuery Documentation:  http://api.jquery.com/event.stopPropagation/

A:
"I need the user to be able to click on anything in the page, therefore I have to use the universal selector (*) to attach a click event to."

You don't need the universal selector, in fact you don't need that second parameter to specify a selector at all. When the document receives the click event it can determine which element the event started with using the event.target property:
$(document).on("click", function(event) {
    // event.target is the element you care about
    alert(event.target.id);  // or whatever
    ...

});


text:
Q: How to Bypass Ngrok Browser Warning I'm pretty new in Ngrok. I always got warning about abuse. It's just annoying, that I wanted to test measure of my site but the endpoint it's get into the browser warning.
How to send an [ngrok-skip-browser-warning] request header to bypass this warning?

A:
Set and send an [ngrok-skip-browser-warning] request header with any
value

This is what you have to do to bypass the browser warning: You have to include the request header ngrok-skip-browser-warning with any value in the request header.
The exact syntax of what is to be included depends on the type of the api call you're making.
For instance for a fetch request in javascript, this is what has to be included to bypass the warning:
fetch(url, {
      method: "get",
      headers: new Headers({
        "ngrok-skip-browser-warning": "69420",
      }),
    })
      .then((response) => response.json())
      .then((data) => console.log(data))
      .catch((err) => console.log(err));

A: TL;DR; For those still curious about how to automate a workaround, I've created a docker image which runs a simple proxy locally and adds ngrok-skip-browser-warning header to each request.
Run
$ docker run -d --rm -p 8080:80 -e NGROK_HOST=https://your-ngrok-domain.ngrok.io igops/ngrok-skip-browser-warning:latest

Then, use http://localhost:8080 as your API webroot. Read more

The main idea under the hood is running Nginx with the following config:
events {
    worker_connections 1024;
}
http {
    server {
        listen 80;

        location / {
            proxy_set_header X-Forwarded-For $proxy_protocol_addr;
            proxy_set_header X-Forwarded-Proto $scheme;
            proxy_set_header Host your-domain.ngrok.io;

            # this line does the actual trick
            proxy_set_header ngrok-skip-browser-warning 1;

            # using "proxy_pass $variable" allows to avoid start-up crash if host is not reachable
            # https://stackoverflow.com/a/32846603/20085654
            resolver 8.8.8.8 valid=30s;
            set $upstream https://your-domain.ngrok.io;
            proxy_pass $upstream;
        }
    }
}

Feel free to use.


text:
Q: Difference between missile and bombs in Wings of Prey During tutorial it was stated that missile 'are heavy and their flight is anything but straight line' and 'require direct hit'. However I found he missiles much more precise then bombs.
I assume that I have misunderstood the statement about missiles - but then when should I use bombs?

A: Bombs operate in an large area of effect way while missles fly towards where you are targeting with a smaller aoe attack though a bit of guess work or spamming is required if you want to hit something far. IMO i prefer the rockets over the bombs since its faster to kill enemies.


text:
Q: Find source of sleeping mysql connections We have a very large number of PHP scripts running on our server that do a variety of things. Lately I've noticed that when looking in PHPMyAdmin there are a large number of connections to our MySQL server just lingering.
Normally we're very good about closing connections when the querying in the script is done but obviously somewhere along the way we missed one or more.
I know which database the connection is being made to but that only narrows it down so much.
TL/DR I'm looking for an easy way to identify which script is maintaining a connection when it shouldn't be.

A: Look in the full processlist for the Host column of theses connections :
show full processlist\G

Take the host and port of one of theses connections.
Then SSH to the source server, and search which process has make this connection :
netstat -ntp |grep :theport

At the end of the line you will have the pid/process name of your script.


text:
Q: Get Children Terms from an Array of ID's? I am using this code to post a list of all children terms for my taxonomy called 'location'
<?php
$termID = 10;
$taxonomyName = "location";
$termchildren = get_term_children( $termID, $taxonomyName );

echo '
';
foreach ($termchildren as $child) {
$term = get_term_by( 'id', $child, $taxonomyName );
echo '
name, $taxonomyName ) . '">' . $term->name . '
';
}
echo '
';
?>

Currently the code is using term id 10 and getting the children for that and displaying in a list.
However I want to add multiple term id's and display a list of all the children of the id's I add.
My id's are 4,6,8,10,14,18,22
Looking for some help to figure out how to do this?
Cheers

A: I figured out the answer to my own question. using get_terms will get all the terms retured, so there is no need to specify individual id's of my terms.
My code is
<?php
$args = array( 'taxonomy' => 'location' );

$terms = get_terms('location', $args);

$count = count($terms); $i=0;
if ($count > 0) {
    $cape_list = '
';

    foreach ($terms as $term) {
        $i++;
        $term_list .= '
slug . '" title="' . sprintf(__('View all post filed under %s', 'my_localization_domain'), $term->name) . '">' . $term->name . '
';
        if ($count != $i) $term_list .= ' · '; else $term_list .= '
';
    }
    echo '
';
    echo $term_list;
    echo '
';

}
?>


text:
Q: Event Receivers Where can we implementthe event receiver?
I am new to the SharePoint so please guide me! Thanks!

A: Event handlers are something "similar" to the triggers databases. If we imagine a list as a table, we can imagine that an event is a trigger.
Then you can create a business rule associated with the creation, modification or deletion of an item.
You can also create events associated with other actions such as creating a site. A good way to generalize is to associate with content types, rather than list.
They are created with Visual Studio C #.


text:
Q: How to enable code folding for markdown in TextMate? I would like to enable code folding for markdown in textmate.
Specifically, I would like any headings (text preceded by one or more '#' characters) to be the line that would toggle blocks between it and the next heading and/or horizontal rule. Example:
# Level 1 Heading - I'd like the block below to fold

The text I'd like to fold away

## Level 2 Heading

More text...

BBEdit seems to do this just fine for markdown. TextMate supports code folding just fine for languages that denote blocks with paired (and identically indented) curly braces.
I know TextMate offers two variables you can set in the language grammar file, but I'd need more talent with regular expressions than I possess to figure it out. Following is what currently resides in the markdown language grammar for the code folding settings:
foldingStartMarker = '(?x)
    (<(?i:head|body|table|thead|tbody|tfoot|tr|div|select|fieldset|style|script|ul|ol|form|dl)\b.*?>
    |<!--(?!.*-->)
    |\{\s*($|\?>\s*$|//|/\*(.*\*/\s*$|(?!.*?\*/)))
    )';
foldingStopMarker = '(?x)
    (</(?i:head|body|table|thead|tbody|tfoot|tr|div|select|fieldset|style|script|ul|ol|form|dl)>
    |^\s*-->
    |(^|\s)\}
    )';

Any help greatly appreciated!

A: TextMate flat-out can't do this.
TextMate's language parser reads files on a line-by-line basis. Which means that in order for code to be folded there needs to be a start marker AND an end marker. Like <ul> and </ul>. In this case, since the end of a section is not marked by anything other than the start of the next section, the line-by-line parser cannot go back and say an empty line should mark the end of a code folded block.
Does that make sense?

A: On the Macromates blog, they explain how to enable basic code folding for markdown. This lets you fold at the header level so long as you're using the "#" symbol for your headers.

For Markdown's folding settings (scoped to text.html.markdown), let's look at some more sneaky patterns:

  {  foldingIndentedBlockStart  = '^#+\s+';
     foldingIndentedBlockIgnore = '^(?!#+\s+)';
  }

We let a heading be a start marker and then we effectively ignore everything which is not a heading, causing those lines to be included in the foldable block despite not being indented. This allows you to collapse entire sections of a Markdown document down to just the headings.


text:
Q: Ejecutar otra función después de un determinado tiempo c# Tengo un script en python que hace un request SOAP pero toma el valor de la tabla en la db, pero ahora quisiera hacer que cuando termine con ese cliente pase al siguiente es algo que no se como, a este lo mando llamar desde un aplicación en Windows Forms
Con un boton mando llamar al tick del timer
private void timer2_Tick(object sender, EventArgs e)
{
    Funciones f = new Funciones();
    ThreadStart delegado = new ThreadStart(f.DatosEnvio);
    //f.DatosEnvio();
    Thread hilo = new Thread(delegado);
    hilo.Start();
}

Luego en una clase tengo la consulta
public void DatosEnvio()
{
   string cnn = ConfigurationManager.ConnectionStrings["prueba"].ConnectionString;
   using (SqlConnection conexion = new SqlConnection(cnn))
   {
      conexion.Open();

      int rest = 0;
      //string consulta = "SELECT Nombre,Empresa FROM SamsaraVehiculos WHERE Disponible=1 AND Folio > 0 AND Empresa <> ''";
      string consulta = "SELECT Nombre,Empresa FROM SamsaraVehiculos";
      using (SqlCommand cmd = new SqlCommand(consulta, conexion))
      {
         cmd.CommandType = CommandType.Text;
         SqlDataReader rd = cmd.ExecuteReader();

         try
         {
            while (rd.Read())
            {
               string Vehiculo = rd["Nombre"].ToString();
               //string Empresa = rd["Empresa"].ToString();

               //if (Empresa == "Transplace")
               //{
               string path = Application.StartupPath + "\\InterfazAssistCargo\\";

               string[] Valores = { Vehiculo, path };
               Thread hilo = new Thread(new ParameterizedThreadStart(Automatico));
               hilo.Start(Valores);
               Thread.Sleep(2000);

               // Lo que quisiera hacer es que cuando termine
               // con todos estos valores pase a esta siguiente
               // introducir el código aquí

               string path2 = Application.StartupPath + "\\InterfazQS3\\";

               string[] Valores2 = { Vehiculo, path };
               Thread hilo2 = new Thread(new ParameterizedThreadStart(Automatico));
               hilo.Start(Valores2);
               Thread.Sleep(2000);

               //}
            }
         }
         catch (Exception ex)
         {
             rest = 99;
         }
      }
   }
}

Es algo que aun no se, estoy usando hilos pero igual es algo tardado, agradezco cualquier idea

A: Bien, si comprendo lo que quieres realizar es llamar a la función Automatico pasandole Valores y cuando termine, llamarla otra vez pasandole Valores2 y todo eso dentro del loop.
Esto lo podrías trabajar con Tasks:
private async void timer2_Tick(object sender, EventArgs e)
{
   Funciones f = new Funciones();
   await f.DatosEnvioAsync();
}

Dentro de la clase Funciones:
public async Task DatosEnvioAsync()
{
   string cnn = ConfigurationManager.ConnectionStrings["prueba"].ConnectionString;
   using (SqlConnection conexion = new SqlConnection(cnn))
   {
       conexion.Open();

       int rest = 0;
       string consulta = "SELECT Nombre,Empresa FROM SamsaraVehiculos";
       using (SqlCommand cmd = new SqlCommand(consulta, conexion))
       {
          cmd.CommandType = CommandType.Text;
          SqlDataReader rd = cmd.ExecuteReader();

          try
          {
             List<Task> tasks = new List<Task>();
             while (rd.Read())
             {
                string Vehiculo = rd["Nombre"].ToString();
                string path = Application.StartupPath + "\\InterfazAssistCargo\\";
                string path2 = Application.StartupPath + "\\InterfazQS3\\";

                string[] Valores = { Vehiculo, path };
                string[] Valores2 = { Vehiculo, path };

                // La función 'IntroducirValores' usará la variable 'Valores' y cuando termine,
                // se ejecutará 'IntroducirValores' pero usando Valores2
                var task = IntroducirValoresTask(Valores)
                                .ContinueWith(t => IntroducirValoresTask(Valores2));

                // Inicializa la task y la agrega a la lista
                // El thread principal ( que está leyendo rd.Read()) continuará y no esperará a que
                // se termine de ejecutar IntroducirValores(Valores) e IntroducirValores(Valores2)
                task.Start();
                tasks.Add(task);

             }

             // Aquí se espera a que todo termine
             await Task.WhenAll(tasks);
          }
          catch (Exception ex)
          {
              rest = 99;
          }
       }

    }
 }

// Función que crea una Task que llama a la función Automatico
private Task IntroducirValoresTask(string[] pValores)
{
   string[] valores = pValores;

   return new Task(async () =>
   {
       Automatico(valores);
       await Task.Delay(2000);
   });
}

private void Automatico(string[] valores)
{
   // Aquí realizas lo que gustes.
   // Asegurate que sea thread safe ya que varios threads podrían mandar a llamar a esta función.
}

De esta manera en cada iteración inicializas una task (que ejecutará la primera función y esperará dos segundos y después ejecutará la segunda función), pero que no bloqueará al thread principal por lo que se seguirá iterando y por lo tanto inicializando tasks. Una vez que salga del ciclo while, esperará a que todas las tasks hayan finalizado para salir de DatosEnvioAsync.
Si quisieras esperar por cada iteración podrías eliminar tasks y esperar a que se termine las task:
...
while(rd.Read())
{
  ...
  // task.Start();
  // tasks.Add(task);

  await task;
}
...


text:
Q: Why does Dynamo DB throw an error when updating a map key with the same value? I am trying to run a simple update query, but got an error when I tried to update the key of a map to the same value. Is there a technical reason this would be disallowed? or some kind of best-practice that I am violating by trying to do this?
Error:
ValidationException: Invalid UpdateExpression: Two document paths overlap with each other;
must remove or rewrite one of these paths; path one: [questions, What is xx?], path two: [questions, What is xx?]

Query object:
{
  TableName: 'notesTable',
  Key: { topic: 'My tooic' },
  ExpressionAttributeNames: { '#qq': 'What is xx?', '#updq': 'What is xx?' },
  ExpressionAttributeValues: { ':updans': 'new answer' },
  UpdateExpression: 'REMOVE questions.#qq SET questions.#updq = :updans'
}

A: Multiple ways to deal with scenario when same key needs to be updated. Instead of removing and updating the same key, we can simply SET the key , which replaced the value anyhow.
So, simple way is to send different updateExpression each time.
const qq = "What is xx2?";
const updq = "What is xx?";
let expressionAttributeNames;
let UpdateExpression;

if (qq === updq) {
  expressionAttributeNames = { "#updq": "What is xx?" };
  UpdateExpression = "SET questions.#updq = :updans";
} else {
  expressionAttributeNames = { "#qq": "What is xx1?", "#updq": "What is xx?" };
  UpdateExpression = "REMOVE questions.#qq SET questions.#updq = :updans";
}

docClient.update(
  {
    TableName: "test",
    Key: {
      id: "My tooic",
    },
    ExpressionAttributeNames: expressionAttributeNames,
    ExpressionAttributeValues: { ":updans": "new answer1" },
    UpdateExpression: UpdateExpression,
  },
  function (error, result) {
    console.log("error", error, "result", result);
  }
);


text:
Q: Ошибка при попытке запуска примера XDevApi MySql Connector С++ Всем добрый день! Пытаюсь запустить пример подключения к базе данных с сайта
Но мне выдается непонятное исключение и ничего не работает. Подскажите как с этим бороться?
Привожу пример кода и ниже приложу скрин ошибки:
#include <stdlib.h>
#include <iostream>

#include <mysqlx/xdevapi.h>
using namespace mysqlx;

int main()
{
    setlocale(LC_ALL, "en_US.UTF-8");

    string usr = "root";
    string pwd = "root";

    // Connect to MySQL Server on a network machine
  Session mySession(SessionOption::HOST, "localhost",
        SessionOption::PORT, 33060,
        SessionOption::USER, usr,
        SessionOption::PWD, pwd);

    Schema myDb = mySession.getSchema("crm");

    return 0;
}

Если пройти дальше есть еще одно исключение его скриншот вот


text:
Q: Regarding asp.net routing in webform & Asterisk sign I saw people use asterisk sign at the time of routing in webform. i just do not understand the importance of Asterisk sign like below one
routes.MapPageRoute(
  "View Category",               // Route name
  "Categories/{*CategoryName}",  // Route URL
  "~/CategoryProducts.aspx"      // Web page to handle route
);

what is the meaning of asterisk sign and also tell me what kind of situation i should use asterisk sign like above.
"Categories/{*CategoryName}"

it would be better if anyone come with small sample code of using Asterisk sign just to show the importance & use of asterisk sign in real life apps.

A: It is called catch all route mapping. See the below question as well :
Infinite URL Parameters for ASP.NET MVC Route

A: Since this was the first resource Google returned me for variable number of parameters I added below example from MSDN so future readers would find the solution here.

The following example shows a route pattern that matches an unknown number of segments.

query/{queryname}/{*queryvalues}

Case 1
URL :
/query/select/bikes/onsale
Resolved Parameter Values:

*

*queryname = "select"

*queryvalues = "bikes/onsale"

Case 2
URL :
/query/select/bikes
Resolved Parameter Values:

*

*queryname = "select"

*queryvalues = "bikes"

Case 3
URL :
/query/select
Resolved Parameter Values:

*

*queryname = "select"

*queryvalues = Empty string

Reference:
MSDN: Handling a Variable Number of Segments in a URL Pattern


text:
Q: Sobrecarga de operadores y su localización en el código tengo una duda que es un poco de perogrullo, pero me gustaría confirmar lo que pienso o aclararlo.
Cuando estas definiendo un tipo y realizas una sobrecarga de operadores para dicho tipo algunos son definidos dentro de la clase y otros fuera. Tengo entendido que eso es así porque algunos necesitan acceso a la representación de la clase, o sea, sus atributos miembro o datos miembro, y otros no, asi que los que no necesitan ese acceso, porque no hacen uso directo de esos atributos se definen fuera.
Ejemplo:
class complex{
double real, imaginario;

public:
complex():real{0}, imaginario{0};

//getters&setters

complex& operator+=(complex z){
    real+=z.real, imaginario+=z.imaginario;
    return *this;}
};

complex operator+(complex a, complex b) {return a+=b;}

Entonces, yo puedo situar, por ejemplo, la sobrecarga del operador + en otro archivo de código fuente, ¿no? Y el compilador sabe que me refiero a ese tipo, ¿por el tipo que devuelve? Asume el contexto.
Y, ¿cuando defino el operador +, el += aritmético que utiliza ya es el que he definido anteriormente?¿Importa el orden?¿Si utilizo un operador no sobrecargado, usaría el del tipo double?

A:
Tengo entendido que eso es así porque algunos necesitan acceso a la representación de la clase, o sea, sus atributos miembro o datos miembro, y otros no, asi que los que no necesitan ese acceso, porque no hacen uso directo de esos atributos se definen fuera.

Eso no es del todo cierto. La única diferencia, en términos generales, la diferencia más significativa entre un operador declarado como miembro y otro declarado como función libre es que el operador miembro tiene a su disposición el puntero this. Este puntero, por supuesto, le permite acceder a todas las variables del objeto sin restricciones... pero también es cierto que una función libre puede ser friend de la clase... lo que asigna el mismo nivel de acceso.
Como norma general es deseable que los operadores no sean funciones miembro, por varias razones:

*

*Reduce el acoplamiento: Si usas operadores binarios (dos parámetros) cuyos parámetros son de diferente tipo, estarás añadiendo dependencias a nivel de la clase que probablemente no necesites (esto complica el diseño del código y hace que tarde más en compilar). Mantener los operadores como funciones libres te permite cargarlos únicamente allí donde se usan de forma efectiva.

*Mejora el encapsulamiento: Los operadores raramente necesitan acceder sí o sí a las variables privadas para poder ser implementados. Obligar a que su implementación haga uso de la interfaz pública del objeto es una garantía de seguridad.

*Operadores más versátiles: Los operadores binarios con parámetros de diferente tipo necesitan implementarse dos veces para tener un comportamiento simétrico.
class A;
class B;

A operator+(A const& a, B const& b);
B operator+(B const& b, A const& a);

Implementar estos operadores como funciones libres te permite tener los dos operadores juntos, mientras que si son miembros tendrás que poner cada operador en una clase diferente.
class B;

class A
{
public:
  A operator+(B const& b);
};

class B
{
public:
  B operator+(A const& a);
};

Si además resulta que uno de los tipos es nativo (int por ejemplo) una de las implementaciones deberá ser obligatoriamente una función libre
// Asimetrico
class A
{
  A operator+(int); // A a; a = a + 5
};

A operator+(int, A const&); // A a; a = 5 + a

// Simetrico
class A;

A operator+(A const&, int);
A operator+(int, A const&);

Entonces, yo puedo situar, por ejemplo, la sobrecarga del operador + en otro archivo de código fuente, ¿no? Y el compilador sabe que me refiero a ese tipo, ¿por el tipo que devuelve? Asume el contexto

El compilador no asume absolutamente nada, ya que asumir implica que no tienes toda la información disponible... y cuando al compilador le falta información finaliza el montaje con un error y se queda tan pancho.
Si implementas una sobrecarga como una función libre podrás poner la declaración y la implementación donde te de la gana. Eso sí, para poder usar esa sobrecarga tendrás que incluir la declaración antes de su uso. Si se te olvida ese pequeño detalle el compilador puede actuar de dos maneras posibles:

*

*No encuentra una sobrecarga adecuada y finaliza con error

*Descubre que puede hacer una conversión implícita y aplica un operador que no esperas.

Lo deseable es que siempre sucediese lo primero, ya que el segundo caso genera errores en tiempo de ejecución bastante desconcertantes.
Un pequeño ejemplo ilustrativo:
struct datos
{
};

void func1()
{
  datos d1;
  std::cout << d1; // <<--- ERROR: No se encuentra la sobrecarga
}

std::ostream & operator<<(std::ostream & os, datos d)
{
  os << "operador de insercion\n";
  return os;
}

void func2()
{
  datos d1;
  std::cout << d1; // <<--- OK
}

Como puedes ver, el compilador no asume absolutamente nada... bueno sí, asume que tu debes resolver todas sus dudas.

Y, ¿cuando defino el operador +, el += aritmético que utiliza ya es el que he definido anteriormente?

Son operadores diferentes que deben declararse por separado. Si declaras el operador + y no declaras el operador += no podrás usar el operador +=, como es obvio.

¿Importa el orden?

En absoluto. Son funciones totalmente independientes y libres.

¿Si utilizo un operador no sobrecargado, usaría el del tipo double?

Los operadores se comportan como funciones. De hecho puedes invocar al operador como si de una función se tratase:
complex a, b;
complex c = operator+(a,b);

Así que el operador no usa un tipo, sino que intenta llamar a la función que actúa como un operador. A la hora de decidir a qué función llama aplica las mismas que en el caso de funciones normales. Es decir:

*

*Busca un operador directo (no requiere conversiones)

*Busca un operador indirecto (requiere conversiones implícitas)

*Error

A: Cuando empiezas a realizar un código y poco a poco lo vas agrandando, llegará un momento en el que tendrás que conocer el concepto de "separación" para que no esté todo dentro de main.cpp.
Ese momento ha llegado para ti.

Entonces, yo puedo situar, por ejemplo, la sobrecarga del operador + en otro archivo de código fuente, ¿no? Y el compilador sabe que me refiero a ese tipo, ¿por el tipo que devuelve? Asume el contexto.

De hecho, lo normal es que sitúes la implementación o definición del código (qué hace) en un archivo y la declaración del código (cómo tienes que llamarlo o declararlo) en otro archivo.
La nomenclatura general es que los archivos .h contengan la declaración  y los archivos .cpp tengan la definición.
Una vez tengas esto claro, vamos al siguiente punto: ¿El compilador sabe qué tipo es al que te refieres? De hecho, ese es su trabajo, saberlo.
Cuando tú haces esto:
a + b

Debes haber definido anteriormente qué es a y qué es b. Una vez sepa el compilador qué son ambas, buscará en tu código fuente, en el suyo y en todas partes donde le hayas dicho que puede buscar, si existe la función operator +( *tipo_a*, *tipo_b* ). Si no la encuentra, te pegará un petardazo. De hecho, no puedes dedirle a ese operator que devuelva ningún tipo sobrecargado, sólo devolverá un único tipo.
Para llamarlo desde un archivo, primero, en el .h, deberás introducir la declaración pelada y mondada, sin llaves, utilizando un ; al final:
class complex
{
  private:
  double re, im;

  public:
  complex():re{0}, im{0};

  complex& operator+=(complex z);
};

Después, en tu .cpp, pondrás tu código para que, cuando se compile, sepa qué tiene que hacer:
complex& complex::operator+=(complex z)
{
  this->re += z.re;
  this->im += z.im;
  return *this;
}

Y prepara tu compilador para que compile el archivo .cpp, claro está.
Me he permitido el lujo de limpiarte y ponerte más legible el código. Recuérdalo para futuras referencias, tu código lo leemos otros.
El puntero this-> te ayudará con IDEs modernos para saltarte la detección de métodos. De hecho, este código no funcionará porque re e im son privados, y necesitarás un accesor a estos elementos.
Creo que esta pequeña introducción a la separación puede serte de ayuda.


text:
Q: use FontAwesome icon in svg without external files I need to create an SVG (with PHP and/or Javascript) where some of the SVG Elements are icons from FontAwesome, but: without external dependencies (like: importing an css file, etc.).
I found this stackoverflow question, which is a similar topic, but does not fit my problem, because there are external dependencies, like adding FontAwesome (CSS Files) at the webpage where the svg is shown.
The difference is, that I need an All-in-one SVG, where all the necessary FontAwesome definition are part of the svg, because the user should be able to download the generated SVG to continue working on it with an svg viewer or editor.
Is there a way, to put the definition of (for example) one "Font Awesome" icon into one svg?
I found this (probably) list of svg informations. So it looks like, the icon paths are available as SVG code. So how can I use this in an svg?

//Update: I found the following example, but I don't know, how to include the FontAwesome definition and how to access an icon :-(
<?xml version="1.0" standalone="yes"?>
<svg width="100%" height="100%" version="1.1"
 xmlns = 'http://www.w3.org/2000/svg'>
  <defs>
    <font id="Font2" horiz-adv-x="1000">
      <font-face font-family="Super Sans" font-weight="normal" font-style="italic"
          units-per-em="1000" cap-height="600" x-height="400"
          ascent="700" descent="300"
          alphabetic="0" mathematical="350" ideographic="400" hanging="500">
        <font-face-src>
          <font-face-name name="Super Sans Italic"/>
        </font-face-src>
      </font-face>
      <missing-glyph><path d="M0,0h200v200h-200z"/></missing-glyph>
      <glyph unicode="!" horiz-adv-x="300"><!-- Outline of exclam. pt. glyph --></glyph>
      <glyph unicode="@"><!-- Outline of @ glyph --></glyph>
      <!-- more glyphs -->
    </font>
  </defs>
</svg>

A: Your example is an SVG Font and it doesn't work on IE or Firefox. You need to encode FontAwesome as a data URI and embed as a @font-face if you want it to work everywhere:
<svg width="500" height="200" version="1.1" xmlns = 'http://www.w3.org/2000/svg' xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 500 200">
    <defs>
      <style type="text/css">
        @font-face {
          font-family: 'FontAwesome';
          src: url(data:font/opentype;base64,[...]) format('opentype');
        }
      </style>
    </defs>
    <rect x="0" y="0" height="100" width="500" fill="#eee" />
    <text x="20" y="50" font-family="FontAwesome" font-weight="normal" font-size="32">
      &#xf007
    </text>
  </svg>

Replace the [...] with the base64 encoded version of the font. You can upload a .ttf or an .otf file to a base64 service or the command line openssl base64 -in <infile> -out <outfile>.
If you want to subset the FontAwesome's library you can head to icomoon http://icomoon.io/app/#library and add the FontAwesome library. Then select the icons you need, download the zip, then upload the ttf to a base64 encoding service such as this http://www.opinionatedgeek.com/dotnet/tools/base64encode/ and paste the resulting string to your src: font-face declaration.


text:
Q: Google sheets: get a list of the sheet names giving a GS file url I have been trying for many hours to get a script that returns the list of names of the sheets of a GS document after giving it the url of said document or the cell that contains said url in the document I am working on.
I previously found this proposal that I modified slightly but it doesn't work for me:
Create list of all sheet names in Google Apps Scripts

function getSheetNamesFromOtherGSfile(otherGSfileURL) {
  var spreadSheetAURL = otherGSfileURL;
  var sheetNameArray = [];

  var spreadSheetsInA = SpreadsheetApp.openByUrl(spreadSheetAURL).getSheets();

  sheetNameArray = spreadSheetsInA.map(function(sheet) {
    return [sheet.getName()];
  });

  var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  var range = sheet.getRange(1, 1, sheetNameArray.length, 1);
  range.setValues(sheetNameArray);
}

Thanks.

A: According to the documentation you cannot call Spreadsheet.openById() within a custom function in a cell.
The approach I recommend is to create a container-bound function, see docs here. With these function, which can be called from a custom menu, there are none of those limitations.


text:
Q: Cmake generated VS project looks untidy I have converted an open source project (Sundials) with cmake to a Visual Studio project. Compilation seems to work, which I am very glad about.
However the generated project looks a little messy in solution explorer of VS. All the header files of the project are sorted into the external dependencies folder and there is no header files folder. I can't really see what belongs to the project and what is external to it.
Is this intended behavior of cmake, or can I do something about it? May I safely move files from external folder to a header folder manually?


text:
Q: Crear elementos del DOM con jQuery Necesito crear elementos de una manera que no sea muy confusa y fácil de darle mantenimiento para hacer un cambio.
Actualmente lo hago con este código con .append() y .html():
$('.Selector').append(
  '
'+
    '
'+
      '
Elemento Menu 1
'
    '
'+
  '
'
)

Pero es demasiado confuso y difícil de darle mantenimiento, o hacer cambios de etiquetas.
¿Hay alguna otra manera de hacerlo mas fácil?

A: Investigando después de un rato encontré esta manera simple, para crear un elemento solo basta con poner la etiqueta  y separar con una coma los atributos:
$('', {
  'html' : 'Un nuevo enlace',
  'class' : 'new',
  'href' : 'foo.html'
});

Ejemplo de código similar a lo que queria lograr:

$("
", {
    'class': 'dropdown'
}).append(
    $('
', {
        'class': 'dropdown-menu',
        'aria-labelledby': 'dropdownMenu1'
    }).append(
      $('
')
        .append(
          $('',{
            'href':'#',
            'text':'Hola Mundo'
          })
        )
    )
).hide().appendTo('#otraDiv').fadeIn('slow');

Referencia

A: esta es una solucion que hice hace poco, si! lo sé es un poco tediosa pero con Brackets y emmet se facilita todo...
        var icon = "./assets/icons/headset.png";

    var cadena = '';

cadena += "
";
cadena += "
";
cadena += "                    ";
cadena += "
";
cadena += "
";
cadena += "
1 - YecidMoreno (Escritor)
";
cadena += "
";
cadena += "                        ";
cadena += "                        ";
cadena += "                        ";
cadena += "                        ";
cadena += "                        ";
cadena += "                         Visitar Perfil";
cadena += "
";
cadena += "                     07/07/2017";
cadena += "
";
cadena += "
  ";

                div1 = $(cadena);
                $("#cd-timeline").prepend(div1);


text:
Q: How to find the dimension of a Quotient Space
Let $c_0 = \{(x_n) : x_n \in\mathbb R ,\ x_n \to 0 \}$ and $M=\{(x_n)\in c_0:x_1 + x_2 + \cdots +x_{10} =0\}$. I need to find the dimension of  quotient  space
  $c_{0}/M$.

Now I know that $c_{0}/M=\{M + (x_n ): (x_n)\in c_{0}\}$. But after that I am stuck.
I don't understand how should I use the property of Vector space $M$ to get the dimension
Can anyone please help me here ?
Thank you

A: The dimension is $1$: note that any $(x_n) \in c_0$ can be moved into $M$ by only changing $x_{10}$.
This observation can be translated so that the sequences ($x_i=0$ for $i\ne 10$) form a full representative set for the cosets.


text:
Q: Is there a performance difference between i++ and ++i in JavaScript? I read Is there a performance difference between i++ and ++i in C?:

Is there a performance difference between i++ and ++i if the resulting value is not used?

What's the answer for JavaScript?
For example, which of the following is better?

*

*
for (var i = 0; i < max; i++) {
  // code
}

*
for (var i = 0; i < max; ++i) {
  // code
}

A: Here is an article about this topic: http://jsperf.com/i-vs-i/2
++i seems to be slightly faster (I tested it on firefox) and one reason, according to the article, is:

with i++, before you can increment i under the hood a new copy of i must be created. Using ++i you don't need that extra copy. i++ will return the current value before incrementing i. ++i returns the incremented version i.

A: No. There is no difference in execution time. The difference in the two code snippets is when i gets incremented.
for(i = 0; i < max; i++)
{
    console.log(i);
}

This first example will yield the results: 0,1,2,3,...,max-1
for(i = 0; i < max; ++i)
{
    console.log(i);
}

This second example will yield the results: 1,2,3,...,max
i++ increments the value after the operation.
++i increments the value before the operation.
There is no performance difference other than the one less iteration it will make on ++i because the increment is done before the first operation


text:
Q: Apache Jersey exception:java.lang.NoSuchMethodError: org.glassfish.hk2.utilities.AbstractActiveDescriptor I am learning Java rest webservices using Jersey Framework.
 Created one sample project in eclipse but not able to deploy it in tomcat. Below libraries added in eclipse project. Can anyone please help me out here
cglib-2.2.jar
hk2-api-2.3.0-b06.jar
hk2-locator-2.1.63.jar
hk2-utils-2.5.0-b04.jar
javassist.jar
javax-inject.jar
javax.annotation-api-1.2.jar
javax.ws.rs-api-2.0.jar
javax.ws.rs.jar
jersey-bean-validation-2.17.jar
jersey-client.jar
jersey-common.jar
jersey-container-servlet-core.jar
jersey-container-servlet.jar
jersey-guava-2.7.jar
jersey-media-jaxb.jar
jersey-server.jar
validation-api-1.0.0.GA.jar

Getting below error while running project in Apache server inside eclipse.

       SEVERE: StandardWrapper.Throwable
    java.lang.NoSuchMethodError: org.glassfish.hk2.utilities.AbstractActiveDescriptor.<init>(Ljava/util/Set;Ljava/lang/Class;Ljava/lang/String;L
    java/util/Set;Lorg/glassfish/hk2/api/DescriptorType;Lorg/glassfish/hk2/api/DescriptorVisibility;ILjava/lang/Boolean;Ljava/lang/String;Ljava/
    util/Map;)V
        at org.jvnet.hk2.internal.ConstantActiveDescriptor.<init>(ConstantActiveDescriptor.java:113)
        at org.jvnet.hk2.internal.Utilities.getLocatorDescriptor(Utilities.java:951)
        at org.jvnet.hk2.external.generator.ServiceLocatorGeneratorImpl.initialize(ServiceLocatorGeneratorImpl.java:71)
        at org.jvnet.hk2.external.generator.ServiceLocatorGeneratorImpl.create(ServiceLocatorGeneratorImpl.java:96)
        at org.glassfish.hk2.internal.ServiceLocatorFactoryImpl.internalCreate(ServiceLocatorFactoryImpl.java:270)
        at org.glassfish.hk2.internal.ServiceLocatorFactoryImpl.create(ServiceLocatorFactoryImpl.java:230)
        at org.glassfish.jersey.internal.inject.Injections._createLocator(Injections.java:138)
        at org.glassfish.jersey.internal.inject.Injections.createLocator(Injections.java:123)
        at org.glassfish.jersey.server.ApplicationHandler.<init>(ApplicationHandler.java:330)
        at org.glassfish.jersey.servlet.WebComponent.<init>(WebComponent.java:392)
        at org.glassfish.jersey.servlet.ServletContainer.init(ServletContainer.java:177)
        at org.glassfish.jersey.servlet.ServletContainer.init(ServletContainer.java:369)
        at javax.servlet.GenericServlet.init(GenericServlet.java:158)
        at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1284)
        at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1197)
        at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1087)
        at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:5253)
        at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5543)
        at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
        at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1574)
        at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1564)
        at java.util.concurrent.FutureTask.run(Unknown Source)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
        at java.lang.Thread.run(Unknown Source) enter code here

A: If you see your exception
Apache Jersey exception:java.lang.NoSuchMethodError : org.glassfish.hk2.utilities.AbstractActiveDescriptor

as per my experience , This Exception NoSuchMethodError because of Incompatible jar has been added to your Project library.
Use latest jar hk2-api-2.5.0-b04.jar instead of hk2-api-2.3.0-b06.jar . Probably this will solve your problem..


text:
Q: how can i substitute a function to make a query faster? I'm trying to make a query without using a funciton, because it takes too much time for it to give the result. this is the code with the function and the result.
SELECT
LEFT(D2.D2_EMISSAO,6),
F2.F2_VEND1,
SUM((D2.D2_TOTAL-dbo.UCOMPRA(D2.D2_COD, D2.D2_EMISSAO)*D2.D2_QUANT)) AS  LUCRO_LIQ
FROM SD2010 D2
INNER JOIN SF2010 F2
    ON D2.D2_DOC = F2.F2_DOC AND D2.D2_SERIE = F2.F2_SERIE AND F2.D_E_L_E_T_= ''
WHERE
D2.D2_EMISSAO >=  '20171201'
AND D2.D2_TES IN ('502','506')
GROUP BY
LEFT(D2.D2_EMISSAO,6),
F2.F2_VEND1
ORDER BY F2.F2_VEND1 DESC

this is the function:
ALTER FUNCTION dbo.UCOMPRA( @CODIGO VARCHAR(25), @DATE VARCHAR(8))
RETURNS float

 BEGIN
 DECLARE @UPRECO float;

    SELECT TOP 1 @UPRECO = ROUND(D1.D1_CUSTO/D1.D1_QUANT,2)
    FROM SD1010 D1
   WHERE D1.D_E_L_E_T_ = ''
       AND D1.D1_TES  IN('015','202','205','206')
           AND D1.D1_COD = @CODIGO
           AND D1.D1_EMISSAO <= @DATE
      ORDER BY D1.D1_EMISSAO DESC ;

RETURN ROUND(@UPRECO,2);
END;
GO

Result of the query with the function

I tried with this:
SELECT  D2.D2_EMISSAO,
D2.D2_DOC,
D2.D2_COD,
D2.D2_QUANT,
D2.D2_PRCVEN,
D2.D2_TOTAL,
ENTRADA.CUSTO,
((D2.D2_TOTAL/D2.D2_QUANT-ENTRADA.CUSTO)*D2.D2_QUANT) AS  LUCRO_LIQ

FROM SD2010 D2
LEFT JOIN SD1010 D1 ON D2.D2_COD=D1.D1_COD
INNER JOIN (SELECT D1.D1_COD AS COD,D1.D1_TOTAL AS D1TOTAL,
D1.D1_TOTAL/D1.D1_QUANT AS CUSTO
        FROM SD1010 D1
        WHERE
        D1.D1_EMISSAO <= '20171201'
        AND D1.D1_TES IN ('015','202','205','206')
        AND D1.D_E_L_E_T_='') ENTRADA
        ON D2.D2_COD = ENTRADA.COD

  WHERE D2.D2_COD = '000712S3B70340'
  AND D1.D1_EMISSAO <= D2.D2_EMISSAO
  AND D2.D2_TES IN ('502','506')
  ORDER BY D2.D2_DOC DESC

Result of the code without You can see that the value from "lucro_liq" is diferent

A: Difference in result is because you are using Order by in function, but in sub-select there is no order by. Also adding order by inside sub-select isn't going to make any sense.
I will prefer inline table valued function over scalar function
DROP FUNCTION dbo.Ucompra

go

CREATE FUNCTION dbo.Ucompra(@CODIGO VARCHAR(25),
                            @DATE   VARCHAR(8))
RETURNS TABLE
    RETURN
      (SELECT TOP 1 UPRECO = Round(D1.D1_CUSTO / D1.D1_QUANT, 2)
       FROM   SD1010 D1
       WHERE  D1.D_E_L_E_T_ = ''
              AND D1.D1_TES IN( '015', '202', '205', '206' )
              AND D1.D1_COD = @CODIGO
              AND D1.D1_EMISSAO <= @DATE
       ORDER  BY D1.D1_EMISSAO DESC)

GO

SELECT LEFT(D2.D2_EMISSAO, 6),
       F2.F2_VEND1,
       Sum(( D2.D2_TOTAL - oa.UPRECO * D2.D2_QUANT )) AS LUCRO_LIQ
FROM   SD2010 D2
       INNER JOIN SF2010 F2
               ON D2.D2_DOC = F2.F2_DOC
                  AND D2.D2_SERIE = F2.F2_SERIE
                  AND F2.D_E_L_E_T_ = ''
       OUTER apply dbo.Ucompra(D2.D2_COD, D2.D2_EMISSAO) oa
WHERE  D2.D2_EMISSAO >= '20171201'
       AND D2.D2_TES IN ( '502', '506' )
GROUP  BY LEFT(D2.D2_EMISSAO, 6),
          F2.F2_VEND1
ORDER  BY F2.F2_VEND1 DESC


text:
Q: How visualize attention LSTM using keras-self-attention package? I'm using (keras-self-attention) to implement attention LSTM in KERAS. How can I visualize the attention part after training the model? This is a time series forecasting case.
from keras.models import Sequential
from keras_self_attention import SeqWeightedAttention
from keras.layers import LSTM, Dense, Flatten

model = Sequential()
model.add(LSTM(activation = 'tanh' ,units = 200, return_sequences = True,
               input_shape = (TrainD[0].shape[1], TrainD[0].shape[2])))
model.add(SeqSelfAttention())
model.add(Flatten())
model.add(Dense(1, activation = 'relu'))

model.compile(optimizer = 'adam', loss = 'mse')

A: One approach is to fetch the outputs of SeqSelfAttention for a given input, and organize them so to display predictions per-channel (see below). For something more advanced, have a look at the iNNvestigate library (usage examples included).
Update: I can also recommend See RNN, a package I wrote.

Explanation:
show_features_1D fetches layer_name (can be a substring) layer outputs and shows predictions per-channel (labeled), with timesteps along x-axis and output values along y-axis.

*

*input_data = single batch of data of shape (1, input_shape)

*prefetched_outputs = already-acquired layer outputs; overrides input_data

*max_timesteps = max # of timesteps to show

*max_col_subplots = max # of subplots along horizontal

*equate_axes = force all x- and y- axes to be equal (recommended for fair comparison)

*show_y_zero = whether to show y=0 as a red line

*channel_axis = layer features dimension (e.g. units for LSTM, which is last)

*scale_width, scale_height = scale displayed image width & height

*dpi = image quality (dots per inches)

Visuals (below) explanation:

*

*First is useful to see the shapes of extracted features, regardless of magnitude - giving information about e.g. frequency contents

*Second is useful to see feature relationships - e.g. relative magnitudes, biases, and frequencies. Below result stands in stark contrast with image above it, as, running print(outs_1) reveals that all magnitudes are very small and don't vary much, so including the y=0 point and equating axes yields a line-like visual, which can be interpreted as self-attention being bias-oriented.

*Third is useful for visualizing features too many to be visualized as above; defining model with batch_shape instead of input_shape removes all ? in printed shapes, and we can see that first output's shape is (10, 60, 240), second's (10, 240, 240). In other words, the first output returns LSTM channel attention, and the second a "timesteps attention". The heatmap result below can be interpreted as showing attention "cooling down" w.r.t. timesteps.

SeqWeightedAttention is a lot easier to visualize, but there isn't much to visualize; you'll need to rid of Flatten above to make it work. The attention's output shapes then become (10, 60) and (10, 240) - for which you can use a simple histogram, plt.hist (just make sure you exclude the batch dimension - i.e. feed (60,) or (240,)).

from keras.layers import Input, Dense, LSTM, Flatten, concatenate
from keras.models import Model
from keras.optimizers import Adam
from keras_self_attention import SeqSelfAttention
import numpy as np

ipt   = Input(shape=(240,4))
x     = LSTM(60, activation='tanh', return_sequences=True)(ipt)
x     = SeqSelfAttention(return_attention=True)(x)
x     = concatenate(x)
x     = Flatten()(x)
out   = Dense(1, activation='sigmoid')(x)
model = Model(ipt,out)
model.compile(Adam(lr=1e-2), loss='binary_crossentropy')

X = np.random.rand(10,240,4) # dummy data
Y = np.random.randint(0,2,(10,1)) # dummy labels
model.train_on_batch(X, Y)

outs = get_layer_outputs(model, 'seq', X[0:1], 1)
outs_1 = outs[0]
outs_2 = outs[1]

show_features_1D(model,'lstm',X[0:1],max_timesteps=100,equate_axes=False,show_y_zero=False)
show_features_1D(model,'lstm',X[0:1],max_timesteps=100,equate_axes=True, show_y_zero=True)
show_features_2D(outs_2[0])  # [0] for 2D since 'outs_2' is 3D

def show_features_1D(model=None, layer_name=None, input_data=None,
                     prefetched_outputs=None, max_timesteps=100,
                     max_col_subplots=10, equate_axes=False,
                     show_y_zero=True, channel_axis=-1,
                     scale_width=1, scale_height=1, dpi=76):
    if prefetched_outputs is None:
        layer_outputs = get_layer_outputs(model, layer_name, input_data, 1)[0]
    else:
        layer_outputs = prefetched_outputs
    n_features    = layer_outputs.shape[channel_axis]

    for _int in range(1, max_col_subplots+1):
      if (n_features/_int).is_integer():
        n_cols = int(n_features/_int)
    n_rows = int(n_features/n_cols)

    fig, axes = plt.subplots(n_rows,n_cols,sharey=equate_axes,dpi=dpi)
    fig.set_size_inches(24*scale_width,16*scale_height)

    subplot_idx = 0
    for row_idx in range(axes.shape[0]):
      for col_idx in range(axes.shape[1]):
        subplot_idx += 1
        feature_output = layer_outputs[:,subplot_idx-1]
        feature_output = feature_output[:max_timesteps]
        ax = axes[row_idx,col_idx]

        if show_y_zero:
            ax.axhline(0,color='red')
        ax.plot(feature_output)

        ax.axis(xmin=0,xmax=len(feature_output))
        ax.axis('off')

        ax.annotate(str(subplot_idx),xy=(0,.99),xycoords='axes fraction',
                    weight='bold',fontsize=14,color='g')
    if equate_axes:
        y_new = []
        for row_axis in axes:
            y_new += [np.max(np.abs([col_axis.get_ylim() for
                                     col_axis in row_axis]))]
        y_new = np.max(y_new)
        for row_axis in axes:
            [col_axis.set_ylim(-y_new,y_new) for col_axis in row_axis]
    plt.show()

def show_features_2D(data, cmap='bwr', norm=None,
                     scale_width=1, scale_height=1):
    if norm is not None:
        vmin, vmax = norm
    else:
        vmin, vmax = None, None  # scale automatically per min-max of 'data'

    plt.imshow(data, cmap=cmap, vmin=vmin, vmax=vmax)
    plt.xlabel('Timesteps', weight='bold', fontsize=14)
    plt.ylabel('Attention features', weight='bold', fontsize=14)
    plt.colorbar(fraction=0.046, pad=0.04)  # works for any size plot

    plt.gcf().set_size_inches(8*scale_width, 8*scale_height)
    plt.show()

def get_layer_outputs(model, layer_name, input_data, learning_phase=1):
    outputs   = [layer.output for layer in model.layers if layer_name in layer.name]
    layers_fn = K.function([model.input, K.learning_phase()], outputs)
    return layers_fn([input_data, learning_phase])

SeqWeightedAttention example per request:
ipt   = Input(batch_shape=(10,240,4))
x     = LSTM(60, activation='tanh', return_sequences=True)(ipt)
x     = SeqWeightedAttention(return_attention=True)(x)
x     = concatenate(x)
out   = Dense(1, activation='sigmoid')(x)
model = Model(ipt,out)
model.compile(Adam(lr=1e-2), loss='binary_crossentropy')

X = np.random.rand(10,240,4) # dummy data
Y = np.random.randint(0,2,(10,1)) # dummy labels
model.train_on_batch(X, Y)

outs = get_layer_outputs(model, 'seq', X, 1)
outs_1 = outs[0][0] # additional index since using batch_shape
outs_2 = outs[1][0]

plt.hist(outs_1, bins=500); plt.show()
plt.hist(outs_2, bins=500); plt.show()


text:
Q: dpkg warning caused by missing steam-libs-i386:i386 Few months ago I accidentally removed two packages: steam-libs-i386:i386 and steam-libs-amd64. Sometimes, when I need to install a new package, I see this warnings after an apt install:
dpkg: warning: files list file for package 'steam-libs-i386:i386' missing; assuming package has no files currently installed
dpkg: warning: files list file for package 'steam-libs-amd64' missing; assuming package has no files currently installed

So far, I have always been able to correctly install the packages, but I would like to remove them before they become an issue of some kind, assuming they will.
After running:
sudo apt-get install --reinstall steam-libs-i386:i386
sudo apt-get install --reinstall steam-libs-amd64

The returned message is
Reinstallation of steam-libs-amd64 is not possible, it cannot be downloaded.

Same goes for steam-libs-i386:i386.
Do I need them? How can I reinstall them? Or, if not necessary, how to get rid of the warning?

A: Seems like you didn't remove them via the package manger, but just deleted some files. To fix, purge the packages:
sudo  apt remove --purge steam-libs-amd64 steam-libs-i386:i386


text:
Q: PHP PDO transaction rollBack doesn't work How is everything
Please can anyone help me in this
I'm trying to use PHP PDO transaction and there is a problem that I face and I can't deal with it.
rollBack function doesn't work when It catch an exception
Here is the connection code
$host   = 'localhost';
$user   = 'root';
$pass   = '';
$error  = '';
$dbname = 'tameras_finance';
// Set DSN
$dsn = 'mysql:host=' . $host . '; dbname=' . $dbname;
// Set options
$options = array(
    PDO::ATTR_PERSISTENT => true,
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
);
// Create a new PDO instanace
try {
    $dbh = new PDO($dsn, $user, $pass);
    $dbh->exec("set names utf8");
}
//Catch any errors
catch (PDOException $e) {
    echo $error = $e->getMessage();
}

and here the code
try{
    $dbh->beginTransaction();
    $dbh->query('SET @newDebit = (SELECT max(`debtor_id`) + 1 AS maxDebit FROM `vocher`)');
    for($x = 0; $x < count($debits); $x++){
        $dbh->query('UPDATE `vocher` SET `debtor_id` = @newDebit, `status_id` = "4" WHERE `id` = '.$debits[$x]);
    }

    for($x = 0; $x < count($others); $x++){
        $columns = '`acc_id`, `value`, `date`, `desc`, `reject`, `vo_type_id`, `user`, `debtor_id`';
        $vals  = "'".$accs[$x]."','".$values[$x]."','".$dates[$x]."','".$descs[$x]."','1','1','".$user."', @newDebit";
        if($others[$x] == 'e'){
            $columns .= ', `cheque_no`, `available_date`, `issue_date`, `bank_id`';
            $vals  .= ", '".$sns[$x]."', '".$availdates[$x]."', '".$issueDates[$x]."', '".$banks[$x]."'";
        }
        $dbh->query("INSERT INTO creditor (".$columns.") VALUES (".$vals.")");
        if($lists[$x] != 'e'){
            $lastId = $dbh->lastInsertId();
            $q  = 'INSERT INTO `creditor_cc` (`creditor`, `cc`) VALUES ';
            for($y = 0; $y < count($lists[$x]); $y++){
                $dif = count($lists[$x]) - $y;
                $q .= '(';
                $q .= '"' . $lastId . '",';
                $q .= '"'.$lists[$x][$y].'"';
                $q .= ')';
                if($dif > 1){
                    $q .= ',';
                }
            }
            $dbh->query($q);
        }
    }
    $dbh->commit();
} catch(PDOException $e) {
    echo $error = $e->getMessage();
    $dbh->rollBack();
}

This code doesn't rollback
Please note that:

*

*$sns, $others, $accs, $values, $dates, $descs, $availdates,
$issueDates and $banks are arrays with the same size

*Also $lists is a two dimension array with the same size

please help me with this why this code doesn't rollBack

A: Transactions are not supported on MySQL's default table type MyISAM. You need to make sure you're using InnoDB tables.
Also check to make sure the exception that's being thrown is PDOException or it'll fall through the try/catch and not hit your rollback.

A: I would say it shoud be done this way:
$pdo = new \PDO(/*...*/);

$pdo->beginTransaction();

try {
//...
} catch(\Exception $e) {
    $pdo->rollBack();
    throw $e;
}

$pdo->commit();


text:
Q: Application icon stuck DELPHI XE5 The first time i update the icon in "project > Options > Application > Load Icon..." the icon as changed as it should, now every time  i change the application icon, my app keep compiling with The old icon even if i click in "project > Options > Application > Default" or try to load a new one
The icon get stuck somewhere, but where ?
There's a way to force icon with resource file or unstuck the old icon ?
I download a icon which is a multi size ico file ( one ico file, 8 sizes )
i already try :
Reboot my computer.
Change the .exe name.
Copy the .exe to another computer.
same error.

A: Had the same experience recently as well.
The "default" button does not seem to work as soon as you have selected an icon.
I got rid of the icon via the following steps:

*

*Close your project.

*In your project folder an icon will be created with the name "Projectname"_ICON.ICO.

*Rename or remove this Icon.

*Reopen your project,

*Get to Project->Options,

*An error message will be raised at every configuration in which you have used the icon, but by pressing default the message will not reappear,

*Now the project is forced to use the default icon again.
Probably there is a more sophisticated manner, but I have not found it elsewhere.

A: For Windows platform, the icon (and version info) is stored in resource file (.res). And by default Delphi project includes in exe all the .res files it founds in project directory (see {$R *.res} directive in your .dpr file).
So check all the .res files you have in your project directory to find out which of contains the default icon. You can use any resource editor for that.
Then, just delete that file, but please keep backup, cause .res file may contain other important information.

A: This was what helped me:
You can just run the following command to clear the icon cache:
ie4uinit.exe -ClearIconCache
For Windows 10, use:
ie4uinit.exe -show


text:
Q: Android TableLayout hexgrid best approach I'm making a game where the user needs to be able to see a grid of hexagons in several colors (they are just different images) and needs to be able to click some of them (the grey ones). I've made the hex-grid using a TableLayout now:
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
>
<TableRow
    android:layout_marginTop="0dp"
    android:layout_marginBottom="@dimen/margin_cell_vertical"
    >
   <ImageView android:src="@drawable/hex_green_border"
       android:layout_column="1"
       android:layout_marginLeft="@dimen/margin_cell_horizontal"
       android:layout_marginRight="@dimen/margin_cell_horizontal"
   />
</TableRow>
<TableRow
    android:layout_marginTop="@dimen/margin_cell_vertical"
    android:layout_marginBottom="0dp"
    >
   <ImageView android:src="@drawable/hex_grey"
       android:layout_column="0"
       android:layout_marginLeft="0dp"
       android:layout_marginRight="@dimen/margin_cell_horizontal"
       />
   <ImageView android:src="@drawable/hex_red_border"
       android:layout_column="2"
       android:layout_marginLeft="@dimen/margin_cell_horizontal"
       android:layout_marginRight="0dp"
       />
</TableRow>

</TableLayout>

(The margin_cell_horizontal and margin_cell_vertical are both negative constants, that specify the exact looks of the grid. Also note the 0dp margins at the top and bottom row and at the most left and right cell.)
This results in

When I do not set the margins to 0dp at the edge, the outeredges of the hexagons at the edge won't be visible.
In practice, the grid will be 15 cells wide and consist of 120 cells in total, but it may vary in the future.
Is the TableLayout the right approach here and is it reasonable to (recreate and) redraw the whole table dynamically based on the state of the game on every update? I've tried to do it with a GridView, where the onClickListeners are easy to handle and it is easy to do updates using an adapter, but I didn't succeed in creating the layout of the grid.
Another small question (I haven't really looked up how to do this yet): When implementing onclicklisteners for the cells, would every cell need its own id and listener? It feels like an overkill to me, but maybe it's necessary.

A: The best way is probably to use neither of the available layouts, but create your own one... a HexLayout... all you have to do is subclass ViewGroup and override the onLayout() method. This post might be of interest... http://arpitonline.com/blog/2012/07/01/creating-custom-layouts-for-android/
From the article ...
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
     int itemWidth = (r-l)/getChildCount();
     for(int i=0; i< this.getChildCount(); i++){
         View v = getChildAt(i);
     v.layout(itemWidth*i, t, (i+1)*itemWidth, b);
     }
}

So in onLayout() you iterate over the children and place them accordingly.


text:
Q: Programmatically checking a ion-radio from TypeScript I have a pretty simple question but I can't find any answer. I have this code :
<ion-list radio-group [(ngModel)]="profile_activities" name="activities">
    <ion-item>
        <ion-label>Option 1</ion-label>
        <ion-radio  (ionSelect)='selectedActivity($event);' value="0"></ion-radio>
    </ion-item>

    <ion-item>
        <ion-label>Option 2</ion-label>
        <ion-radio (ionSelect)='selectedActivity($event);' value="1"></ion-radio>
    </ion-item>

    <ion-item>
        <ion-label>Option 3</ion-label>
        <ion-radio (ionSelect)='selectedActivity($event);' value="2"></ion-radio>
    </ion-item>
</ion-list>

... and I would just like to pre-check a value from typescript based on an info I get from my database. How can I check a ion-radio from Typescript?
Thanks!

A: Ok, managed to find the answer by myself. In TypeScript, I just need to enter the default value of the radio to be checked like that :
this.profile_activities = "1";

... for example, in the ionViewWillEnter() function and the radio with value="1" is checked !


text:
Q: Virtualmin/Apache and redirects I am running Virtualmin and added a website to the system.
However, I have a problem getting it to run probably.
If I go to website.com then it redirects me to default website.com. However, if I go to www.website.com I am going to the website correctly.
This is my .conf file for the website, but I would expect there must be a configuration elsewhere in Apache that causes this redirect. I have no problems on any other of the virtual servers.
<VirtualHost *:80>
SuexecUserGroup #1020 #1018
ServerName website.com
ServerAlias www.website.com
ServerAlias webmail.website.com
ServerAlias admin.website.com
DocumentRoot /home/website/public_html
ErrorLog /var/log/virtualmin/website.com_error_log
CustomLog /var/log/virtualmin/website.com_access_log combined
ScriptAlias /cgi-bin/ /home/website/cgi-bin/
DirectoryIndex index.html index.htm index.php index.php4 index.php5
<Directory /home/website/public_html>
Options -Indexes +IncludesNOEXEC +SymLinksIfOwnerMatch
allow from all
AllowOverride All Options=ExecCGI,Includes,IncludesNOEXEC,Indexes,MultiViews,SymLinksIfOwnerMatch
Require all granted
AddType application/x-httpd-php7.0 .php7.0
AddType application/x-httpd-php .php
</Directory>
<Directory /home/website/cgi-bin>
allow from all
AllowOverride All Options=ExecCGI,Includes,IncludesNOEXEC,Indexes,MultiViews,SymLinksIfOwnerMatch
Require all granted
</Directory>
RewriteEngine on
RewriteCond %{HTTP_HOST} =webmail.website.com
RewriteRule ^(.*) https://website.com:20000/ [R]
RewriteCond %{HTTP_HOST} =admin.website.com
RewriteRule ^(.*) https://website.com:10000/ [R]
</VirtualHost>


text:
Q: Issues with struct I am trying to call a library function with signature
void GPIO_Init(GPIO_InitTypeDef* GPIO_InitStruct)

where GPIO_InitTypeDef is a typedef struct.
I have tried doing the following:
GPIO_InitTypeDef NE1 = {
    7, GPIO_Mode_AF, GPIO_Speed_25MHz, GPIO_OType_PP, GPIO_PuPd_UP
};
GPIO_Init(NE1);

but I get a compiler error

error: incompatible type for argument 1 of 'GPIO_Init' expected
  'struct GPIO_InitTypeDef *' but argument is of type 'GPIO_InitTypeDef'

I have also tried using the struct keyword:
struct GPIO_InitTypeDef NE1 = {
    7, GPIO_Mode_AF, GPIO_Speed_25MHz, GPIO_OType_PP, GPIO_PuPd_UP
};
GPIO_Init(NE1);

but them I get the compiler error

error: storage size of 'NE1' isn't known

What am I doing wrong, and what is the proper way to call GPIO_Init?

A: You need to use:
GPIO_Init (&NE1); // <- Note the '&' indicating pointer-to

That function expects a pointer to a GPIO_InitStruct structure, as indicated with:
void GPIO_Init (GPIO_InitTypeDef * GPIO_InitStruct)
//                               ^
//                            pointer

But your NE1 variable is an actual structure, so you have to use & to get the pointer to it, so you can pass that.
Because you're trying to pass the structure instead of a pointer to a structure, that's what's causing your incompatible type error.


text:
Q: How to use Javascript to pull api, run calculations on pull data, and post results to webpage? I am attempting to inject code into a webpage. Here is the situation:
api url: https://blockchain.info/q/hashrate
calculation: ((hashrate * 1249)/(27518 * 1000000)
then post calculation result to page.
Here is the javascript I have created so far:
$(document).ready(function () {
    $.ajax({
        url: 'https://blockchain.info/q/hashrate',
        type: "GET",
        dataType: "jsonp",
        success: function (data) {
            console.log(data);
            var hashrate = (data);
            var miner_cost = ((hashrate * 1249)/(27518 * 1000000)
            $.html(miner_cost);
        }
    });
});

I have already created this successfully in python:
import requests
import json

url = 'https://blockchain.info/q/hashrate'

BTC_Hashrate = requests.get(url).json()

BTC_Minercost_S15_28T = ((BTC_Hashrate *1249)/(28*39*2016*12.5*1000))

print BTC_Minercost_S15_28T

Any help would be greatly appreciated. Forgive me Javascript gods for I have sinned... I am a python user.
Many Thanks!

A: You don't really need jQuery:
fetch('https://blockchain.info/q/hashrate')
    .then(res => res.json())
    .then(hashRate => {
        const minerCost = (hashRate * 1249) / (27518 * 1000000)
        document.body.innerHTML = minerCost
    })

Here's a fiddle: https://jsfiddle.net/jz4n2ydm/

A: You may have some issue with jQuery. This one is working for me. I have changed the datatype to json.
$(document).ready(function () {
$.ajax({
    url: 'https://blockchain.info/q/hashrate',
    type: "GET",
    dataType: "json",
    success: function (data) {
        console.log(data);
        var hashrate = (data);
        var miner_cost = (hashrate * 1249)/(27518 * 1000000);
        alert(miner_cost);
    }
});  });

A: You cannot alter the response of an API through JavaScript. (Think of what would happen if anyone could just write a script and change any data that is accessible through the web.)
In order to achieve your goal, you would have to configure the server of that API such that it can receive data sent to it via HTTP (i.e., it must not only handle a GET request to /q/hashrate, but also a POST request, possibly to some other route), and change its internal state accordingly. It can then return the updated data in subsequent GET requests.
But since you seem to have no control over the server, there is really nothing you can do to change the data.


text:
Q: NSManagedObject setValue problem (Core Data) I wish to edit an existing record in core data. At the moment, I have this code, but it creates a new record (and inserts the correct data into the correct column):
NSManagedObjectContext *context = [[NSApp delegate] managedObjectContext];
NSManagedObject *instrument  = nil;

instrument = [NSEntityDescription insertNewObjectForEntityForName: @"Instrument"
                  inManagedObjectContext: context];

[instrument setValue:[NSNumber numberWithInt:quantityInStockInstruments]
    forKey: @"quantity"];

The result will look like this:
Instrument | Value | Quantity

Violin     | £25   | 9

           |       | 8 <<< This is the new record that is created, instead of setting the
                           quantity of violin from '9' to '8'

I want the program to edit the quantity column of the currently highlighted row, (which in this case is the 'violin' row. How would I do this?

A: As refulgentis said, the clue is in the name of the selector. You're adding a new object.
A better way to do it, rather than using the table, is by using the selectedObjects of your NSArrayController. As an example (this is long winded for clarity and I've written it off the top of my head):
// Get the selected objects from the NSArrayController.
// There may be more than one object selected, so this needs to be accounted for.
NSArray *selectedObjectsArray = [yourArrayController selectedObjects];

// Get the first object in the array, this is the one that will have it's values changed.
id firstSelectedObject = [selectedObjectsArray objectAtIndex:0];

// Change a value in a KVC compliant way
[firstSelectedObject setValue:newValue forKey:@"keyValueToChange"];

Edited to add after the comment
Have you got an outlet to the array controller and connected it correctly in Interface Builder?
Anyway, the code works for me. Here's an example project showing it working.

A: Note the selector name: "insert New Object:inContext".
As amrox says, it depends on how your model (i.e. Core Data) and your controller are connected. It's hard for me to say without knowing more about your code, especially since I'm usually more on the iPhone side of things (which doesn't have bindings), but basically you need to be saying [[yourDataArray objectAtIndex:[table selectedRow]] setValue:@"whatever" forKey:@"whatever"]


text:
Q: Why does dataflow use additional disks? When I see the details of my dataflow compute engine instance, I can see two categories of disks being used - (1) Boot disk and local disks, and (2) Additional disks.
I can see that the size that I specify using the diskSizeGb option determines the size of a single disk under the category 'Boot disk and local disks'. My not-so-heavy job is using 8 additional disks of 40GB each.
What are additional disks used for and is it possible to limit their size/number?

A: Dataflow will create for your job Compute Engine VM instances, also known as workers.
To process the input data and store temporary data, each worker may require up to 15 additional Persistent Disks.
The default size of each persistent disk is 250 GB in batch mode and 400 GB in streaming mode. 40GB is very far from the default value
In this case, the Dataflow service will span more disks for your worker. If you want to keep a 1:1 ratio between workers and disks, please increase the 'diskSizeGb' field.

A: The existing answer explains how many disks, and information about the disks - but it does not answer the main question: Why so many disks per worker?
WHY does Dataflow need several disks per worker?
The way in which Dataflow does load balancing for streaming jobs is that a range of keys is allocated to each disk. Persistent state about each key is stored in these disks.
A worker can be overloaded if the ranges that are allocated to its persistent disks have a very high volume. To load-balance, Dataflow can move a range from one worker to another by transferring a persistent disk to a different worker.
So this is why Dataflow uses multiple disks per worker: Because this allows it to do load balancing and autoscaling by moving the disks from worker to worker.


text:
Q: Cannot access before initialization using Node JS and Chrome I have three js files as below
index.js
function getNumberToDisplay(){
    document.getElementById("currentDay").innerHTML = getNumber();
}

checkDay.js
const randomDate = require("./randomDate");
module.exports = {};
function getNumber(){
    return randomDate.getSmallNumber();
}
module.exports.getNumber = getNumber;

randomDate.js
module.exports = {};
function getSmallNumber(){
    return 3;
}
module.exports.getSmallNumber = getSmallNumber;

I also have a html page which has a button which calls the getNumberToDisplay function. All 3 scripts are included in the html page by using the  tags. When I press the button to call getNumberToDisplay I get the error Uncaught ReferenceError: Cannot access 'randomDate' before initialization
What is it that I am missing in order to be able to get the button to execute the function? The tests of the functions return the expected results in Jest, but the button doesn't work when opening the html page in Chrome.


text:
Q: How do I get rid of the marks at the top of bars in DiscretePlot? I for some data I have
Show[{
  DiscretePlot[A, {z, 0, 12},
   PlotRange -> {All, {0, 0.5}},
   Filling -> Axis,
   PlotStyle -> Black,
   ExtentSize -> 0.9],
  DiscretePlot[B {z, 0, 12},
   PlotRange -> {All, {0, 0.5}},
   Filling -> None,
   PlotStyle -> Gray,
   ExtentSize -> 0.9]
  }]

with gives figures that look like

How do I get rid of the black horizontal lines only, leaving everything else as it is.