text:
Q: Nested UICollectionView returning the same values for each section - Swift I have a UICollectionView nested inside of a UITableViewCell. The collectionview inside of each tableviewcell section should return different data according to the section. Here is my code:
ViewController.swift
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UISearchBarDelegate {

  var categoryKeys: [String]?

  let network = MediaNetworking()

  @IBOutlet weak var tableView: UITableView!

  override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.

// fetch data
    network.fetchMedia()

    tableView.delegate = self
    tableView.dataSource = self

    print("hello world")
  }

  func numberOfSections(in tableView: UITableView) -> Int {

    self.categoryKeys = network.categoryKeys

    return self.categoryKeys!.count
  }

  func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 1
  }

  func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! SectionTableViewCell

    cell.theArray = network.sharedArray
    cell.accessArray = network.accessArray

    cell.backgroundColor = .purple

    return cell
  }

  func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {

    self.categoryKeys = network.categoryKeys

    return self.categoryKeys?[section]

  }

  func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return 300
  }

}

SectionTableViewCell.swift
class SectionTableViewCell: UITableViewCell, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {

  var categoryKeys: [String]?
  var theArray: [String: [Entity]]?
  var accessArray: [Entity]?

  @IBOutlet weak var collectionView: UICollectionView!

  override func awakeFromNib() {
    super.awakeFromNib()
    // Initialization code

    collectionView.delegate = self
    collectionView.dataSource = self

  }

  override func setSelected(_ selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)

    // Configure the view for the selected state
  }

  func numberOfSections(in collectionView: UICollectionView) -> Int {

    return 1
  }

  func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

    return accessArray!.count
  }

  func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! MediaCollectionViewCell

    cell.artistLabel.text = accessArray![indexPath.row].name

    return cell

  }

  func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
    if kind == UICollectionView.elementKindSectionHeader {
      let sectionHeader = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "SectionHeaderView", for: indexPath) as! SectionHeaderView

      if indexPath.section < categoryKeys!.count {

        let category = categoryKeys![indexPath.section]
        sectionHeader.categoryLabel.text = category
      }
      return sectionHeader
    }

    return UICollectionReusableView()
  }

  func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

    return CGSize(width: 400, height: 300)
  }

}

Right now all the collectionview cells are returning the same values. Any ideas on what I might be missing?..

A: Did you try to call collectionView.reloadData() after changing the data arrays?
cell.theArray = network.sharedArray
cell.accessArray = network.accessArray
cell. collectionView.reloadData()


text:
Q: Add object as value to to a parent object inside of an array My goal is to map through my  results array and 6 components.
The first three components will render the results of location1 and the last three components will render the results of location2.
However, I am having a bit of difficulty trying to figure out how to structure the data inside of my results array.
Here is what I have and it's incorrect:
const results = [
    (location1: {
      result: { name: "Rome, Italy", price: 100, distance: 1299, match: 96 },
      result: { name: "Beijing, China", price: 200, distance: 3000, match: 93 },
      result: { name: "California, USA", price: 250, distance: 420, match: 75 },
    }),
    (location2: {
      result: { name: "Rome, NY", price: 100, distance: 1299, match: 96 },
      result: { name: "Spain", price: 200, distance: 3000, match: 93 },
      result: { name: "California, USA", price: 250, distance: 420, match: 75 },
    }),
  ];

A: There are a few ways you could restructure your data, but I would try the following.
const results = {
    location1: [
      { name: "Rome, Italy", price: 100, distance: 1299, match: 96 },
      { name: "Beijing, China", price: 200, distance: 3000, match: 93 },
      { name: "California, USA", price: 250, distance: 420, match: 75 },
    ],
    location2: [
      { name: "Rome, NY", price: 100, distance: 1299, match: 96 },
      { name: "Spain", price: 200, distance: 3000, match: 93 },
      { name: "California, USA", price: 250, distance: 420, match: 75 },
    ],
  };

A: location1 and location2 should be also an array (an object can't have more fields with the same name).
const results = [
    {location1: [
      {result: { name: "Rome, Italy", price: 100, distance: 1299, match: 96 }},
      {result: { name: "Beijing, China", price: 200, distance: 3000, match: 93 }},
      {result: { name: "California, USA", price: 250, distance: 420, match: 75 }},
    ]},
    {location2: [
      {result: { name: "Rome, NY", price: 100, distance: 1299, match: 96 }},
      {result: { name: "Spain", price: 200, distance: 3000, match: 93 }},
      {result: { name: "California, USA", price: 250, distance: 420, match: 75 }},
    ]},
  ];

A: You should make it a valid array of objects.

const locations = [
    {
      results: [
        { name: "Rome, Italy", price: 100, distance: 1299, match: 96 },
        { name: "Beijing, China", price: 200, distance: 3000, match: 93 },
        { name: "California, USA", price: 250, distance: 420, match: 75 },
      ]
    },
    {
      results: [
        { name: "Rome, NY", price: 100, distance: 1299, match: 96 },
        { name: "Spain", price: 200, distance: 3000, match: 93 },
        { name: "California, USA", price: 250, distance: 420, match: 75 },
      ]
    },
  ];

console.log(locations[0].results[0].name);

That way you can easily loop trough it.

const locations = [
    {
      results: [
        { name: "Rome, Italy", price: 100, distance: 1299, match: 96 },
        { name: "Beijing, China", price: 200, distance: 3000, match: 93 },
        { name: "California, USA", price: 250, distance: 420, match: 75 },
      ]
    },
    {
      results: [
        { name: "Rome, NY", price: 100, distance: 1299, match: 96 },
        { name: "Spain", price: 200, distance: 3000, match: 93 },
        { name: "California, USA", price: 250, distance: 420, match: 75 },
      ]
    },
  ];

let html = '';
locations.forEach(location => {
  html += '

';
  location.results.forEach(result => {
    html += `<li>${result.name}</li>`
  })
  html += '

'
});

let locations_element = document.getElementById('locations');
locations_element.innerHTML = html;
.location {
  border: 1px solid red;
}

forEach and template ${literals} are used.

redpajama_set_name: RedPajamaStackExchange


text:
Q: SubSonic 2.2 + SharedDbConnectionScope I have seen posts (first, second) on StackOverflow that say that SubSonic 2.2's SharedDbConnectionScope doesn't work with TransactionScope.
Can we still rely on SharedDbConnectionScope in other contexts? I want to know if I should be concerned when using code such as the following (where ProviderName is not the default provider for item's type):
using (var scope = new SharedDbConnectionScope(DataService.Providers[ProviderName]))
{
    item.Save();
}

In my system, it looks like it works fine, but I think I may have had it try to save to the wrong database on rare occasions (may be unrelated).
Thanks!


text:
Q: How to create a facebook feed for wordpress? I'm new to worpdress and completed a basic development in wordpress course, our final project it's to bring a facebook page data like states and pics, to be displayed in a word press site, to be specific to be listed in a page, I've been researching using facebook developers and found out, tha  when querying this url, https://www.facebook.com/feeds/page.php?id=[pageID]&format=json y got the JSON with all de data, also I've tested in http://jsonviewer.net/ and looks good, no I'm stuck in how to make that JSON to be displayed on a page at my site.
Please need some help with this,

A: You can use a Shortcode for that [fb-page id="ID-NUM"], use the function wp_remote_get() to pull the feed and then convert the returned JSON into array using PHP's json_decode().
add_shortcode( 'fb-page', 'shortcode_so_25919996' );

function shortcode_so_25919996( $atts )
{
    if( empty( $atts['id'] ) )
        return 'Please, provide an ID';

    # Request URL content.
    $url = 'https://www.facebook.com/feeds/page.php?id=' . $atts['id'] . '&format=json';
    $response = wp_remote_get( $url );

    if ( is_wp_error( $response ) )
        return 'Error fetching the feed.';

    # Response OK. Decode the response body.
    $json_to_array = json_decode( wp_remote_retrieve_body( $response ), true );

    # Print the array as code block. Use a loop to build the output as HTML string.
    return '
' . print_r( $json_to_array, true ) . '
';
}

Or you can call this same function as:
<?php echo shortcode_so_25919996( array( 'id' => 'ID-NUM' ) ); ?>


text:
Q: How to compress or normalise or level audio recordings? I have an phone recording, where one person sound much MUCH louder than the other because it was recorded only on one side of the phone. The original audio I was given was in mp3 format, where only the left side of the earphone has sound (though it does 2 channels). I have saved the mp3 file in mono wav file using pydub.
I have read on audio compression vs. normalisation (peak and loudness) vs. sound volume levelling. However, I am still confused which way I should go for.
Actually I have tried the normalisation implemented in pydub described here, also tried ffmpeg loudnorm as well as dynaudnorm (I didn't add any parameters though). But the resulting audio sounds no much difference to the original one. Should I manually segment out speaker turns and then apply normalisation? But then again, should I apply norm or levelling or compression? I am guessing it's between norm and levelling. I also don't want to change the characteristics of the audio since the aim here is to preprocess the audio for downstream machine learning modelling..
Does anyone have any suggestions please? Thanks.

A: Normalization applies gain (or negative gain) to raise (or lower) the average level.  Compression reduces loud moments and amplifies quiet moments to reduce the differences in level, and seems more appropriate for your case.
To use it in Audacity (an open source sound app available for all three major operating systems), load the audio, then select the entire audio track, or just portions if you want to limit the effect to a particular passage. Choose Effects, then Compressor.

Once the Compressor dialog box appears, press F1 for an explanation of what the options available will do, or read it here. I would definitely recommend turning on Compress based on Peaks, but other settings will vary based on the characteristics of the original recording.
You can experiment with different values in that dialog box to get the least worst final result; you'll never get a perfect recording, but improvement is nearly certain.
If, as often happens, a telephone audio recording has noise or other distracting audio in a particular frequency, filtering down that frequency may also be helpful.


text:
Q: Rules for adding/upgrading RAM I need to upgrade RAM on my machine.
I've done this before, but it was ages ago. There were rules or guidelines then as to what could and couldn't be done (some rather obvious) :

*

*All RAM to be of the same type

*When adding two sticks of RAM to parallel (twinned?) slots, both need to be of the same capacity and preferably of the same manufacturer.

etc..
There are lots more types of RAMs and processors now, and I'm not sure what I need to be aware of when I buy new RAM for my machine.
So my question is, what are the rules you know of that I need to follow while upgrading RAM ? Are there dependencies between processor and RAM type, or motherboard and RAM ? Do you know of any downsides to having 4GB RAM on a machine running a 32-bit OS, besides it not recognising the full capacity ? What are the chances I'll be able to use this RAM when I upgrade to a newer CPU/motherboard in future ?

A: When you look at the Crucial references on my answer to your other question about memory,
you'll get an idea on some of the questions here.
To understand the double channel Twinned performance, have a look at my answer to,
Should I be worrying about Single Channel and Double Channel for my RAM?.
For matching requirements of good dual channel performance,
manufacturers usually pack matched devices into a 'kit'.
That is a bit more than the same manufacturer.
Regarding upgrade to another system and moving the new RAM sticks there.
I guess, it is important to note that you are using SODIMM on a Dell Inspiron laptop.
You will be limited to motherboards that take SODIMM modules (at the least).

A: I've found the easiest way to be sure you're buying the right thing, is to simply use automated tools to do it for you, such as here.
I've never heard of any issue using 4GB of RAM on a 32 bit system (and i've never had any issues), at least for windows.
As for compatibility with a motherboard you may buy in the future, it'd probably be best to pick your motherboard at the time to fit the ram, although if you are buying a new motherboard in the future, it's probably for a new processor too and ram is fairly cheap if worst comes to worst.
Somebody else should be able to give more specific answers (look at "nik"s), but i hope this pushes you in the right direction. Good luck.


text:
Q: If-Statement hadn't been obeserved in my Unity project I have a script attached to a couple of prefabs. Every few seconds a random prefab is spawned. This is a part of my attached script:
private void OnCollisionEnter2D(Collision2D collision)
{
    if (collision.transform.CompareTag("ground"))
    {
        if (transform.gameObject.name == "FallingKeule(Clone)")
        {
            Destroy(transform.gameObject);
        }
        if (transform.gameObject.name == "FallingHeart(Clone)")
        {
            Destroy(transform.gameObject);
        }
        if (transform.gameObject.name == "FallingCup(Clone)")
        {
            Destroy(transform.gameObject);
        }
        else
        {
            print("You lost a life!");
            Player.GetComponent<Colliding>().LostLife();
            Destroy(transform.gameObject);
        }
    }
}

If a GameObject is spawned by random and it hit's the ground, and it is a "FallingKeule(Clone)" --> "(Clone)" because the prefab is cloned by it's initalisation the Code from
if (transform.gameObject.name == "FallingKeule(Clone)")

isn't be done! The else code is been done:
else
{
    print("You lost a life!");
    Player.GetComponent<Colliding>().LostLife();
    Destroy(transform.gameObject);
}

A: You should use else if statement:
if (transform.gameObject.name == "FallingKeule(Clone)")
{
    Destroy(transform.gameObject);
}
else if (transform.gameObject.name == "FallingHeart(Clone)")
{
    Destroy(transform.gameObject);
}
else if (transform.gameObject.name == "FallingCup(Clone)")
{
    Destroy(transform.gameObject);
}
else
{
    print("You lost a life!");
    Player.GetComponent<Colliding>().Destroy(transform.gameObject);
}

or much better:
var gameObjectName = transform.gameObject.name;
if(gameObjectName == "FallingKeule(Clone)" || gameObjectName == "FallingHeart(Clone)" || gameObjectName == "FallingCup(Clone)")
{
    Destroy(transform.gameObject);
}
else
{
    print("You lost a life!");
    Player.GetComponent<Colliding>().Destroy(transform.gameObject);
}

or even:
string[] dObjects = new string[] { "FallingKeule(Clone)", "FallingHeart(Clone)", "FallingCup(Clone)" };

private void OnCollisionEnter2D(Collision2D collision)
{
    if (collision.transform.CompareTag("ground"))
    {
        if(dObjects.Contains(transform.gameObject.name))
        {
            Destroy(transform.gameObject);
        }
        else
        {
            print("You lost a life!");
            Player.GetComponent<Colliding>().Destroy(transform.gameObject);
        }
    }
}


text:
Q: How can I create a list of values for a field in Kibana? I am using Kibana to view data from Elasticsearch index. There is a field only has a few values. When I do search the field, how can I make the search bar as a select rather than a free text input? I know that there is a filter list like below image:

but it doesn't work for the case that top 5 values in 500 records have one value. How can I show all values in the history as a list for a field?

A: I think your are looking for "controls" visualization.

Go to visualization > controls
Then choose option list, your index and your field.
The result will be a dropdown with values like if you did a select distinct on your field within the whole kibana range.
Add it to a dashboard to have a filtering interface human usable dashboard.

Update:
Maybe a simple filter on the discover page can answer to your question.


text:
Q: Can I enable DEX verbose logging? I moved my Android IntelliJ IDEA project from one location to another. For some reason, IDEA lost all the modules and I had to re-import them.
Now when I compile, I get this DEX error:
Error:Android Dex: [MyApp] Unable to execute DX
Error:Android Dex: [MyApp] com.android.dex.DexException: Multiple dex files define Lcom/google/common/base/FinalizableReference;
Error:Android Dex: [MyApp] at com.android.dx.merge.DexMerger.readSortableTypes(DexMerger.java:594)
Error:Android Dex: [MyApp] at com.android.dx.merge.DexMerger.getSortedTypes(DexMerger.java:552)
Error:Android Dex: [MyApp] at com.android.dx.merge.DexMerger.mergeClassDefs(DexMerger.java:533)
Error:Android Dex: [MyApp] at com.android.dx.merge.DexMerger.mergeDexes(DexMerger.java:170)
Error:Android Dex: [MyApp] at com.android.dx.merge.DexMerger.merge(DexMerger.java:188)
Error:Android Dex: [MyApp] at com.android.dx.command.dexer.Main.mergeLibraryDexBuffers(Main.java:439)
Error:Android Dex: [MyApp] at com.android.dx.command.dexer.Main.runMonoDex(Main.java:287)
Error:Android Dex: [MyApp] at com.android.dx.command.dexer.Main.run(Main.java:230)
Error:Android Dex: [MyApp] at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
Error:Android Dex: [MyApp] at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
Error:Android Dex: [MyApp] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
Error:Android Dex: [MyApp] at java.lang.reflect.Method.invoke(Method.java:597)
Error:Android Dex: [MyApp] at org.jetbrains.android.compiler.tools.AndroidDxRunner.runDex(AndroidDxRunner.java:161)
Error:Android Dex: [MyApp] at org.jetbrains.android.compiler.tools.AndroidDxRunner.main(AndroidDxRunner.java:294)
Error:Android Dex: [MyApp] at com.intellij.rt.execution.CommandLineWrapper.main(CommandLineWrapper.java:121)

I can't figure out what the cause is, all the usual suspects of multiple JARs seems to be ok.
Is there a way to turn on verbose logging to get a better understanding on which libs are in conflict?

A: I don't know how to get better error description from DEX, but here are 2 suggestions to troubleshoot:

*

*If using Android Studio, just search for the offending class FinalizableReference (include non-project classes in the search).
(Use Command+N for find class or double tap Shift for "search everywhere".
For eclipse: Ctrl+Shift+T? others can confirm.

*Using the command line: jar tf mylib.jar | grep FinalizableReference will search mylib for the class. You can then use some shell for loop over the jar files (usually in libs dir).
Also grep -r FinalizableReference libs/*\.jar will scan all the jars (assuming you have them in libs) and notify the ones that have a match (the duplicates).


text:
Q: Yoast setup for Robots is weird,  How do we remove the noindex part? On one of our sites, we have the Yoast plugin turned on.
However, on it's content tag is the weirdest thing. We see 3 values: index,follow, noindex
How do we exactly remove the noindex value? we tried looking at header.php as well as functions.php to no avail.
We also looked at the Yoast plugin, but there was no point there as to which we can edit the content

A: Can override in functions.php globally or only for specific post type
add_filter( 'wpseo_robots', 'yoast_seo_robots_remove_single' );
/**
 * Set certain posts to noindex nofollow
 */
function yoast_seo_robots_remove_single( $robots ) {
    $postType = get_post_type();
    if ( is_single() && ($postType === "custom_event_name")) {
     return 'noindex,nofollow';
    }
    else {
     return 'index,follow';//to everything else, originally $robots value
    }
}


text:
Q: can't read property 'renderSubCategory' of undefined Below is my component
import React,{Component} from 'react'
import {connect} from 'react-redux'

import {megaNavContent} from '../actions'

class MegaNavComponent extends Component{
  constructor(props){
    super(props);
    this.renderSubCategory = this.renderSubCategory.bind(this);
    this.megaNavRender = this.megaNavRender.bind(this);
  }
  componentDidMount(){
    this.props.megaNavContent("Row");
  }
  megaNavRender(){
    var list = [];
    const MegaNavData = this.props.content.Row4;
    if(MegaNavData != null && MegaNavData.categorie){
      const Categories = MegaNavData.categorie
      Categories.forEach(function(category){
        list.push(

            {category.name}

                    {this.renderSubCategory(category)}

        )
      })
    }
  return list;
  }
  renderSubCategory(){
    var cat = []
    console.log("looking for subcategory")
    const subCategory = category.data;
    subCategory.forEach(function(sub){
     cat.push(
{sub}
);
    })
    return cat;
  }
  render(){
    const MegaNavData = this.props.content.Row;
    return(

          {this.megaNavRender()}

        );
      }
    }

function mapStateToProps(state){
  return{
    content : state.content
  }
}

export default connect(mapStateToProps,{megaNavContent})(MegaNavComponent);

From the above code, I want to call renderSubCategory and get some HTML/JSX to display, but getting the error.
Also, Is there a better way to write above megaNavRender() function to loop through JSON. i.e forEach(HTML/JSX(forEach(HTML/JSX(forEach(HTML/JSX)))))
instead of having many callbacks called for every forEach loop.

A: Javascript functions declared with function keyword has their own this context, so this inside Categories.forEach(function(category){ does not refer to the class. You can use arrow syntax for function declaration which will laxically resolve value of this. Change
Categories.forEach(function(category){
to
Categories.forEach((category) => {


text:
Q: Ask for unlock pattern - Android Is there a way, I can ask a user for perform the unlock operation on his phone using the set pattern(passcode, fingerprint, etc) to access certain features of my application?
For example, in iOS, I generate an OTP based on a QR code. I can ask the user for the unlock pin before showing him the generated OTP token. I want the same for my android application. This prevents the misuse of the application.

A: You can create that intent with the KeyguardManager class, using the createConfirmDeviceCredentialIntent method available since API 21, it should be called from your activity with the startActivityForResult(intent) method.
In your activity:
private static final int CREDENTIALS_RESULT = 4342; //just make sure it's unique within your activity.

void checkCredentials() {
  KeyguardManager keyguardManager = this.getSystemService(Context.KEYGUARD_SERVICE);
  Intent credentialsIntent = keyguardManager.createConfirmDeviceCredentialIntent("Password required", "please enter your pattern to receive your token");
  if (credentialsIntent != null) {
    startActivityForResult(credentialsIntent, CREDENTIALS_RESULT);
  } else {
    //no password needed
    doYourThing();
  }
}

@Override
public void onActivityResult(int requestCode, int resultCode, Bundle data) {
  if (requestCode == CREDENTIALS_RESULT) {
    if(resultCode == RESULT_OK) {
      //hoorray!
      doYourThing();
    } else {
      //uh-oh
      showSomeError();
    }
  }
}


text:
Q: Red Screen between screens with Provider When I navigate from one page to another a red screen throwing an error is shown very quickly, but afterwards the screen goes normally. It shows The following NoSuchMethodError was thrown building Consumer<StoresManager>. Do you guys know how I can fix this?
here is the onPressed that calls the Navigator:
Container(
        width: _deviceWidht * 0.43,
        height: 27,
        alignment: Alignment.center,
        decoration: BoxDecoration(
            border: Border.all(width: 1, color: Colors.grey),
            borderRadius: BorderRadius.circular(5)),
        child: FlatButton(
            onPressed: () {

              Navigator.push(
                  context,
                  MaterialPageRoute(
                    builder: (context) => StoreScreen(
                      profileId: profile.id,
                    ),
                  ));
            },
            child: Text('Comprar')),
      ),

Here is my new screen with a consumer:
class StoreScreen extends StatelessWidget {
 final String profileId;
 final String categoryId;

 final Store store;

 StoreScreen({this.profileId, this.categoryId, this.store});

 @override
  Widget build(
    BuildContext context,
  ) {
    final userManager = context.watch<UserManager>();

   return Consumer<StoresManager>(
     builder: (_, storesManager, __) {
       storesManager.loadStore(profileId);
       if (userManager.adminEnabled) {
        storesManager.store.status = StoreStatus.open;
    }
    return Stack(
      children: [
        gradientBackground(),
        Scaffold(
          appBar: AppBar(
            backgroundColor: Colors.transparent,
            elevation: 0,
            title: Text(
              storesManager.store.name,
              style: TextStyle(fontFamily: 'MontSerrat'),
            ),
            centerTitle: true,
            leading: IconButton(
              icon: Platform.isIOS
                  ? Icon(Icons.arrow_back_ios)
                  : Icon(Icons.arrow_back),
              onPressed: () {
                context.read<CartManager>().clear();
                Navigator.pop(context);
              },
            ),
          ),
          backgroundColor: Colors.transparent,
          body: storesManager.store.status == StoreStatus.closed
              ? AlertDialog(
                  title: Text(storesManager.store.statusText),
                  content: Text(
                      'Horário de funcionamento\n\n${storesManager.store.openningText}'),
                )
              : buildCategories(),
          floatingActionButton: FloatingActionButton(
            backgroundColor: Theme.of(context).primaryColor,
            foregroundColor: Colors.white,
            onPressed: () {
              Navigator.push(
                  context,
                  MaterialPageRoute(
                    builder: (context) => CartScreen(
                      profileId: profileId,
                    ),
                  ));
            },
            child: Icon(Icons.shopping_cart),
          ),
        )
      ],
    );
  },
 );
}
}

my Stack trace:
The following NoSuchMethodError was thrown building Consumer<StoresManager>(dirty,
dependencies: [_InheritedProviderScope<StoresManager>]):
The setter 'status=' was called on null.
Receiver: null
Tried calling: status=Instance of 'StoreStatus'

The relevant error-causing widget was
Consumer<StoresManager>
package:e_ai_casimiro/screens/store_screen.dart:58
When the exception was thrown, this was the stack
#0      Object.noSuchMethod (dart:core-patch/object_patch.dart:51:5)
#1      StoreScreen.build.<anonymous closure>
package:e_ai_casimiro/screens/store_screen.dart:62
#2      Consumer.buildWithChild
package:provider/src/consumer.dart:175

my provider:
class StoresManager extends ChangeNotifier {
   StoresManager() {
 _starTimer();
 }

  Store store;

  String profileId;

  Timer _timer;

  Future<void> loadStore(String profileId) async {
    final snapshot = await storeRef.doc(profileId).get();

    store = Store.fromDocument(snapshot);

    notifyListeners();
   }

  void _starTimer() {
   _timer = Timer.periodic(const Duration(minutes: 1), (timer) {
   _checkOpening();
   });
  }

 void _checkOpening() {
   store.updateStatus();

   notifyListeners();
 }

 @override
 void dispose() {
  super.dispose();
 _timer?.cancel();
 }
}

enum StoreStatus { closed, open, closing }

class Store {
  Store.fromDocument(DocumentSnapshot doc) {
   image = doc['image'] as String;
   name = doc['name'] as String;
   storeId = doc.id;
   delPrice = doc['delPrice'] as num;
   minPrice = doc['minPrice'] as num;
   openning = (doc['openning'] as Map<String, dynamic>).map((key,
 value) {
   final timeString = value as String;

   if (timeString != null && timeString.isNotEmpty) {
    final splitted = timeString.split(RegExp(r"[:-]"));

    return MapEntry(key, {
      'from': TimeOfDay(
          hour: int.parse(splitted[0]), minute:
int.parse(splitted[1])),
      'to': TimeOfDay(
          hour: int.parse(splitted[2]), minute:
int.parse(splitted[3]))
    });
  } else {
    return MapEntry(key, null);
  }
 });
  updateStatus();
 }

String image;
String phone;
String name;
String facebook;
String instagram;
String storeId;
num delPrice;
num minPrice;
Map<String, Map<String, TimeOfDay>> openning;
StoreStatus status;

String get openningText {
 return 'Seg: ${formattedPeriod(openning['monday'])}\n'
    'Ter: ${formattedPeriod(openning['tuesday'])}\n'
    'Qua: ${formattedPeriod(openning['wednesday'])}\n'
    'Qui: ${formattedPeriod(openning['thursday'])}\n'
    'Sex: ${formattedPeriod(openning['friday'])}\n'
    'Sáb: ${formattedPeriod(openning['saturday'])}\n'
    'Dom: ${formattedPeriod(openning['sunday'])}\n';
 }

 String formattedPeriod(Map<String, TimeOfDay> period) {
  if (period == null) return 'Fechado';
  return '${period['from'].formatted()} -
${period['to'].formatted()}';
}

void updateStatus() {
  final weekDay = DateTime.now().weekday;

  Map<String, TimeOfDay> period;
  if (weekDay == 1) {
    period = openning['monday'];
  } else if (weekDay == 2) {
    period = openning['tuesday'];
  } else if (weekDay == 3) {
    period = openning['wednesday'];
  } else if (weekDay == 4) {
    period = openning['thursday'];
  } else if (weekDay == 5) {
    period = openning['friday'];
  } else if (weekDay == 6) {
    period = openning['saturday'];
  } else if (weekDay == 7) {
    period = openning['sunday'];
 }

final now = TimeOfDay.now();

if (period == null) {
  status = StoreStatus.closed;
} else if (period['from'].toMinutes() < now.toMinutes() &&
    period['to'].toMinutes() - 15 > now.toMinutes()) {
  status = StoreStatus.open;
} else if (period['from'].toMinutes() < now.toMinutes() &&
    period['to'].toMinutes() > now.toMinutes()) {
  status = StoreStatus.closing;
} else {
  status = StoreStatus.closed;
  }
}

String get statusText {
  switch (status) {
    case StoreStatus.closed:
      return 'Loja Fechada';
    case StoreStatus.closing:
      return 'Loja Fecha em 15 minutos';
    default:
    return '';
  }
 }
}

A: The line throwing the error is storesManager.store.status = StoreStatus.open;. The error says the store is null. What you can try is adding storesManager.store != null in the condition wrapping that line.


text:
Q: Build only and not Deploy Quick question. I was wondering is there any way to just build an app made in WL6, without the need to deploy to the server?
I know that in Cordova you can simply just run: cordova build android in terminal, but I can't seem to find an option on the WL IDE to do this...
I'm just wanting to test the UI standalone without server functionality. Rather than waiting for a deployment each time (I know it doesn't take too long but just looking to save a little time).
Any help would be much appreciated.
Thanks in advanced.

A: This is not possible using Worklight Studio 6.0.0.x (the Eclipse plug-in).
You could possibly use an Ant task to build the application/adapter.

A: The deployment to the internal development server is pretty fast and gives you the capability of testing your UI through a web browser or the mobile web simulator. I typically will use the browser with the Ripple Emulator plugin in Chrome to get the sizing right without waiting on the Java simulator to start.
The slowest component in my environment is waiting for the Android emulator to run, so I try to avoid that.
Here's a tip if you are testing the UI on-device or are using a component such as JSONStore, which requires an full device or emulator to run:

*

*Set up your application to check for updates from the Worklight server.

*Point the application at the embedded development server (this is the default for dev)

*Keep your device connected when you do Build and Deploy in Worklight Studio.

*Restart the app on the device and it will load the new version.

As long as you aren't changing native code such as Cordova plugins, this lets you iterate UI changes and test them on the real device without the time to do a new app deployment or waiting on the compilers and emulators.


text:
Q: Dynamic number of arguments in bind_param I have been trying to use call_user_func_array()but dont seem to get it right.
$sql_sentence = "SELECT * FROM test_table WHERE Fag = ? AND (" . $sql_subject . ") AND (" . $sql_grade . ") AND (" . $sql_type . ")";
    $sql = $conn->prepare($sql_sentence);

$allarrays = array_merge(array('ssss'),array($_POST['Fag']),$_POST['subject'],$_POST['Grade'],$_POST['Type']);

//testing to see if it prints out right values of array.
for ($x = 0; $x < count($allarrays); $x++) {
    echo "The number $x is $allarrays[$x] <br>";
}

call_user_func_array(array($sql, "bind_param"),$allarrays);
$sql->execute();

But I get this error Warning: Parameter 2 to mysqli_stmt::bind_param() expected to be a reference, and it points it to line call_user_func....
When I print out the SQL sentence it looks like this:
SELECT * FROM test_table WHERE Fag = ? AND (Subject LIKE ?) AND (Grade LIKE ?) AND (Type LIKE ?)
and all array-values are right, and the first array value is 'ssss', and after the first array comes four arrays with different values.
Have I done anything wrong here?
Do you need more code?
EDIT: Can you open this question. I found an answer which was different than the similar question! Think it should be printed here.

A: call_user_func_array expects its first argument to be a callable not an array:

mixed call_user_func_array ( callable $callback , array $param_arr )

Which function are trying to call, exactly?  mysqli_stmt::bind_param()?
If so, it would need to look something like this:
call_user_func_array(array($stmt, 'bind_param'), array('s', $_POST['Fag']) );


text:
Q: Trouble understanding order of execution in a java algorithm (k= and ++k) I've had to do a Java exam recently, and was wondering about one of the questions I had wrong. The question was as follows:
What will the following code print when run without any arguments ...
public class TestClass {

    public static int m1(int i){
        return ++i;
    }

    public static void main(String[] args) {
        int k = m1(args.length);
        k += 3 + ++k;
        System.out.println(k);
    }

}

With the answers being a number between 1 and 10.
My original answer was 7, whereas they state that the correct one is 6.
My logic:
m1 sets k to 1, as it's ++i and thus gets incremented prior to returning.
then the += is unrolled, making: 'k = k + 3 + ++k'.
++k is executed, making k 2.
Replace the variables with their value: 'k = 2 + 3 + 2'
k = 7.

However, they state it as k = 1 + 3 + 2.
Could anyone explain as to why the variable is replaced first, before performing the ++k?

A: The post and pre increment operators do operate on a temporary value which is getting assigned after the equation. Which means that
i = 0;
i = i++ // still 0
i = ++i // 1

Because the right hand side is temporary and do not reflect the left side before the assignment.
With your logic this would result in
int i = 0;
i = ++i // 2 - wrong.

A: Without any arguments means args.length = 0
int k = m1(args.length);
m1 (0) = ++0 = 1
So k = 1
k += 3 + ++k;
k = k + 3 =4.
++k = ++1 = 2
So
4 + 2 = 6

A: I do believe that even if the order is correct, the JVM prepare the statement with the k value so this is looking like this (simplified) :
  k += 3+ ++k; // k = 1
> k = k + 3 + ++k // k = 1
> k = 1 + 3 + ++k // k = 1
> k = 1 + 3 + 2   // k = 2

Let go further with :
  int k = 2;
  k *= 3 + ++k; // > 12
> k = 2 * 3 + ++k // k = 2
> k = 2 * 3 + ++k // k = 2
> k = 2 * 3 + 3   // k = 3
> k = 2 * 6 = 12

We see that the *= is done last be with the beginning value.
  int k = 1;
  k += 3 + ++k + ++k; // > 9
> k = k + 3 + ++k + ++k // k = 1
> k = 1 + 3 + ++k + ++k // k = 1
> k = 1 + 3 + 2   + ++k // k = 2
> k = 1 + 3 + 2   + 3   // k = 3
> k = 9

So we can see that this is not true for post increment. Those will get the value of k on the first reading
The only logic I see is that the values are evaluated from left to right but the operator are only executed depending on the order. At the exception of post and pre increment that are evaluated during the first reading

A: Ok, you are correct in stating that the ++ operator has precedence over the += operator and therefore the += will not be unrolled until the ++ operation has been carried out .... however before any operation is carried out the interpreter first evaluates the operands of most operators and this is done from left to right.
So in your example, where k = 1,
k += 3 + ++k;

effectively is:
1 += 3 + ++k;

and then the ++k is evaluated as this has precedence and becomes:
1 += 3 + 2;

the + has precedence and becomes:
1 += 5;

and at this point the += is unrolled, which of course gives 6 ... QED
Edit
Although operator precedence is important Java does evaluate left to right unless the precedence dictates otherwise:
For example:
a + b + c * d
Although c * d has precedence it isn't evaluated first.
a + b + c * d
  ^   ^
 these 2 operators compared

Both have same level of precedence so evaluating left to right and a + b is evaluated first (lets call the result d).
 d + c * d
   ^   ^
 next these 2 operators compared

* has precedence over + so c * d is evaluated first.


text:
Q: AsyncAPI enum with specific values Is it possible to create an enum with specific values in AsyncAPI? In my legacy c# code theres an enum like this
public enum OrderStatus
{

    Ordered = 30,
    UnderDelivery = 40,
    Deliveret  = 50,
    Cancelled = 99
}

I would like to create the same enum, with the same values in AsyncAPI. But it seems that you cannot specify the values in async API. Am I missing something? Is there an alternative solution?

A: It is not, or at least not in the general sense.
With AsyncAPI 2.4 you can define payloads with different schema formats (schemaFormat), by default this is an AsyncAPI Schema Object which is a superset of JSON Schema Draft 7. There might exist a schema format you can use that allows this, I just don't recall knowing one, for example not even JDT allows this.
Looking into JSON Schema Draft 7, you will not find it possible to define an enum value with an associated name such as Ordered and UnderDelivery. This means the only way to define it is something like this:
{
  "title": "OrderStatus",
  "type": "number",
  "enum": [
    30,
    40,
    50,
    99
  ]
}

This is because JSON Schema focuses on validating JSON data, and in the JSON world, there is no such thing as an associated name to the enum value. That is entirely related to programming languages.
Solution
There are a couple of solutions and how you can proceed, let me highlight one way I see it could be achieved.
Specification Extensions
If you use the default AsyncAPI 2.4.0 Schema Object, AsyncAPI allows you to add your own extension such as:
{
  "title": "OrderStatus",
  "type": "number",
  "enum": [
    30,
    40,
    50,
    99
  ],
  "x-enumNames": {
    30: "Ordered",
    40: "UnderDelivery",
    50: "Deliveret",
    99: "Cancelled"
  }
}

This will also work if you use pure JSON Schema draft 7 because any extra properties are allowed.
In newer versions of JSON Schema, they introduce something called vocabularies, which could standardize this feature. I started some work around a code generation vocabulary unfortunately, there are many other areas that need to be solved first, so I don't have the bandwidth to personally push it forward.
Generating the enum model
Regardless of how you actually define it with the specification, I expect you want tooling to generate the "accurate" enum model in code generation so here is one way to do it.
Modelina is an open-source tool that is being developed exactly for these cases. I have added an example test case to showcase how it could be done for Modelina v0.59.
Let me break the implementation down:
const generator = new CSharpGenerator({
  presets: [
    {
      enum: {
        item: ({model, item, content}) => {
          // Lets see if an enum has any associated names
          const hasCustomName = model.originalInput !== undefined && model.originalInput['x-enumNames'] !== undefined;
          if (hasCustomName) {
            // Lets see if the specific value has an associated name
            const customName = model.originalInput['x-enumNames'][item];
            if (customName !== undefined) {
              return customName;
            }
          }
          return content;
        }
      }
    }
  ]
});

The Csharp generator is being instructed to use a custom preset (can be seen as a Node.js middleware) for the enum renderer. Here we add a middleware to overwrite the name of each enum "item"/value based on whether it has our extension or not.
This results in the following generated model:
public enum OrderStatus
{
  Ordered,
  UnderDelivery,
  Deliveret,
  Cancelled
}

public static class OrderStatusExtensions
{
  public static dynamic GetValue(this OrderStatus enumValue)
  {
    switch (enumValue)
    {
      case OrderStatus.Ordered: return 30;
      case OrderStatus.UnderDelivery: return 40;
      case OrderStatus.Deliveret: return 50;
      case OrderStatus.Cancelled: return 99;
    }
    return null;
  }

  public static OrderStatus? ToOrderStatus(dynamic value)
  {
    switch (value)
    {
      case 30: return OrderStatus.Ordered;
      case 40: return OrderStatus.UnderDelivery;
      case 50: return OrderStatus.Deliveret;
      case 99: return OrderStatus.Cancelled;
    }
    return null;
  }
}


text:
Q: pandas python - how to convert array (different length with data frame) to data frame and keep the row and column name? first of all, I have calculated the cosine similarities using the data frame and the result is returned array object.
assumed that, this is my data frame
   A B C D E
X1 0 0 1 0 1
X2 0 1 2 3 1
X3 0 1 1 0 1

here is the way I have calculated the df
df = df.drop(['colX'], axis=1)
cos_sim = cosine_similarity(df_new_jac)

and it returns like this
array([[0.,   0., 1.],
       [0.,  1., 2.],
       [0.,  1., 1.]

however, i hope to see the result like this
   X1 X2 X3
X1 0  0  1
X2 0  1  2
X3 0  1  1

but, according to the shape of 'df' and 'cos_sim' are having the different shape, I can't use this code
df = df.set_index('colX')
v = cosine_similarity(df.values)

df[:] = v
df.reset_index()

the error shows, the len must be equivalent. is any suggestion to fix this issue?

A: not exactly sure what you're trying to achieve here, but here is my best guess:
import pandas as pd
# the original df
df1 = pd.DataFrame({'index': ['X1','X2','X3'], 'A':[0,0,0], 'B':[0,1,1], 'C': [1,2,1], 'D': [0,3,0], 'E':[1,1,1]})
# the cosine_similarity df
df2 = pd.DataFrame({'index': ['X1','X2','X3'], 'X1':[0,0,0], 'X2':[0, 1,1], 'X3':[1,2,1]})
# note the 'index' column is a column, not the index.

# merge the 2, by default on the common column (i.e. the 'index' column)
df = df1.merge(df2)
df.set_index('index', inplace=True)
>   A   B   C   D   E   X1  X2  X3
index
X1  0   0   1   0   1   0   0   1
X2  0   1   2   3   1   0   1   2
X3  0   1   1   0   1   0   1   1


text:
Q: Pivot Parcela (Linha em coluna) Senhores, bom dia !
Eu estou tentando fazer um PIVOT simples de parcela sob mesmo numero do cliente (330162210001), porem nao estou conseguindo...
A ideia é que a cada resultado de parcela encontrado seja uma coluna.
Ja tentamos diversos aggregation function sql, porem sem êxito.
Esta dando este erro :

Já tentamos converter todos os tipos de type possivel para que ele consiga fazer a leitura. Mas sem êxito.
Type da Tabela que estamos trabalhando:

Resultado da Subquery:

Code utilizado:
SELECT * FROM (
              SELECT dup.cliente, dup.VR_LIQ_ATU,dup.NUMERO, DUP.VALOR
              FROM DUPLICATAS_ABERTAS DUP WHERE dup.CLIENTE = 330162210001) as Q
PIVOT(
       MAX (cliente)
       FOR VR_LIQ_ATU IN ([VALOR_C]))AS PVT

Se alguem conseguir dar uma luz, Agradecemos a compreensão.

A: Maguim,
conforme mencionei no comentário, o que fica dentro do IN é o identificador da coluna pivotada, pra você entender melhor, ele deve ser o elemento que consta na linha. Pelos dados fornecidos, daria para montar assim (pode haver outras formas, mas não sei como está a arquitetura do seu banco em relação aos campos):
SELECT *
FROM
(SELECT
    ROW_NUMBER() OVER(PARTITION BY CLIENTE ORDER BY CLIENTE) AS ORDEM,
    DUP.CLIENTE,
    DUP.VR_LIQ_ATU,
    DUP.NUMERO
    --DUP.VALOR
    FROM TESTE DUP
    --WHERE DUP.CLIENTE = 3301
) AS Q
PIVOT(SUM(VR_LIQ_ATU) FOR ORDEM IN ([1], [2], [3]) )AS PVT

outros scripts:
--CREATE TABLE TESTE (
--CLIENTE VARCHAR(100),
--VR_LIQ_ATU NUMERIC(10,4),
--NUMERO VARCHAR(100),
--VALOR VARCHAR(100)
--);

--INSERT INTO TESTE VALUES (3301, 173.55, 62, 'R$ 177,59' )
--INSERT INTO TESTE VALUES (3301, 1395.55, 62, 'R$ 1395,59' )
--INSERT INTO TESTE VALUES (3301, 1455.55, 62, 'R$ 1455,59' )
--INSERT INTO TESTE VALUES (3302, 152.55, 62, 'R$ 152,59' )
--INSERT INTO TESTE VALUES (3302, 11.55, 62, 'R$ 11,59' )
--INSERT INTO TESTE VALUES (3303, 1365.55, 62, 'R$ 1365,59' )
--INSERT INTO TESTE VALUES (3303, 188.55, 62, 'R$ 188,59' )


text:
Q: How to implement a location specific convolutional filters in Tensorflow or Pytorch? I want to implement a convolutional layer, with a different convolutional filter for each output location. Specifically, think of the case when the output is of 16*16*128 (W * H * C). Instead of having a 3*3*128 filter we have 16*16 filters; each with size 3*3*128. This would lead to huge amount of parameters, but it can the case be that each of the 3*3*128 filter may be the same except scaled by a different constant, and the constants can be learned through a side network. In this way the number of parameters won't be too much.
The similar idea is briefly in Dynamic Filter Networks, but I cannot find an implementation of location specific filters. My question is, if we want a location specific convolutional filter how do I implement it in Tensorflow or Pytorch? Do I need to write my own operation or there is some smart way to use the functions provided? If I have to write an OP is there any trick that can easily achieve this idea? Any help is appreciated!

A: A convolution, by definition, is not location specific - this is what makes it a convolution. If you wish to generalize convolution, bear in mind that eventually a convolution is a special case of a simple linear operation. Therefore, you can implement your "location specific" convolution as a fully-connected layer (nn.Linear) with a very specific sparse weights.

A: The reason why convolutions are more efficient than fully connected layers is beacause they are translation invariant. If you wish to have convolutions which are dependent on location you would need to add two extra parameters to the convolution i.e. having N+2 input channels where x, y coord are the values of the two additonal channels (as in e.g. CoordConv, or Location Biased Convolutions).


text: Q: customize context menu of webview in windows8 In webview control, we can select contents and right click to call the context menu, there's only a 'copy' option, I want to add my custom items into the context menu, but I found it seems not possible from this thread: http://social.msdn.microsoft.com/Forums/en-GB/winappswithcsharp/thread/20c05893-d26f-474e-88b9-b42800071ccb. Is it possible to disable the native context menu and create my own context menu for the webview?


text:
Q: Code to include HTML snipets not working I tried including the 'tab.html' and 'content.html' into my 'index.html' (using w3school code: how to include HTML, found at: https://www.w3schools.com/howto/howto_html_include.asp), but the javascript and css elements do not work. The buttons don't work as intended. Look at:
https://rads-198409.appspot.com
If you resize (to a smaller size) the browser window, the tab is supposed to change to a drop-down menu, but the button does not work at all. I have checked the individual pages and they seem to work just fine, just not when they are combined.
Am I doing something wrong? Could someone help? All the code I used is from w3school and I have only modified the file names (tab.html and content.html to point to the right files). Below are links to the code:
Code for 'tab.html' - https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_topnav
Code for 'content.html' - https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_collapsible_symbol
Code for 'index.html' - https://www.w3schools.com/howto/tryit.asp?filename=tryhow_html_include_2

A: This is why:

*

*The links take you nowhere. #home (or # then whatever) is referring to an element in the page. This means that the link doesn't actually take you anywhere, unless you actually change the link to something else.

*You're using a w3schools template. Come on, man!
Explanation on #1:
Say there was a footer at the bottom of a page, named "footer". To jump to that element, all you have to do is put #footer at the end of the url, and your browser will jump your screen to the bottom. Similarly, the #home hash means that it goes to a place where an element called home is. In this case, that's the top. The other buttons though, refer to different elements. The problem is that these elements don't exist in the template. To make them work, you must change the url to a real working url, or create elements with ids such as "news", "contacts", and such.


text:
Q: How to access Array elements as constants - Java I am trying to store the Color values in Java Array but I know that these values are stored as strings,
String[] colorarray = {"Color.yellow","Color.red","Color.blue"};

Now, I couldn't access this array element to set the color, i.e
g.setColor(colorarray[0]);

Because all the values in the array are strings.
How could I convert these values to the constants ?

A: Straightforward, use this :
Color[] colorarray = {Color.YELLOW, Color.RED, Color.BLUE};

A: If you have control over the array, by all means change it to just be an array of Colors as suggested by several other people.
Color[] colorArray = {Color.YELLOW, Color.RED, Color.BLUE};

If you don't have control over the array and you have to use it as-is, you'll need to do one of two things:

*

*Use reflection to access the static members of the Color class
(a quick Google search will give you plenty of examples on how to do this so I won't go into it here)

*Create a Java 7 switch statement on the Strings to interpret each possible color value in the array into Color.XXX where XXX is the name of your color. (This could also be done using a big if-else block but that wouldn't be as clean)

One other quick note - variable names in Java are, by convention, in camelCase starting with a lower-case letter.  This helps make your code more readable.  (Class names are CamelCase, package names are lower.case)

A: Use
Color[] colorArray = {Color.YELLOW, Color.RED, Color.BLUE};


text:
Q: Set baud rate to esp8266 at 9600 I brought an esp8266-12, it works at 115200 baud rate. I sometime connect it to arduino uno to work for some projects. It would be easy if I connect esp8266 with arduino at 9600 baud rate. The AT version is 0.25. I googled and saw the AT command set documentation it had a command to set baud rate. It was like
AT+ UART_DEF=<baudrate>,<databits>,<stopbits>,<parity>,<flow control>

But the problem is I don't know what these parameters are and how to set the parameters so that is works at 9600 baud rate with arduino.

A: After a long time of searching, I found the parameters to work with Arduino at 9600 baud rate.
AT+UART_DEF=9600,8,1,0,0

A: To change the baud rate of esp8266, use this command.
AT+CIOBAUD=9600

Easy and simple. Command can be sent through serial communication from Arduino UNO.


text:
Q: Display distinct values on a laravel blade view I have a prices table that stores the date which a product cost was stored. There is a relationship between the product & price model which works very well by returning the collection. I want to display a table with a date & product name as the columns, then display the DISTINCT dates & the corresponding product cost on each row. Below is my blade view code and what the table looks like
view - code

    Date
    @if (isset($products) && !empty($products))

        @foreach ($products as $product)
            {{ ucwords($product->name) }}

        @foreach ($product->prices as $price)

            {{ $price->date }}
            {{ $price->cost }}

        @endforeach

        @endforeach
    @else
        Product price is not available
    @endif

browser-view

Changing my code by ending the first foreach loop, gives me something close to what i want but only the cost for the last product is displayed
alternative code

    Date
    @if (isset($products) && !empty($products))

        @foreach ($products as $product)
            {{ ucwords($product->name) }}
        @endforeach

        @foreach ($product->prices as $price)

            {{ $price->date }}
            {{ $price->cost }}

        @endforeach

    @else
        Product price is not available
    @endif

Browser-view

How do i display all of my product cost values for each date in the format of the last picture?


text:
Q: Problema com API Laravel em produção Fiz um deploy de uma API em laravel. O problema que está ocorrendo é o seguinte: a API online sempre me retorna '200 ok', sem chegar ao menos ao controller de login. Com essa mesma API, fiz o teste em localhost e funcionou. Preciso definir mais alguma permissão?

A: Seria interessante posta o código do método do seu controller, pois dependendo das condições utilizadas ele pode está passando no método sem efetuar nenhuma operação, até chegar no return, por isso está dando 200.
Ex:
{
   $dados = (object) $request->all();
   $usuario = usuairo::where('email',$dados->email)->first();
   if($usuario){
      if($this->testeUsuarioSenha($dados))
         return Response::json(['message' => 'Login realizado com sucesso'], 200);
      else
         return Response::json(['message' => 'Não encontrado'], 404);
   }
   return '';

}

Analisando o código acima, concorda que para emails que não existem na base vai retornar http 200? Emfim para ajudar precisaria de mais informações.
No servidor execute o seguinte comando e analise suas rotas:
php artisan route:list
Outro ponto interessante a se observar, é em produção rodar também.
    php artisan route:cache


text:
Q: combinatorial design problem A combinatorial design has six varieties {1, 2, 3, 4, 5, 6}, and nine blocks of size 2. Every variety occurs in three blocks, and the design is simple. Prove that there are exactly two non-isomorphic ways to do this.
I was able to solve a similar problem which asked me to construct two non-isomorphic designs with three varieties and five blocks of size 2, and  every possible pair of varieties occurring at least once.
How can I develop this one to solve the first quesion?

A: Notice that you are counting isomorphism classes of simple graphs on six vertices in which every vertex has degree three.
If there is a triangle in the graph, then one easily sees that the whole graph is

Indeed, no two triangles can share an edge, so that is the only possibility.
If there is no triangle, let $x$ be a vertex and let $a$, $b$, $c$ be its neighbors. No two of $a$, $b$, $c$ can be connected, because that would create a triangle. It follows that all three of them are connected to the other two vertices $u$ and $v$. That completely determines the graph, which is then


text:
Q: regex get decimal value from a string e.g 1.4em I have been scratching my head and searching around and i cannot seem to find another question quite like the problem i am having.
i have a variable e.g:
var style = ' font-size: 12px; line-height: 1.4em; ';

and i can quite easily extract the value of font-size using (and use this method for a lot of other values i need to retrive):
var match = /(?:^|\s)font-size\s*:\s*(\d+)px/i.exec( style );
fontsizetest = match && match[1];
console.log(fontsizetest);

but when i try to extract the value of the line height (with relative em sizing) i get all sort of problems (mainly due to the decimal place):
After playing around for quite a while this is the closest i can get to a solution:
var match = /(?:^|\s)line-height\s*:\s*(\d|\.|\d*)em/i.exec( style );
lineheighttest = match && match[1];
console.log(lineheighttest);

but this does not return my value of 1.4
Any ideas or advice of pointing me in the right direction would be greatly appreciated. I am sure there is a simple explanation but i have just been looking at it for too long?
Many Thanks

A: Your problem is that you're weak at regular expression syntax.
Try this:
var match = /(?:^|\s)line-height\s*:\s*((?:\d*\.)?\d+)em/i.exec( style );

This accepts numers like 2, .8 or 1.2.


text:
Q: Using HTML Helper @Html.HiddenFor from a Tuple model So previously this view was bound to only one model but now I am using:
@model Tuple<Namespace.Models.Model1, Namespace.Models.Model2>

So now when I bind:
@Html.HiddenFor(p => p.Id);

The compiler does not know which model to use and as a result throws this error:
The type arguments for method 'InputExtensions.HiddenFor<TModel, TProperty>(HtmlHelper<TModel>, Expression<Func<TModel, TProperty>>)' cannot be inferred from the usage. Try specifying the type arguments explicitly.

I tried to explicitly infer the model using:
 @Html.HiddenFor(Model1 => Model1.Id);

But I get:
The type arguments for method 'InputExtensions.HiddenFor<TModel, TProperty>(HtmlHelper<TModel>, Expression<Func<TModel, TProperty>>)' cannot be inferred from the usage. Try specifying the type arguments explicitly.

So I try the below:
 @Html.HiddenFor<TModel, TProperty>(HtmlHelper<TModel> p => p.Id);

The Id property is defined in Model1.
And get a whole bunch of other errors. After extensive reading online, I still have not found a solution. How do I get around this?

A: As @Stephen Muecke mentioned, the way to accomplish mixing your models into one view is to create a ViewModel:
public class Model1
{
    public string Model1Prop { get; set; }
    public string Model1Name { get; set; }
}
public class Model2
{
    public string Model2Prop { get; set; }
    public string Model2Name { get; set; }
}

Those are your Domain Models, now suppose you want to register those properties in the same View:
public class RegisterViewModel
{
    [Required]
    public string Model1Prop { get; set; }
    [Required]
    public string Model2Prop { get; set; }
    [Required]
    public string Model1Name { get; set; }
    [Required]
    public string Model2Name { get; set; }
}

Since those are the fields that will be displayed on the view, this is where you put DataAnnotations for your model validation. You'll get whatever the user types on these inputs in the controller action, then just pass whatever you need to your Domain Models.
I remember struggling with this question myself not so long ago, hope it helps.


text:
Q: C++ polymorphism: Is there any way to find the address of an object's member function? If I have a pure virtual base class with several derivations of it...
class Base
{
public:
   virtual void method1() = 0;
}

class Derived1 : public Base
{
public:
   void method1() override { ... }
}

class Derived2 : public Base
{
public:
   void method1() override { ... }
}

Is there any way for code that holds a Base* of an object of unknown derived type to determine the address of the method1() function for the object it holds the Base* pointer to?
What I want to do is something like this:
void someOtherFunction(Base * pb)
{
   printf("If I call pb->method1(), it will call a function at %p.\n",
          &(pb->method1));
}

But I get a compiler error:

error: ISO C++ forbids taking the address of a bound member function
  to form a pointer to member function.

Ideally any solution would avoid RTTI & dynamic_cast because that isn't enabled/allowed for my embedded system.

A: What you are looking for are pointer to (virtual) member function. Note that such a pointer is not an address to a function but usually an offset inside a vtable, since the actual called function depends on the real type of the object. You can not even cast this pointer to void*, the representation is implementation-defined. This also means that you cannot find the address of the actual function that will be called in a generic way.
If you really need to know the target function to call, maybe you would be better by using several separate functions and an enum ?
Anyway, if you just want to be able to call a virtual member function through a pointer, you can do something like this:
void someOtherFunction(Base* pb)
{
    using func_t = void(Base::*)(); // Type of a pointer to member function of
                                    // signature void() and object type Base
    func_t fn = &Base::method1; // Take the address of the function
    (pb->*fn)(); // Call it. Note the extra parenthesis and the operator: ->*
                 // The actual function called depends on the actual type of pb,
                 // it can be Derived1::f() or Derived2::f() in the example code you have
}

A: Without knowing what you're trying to accomplish, it's quite hard giving an advice. I'd go with the following: use lambdas.
For example, capturing and non-capturing:
Base* b = ...;

// non capturing, convertible to function pointer
auto lambda1 = [](Base*) { b->method1() }
auto fptr = static_cast<void(*)(Base*)>(lambda1);

lambda1(b);
fptr(b);

// capturing
auto lambda2 = [b]{ b->method1() };

lambda2();

// can be stored in a std::function if you need them in a collection
std::function func = lambda2;


text:
Q: How can I replicate this SQL within SQLAlchemy ORM I need to replicate the following SQL statement in SQLAlchemy, I use the ORM, and although I could just use the raw engine to run the SQL I then loose the object oriented goodness in the results.
SELECT *,
  (6371 * acos(cos(radians(50.4)) * cos(radians(latitude)) * cos(radians(longitude) - radians(-4.15)) + sin(radians(50.4)) * sin(radians(latitude)))) distance
FROM mapobject
HAVING distance < 150
ORDER BY distance;

A: Alright in the end I conceded that this is a lot easier using the engine inside of the session directly and loosing out on the ORM goodness for this one query and hence...
    sql = text('SELECT *, (6371 *acos(cos( radians( %s ) ) * cos( radians( `latitude` ) ) * cos(radians( `longitude` ) - radians( %s )) + sin(radians(%s)) * sin(radians(`latitude`)))) `distance` FROM `mapobject` JOIN user ON mapobject.created_by = user.id WHERE deleted=0 HAVING `distance` < %s ORDER BY `distance`;' % (latitude, longitude, latitude, distance))
    map_objects = g.db.connection().execute(sql)
    humanised_map_objects = []
    for map_object in map_objects:
        tags = g.db.query(MapObjectTag).filter(MapObjectTag.map_object_id == map_object[0]).all()
        text_tags = []
        for tag in tags:
            text_tags.append(tag.tag)

        map_object_humanised = {'id': map_object[0],
                                'object_type': map_object[1],
                                'longitude': map_object[3],
                                'latitude': map_object[2],
                                'description': map_object[6],
                                'created_at': map_object[5].isoformat(),
                                'created_by': map_object[9],
                                'tags': text_tags}
        humanised_map_objects.append(map_object_humanised)

however as always if someone has a better way todo this and still have the ORM goodness let me know.


text:
Q: Find max and min of a column and update the first column sql server Based on the product and product key, update the column ord_by. There should be only one min  and max for a product and product_key .
E.g: Table

  +-------------+---------+-------+--------+
| Product_key | product | price | ord_by |
+-------------+---------+-------+--------+
|           1 | ABC     |    10 |        |
|           1 | ABC     |    10 |        |
|           1 | ABC     |    20 |        |
|           1 | ABC     |   100 |        |
|           1 | ABC     |   100 |        |
|           2 | EFG     |    20 |        |
|           2 | EFG     |    40 |        |
|           3 | ABC     |   100 |        |
+-------------+---------+-------+--------+

Expected output:
+-------------+---------+-------+--------+
| Product_key | product | price | ord_by |
+-------------+---------+-------+--------+
|           1 | ABC     |    10 | Min    |
|           1 | ABC     |    10 | Mid    |
|           1 | ABC     |    20 | Mid    |
|           1 | ABC     |   100 | Mid    |
|           1 | ABC     |   100 | Max    |
|           2 | EFG     |    20 | Min    |
|           2 | EFG     |    40 | Max    |
|           3 | ABC     |   100 | None   |
+-------------+---------+-------+--------+

My try :
;WITH ord_cte
            AS (
                SELECT product
                    ,product_key
                    ,max(price) as max_price
                    ,min(price) as min_price
                FROM t_prod_ord

                group by   product,product_key

                )
            UPDATE t1
SET ord_by = case
when t2.max_price =t2.min_price then 'none'
when t2.max_price=t1.price then 'max'
when t2.min_price=t1.price then 'min'
else 'mid' end
            FROM t_prod_ord t1
            INNER JOIN ord_cte t2 ON t1.product_key = t2.product_key   and t1.product=t2.product

using this query it is updating more than one max and min value for column ord_by.

A: Generate row number for each Product_key order by Price in both ASC and DESC order. Then use the row number in CASE statement to find the Min/Max values
Count() Over() aggregate window function will help you find the total count of each Product_key which we can use it for finding None
Here is one way
;WITH cte
     AS (SELECT *,
                Row_number()OVER(PARTITION BY Product_key ORDER BY price) AS Min_KEY,
                Row_number()OVER(PARTITION BY Product_key ORDER BY price DESC) AS Max_KEY,
                Count(1)OVER(partition BY Product_key) AS cnt
         FROM   Yourtable)
SELECT Product_key,
       product,
       price,
       CASE
         WHEN cnt = 1 THEN 'None'
         WHEN Min_KEY = 1 THEN 'Min'
         WHEN Max_Key = 1 THEN 'Max'
         ELSE 'Mid'
       END
FROM   cte

A: Another way to do with out cte...
 SELECT [Product_key],
           [product],
           [price],
           CASE
           WHEN Max(RN)
                    OVER(
                      PARTITION BY PRODUCT_KEY, PRODUCT
                      )=1 AND RN=1 THEN 'NONE'
             WHEN Min(RN)
                    OVER(
                      PARTITION BY PRODUCT_KEY, PRODUCT
                     ) = RN THEN 'MIN'
             WHEN Max(RN)
                    OVER(
                      PARTITION BY PRODUCT_KEY, PRODUCT
                      ) = RN THEN 'MAX'

             ELSE 'MID'
           END ORDER_BY
    FROM   (SELECT *,
                   Row_number()
                     OVER(
                       PARTITION BY PRODUCT_KEY, PRODUCT
                       ORDER BY PRICE) RN
            FROM   TABLE1)Z


text:
Q: Laptop keyboard stops working after x2x install and use I'm new to linux/ubuntu and I have encountered a little problem: After installing x2x (following ubuntu community documentation about x2x) my laptop keyboard no longer works. The x2x system worked great - I was able to control my laptop from the desktop which was ssh'd into it... but the keyboard on the laptop no longer works. I have a dual-boot, and when I boot into lion (it's an early 2008 macbook) the keyboard works fine. Also, if I use a wireless usb mouse/keyboard when in ubuntu they work... just the actual computer hardware doesn't. Help?
Summary:

*

*Installed x2x, worked great

*Now the keyboard on my laptop dosen't work when logged into Ubuntu, but works in native OS (mac, lion)
Edit:
Additionally, if I log into a guest account in Ubuntu they keyboard works fine... So I'm assuming there's something wrong just in my main account.

A: If anyone runs into this problem it turns out I accidentally hit NumLock on the keyboard that was ssh'd into my mac. Hitting numlock again fixed the issue. I'm not a smart man...


text:
Q: Constructing a metric for the tautological line bundle of $\mathbb C P^2$ I'm doing some independent reading in differential geometry, and the following is my attempt to work out the details of the construction of the tautological bundle on $\mathbb CP^2$ and the induced metric. I'm posting this as a sort of sanity check. Any corrections or nitpicks are very welcome.
Let me first consider $CP^2$ with the standard charts, just to fix notation. That is , $U_2=\{[x:y:z] : z\neq 0\}$ with the map $\phi_0([x:y:z])=(x/z, y/z)$ and similarly for $U_0$ and $U_1$. The transition map from $U_2$ to $U_1$, for example, is
$(x,y) \rightarrow [x:y:1]\rightarrow (x/y, 1/y)$.
We let $E\subset \mathbb CP^2 \times \mathbb C^3$ be the set of points $([s], ws)$ with $s$ nonzero and $w\in \mathbb C$. I claim this is a line bundle. It suffices to give trivializations and transition functions. Over $U_2$, we give $([x:y:z], w(x,y,z))\rightarrow (x/y, y/z, w)$ and similarly for the other $U_i$.
Let us compute the transition function from part of the bundle over $U_2$ to the part over $U_1$.
$$(x,y, t)\rightarrow ([x:y:1], t(x,y,1))=([x/y:1:1/y], ty(x/y,1,1/y))\rightarrow (x/y, 1/y, ty)$$
We get similar transitions for the other two intersections.
If $([z], tz)$ and $([z], sz)$ are two elements of the tangent space over $[z]$, we can introduce the metric $\langle tz,sz\rangle $, where the brackets indicate the standard Hermitian metric on $\mathbb C^3$.
In coordinates over $U_2$, we look at the points $(x,y,t)$ and $(x,y,s)$ and define the inner product here to be $\langle t(x,y,1), s(x,y,1)\rangle$.
Is there anything else I should be checking here?


text:
Q: process cannot access the file because it is being used by another process error while running sql files using command prompt I want to run a set of sql files and created a batch file that will run all the sql files using sqlcmd command
for /R %%a IN (*.sql) do sqlcmd -H dbip:dbport-U dbname -P dbpwd -d dbname -i "%%~fa" >> results.txt

This batch file will iterate and run all the sql file(including some 4000kb file).
I wrote a java program to execute this batch file using ProcessBuilder
    String batchFilePath = "D:/path1/path2";
    List<String> command = new ArrayList<String>();
    command.add("cmd.exe");
    command.add("/C");
    command.add("start");
    command.add("mybatch.bat");

    ProcessBuilder processBuilder = new ProcessBuilder(command);
    processBuilder.directory(new File(batchFilePath));
    Process process = processBuilder.start();
    InputStream inputStream = process.getInputStream();
    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
    String line = null;
    while ((line = reader.readLine()) != null) {
    System.out.println(line);
    }
inputStream.close();
reader.close();

The batch is started to execute all sql file but after some time, separate command prompt is opened and throws an error like process cannot access the file because it is being used by another process for all remaining sql file. After throwing this error message in new window, the previous window again started to execute the remaining sql file.
Can anyone help me to understand why that error message is getting displayed and how to solve this problem ? or Is there any other better approach instead of using ProcessBuilder ?


text:
Q: Approaching player scores? Looking for help in approaching player scores in my game. How do I assign the scores at the end of each game to the player playing? What would be the best approach to a game like this?
class Player:
    def __init__(self, username, playerscore):
        self.username = username
        self.playerscore = playerscore

def question(Player):
    score = 0
    question = input("what direction is the arrow pointing, left or right? ->")
    if question == "right":
        score += 1
    else:
        score += 0

    question2 = input("What direction is arrow pointing, up or down? ^")
    if question2 == "up":
        score += 1
    else:
        score += 0

intro = input("Are you ready to play?")
if intro.lower() in ("yes", "go", "y"):
    user = input("What is your username? ")
    p1 = Player(user, 0)
else:
    exit()

cont = input("Player 2, are you ready to play? ")
if cont.lower() in ("yes", "go", "y"):
    user2 = input("What is your username? ")
    p2 = Player(user2, 0)
else:
    print(p1, "wins by default.")

if p1.playerscore>p2.playerscore:
    print (p1.username, "is the winner!")
elif p1.playerscore == p2.playerscore:
    print ("No one wins. It's a tie!")
else:
    print (p2.username, "is the winner!")

A: If I am understanding you correctly, you set up two player objects from the "Player" class and initialize their scores to zero.  If you want to increment a particular player's score you should just be able to add a value to the "p1.playerscore" or "p2.playerscore" value.  Following is a tweaked version of your code with a simple increment of the player's score.
class Player:
    def __init__(self, username, playerscore):
        self.username = username
        self.playerscore = playerscore

def question(Player):
    #score = 0
    question = input(Player.username + " what direction is the arrow pointing, left or right? ->")
    if question == "right":
        Player.playerscore += 1
    else:
        Player.playerscore += 0

    question2 = input(Player.username + " what direction is arrow pointing, up or down? ^")
    if question2 == "up":
        Player.playerscore += 1
    else:
        Player.playerscore += 0

intro = input("Are you ready to play?")

if intro.lower() in ("yes", "go", "y"):
    user = input("What is your username? ")
    p1 = Player(user, 0)
else:
    exit()

cont = input("Player 2, are you ready to play? ")

if cont.lower() in ("yes", "go", "y"):
    user2 = input("What is your username? ")
    p2 = Player(user2, 0)
else:
    print(p1.username, "wins by default.")
    quit()                  # Exit if two players are not found

question(p1)

question(p2)

if p1.playerscore>p2.playerscore:
    print (p1.username, "is the winner with a score of:", p1.playerscore)
elif p1.playerscore == p2.playerscore:
    print ("No one wins. It's a tie!")
else:
    print (p2.username, "is the winner with a score of:". p2.playerscore)

One could get fancy with creating "setter" functions as is done in other object oriented programs, but this seems to be the most straightforward way to accomplish this with little fuss.
This is a sample of the output with this tweak.
@Una:~/Python_Programs/PlayerScore$ python3 PlayerScore.py
Are you ready to play?yes
What is your username? Lily
Player 2, are you ready to play? yes
What is your username? Craig
Lily what direction is the arrow pointing, left or right? ->right
Lily what direction is arrow pointing, up or down? ^up
Craig what direction is the arrow pointing, left or right? ->left
Craig what direction is arrow pointing, up or down? ^down
Lily is the winner with a score of: 2

Give that a try.


text:
Q: How is MPI related to "message passing"? How, if at all, is Message Passing Interface (MPI) related to the general concept of "message passing"?

Admittedly, the question does sound ridiculous. Surely, "Message Passing Interface" is an interface for message passing, right? Nonetheless, it's not actually clear to me if MPI is somehow related to the general concept of message passing in programming languages or if the name "Message Passing Interface" is a historical artifact.
As described by Wikipedia, and as I'm familiar with it, message passing is a concept from object oriented programming in which objects are sent "messages" that request an action but are not tightly coupled to the code implementing that action. The details vary a lot between programming languages but the crucial element that there is a layer of indirection allowing objects to decide how to implement a member functions at runtime and without the caller knowing the details. For example, messages could be a string specifying the requested action along with appropriate arguments and objects receiving a message would decide what code to dispatch to based on the string and arguments. Another component is usually that the message is self-contained and arguments in the message are not references to data outside the message. The caller may have to copy data but the called object is free to modify received data as needed without concern for affecting the caller.
In contrast, MPI is relatively low-level -- being only slightly higher level than BSD sockets by abstracting away OS details -- and is not OOP in nature.

A:
message passing is a concept from object oriented programming

No, message passing is not a concept from object oriented programming, and the Wikipedia article does not state this. Instead, the definition is

message passing sends a message to a process (which may be an [...] object) and relies on the process and the supporting infrastructure to select and invoke the actual code to run.  Message passing differs from conventional programming where a process, subroutine, or function is directly invoked by name.

(OOP, or at least certain forms of OOP, make use of this concept, but that does not make MP a concept based on OOP, only vice versa).
MPI provides means to do exactly what the above definition says: for example, a send operation (see here) sends a message to another process (which runs in parallel), with not specifing the name of the called function or the exact code to run. The receiving process has to call MPI_Recv to get the message, so the exact code which gets the message is determined by the receiver, not by the caller.
So in short, the name is not just a "historical artifact", quite the opposite, the name fits well.

A:
message passing is a concept from object oriented programming

No, message passing is a concept in object-oriented programming, not from object-oriented programming.
The term message passing has a general meaning outside of OOP, and in fact outside of programming in general. Alan Kay didn't invent the term message passing specifically for OOP, he simply used the already existing term because it fits perfectly.
OOP has many similarities with the Internet: objects are little machines (interpreters) that have their own private RAM (instance variables) and code (methods) and can only communicate with each other by sending messages. Just like on the Internet, you cannot access another machine's RAM directly, you cannot access another machine's code directly. The only thing you can observe is the response to your message, but you have no idea how that response came into being: it could be a pre-canned response (instance variable), a constructed response (method invocation), the object might have asked someone else to craft the response (delegation / proxying), and so on.
This is no accident: while the Internet and even its predecessor (ARPANet) didn't yet exist back then, Alan Kay knew the people involved and knew their research, and their ideas. Plus, another group at Xerox PARC was just in the process of inventing the Ethernet and personal networking.
And if you think about it, that's also exactly how messages between humans work in the real world. So, it's exactly the other way around from your assumption: the term exists in the real world, it was then used in networking, because it fits the metaphor, and was then used in OOP for the same reason.
Note that, as explained in Doc Brown's answer, MPI in fact works pretty much exactly as you describe for the OOP case, which in turn makes MPI OO.


text:
Q: What is the earliest instance of a SciFi work describing a massive universal database of knowledge? What is the earliest instance of a SciFi work describing a system satisfying the following criteria (basically a massive computer database coupled with the networking system to access it available to everyone)?

*

*Database contains 100% of available knowledge (or as practically close to it as possible), necessarily including but not limited to:

*

*scientific information

*personal data

*news/events

*All of that information can be queried out, possibly with some controls to satisfy privacy needs.

*Universal access (e.g. practically any person on Earth can connect as a person, not just select few or limited by profession/organization). This one trips up many possibilities, e.g. H2G2 which arguably might fit the other criteria.
The precise implementation doesn't matter, some supercomputer, a super-AI, a whole planet ala H2G2 or a who-knows-how-it-works black box - doesn't matter. But it must satisfy the rules above.
The earliest one I can think of is from 1978, but it's in Russian (for those who care but can't guess, "BVI" - Big World Informatory - from Strugatsky brothers).

A: I think most of the Multivac stories written by Asimov are some of the earliest examples of this.  Namely, The Last Question which contains, especially near the end, a galaxy spanning super computer that anyone in the human race can access.  The earliest of these stories were written in the mid 1950s.

A: The oldest version of this idea that I know of is not strictly science fiction; it's called the Akashic Records which is a Hindu belief dating back to at least the late 18th century that there is a record kept of all experiences by every living thing. The records can be accessed via near-death experiences or by achieving certain Astral mental states.
Like I said, not actually sci-fi but if you're looking for old I think the Akashic Records are your best bet.

A: Paris in the Twentieth Century (French: Paris au XXe siècle) is a science fiction novel by Jules Verne, written in 1863 but first published in 1994, where a worldwide "telegraphic" communications network is mentioned, a possible premonition of the Internet, that I think satisfy the rules above.

A: Mark Twain's short story, From The 'London Times' of 1904, from 1898 is often regarded as the first writing that describes a world-wide communications network for information sharing although I'm not sure if it fits your requirement for a database. While it does mention a level of interactivity and such that would probably require a database of some sort it doesn't explicitly state it outright.
The Machine Stops by E. M. Forster, published in 1909 might fit your requirements better. It's about the dystopian world that develops when a machine that's controlling everything and facilitates the endless discussion of secondhand ideas (sound familiar?) breaks down.  Read it and see what you think.

A: "The Life and Times of Multivac" (1975) is one of a series of short stories that describe a very big computer called Multivac, the computer is first mentioned in the short story Question (1955).

A: Well.. I am not sure if it qualifies for a book or not but Hindu mythology talks about a recordkeeping of all the good and  bad stuff that every human does based on which the person's after life "benefits"/Quality of life are decided..

A: Ernst Jünger's Eumeswil (1977) (see German wikipedia article for more detail - English wikipedia article is quite short and omits discussion of the SF aspects) describes a sort of wikipedia like database of historical-only knowledge called the Luminar. The user can query it over things in the past which are then displayed on a monitor.


text:
Q: Adding values in ManyToManyField through the Django admin I'm a newbie in Django, so can you help me to understand how the save() method works?
Here's my models:
class Tag(models.Model):
    name = models.CharField(verbose_name=u'Tag', max_length=200, unique=True)

class Entry(models.Model):
    title = models.CharField(verbose_name=u'Entry title', max_length=200)
    # some more fields here
    tags_string = models.CharField(verbose_name=u'Tags', max_length=200, blank=True)
    tags = models.ManyToManyField(Tag, blank=True)

There is tags_string where user enters tags separated by comma. It's just a string.
Then I'm trying to add tags to ManyToManyField by clicking "Save" in Django admin:
def save(self):
    super(Entry, self).save()
    if self.tags_string:
        for tag in tags_string.split(","):
            t = Tag.objects.create(name=tag)
            self.tags.add(t)

but it doesn't work. entry.tags.add(t) works perfectly through the Django shell - it adds the values to the database. I think that something is wrong in my save() method.
Could you suggest me how to fix it, please?

A: try this
def save(self):
    super(Entry, self).save()
    if self.tags_string:
        for tag in tags_string.split(","):
            self.tags.create(name=tag)

A: Check the M2M tags format and print those?
def save(self):
   super(Entry, self).save()
   if self.tags_string:
       print self.tags,type(self.tags)
       for tag in tags_string.split(","):
          .......

A: First, save has additional parameters that you need to account for. Second, you should be using get_or_create instead of create for the tags:
def save(self, *args, **kwargs):
    super(Entry, self).save(*args, **kwargs)
    if self.tags_string:
        for tag in tags_string.split(","):
            t, created = Tag.objects.get_or_create(name=tag)
            self.tags.add(t)

Those may not fix the current issue, but it would have got you eventually.
You should also probably be doing some sort of normalization on the tags as well, using str.lower() or title() from django.template.defaultfilters. Otherwise, you'll end up with "Tag", "tag", "TAG" and "tAg".


text:
Q: Convergence of measurable functions in a locally compact space Set $(X,\mathcal{B})$ a measurable space. If $f:X\rightarrow[0,\infty)$ is a measurable function then exists a sequence of simple functions $\{s_n\}_{n\geq1}$ such that
$$0\leq s_1 \leq s_2\leq \ldots \leq s_n\leq\ldots\leq f$$
e
$$f(x)=\lim_{n\to\infty}s_n(x).$$
What happens if X is locally compact?
In this case, I can take for every $n\in\mathbb{N}$
$s_n(x)=\sum_{k=1}^mc_k{1}_{A_k}(x)$
where $A_k$ is compact?

A: This is not possible, except perhaps in cases where the topology of $X$ is somewhat degenerate. Recall that a subset $A$ of a topological space $X$ is said to be $F_\sigma$ if $A$ is a countable union of closed sets. If $X$ is an uncountable Polish space then there exist Borel subsets of $X$ which are not $F_\sigma$. I believe that this should be true in greater generality than Polish spaces, but I'm not sure what the right conditions are to guarantee the existence of such sets.
It is not hard to see that if $A \subseteq X$ is measurable, then you can find a sequence of simple functions as in your question for $f = \mathbf{1}_A$ only if $A$ is $F_\sigma$. Indeed, if we are to have $\lim_{n \to \infty} s_n(x) = \mathbf{1}_A(x)$ for all $x$ then we must eventually have $s_n(x) > 0$ for all $x \in A$. Since $0 \leq s_n \leq \mathbf{1}_A$ we always have $s_n(x) = 0$ for $x \notin A$. From this it follows that the union of the supports of $s_n$ is equal to $A$. Hence if the support of each $s_n$ is compact then $A$ is $F_\sigma$.


text:
Q: Web api netcore set Cors in appsettings.json file I'm using a webapi .netcore project.
I want to put all the cross settings in the appsettings.json file.
How do I do this?
This is my code:
 app.UseCors(x => x.WithOrigins("http://localhost:4200")
    .AllowCredentials()
    .WithHeaders("content-type")
    .WithMethods("GET", "POST", "PUT", "DELETE"));

A: If you want to set the CORS settings in appsettings.json and use the settings in startup.cs, you can follow the code below:
This is my appsettings.json:
{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*",
  "AllowedOrigins": "http://localhost:4200",
  "AllowedHeaders": "content-type",
  "AllowedMethods": "GET,POST,PUT,DELETE"
}

This is my partial code in startup.cs:
app.UseCors(x => x.WithOrigins(Configuration.GetSection("AllowedOrigins").Value.Split(","))
                  .AllowCredentials().WithHeaders(Configuration.GetSection("AllowedHeaders").Value.Split(","))
                  .WithMethods(Configuration.GetSection("AllowedMethods").Value.Split(",")));

app.UseHttpsRedirection();


text:
Q: MSBuild incremental build error I am facing one problem in building and copying .NET solution output to a deployment folder.
What i want to do is. Build solution and put the output into C:\TempOutput
then copy the outfiles from C:\TempOutput to another deployment folder.
at 1st attemp it creates folder in C:\TempOutput and creates output dlls and exes in this folder
also it creates folder "Exec\Debug\Bin" but does not copy files from C:\TempOutput
logs says that

Target CopyBuildFiles:
        Skipping target "CopyBuildFiles" because it has no outputs.

When i run the script again this time it copies the files from C:\TempOutput to "Exec\Debug\Bin"
Am i missing something? Why it is not detecting output at 1st attempt?
following is the msbuild script
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003" DefaultTargets="Deploy">

  <PropertyGroup>
    <ProjectName>Common Projects</ProjectName>
    <SolutionFilePath>..\..\Solution\Solution.sln</SolutionFilePath>

    <!--Build/Rebuild-->
    <BuildType>Build</BuildType>

    <!--Debug -> output : local-->
    <!--Release -> output : local-->
    <!--ProduDbg -> output : X:\Debug-->
    <!--ProduRel -> output : X:\Release-->

    <BuildMode>Debug</BuildMode>

    <OutputPath>..\Exec\$(BuildMode)\Bin\</OutputPath>
    <ExecPath>..\..\bin\$(BuildMode)</ExecPath>

    <DestinitionFolder>$(OutputPath)</DestinitionFolder>
    <SubDirPath>$(ExecPath)\**</SubDirPath>

    <BuildFolder>C:\TempOutputs\</BuildFolder>

  </PropertyGroup>

  <ItemGroup>
    <File Include="
          $(BuildFolder)\*.*
          "

          Exclude="
          $(BuildFolder)\*.vshost*
          "
          >

    </File>

  </ItemGroup>

  <Target Name="PreBuild">
    <MakeDir Directories="$(BuildFolder)" />
    <MakeDir Directories="$(DestinitionFolder)" />
  </Target>

  <Target Name="Compile">

    <MakeDir Directories="$(BuildFolder)" />
    <!-- Build does build only-->

    <Message Text="*******************************************************"/>
    <Message Text="-->Building $(ProjectName)"/>
    <Message Text="*******************************************************"/>

    <Message Text="*******************************************************"/>
    <Message Text="-->Building in [$(BuildMode) | $(BuildType)] mode"/>
    <Message Text="*******************************************************"/>

    <MSBuild Projects="$(SolutionFilePath)" Targets="$(BuildType)" Properties="Configuration=$(BuildMode);OutDir=$(BuildFolder)"/>
  </Target>

  <Target Name="CopyBuildFiles"
             Inputs="@(File)"
             Outputs=
          "@(File->'$(DestinitionFolder)%(RecursiveDir)%(Filename)%(Extension)')">

    <Copy SourceFiles="@(File)"
          DestinationFiles="@(File->'$(DestinitionFolder)%(RecursiveDir)%(Filename)%(Extension)')"
          />
  </Target>

  <Target Name="Deploy">

    <CallTarget Targets="PreBuild"/>
    <CallTarget Targets="Compile"/>

    <Message Text="*******************************************************"/>
    <Message Text="@(File)"/>
    <Message Text="$(DestinitionFolder)"/>
    <Message Text="*******************************************************"/>

    <CallTarget Targets="CopyBuildFiles"/>
  </Target>

</Project>

A: Try changing this bit
  <Target Name="CopyBuildFiles"
          Inputs="@(File)"
          Outputs="@(File->'$(DestinitionFolder)%(File.RecursiveDir)%(File.Filename)%(File.Extension)')">

      <Copy SourceFiles="@(File)"
            DestinationFiles="@(File->'$(DestinitionFolder)%(File.RecursiveDir)%(File.Filename)%(File.Extension)')"/>
   </Target>


text:
Q: How to add already available element in to fieldset of Magento? $button = Mage::app()->getLayout()->createBlock('adminhtml/widget_button');
$button->setData(array(
    'label' => $this->__('Some label'),
    'type' => 'submit',
    'class' => 'button'
));

I have the above mentioned code which creates a field element.Now I already have the following Fieldset
$fieldset = $form->addFieldset('display', array(
                    'legend'       => $helper->__('Connection Settings'),
                    'class'        => 'fieldset-wide'
            ));

How do I add the button to the field set.
Thank you,

A: This should do the trick:
$button = $this->getLayout()->createBlock('adminhtml/widget_button', '', array(
    'type'  => 'button',
    'label' => $this->__('Some label'),
    'class' => 'button'
));

$fieldset->addField('my_button', 'note', array(
    'text' => $button->toHtml()
));


text:
Q: GoCD: How to define a pipeline's entire workspace as an artifact for the next stage? Using GoCD, how can I define a stage's entire workspace (as a single artifact) for the next stage? This would highly simplify my setup, in which the second stage needs to fetch many different artifacts from the previous one.
I have tried the following artifact declarations:

*

*Artifact source = .
This causes an error already during the upload in the first stage:
[go] The rule [.] cannot match any resource under [pipelines/mypipeline]
[go] [go] Uploading finished. Failed to upload [.]

*Artifact source = *
This does not cause errors, but causes a separate upload for each directory in the root folder, instead of a single artifact of the entire workspace. As a result, I still need to fetch multiple concrete artifacts, instead of one big workspace artifact.
[go] Uploading artifacts from /var/lib/go-agent/pipelines/mypipeline/.svn to [defaultRoot]
[go] Uploading artifacts from /var/lib/go-agent/pipelines/mypipeline/cruise-output to [defaultRoot]
[go] Uploading artifacts from /var/lib/go-agent/pipelines/mypipeline/<dir1> to [defaultRoot]
[go] Uploading artifacts from /var/lib/go-agent/pipelines/mypipeline/<...> to [defaultRoot]
[go] Uploading artifacts from /var/lib/go-agent/pipelines/mypipeline/<dirN> to [defaultRoot]

I could probably zip everything myself with another task and define that as an artifact, but with GoCD already zipping and unzipping on its onw, I thought there must be a simpler solution to my problem.

A: I am not an expert, just a newbie with GoCD, but having gone through the same pain of trial and error, I'll share the syntax I found to work from my experience. For build artifacts in an upstream pipeline:

*

*Source: #{BUILD_DIR}/*.whl - it seems wild card syntax works when defining build artifacts; NOTE: the values between the curly braces {XXX_XX} are pipeline parameters.

*Destination: #{ARTIFACT_DIR} - I prefer to put all my artifacts in a separate folder as it is easier to fetch. GoCD will zip and transfer the folder and unzip it in the downstream pipeline.

In downstream pipeline or another stage in the same pipeline when retrieving artifacts using "Fetch Artifact" task:

*

*Source: #{ARTIFACT_DIR} - I use only the directory name to fetch the entire directory

*Destination ./ - the fetched directory will be extracted in current folder in this case

NOTE: The above syntax is for fetching directory of artifacts only where the Source is a file(Not a directory) checkbox in the "Fetch Artifact Task" is not selected.
I was not able to fetch artifact files when I tried parametrizing a file name with pipeline parameters or environment variables (for example my file artifact contained a dynamically generated version) and I did not find anything in the GoCD documentation or examples suggesting it is possible. The docs have example of downloading a file name that is a constant and does not change.
Please share examples of parametrizing file artifacts if possible or suggested workarounds if possible at all.