text:
Q: Insert Stored Procedure, Using Asp.Net WebForm to Insert new [Customer] Can someone please help me create a stored procedure to insert a new customer from a web form.
I am having difficulty making the state a drop down list for customer to pick a state from the list and having that inserted into the database.
                    INSERT INTO Customer
                    (
                    Cust_First,
                    Cust_Middle,
                    Cust_Last,
                    Cust_Phone,
        Cust_Alt_Phone,
                    Cust_Email,
                    Add_Line1,
                    Add_Line2,
                    Add_Bill_Line1,
                    Add_Bill_Line2,
                    City,
                    State_Prov_Name,
                    Postal_Zip_Code,
                    Country_ID
                    )

                    VALUES
                    (
                    @Cust_First,
                    @Cust_Middle,
                    @Cust_Last,
                    @Cust_Phone,
        @Cust_Alt_Phone,
                    @Cust_Email,
                    @Add_Line1,
                    @Add_Line2,
                    @Add_Bill_Line1,
                    @Add_Bill_Line2,
                    @City,
                    @State_Prov_Name,
                    @Postal_Zip_Code,
                    @Country_ID
                    )">

        <InsertParameters>
            <asp:Parameter Name="Cust_First" Type="String"></asp:Parameter>
            <asp:Parameter Name="Cust_Middle" Type="String"></asp:Parameter>
            <asp:Parameter Name="Cust_Last" Type="String"></asp:Parameter>
            <asp:Parameter Name="Cust_Phone" Type="String"></asp:Parameter>
            <asp:Parameter Name="Cust_Alt_Phone" Type="String"></asp:Parameter>
            <asp:Parameter Name="Cust_Email" Type="String"></asp:Parameter>
            <asp:Parameter Name="Add_Line1" Type="String"></asp:Parameter>
            <asp:Parameter Name="Add_Line2" Type="String"></asp:Parameter>
            <asp:Parameter Name="Add_Bill_Line1" Type="String"></asp:Parameter>
            <asp:Parameter Name="Add_Bill_Line2" Type="String"></asp:Parameter>
            <asp:Parameter Name="City" Type="String"></asp:Parameter>
            <asp:Parameter Name="Postal_Zip_Code" Type="String"></asp:Parameter>
            <asp:Parameter Name="Cust_ID" Type="Int32"></asp:Parameter>
            <asp:Parameter Name="State_Prov_Name" Type="String"></asp:Parameter>
            <asp:Parameter Name="Country_Name" Type="String"></asp:Parameter>
        </InsertParameters>


text: Q: How can my Azure App Services use more outbound IP addresses? My collection of app services in Azure have several web jobs that run behind-the-scenes and consume an external, third-party api via the web. This third-party api throttles me by my IP address. As my app is growing, I am scaling out and even separating modules out into separate app services. However, even with separate app services, each app service and scale out instance uses the same set of outbound IP addresses. So no matter how much I scale out, I am still throttled the same by this external api. I am getting more and more customers, and I am starting to get more and more timeouts from this external api. Is there a way to configure each of my app services to use a different set of outbound IPs? Or, am I able to have more than 4 separate outbound IP addresses assigned to an app service?

redpajama_set_name: RedPajamaStackExchange


text:
Q: auto download .dmg files in selenium firefox webdriver I am trying to download files through selenium firefox webdriver. I was able to configure firefox such that there is no pop up to save the file when downloading for all file formats except .dmg files. I have worked around this but was not able to figure out the solution. Below is my firefox webdriver configuration:

BroswerProfile.set_preference ( "browser.helperApps.alwaysAsk.force", False )
      BroswerProfile.set_preference("browser.helperApps.neverAsk.saveToDisk","application/x-msdownload,application/x-7z-compressed,application/zip,application/vnd.ms-cab-compressed,application/vnd.ms-artgalry,application/x-msaccess,application/octet-stream,application/x-apple-diskimage,dmg application/octet-stream")
      BroswerProfile.set_preference("browser.download.manager.alertOnEXEOpen", False);
      BroswerProfile.set_preference("browser.download.manager.focusWhenStarting", False);
      BroswerProfile.set_preference("browser.download.manager.useWindow", False);
      BroswerProfile.set_preference("browser.download.manager.showAlertOnComplete", False);
      BroswerProfile.set_preference("browser.download.manager.closeWhenDone", False);
      #set path to download directory
      BroswerProfile.set_preference("browser.download.folderList", 2)
      BroswerProfile.set_preference("browser.download.dir", downloadpath)

A: I think you need to add mime type for that .dmg files. use httpfox add-on in firefox
  https://addons.mozilla.org/en-US/firefox/addon/httpfox/

in Type column it will display type of dmg files and add same in set preference.
Thank You,
Murali


text:
Q: A more recent version of _catalogs/masterpage... has been saved by Test_User on 4-20-2015. page not saved I have edited my Master Page and trying to save it but a message shown by this dialog box. But this file is not replacing my updated code.
please ignore my bad English


text:
Q: Powershell Winforms - handling window-events Code doesn't work as expected. ShowDialog() is blocking thread. Events aren't handled. How can I make this work? Window has to close after 3 times clicking. Window may or may not run in a separate thread. Mainloop(write-host $x) has to run while window can handle mouseclick-events.
function myform{
        $m=0
        $fr = New-Object -TypeName System.Windows.Forms.Form
        $ev = Register-ObjectEvent -InputObject $fr -EventName Mouseclick -Action {
            $m++
            if($m -ge 3){
                $fr.Close()
                }
            }
        $fr.Activate()
        $fr.ShowDialog()
    }
    #$myjob = Start-Job $Function:myform
    $myjob
    $x = 0
    myform

    while($x -lt 3){
        $x++
        write-host $x
        Start-Sleep 2
        }
    Stop-Job -id $myjob.id


text:
Q: Why am I getting an error when calling fixHeight method in Smartwizard? I am adding some dynamic content during the showStep event of a Smart Wizard form (I create some DIVS), and I would like to resize the step accordingly.
I am calling it like this :
$("#smartwizard").on("showStep", function (e, anchorObject, stepIndex, stepDirection, stepPosition) {
//When loading STEP3, add a new empty row
if (stepIndex == 2){
    //addNewRow();
    $("#smartwizard").smartWizard('fixHeight');
}

}
This causes the following error
jquery.smartWizard.min.js:12
Uncaught TypeError: Cannot read properties of null (reading 'outerHeight')
at n.value (jquery.smartWizard.min.js:12:8279)
at n.value (jquery.smartWizard.min.js:12:12392)
at l.fn.smartWizard (jquery.smartWizard.min.js:12:12778)
at HTMLDivElement.<anonymous> (new:2147:35)
at HTMLDivElement.dispatch (jquery-3.6.1.js:5430:27)
at elemData.handle (jquery-3.6.1.js:5234:28)
at Object.trigger (jquery-3.6.1.js:8745:12)
at HTMLDivElement.<anonymous> (jquery-3.6.1.js:8823:17)
at Function.each (jquery-3.6.1.js:385:19)
at jQuery.fn.init.each (jquery-3.6.1.js:207:17)

How can I fix it? Thank you.


text:
Q: How to create default Vuex state with proper isLoading property I have created actions that I dispatch directly in the store.js file in order to create a 'default' state. I have a default state property:
isLoading: false

I dispatch an action that makes multiple commits with payloads:
import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'

Vue.use(axios)
Vue.use(Vuex)

const store = new Vuex.Store({
  strict: true,
  state: {
    projects: null,
    posts: null,
    isLoading: false,
    baseUrl: 'https://example.com/v2/'
  },
  getters: {

  },
  mutations: {
    SET_PROJECTS (state, payload) {
      state.projects = payload;
    },
    SET_POSTS (state, payload) {
      state.posts = payload;
    },
    IS_LOADING (state, payload) {
      state.isLoading = payload;
    }
  },
  actions: {
    setProjects ({ commit, state }) {
      let uri = `${state.baseUrl}projects`;

      commit('IS_LOADING', true);

      axios.get(uri).then((response) => {
        commit('SET_PROJECTS', response.data);
      }).finally(commit('IS_LOADING', false));
    },
    setPosts ({ commit, state }) {
      let uri = `${state.baseUrl}posts?per_page=100`;

      commit('IS_LOADING', true);

      axios.get(uri).then((response) => {
        commit('SET_POSTS', response.data);
      }).finally(commit('IS_LOADING', false));
    }
  }
})

store.dispatch('setProjects');
store.dispatch('setPosts');

export default store

My IS_LOADING commits seem to never happen and the mutations are not being recorded in the Vue devtools Vuex section. My SET_POSTS and SET_PROJECTS commits happen and are recorded.
I am accessing isLoading in a couple components via ...mapState and isLoading is attached to a Buefy component :
<template>

{{project.title.rendered}}

          Lorem ipsum dolor sit amet, consectetur adipiscing elit.
          Phasellus nec iaculis mauris. @bulmaio.
          #css #responsive

          <time datetime="2016-1-1">11:09 PM - 1 Jan 2016</time>

</template>

The point is to render an animated loading wheel on the components that are needing the data from the api. So, why are my IS_LOADING mutations not working? Any help is appreciated.
I would like keep the dispatch calls in the store.js file. The API data is needed in multiple places within the site, so it makes sense to me to dispatch the actions in store.js.
With that I am new to Vue and Vuex, so please let me know where I am not implementing best practices.

A: finally takes a function and not a value.
Your current code now immediately executes the commit('IS_LOADING', false) so the state never changes...
The fix is simple just use a function in your finally:
setProjects ({ commit, state }) {
  let uri = `${state.baseUrl}projects`;

  commit('IS_LOADING', true);

  axios.get(uri).then((response) => {
    commit('SET_PROJECTS', response.data);
  }).finally(() => commit('IS_LOADING', false));
},


text:
Q: Cloudfront redirecting to S3 endpoint with 307 Temporary Redirect I'm getting cloudfront endpoint redirecting to S3 with 307 Temporary Redirect. Is there a reason why this is happening?
I've tried creating website endpoint and changed the origin but no luck with same result.

A: The Temporary Request Redirection It's actually caused by the way S3 buckets behave when they are newly-created (thanks to @Michael-sqlbot) for clarifying this.
From the docs (Temporary Request Redirection)

Due to the distributed nature of Amazon S3, requests can be temporarily routed to the wrong facility. This is most likely to occur immediately after buckets are created or deleted. For example, if you create a new bucket and immediately make a request to the bucket, you might receive a temporary redirect, depending on the location constraint of the bucket.

A: Change your Origin Domain Name to bucketname.s3-region.amazonaws.com per the docs:

If you're using an Amazon CloudFront distribution with an Amazon S3 origin, CloudFront forwards requests to the default S3 endpoint (s3.amazonaws.com), which is in the us-east-1 Region. If you must access Amazon S3 within the first 24 hours of creating the bucket, you can change the Origin Domain Name of the distribution to include the regional endpoint of the bucket. For example, if the bucket is in us-west-2, you can change the Origin Domain Name from bucketname.s3.amazonaws.com to bucketname.s3-us-west-2.amazonaws.com.


text:
Q: Is there a way to make an exception for the beforeunload method? I would like to make an exception for the beforeunload event in javascript. I mean exception as in that I would like to exclude a url or form button from this not in the sense of an error handling exception. I will post my relavant javascript code right now.
if(loggedin == 1){
    $(window).bind('click', function(event) {
        if(event.target.href) $(window).unbind('beforeunload');
    });
    $(window).bind('beforeunload', function(event) {
        $('div.offerWindow').css("visibility", "visible");
        return 'Press "Stay on Page" and get a special offer!';
    });

    function Close(){
        $('div.offerWindow').css("visibility", "hidden");
    };
}

The site is at http://www.redlakewalleye.com when in the shopping cart where this javascript is. The site then redirects to https://redlakefisheries.worldsecuresystems.com/OrderRetrievev2.aspx... when the checkout button is clicked. I need to make an exception for this url, I am not sure if it would be a paremeter or what. Any help or alternate solutions would be awesome.

A: If I understand this correctly, then: in that button's onclick simply unbind the onbeforeunload event for the window.
Edit:
In your code above you "bind" (or set) the beforeunload event handler:
$(window).bind('beforeunload', function(event) {
    $('div.offerWindow').css("visibility", "visible");
    return 'Press "Stay on Page" and get a special offer!';
});

So, in the onclick event handler for the button in question (you have that code somewhere) you "unbind" the above:
$(window).unbind('beforeunload');

I think that's all.


text:
Q: Bash script hand over input instead of exit Is there a way to have a bash script hand over execution to the user in its current state upon exiting?  For example, I would a script that logs into an FTP server with "nc ip-address 21", runs a couple of commands, and then hands over an already initiaed FTP shell to the user.  Is this possible?

A: if all you want is auto login, use ncftp... it supports auto login and scripting for ftp

A: You can add a cat command at the end of a piped input, but then make sure to start bash interactive (-i option) in order to be shown the prompt:
Example with an echo and a list command, then accepting user input
( echo '
echo "these commands are piped before user input begins"
ls -lrt /directory/you/want/to/show/the/contents/of/before/user/input/begins/
' ; cat) | bash -i

btw, I use it to define functions in bash.
Possibly, you may have to adjust the ftp program to accept ordinary standard input, but if that is the case, it would probably accept your commands anyway.


text:
Q: How do I bind a function to a Backbone Router? I am trying to bind my router to a method in my router.  Here is the router:
define(function(require) {

  var Backbone = require('backbone');
  var User = require('models/user.model');

  var Router = Backbone.Router.extend({
    user: null,

    initialize: function() {
      _.bind(this.updateUser, this);
      Backbone.on('userAuthenticated', this.updateUser);

      this.user = new User();
      this.user.fetch();
    },

    updateUser: function() {
      debugger;
    }
  });

  return Router;
});

I am binding the method updateUser to my router.  When the event userAuthenticated is triggered, then I want to run the code in updateUser.  The event gets thrown and the method gets called, but when I get into the updateUser method, my this is not the router like I expect, but the global object.  What am I doing wrong?

A: I pointed out in a couple comments that _.bind() returns a new function, which your example doesn't assign to anything.  However, a simpler solution would be to use the optional third argument to on():
Backbone.on('userAuthenticated', this.updateUser, this);

Backbone documentation


text:
Q: I need Java Custom Autoboxing Is it possible to define custom autoboxing in Java?
I need to automatically convert java.lang.Number into my class org.expr.NumberExpression when typing parameters of a function. For two parameters, I ended up writing four very similar methods:
public class Assemble {

  public NumberExpression add(NumberExpression a, NumberExpression b) {
    // do something
  }

  public NumberExpression add(NumberExpression a, Number b) {
    return add(a, new NumberConstant(b));
  }

  public NumberExpression add(Number a, Number b) {
    return add(new NumberConstant(a), new NumberConstant(b));
  }

  public NumberExpression add(Number a, NumberExpression b) {
    return add(new NumberConstant(a), b);
  }

}

So I can type:
assemble.add(5, assemble.add(7, 3));
assemble.add(5, assemble.add(7, 3), 8, 15); // does not work

However, I think this becomes unmanageable for 10 parameters (that I wanted to do); I guess I would need to write 1024 similar methods.
The other solution I was thinking about is to write a method like:
  public NumberExpression add(NumberExpression... numbers) {
    // do something
  }

But would I be able to type Number and NumberExpression mixed together as parameters?

A: *

*As people said it can't be done

*How your problem usually solved is you wrap the values yourself and have only one method (look at BigDecimal)

assemble.add(
    new IntegerConstant(5),
    assemble.add(new IntegerConstant(7), new IntegerConstant(3))

or using a factory:
assemble.add(
    NumberExpression.of(5),
    assemble.add(NumberExpression.of(7), NumberExpression.of(3))

where:
   class NumberExpression {
       public static IntegerConstant of(Integer v) {
           //...
       }

       public static DoubleConstant of(Double v) {
           //...
       }
    }

A: No, you can't define custom autoboxing


text:
Q: Vagrant to use Puppet modules In order to install Puppet modules you need Puppet installed. To install Puppet you need a Puppet Master. I'm using Windows, Puppet Master does not install for Windows. What should I do? I just need to install a Puppet module so that I can use it when provisioning a vagrant instance.

A: First you have to chose puppet architecture. Master-agent architecture in puppet is recommended approach but you can also use stand-alone architecture. So you don't have to install puppet master.
If you are using vagrant, you can create shell script, to provision guest machine, which will install and setup standalone puppet, or just setup a puppet provisioner.
With puppet provisioner, remember to setup module_path (Path, on the host, to the directory which contains Puppet modules, if any).
Last but not least, you don't need a puppet on host machine to "install" a puppet module. Just download latest tar.gz (e.g for mysql module) package with that module, and extract in to the directory pointed by module_path.


text:
Q: OpenCV compiled with CUDA support usable without CUDA? I've just compiled openCV (2.4.7) with Cuda and OpenCL support. Now we have another version (2.4.6) already in use, which was compiled without cuda and openCL support. I would like to replace the older binaries with the new ones.
Now I have the problem/question: Can I "deliver" the binaries (2.4.7) that were compiled with cuda support, without any problems instead of the old (2.4.6) binaries (that were compiled without cuda etc.), if I don't use any functionality from gpu or ocl? Or do they have any dependencies that could lead into problems?
Thank you for your help!
Mike

A: First of all you must consider if the functions you are using in openCV lib in 2.4.6 are defined with the same way as in 2.4.7. I think this has to do with the backward compatibility and I think you are ok as far as this concept. Now If you are gone to use cuda build opencv maybe cudart.dll is probably needed. Maybe some other .ddl form the cuda sdk is also needed. According to my knowledge in the past I had to use opencvcore and opencvhighgui dlls (not gpu dll) and the cuda sdk dlls was needed.
I hope that helps, If I understand correctly you question.
PS: Sorry for the not exactly mentioned dll file names. I do not have access to the lib files for these days.


text:
Q: Wordpress — Replace TinyMCE with TEXTAREA? I'm using Wordpress with TinyMCE.
What a piece of junk TinyMCE is!
TinyMCE reformats my HTML, including by removing all of the p tags. I've even chosen the wordpress option to have it to not do that. Doesn't work.
Sometimes, TinyMCE doubles sections of content or completely changes the HTML source to be totally broken.
How can I replace TinyMCE with TEXTAREA? I just want to type my HTML code in and not have it be damaged by the plugin.


text:
Q: Check if SSH Private Key is Encrypted Key pairs generated with ssh-keygen on macOS can have different formats.

*

*The standard PEM ASN.1 object which is readable by macOS' SecKey APIs

*A PEM with textual headers

*OpenSSH Keys

*OpenSSH Encrypted Keys

OpenSSH/BSD uses this non-standardized format here.
Now I only need to be able to check if a private key has a passphrase set or not, so I can prompt the user to enter it, without having to deal with the complexities of different key formats.
Is there a quick way on macOS via Swift or C API, to check if a key has a passphrase set?

A: The difference between the unencrypted and encrypted private keys is the fact that the key blob is encrypted.  You need to decrypt the private key blob data before you can use the private key blob.  So once the encrypted private key data is decoded, you can treat it the same as the unencrypted private key data.
A unencrypted private key blob PEM file looks like this:
—–BEGIN PRIVATE KEY—–
{base64 private key blob)
—–END PRIVATE KEY—–

The encrypted RSA private key PEM file looks like this:
—–BEGIN RSA PRIVATE KEY—–
Proc-Type: 4,ENCRYPTED
DEK-Info: {encryption algorithm},{salt}
{base64 encrypted private key blob)
—–END RSA PRIVATE KEY—–

e.g.
—–BEGIN RSA PRIVATE KEY—–
Proc-Type: 4,ENCRYPTED
DEK-Info: AES-256-CBC,AB8E2B5B2D989271273F6730B6F9C687
{base64 encrypted private key blob)
—–END RSA PRIVATE KEY—–

So to decode the private key data you need to:

*

*Parse the DEK-Info encryption algorithm and the salt (good idea to confirm the first line is: "Proc-Type: 4,ENCRYPTED" as well).

*Decode the base64 encrypted private key blob.

*Generate the encryption algorithm "key" and "IV" based on the salt and the passphrase

*Decode the encrypted private key blob.

Once you have done that the decrypted private key blob can be treated just like the unencoded private key blob.
The number of supported encryption algorithm's are rather large, so you may like to support a sub-set of algorithms. e.g. "DES-EDE3-CBC", "AES-xxx-CBC", etc
To generate the IV you need to convert salt string to binary.  The salt string is a hex encoded string, so convert each two strings characters into a byte using a hex string character to byte converter.
For the generation of the encryption algorithm key you need the key size (e.g. DES-EDE3-CBC is 192bits, AES-256-CBC is 256bits). Build up the key "bits" with a loop appending MD5 hash results to the key until generate all the key bits required.
The MD5 HASH loop generation will consist of:

*

*First MD5 Hash: MD5 hash of the first 8 bytes of the IV and the Passphrase

*All other MD5 Hashes is the MD5 hash of the last MD5 hash result and the first 8 bytes of the IV and the Passphrase

See the openssl source for EVP_BytesToKey method for an example of the key bits generation.
The encrypted private key blob can now be decoded using the selected encryption algorithm using the IV and KEY build above.

A: There are two ways that I would suggest. Either reading the command line output using readLine() and checking if it asks for a password then do something accordingly.
import Foundation

func runCommand(cmd : String, args : String...) -> (output: [String], error: [String], exitCode: Int32) {

    var output : [String] = []
    var error : [String] = []

    let task = Process()
    task.launchPath = cmd
    task.arguments = args

    let outpipe = Pipe()
    task.standardOutput = outpipe
    let errpipe = Pipe()
    task.standardError = errpipe

    task.launch()

    let outdata = outpipe.fileHandleForReading.readDataToEndOfFile()
    if var string = String(data: outdata, encoding: .utf8) {
        string = string.trimmingCharacters(in: .newlines)
        output = string.components(separatedBy: "\n")
    }

    let errdata = errpipe.fileHandleForReading.readDataToEndOfFile()
    if var string = String(data: errdata, encoding: .utf8) {
        string = string.trimmingCharacters(in: .newlines)
        error = string.components(separatedBy: "\n")
    }

    task.waitUntilExit()
    let status = task.terminationStatus

    return (output, error, status)
}

//Sample usage

let (output, error, status) = runCommand(cmd: "/usr/local/bin/node", args: "--version")
print("program exited with status \(status)")
if output.count > 0 {
    print("program output:")
    print(output)
    //HERE YOU CAN CHECK IF PASSWORD REQUEST HAS BEEN MADE
}
if error.count > 0 {
    print("error output:")
    print(error)
}

The example code will return your node version installed if there is one, but you could use it to check if a password prompt has been made by the system for the RSA Key.
The other way could be perhaps using a third-party library like SwiftyRSA or BlueRSA which might help with validation.

A: I implemented my own OpenSSH check for the 2 most common formats

*

*For one I'm checking the PEM headers for DEK-Info for Linux-style SSH PEMs

*For OpenSSH style keys I manually parse the format using the class below

import Foundation

private let opensshMagic = "openssh-key-v1"

public class SSHPrivateKey {

    public struct OpenSSHKey {
        let cipherName: String
        let kdfName: String
        let kdfOptions: Data
        let numKeys: Int

        var isEncrypted: Bool {
            return cipherName != "none"
        }
    }

    public let data: Data

    public init(data: Data) {
        self.data = data
    }

    public func openSSHKey() -> OpenSSHKey? {
        // #define AUTH_MAGIC      "openssh-key-v1"
        //
        // byte[]  AUTH_MAGIC
        // string  ciphername
        // string  kdfname
        // string  kdfoptions
        // int     number of keys N
        // string  publickey1
        // string  publickey2
        // ...
        // string  publickeyN
        // string  encrypted, padded list of private keys

        guard let magic = opensshMagic.data(using: .utf8) else {
            return nil
        }

        if data.prefix(magic.count) != magic {
            return nil
        }

        var offset = magic.count + 1

        guard let cipherName = data.consumeString(offset: &offset),
            let kdfName = data.consumeString(offset: &offset) else {
                return nil
        }

        let kdfOptions = data.consumeBytes(offset: &offset)
        let numKeys = data.consumeUInt32(offset: &offset)

        return OpenSSHKey(cipherName: cipherName,
                          kdfName: kdfName,
                          kdfOptions: kdfOptions,
                          numKeys: Int(numKeys))
    }
}

private extension Data {

    func consumeBytes(offset: inout Int) -> Data {
        let n = Int(consumeUInt32(offset: &offset))
        let b = Data(self[offset..<offset + n])
        offset += n
        return b
    }

    func consumeString(offset: inout Int) -> String? {
        return consumeBytes(offset: &offset).utf8String
    }

    func consumeUInt8(offset: inout Int) -> UInt8 {
        let v = self[offset] & 0xFF
        offset += 1

        return v
    }

    func consumeUInt32(offset: inout Int) -> UInt32 {
        var i: UInt32 = 0

        i = (i << 8) | UInt32(consumeUInt8(offset: &offset))
        i = (i << 8) | UInt32(consumeUInt8(offset: &offset))
        i = (i << 8) | UInt32(consumeUInt8(offset: &offset))
        i = (i << 8) | UInt32(consumeUInt8(offset: &offset))

        return i
    }
}


text:
Q: How can i solve Application Error caused after deploying my model on Heroku using Flask? The application runs perfectly on the local computer, but after deployment to the Heroku, I am getting an application error when I try to open the application in my browser. Checked the log file and solved some minor problems myself, but I can not go further now. What I have done before deployment:

*

*pip install gunicorn

*pip freeze > requirements.txt

*Created procfile and inside I wrote web: gunicorn app:app

*heroku login

*git init

*heroku git:remote -a my-application

*git add .

*git commit -am "1"

*git push heroku master

2020-10-30T21:02:37.970885+00:00 app[web.1]: worker.init_process()
2020-10-30T21:02:37.970885+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/workers/base.py", line 119, in init_process
2020-10-30T21:02:37.970886+00:00 app[web.1]: self.load_wsgi()
2020-10-30T21:02:37.970886+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/workers/base.py", line 144, in load_wsgi
2020-10-30T21:02:37.970886+00:00 app[web.1]: self.wsgi = self.app.wsgi()
2020-10-30T21:02:37.970888+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/app/base.py", line 67, in wsgi
2020-10-30T21:02:37.970888+00:00 app[web.1]: self.callable = self.load()
2020-10-30T21:02:37.970888+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/app/wsgiapp.py", line 49, in load
2020-10-30T21:02:37.970888+00:00 app[web.1]: return self.load_wsgiapp()
2020-10-30T21:02:37.970889+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/app/wsgiapp.py", line 39, in load_wsgiapp
2020-10-30T21:02:37.970889+00:00 app[web.1]: return util.import_app(self.app_uri)
2020-10-30T21:02:37.970890+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/util.py", line 358, in import_app
2020-10-30T21:02:37.970890+00:00 app[web.1]: mod = importlib.import_module(module)
2020-10-30T21:02:37.970890+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/importlib/__init__.py", line 126, in import_module
2020-10-30T21:02:37.970891+00:00 app[web.1]: return _bootstrap._gcd_import(name[level:], package, level)
2020-10-30T21:02:37.970892+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 994, in _gcd_import
2020-10-30T21:02:37.970892+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 971, in _find_and_load
2020-10-30T21:02:37.970892+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
2020-10-30T21:02:37.970893+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 665, in _load_unlocked
2020-10-30T21:02:37.970893+00:00 app[web.1]: File "<frozen importlib._bootstrap_external>", line 678, in exec_module
2020-10-30T21:02:37.970893+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
2020-10-30T21:02:37.970894+00:00 app[web.1]: File "/app/app.py", line 2, in <module>
2020-10-30T21:02:37.970894+00:00 app[web.1]: from main import views
2020-10-30T21:02:37.970894+00:00 app[web.1]: File "/app/main/views.py", line 5, in <module>
2020-10-30T21:02:37.970895+00:00 app[web.1]: from main.utils import pipeline_model
2020-10-30T21:02:37.970895+00:00 app[web.1]: File "/app/main/utils.py", line 6, in <module>
2020-10-30T21:02:37.970896+00:00 app[web.1]: import cv2
2020-10-30T21:02:37.970897+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/cv2/__init__.py", line 5, in <module>
2020-10-30T21:02:37.970897+00:00 app[web.1]: from .cv2 import *
2020-10-30T21:02:37.970905+00:00 app[web.1]: ImportError: libGL.so.1: cannot open shared object file: No such file or directory
2020-10-30T21:02:37.973156+00:00 app[web.1]: [2020-10-30 21:02:37 +0000] [10] [INFO] Worker exiting (pid: 10)
2020-10-30T21:02:38.493246+00:00 app[web.1]: [2020-10-30 21:02:38 +0000] [11] [ERROR] Exception in worker process
2020-10-30T21:02:38.493257+00:00 app[web.1]: Traceback (most recent call last):
2020-10-30T21:02:38.493259+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/arbiter.py", line 583, in spawn_worker
2020-10-30T21:02:38.493259+00:00 app[web.1]: worker.init_process()
2020-10-30T21:02:38.493260+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/workers/base.py", line 119, in init_process
2020-10-30T21:02:38.493260+00:00 app[web.1]: self.load_wsgi()
2020-10-30T21:02:38.493261+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/workers/base.py", line 144, in load_wsgi
2020-10-30T21:02:38.493261+00:00 app[web.1]: self.wsgi = self.app.wsgi()
2020-10-30T21:02:38.493262+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/app/base.py", line 67, in wsgi
2020-10-30T21:02:38.493262+00:00 app[web.1]: self.callable = self.load()
2020-10-30T21:02:38.493263+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/app/wsgiapp.py", line 49, in load
2020-10-30T21:02:38.493263+00:00 app[web.1]: return self.load_wsgiapp()
2020-10-30T21:02:38.493263+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/app/wsgiapp.py", line 39, in load_wsgiapp
2020-10-30T21:02:38.493264+00:00 app[web.1]: return util.import_app(self.app_uri)
2020-10-30T21:02:38.493264+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/util.py", line 358, in import_app
2020-10-30T21:02:38.493264+00:00 app[web.1]: mod = importlib.import_module(module)
2020-10-30T21:02:38.493265+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/importlib/__init__.py", line 126, in import_module
2020-10-30T21:02:38.493265+00:00 app[web.1]: return _bootstrap._gcd_import(name[level:], package, level)
2020-10-30T21:02:38.493266+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 994, in _gcd_import
2020-10-30T21:02:38.493267+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 971, in _find_and_load
2020-10-30T21:02:38.493267+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
2020-10-30T21:02:38.493267+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 665, in _load_unlocked
2020-10-30T21:02:38.493268+00:00 app[web.1]: File "<frozen importlib._bootstrap_external>", line 678, in exec_module
2020-10-30T21:02:38.493268+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
2020-10-30T21:02:38.493269+00:00 app[web.1]: File "/app/app.py", line 2, in <module>
2020-10-30T21:02:38.493269+00:00 app[web.1]: from main import views
2020-10-30T21:02:38.493269+00:00 app[web.1]: File "/app/main/views.py", line 5, in <module>
2020-10-30T21:02:38.493270+00:00 app[web.1]: from main.utils import pipeline_model
2020-10-30T21:02:38.493270+00:00 app[web.1]: File "/app/main/utils.py", line 6, in <module>
2020-10-30T21:02:38.493271+00:00 app[web.1]: import cv2
2020-10-30T21:02:38.493271+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/cv2/__init__.py", line 5, in <module>
2020-10-30T21:02:38.493272+00:00 app[web.1]: from .cv2 import *
2020-10-30T21:02:38.493280+00:00 app[web.1]: ImportError: libGL.so.1: cannot open shared object file: No such file or directory
2020-10-30T21:02:38.494646+00:00 app[web.1]: [2020-10-30 21:02:38 +0000] [11] [INFO] Worker exiting (pid: 11)
2020-10-30T21:02:38.670078+00:00 app[web.1]: Traceback (most recent call last):
2020-10-30T21:02:38.670085+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/arbiter.py", line 209, in run
2020-10-30T21:02:38.670559+00:00 app[web.1]: self.sleep()
2020-10-30T21:02:38.670617+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/arbiter.py", line 357, in sleep
2020-10-30T21:02:38.671121+00:00 app[web.1]: ready = select.select([self.PIPE[0]], [], [], 1.0)
2020-10-30T21:02:38.671176+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/arbiter.py", line 242, in handle_chld
2020-10-30T21:02:38.671571+00:00 app[web.1]: self.reap_workers()
2020-10-30T21:02:38.671632+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/arbiter.py", line 525, in reap_workers
2020-10-30T21:02:38.672179+00:00 app[web.1]: raise HaltServer(reason, self.WORKER_BOOT_ERROR)
2020-10-30T21:02:38.672283+00:00 app[web.1]: gunicorn.errors.HaltServer: <HaltServer 'Worker failed to boot.' 3>
2020-10-30T21:02:38.672324+00:00 app[web.1]:
2020-10-30T21:02:38.672325+00:00 app[web.1]: During handling of the above exception, another exception occurred:
2020-10-30T21:02:38.672325+00:00 app[web.1]:
2020-10-30T21:02:38.672407+00:00 app[web.1]: Traceback (most recent call last):
2020-10-30T21:02:38.672450+00:00 app[web.1]: File "/app/.heroku/python/bin/gunicorn", line 8, in <module>
2020-10-30T21:02:38.672772+00:00 app[web.1]: sys.exit(run())
2020-10-30T21:02:38.672828+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/app/wsgiapp.py", line 58, in run
2020-10-30T21:02:38.673110+00:00 app[web.1]: WSGIApplication("%(prog)s [OPTIONS] [APP_MODULE]").run()
2020-10-30T21:02:38.673183+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/app/base.py", line 228, in run
2020-10-30T21:02:38.673593+00:00 app[web.1]: super().run()
2020-10-30T21:02:38.673651+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/app/base.py", line 72, in run
2020-10-30T21:02:38.673950+00:00 app[web.1]: Arbiter(self).run()
2020-10-30T21:02:38.674006+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/arbiter.py", line 229, in run
2020-10-30T21:02:38.674395+00:00 app[web.1]: self.halt(reason=inst.reason, exit_status=inst.exit_status)
2020-10-30T21:02:38.674451+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/arbiter.py", line 342, in halt
2020-10-30T21:02:38.674927+00:00 app[web.1]: self.stop()
2020-10-30T21:02:38.674986+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/arbiter.py", line 393, in stop
2020-10-30T21:02:38.675477+00:00 app[web.1]: time.sleep(0.1)
2020-10-30T21:02:38.675534+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/arbiter.py", line 242, in handle_chld
2020-10-30T21:02:38.675933+00:00 app[web.1]: self.reap_workers()
2020-10-30T21:02:38.675990+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/arbiter.py", line 525, in reap_workers
2020-10-30T21:02:38.676549+00:00 app[web.1]: raise HaltServer(reason, self.WORKER_BOOT_ERROR)
2020-10-30T21:02:38.676613+00:00 app[web.1]: gunicorn.errors.HaltServer: <HaltServer 'Worker failed to boot.' 3>
2020-10-30T21:02:38.760092+00:00 heroku[web.1]: Process exited with status 1
2020-10-30T21:02:38.805325+00:00 heroku[web.1]: State changed from up to crashed
2020-10-30T21:03:14.847423+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=face-1907.herokuapp.com request_id=9cc9542b-0ea0-481c-b2bd-29b1cc407769 fwd="88.252.193.107" dyno= connect= service= status=503 bytes= protocol=https

A: It seems like the cv2 module is missing. You can install these missing libraries taking advantage of the heroku-buildpack-apt.
At the time of this writing, I have successfully done it for this repo, hosted here, with the following steps:

*

*Add heroku-buildpack-apt to your buildpacks on Heroku platform

*Create a file named Aptfile and add the following libs: libsm6, libxrender1, libfontconfig1, libice6 (one per line). Example here.


text:
Q: How to pass more than one value within dispatch in redux I am using redux in my react native app to manage cart item when add and remove, so when i want to add item to cart i am using the following:
const dispatch = useDispatch()
const addItemToCart = item => dispatch({ type: 'ADD_TO_CART', payload: item })

and here is the button when it pressed the above dispatcher is triggered:
  <TouchableOpacity onPress={() => { addItemToCart(itemData, total) }} >
              <Text style={{ ...FONTS.h5 }}>Add to cart</Text>
               <Icon
                     name="cart-outline"
                     size={25}
                     color={COLORS.black}
                      backgroundColor={COLORS.primary2}

                  />
        </TouchableOpacity>

so here i am passing itemData, total to dispatcher which should be passed to cart.
and the following is the reducers:
const initialState = []

const cartItemsReducer = (state = initialState, action) => {
    switch (action.type) {
        case 'ADD_TO_CART':
            return [...state, action.payload]
        case 'REMOVE_FROM_CART':
            return state.filter(cartItem => cartItem.id !== action.payload.id)
    }
    return state
}

export default cartItemsReducer

So, what I want is that the two passed values to be received in cartscreen and in cart screen I did the following to check if both two values are received or not:
  cartItems = useSelector(state => state)
    console.log("cart item: ", cartItems)

but only get itemData and  total is not passed.
What I can do to make both two values are passed?

A: You are not passing the second parameter to the dispatcher, as your dispatcher only intakes one argument
const addItemToCart = item => dispatch({ type: 'ADD_TO_CART', payload: item })

If you wanna pass two parameters, then just modify your fn to
const addItemToCart = (item, total) => dispatch({ type: 'ADD_TO_CART', payload: { item, total } })

And then in your reducer, instead of having action.payload you will have action.payload.item, action.payload.total.


text:
Q: Displaying a loading animation during a vue js function A simple show and hide on the loading element is failing during the Vue js function execution.
I have a vue js function which will do some things and update the data when it's done.  I'm trying to show a loading animation during this process.  I've dummied the process down to a simple loop for the purposes of this discussion to eliminate all other issues (i.e ajax, async, etc.).
My HTMl for the button looks like this:
<button type="button" v-on:click="DoStuff()">Do Stuff</button>

My vue js code looks like this:
var client = new Vue({
    el: '#client',
    data: {
        someData: []
},
methods: {
    DoStuff: function() {

        //Show Loader
        $(".loader").show();

        //Waste 5 seconds
        for (var i = 0; i < 100000000; i++) {
            var x = i;
        }

        //Hide loader
        $(".loader").hide();

        // let me know it's done.
        alert('cool');
    }

The loader never shows.  If I comment out the hide command, the loader show up AFTER the alert.  Makes me think some sort of async operation is going on under the hood but I'm not doing async stuff.

A: You don't need to use jQuery to set and hide elements on the page based on a condition, in fact that kind of defeats the purpose of what VueJS and other front end javascript frameworks are used for.
First you should add a property called loading to your data object
data: {
   someData: [],
   loading: false
}

Then, in your doStuff function, remove the jquery lines and set the loading property accordingly
methods: {
    doStuff: function() {
        //Show Loader
        this.loading = true;

        //Waste 5 seconds
        setTimeout(() => {
           this.loading = false;
        }, 5000)
    }
}

Finally, in your view, add this line

Loading some data

Ill end this by saying that I also think your snippet is a little messed up. the methods property should be inside the Vue instance definition.
var client = new Vue({
    el: '#client',
    data: {
        someData: [],
        loading: false
    },
    methods: {
       doStuff: function() {
          //Show Loader
          this.loading = true;

          //Waste 5 seconds
          setTimeout(() => {
            this.loading = false;
          }, 5000)
       }

   }
}

A: Don't use jquery. You can so this with vuejs.

var client = new Vue({
    el: '#client',
    data: {
        someData: [],
        loading: false,
},
methods: {
    DoStuff() {

        //Show Loader
        this.loading = true;

        //Waste 5 seconds

        //Hide loader
        this.loading = true;

        // let me know it's done.
        alert('cool');
    }

And your HTML.

    Loading....

The rest of your website

A: It's better to not mix with JQuery, just use Vue conditional displaying instead (v-show).
In your loader:

In your Vue code:
var client = new Vue({
    el: '#client',
    data: {
        someData: [],
        loading: false
},
methods: {
    DoStuff: function() {

        this.loading = true;

        //Waste 5 seconds
        for (var i = 0; i < 100000000; i++) {
            var x = i;
        }

        this.loading = false;

        // let me know it's done.
        alert('cool');
    }

A: Thanks Everyone.  I have to focus on a more important feature that came up.  But I just wanted to share what I've gleamed.  This is not a (or the) final answer but it explains the problem and the correct approach.
The problem was correctly identified by Andrew Lohr as is further explained here:
jQuery hide() and show() not immediately run when reversed later in the function
The best (but not only) solution would be use an event bus as mentioned by perellorodrigo here:  https://flaviocopes.com/vue-components-communication/
I will post my final solution when I get around to it.


text:
Q: ASP.net get form values from postback inline vb.net This codes works great except for getting the post values...  I have the select hard coded now, but I want to obtain the values from the form post and populate from that...  I hope there's a way to do this using inline asp.net (vb.net)...
<%@ Page language="VB" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <title>ListView Templates Example</title>

    <form id="form1" runat="server">

Modifying Quantities for:

    <asp:SqlDataSource ID="Sql" runat="server"
        ConnectionString="<%$ ConnectionStrings:myConnectionString %>"
        SelectCommand="SELECT [name],[id] FROM [markets]">
    </asp:SqlDataSource>

    <asp:SqlDataSource ID="yearSQLDataSource" runat="server"
        ConnectionString="<%$ ConnectionStrings:myConnectionString %>"
        SelectCommand="SELECT distinct(year) as year from transactions order by year asc">
    </asp:SqlDataSource>

    <asp:SqlDataSource ID="SqlDataSource1" runat="server"
        ConnectionString="<%$ ConnectionStrings:myConnectionString %>"
        SelectCommand="SELECT shortname, id from products order by name asc">
    </asp:SqlDataSource>

    <asp:Label ID="market" runat="server" Text="Market:" />
        <asp:DropDownList ID="markets" runat="server"
        DataSourceID="Sql" DataTextField="name" DataValueField="id" >
    </asp:DropDownList>

    <asp:Label ID="Label2" runat="server" Text="Products:" />
        <asp:DropDownList ID="products" runat="server"
        DataSourceID="SqlDataSource1" DataTextField="shortname" DataValueField="id" >
    </asp:DropDownList>

    <asp:Label ID="year" runat="server" Text="Year:" />
        <asp:DropDownList ID="years" runat="server"
        DataSourceID="yearSQLDataSource" DataTextField="year" DataValueField="year" >
    </asp:DropDownList>

  <asp:button ID="Button1" runat="server" text="Submit" postbackurl="fourrosesformDataList3.aspx" />

      <asp:ListView ID="ContactsListView"
        DataSourceID="ContactsDataSource"
         DataKeyNames="id"
        runat="server">
        <LayoutTemplate>

              Action
              Month
              Quantity

        </LayoutTemplate>
        <ItemTemplate>

              <asp:LinkButton ID="EditButton" runat="Server" Text="Edit" CommandName="Edit" />

              <asp:Label ID="Label1" runat="Server" Text='<%#Eval("MonthName") %>' />

              <asp:Label DataTextField = "standardcase" ID="standardcase" runat="Server" Text='<%#Eval("standardcase") %>' />

        </ItemTemplate>
        <EditItemTemplate>

              <asp:LinkButton ID="UpdateButton" runat="server" CommandName="Update" Text="Update" />
              <asp:LinkButton ID="CancelButton" runat="server" CommandName="Cancel" Text="Cancel" />

              <asp:Label ID="Label3" runat="Server" Text='<%#Eval("MonthName") %>' />

              <asp:TextBox ID="standardcase" DataTextField = "standardcase" runat="server" Text='<%# Bind("standardcase") %>'
                MaxLength="50" />

        </EditItemTemplate>
      </asp:ListView>

      <asp:SqlDataSource ID="ContactsDataSource" runat="server"
        ConnectionString="<%$ ConnectionStrings:myConnectionString %>"
        SelectCommand="SELECT standardcase, shortname, datename(month,dateadd(month, t.month - 1, 0)) as MonthName, t.id as id
         from transactions t, products p where p.id=t.product_id and year = 2009 and market_id = 1 and product_id = 1"
        UpdateCommand="UPDATE transactions
                       SET standardcase = @standardcase
                       WHERE id = @id"
                       >
      </asp:SqlDataSource>

    </form>

so instead of "where p.id=t.product_id and year = 2009 and market_id = 1 and product_id = 1"
I want to do "where p.id=t.product_id and year = @postYear and market_id = @postMarket and product_id = @postProduct" from the form at the top of the page.

A: Use the selectparameters tag of asp:sqldatasource.  Exactly how you do it depends on whether you are getting the value from a control on the current page.
 <asp:sqldatasource
      id="SqlDataSource1"
      runat="server"
      connectionstring="<%$ ConnectionStrings:MyNorthwind%>"
      selectcommand="SELECT standardcase, shortname, datename(month,dateadd(month, t.month - 1, 0)) as MonthName, t.id as id
     from transactions t, products p where p.id=t.product_id and year =  @year and market_id = @market and product_id = @product">
      <selectparameters>
          <asp:controlparameter name="year" controlid="DropDownList1" propertyname="SelectedValue"/>
          <asp:controlparameter name="market" controlid="DropDownList1" propertyname="SelectedValue"/>
          <asp:controlparameter name="products" controlid="DropDownList1" propertyname="SelectedValue"/>
      </selectparameters>
  </asp:sqldatasource>

Be aware that this does leave a vulnerability, see http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.sqldatasource.selectparameters(v=vs.110).aspx?cs-save-lang=1&cs-lang=vb#code-snippet-2  for more details.

A: The formparamter property worked for me:
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.formparameter.formfield(v=vs.110).aspx
I may look at the controlparameter too...  T


text:
Q: Masonry-rails not working I want to add in Masonry-rails/gem in my app. add in gem, JavaScript, and necessary function, but now do not works masonry successfully.
So this time. I want to help you.

*

*First Bundle install  => "gem 'masonry-rails'"

*Second Include CSS/application.scss => below application.js

*Third Include application.js => //= require masonry/jquery.masonry

*forth Write code pins.js.coffee => below pins.js.coffee

*fifth Write view => below index.html.erb
application.js
 *= require 'masonry/basic'
 *= require 'masonry/centered'
 *= require 'masonry/fluid'
 *= require 'masonry/gutters'
 *= require 'masonry/infinitescroll'
 *= require 'masonry/right-to-left'
 *= require 'masonry/transitions'

pins.js.coffee
$ ->
  $('#pins').imagesLoaded
    $('#pins').masonry
      itemSelector: '.box'
      isFitWidth: true

index.html.erb

  <% @pins.each do |pin| %>

      <%= link_to (image_tag pin.image.url(:medium)) %>

<%= link_to pin.title, pin_path(pin.id) %>

  <% end %>

<%= paginate @pins %>

I want solve this problem.


text:
Q: Update a query value using javascript/php I know that this might be answered already by someone, but all the answers I could find, are intended for people who already know what they are doing and they paste thousands of lines of code, so I want something more on a begginer's side.
I have a value that I want to update ever 15 seconds to show the most updated information from a mysql db. I managed to show the latest result every once you reload the webpage.
The code is the following (everything is on the same file index.php):
PHP part:
<?php
$link = mysql_connect('localhost', 'root', '');
$LastUpdate = mysql_query('SELECT dateTime FROM LastUpdate where id=1');
if (!$LastUpdate) {
die('Could not query:' . mysql_error());
}

HTML part:
Last Update: <?php echo mysql_result($LastUpdate, 0); ?>

Jscript part:

ajax.php
<?php
$link = mysql_connect('localhost', 'root', '');
mysql_select_db('testdatabase', $link);

$LastUpdate = mysql_query('SELECT dateTime FROM LastUpdate where id=1') or die(mysql_error());
$firstData = mysql_fetch_assoc($LastUpdate);

$count = mysql_query('SELECT COUNT(Name) AS count FROM users, LastUpdate WHERE lastConnection = dateTime') or die(mysql_error());
$secondData = mysql_fetch_assoc($count);

$returnValues = array(
    'firstData' => $firstData,
    'secondData' => $secondData
);

echo json_encode($returnValues);

response example (JSON)
{
    "firstData": {
        "dateTime": "2016-06-16 00:00:00"
    },
    "secondData": {
        "count": "1"
    }
}


text:
Q: Tomcat error while starting the server? I'm having the following error while deploying my java dynamic web project on tomcat server.

Could not publish server configuration for Tomcat v6.0 Server at localhost.
      Multiple Contexts have a path of "/CRM".

A: Delete any old war files if present at deployment location.


text:
Q: Make image fill whole container of stacklayout
Hi I have this Xamarin Forms app where I have the following layout:
 <ContentPage Title="Live" Icon="tv_show-32.png">
        <ScrollView>
            <Grid Margin="10">
                <Grid.RowDefinitions>
                    <RowDefinition Height="Auto"></RowDefinition>
                    <RowDefinition Height="Auto"></RowDefinition>
                    <RowDefinition Height="Auto"></RowDefinition>
                    <RowDefinition Height="Auto"></RowDefinition>
                </Grid.RowDefinitions>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="*"></ColumnDefinition>
                </Grid.ColumnDefinitions>
                <StackLayout Grid.Row="0" Grid.Column="0" Spacing="50,20,50,30">
                    <Image Source="http://kanal10.se/images/logga/kanal10.png" HorizontalOptions="FillAndExpand"></Image>
                </StackLayout>

                <StackLayout Grid.Column="0" Grid.Row="1" Style="{StaticResource StackBG}">

                    <BoxView WidthRequest="100" HeightRequest="1" BackgroundColor="#009fe3"></BoxView>
                    <Image Source="http://kanal10.se/storage/images/kanal10/kanal-10/tvbild.png" HorizontalOptions="Fill"></Image>
                    <Button x:Name="Sweden" Text="Watch Live" Clicked="Sweden_OnClicked" HorizontalOptions="FillAndExpand" Style="{StaticResource PlayButtonStyle}"></Button>
                </StackLayout>
                <StackLayout Grid.Column="0" Grid.Row="2" Style="{StaticResource StackBG}">

                    <BoxView WidthRequest="100" HeightRequest="1" BackgroundColor="#009fe3"></BoxView>
                    <Image Source="http://kanal10.se/storage/images/kanal10/kanal-10/tvbild.png" HorizontalOptions="FillAndExpand"></Image>
                    <Button x:Name="Norway" Text="Watch Live" Clicked="Norway_OnClicked" HorizontalOptions="FillAndExpand" Style="{StaticResource PlayButtonStyle}"></Button>
                </StackLayout>
                <StackLayout Grid.Column="0" Grid.Row="3" Style="{StaticResource StackBG}">

                    <BoxView WidthRequest="100" HeightRequest="1" BackgroundColor="#009fe3"></BoxView>
                    <Image Source="http://kanal10.se/storage/images/kanal10/kanal-10/tvbild.png" HorizontalOptions="FillAndExpand"></Image>
                    <Button x:Name="Asia" Text="Watch Live" Clicked="Asia_OnClicked" Style="{StaticResource PlayButtonStyle}"></Button>
                </StackLayout>
            </Grid>
        </ScrollView>
    </ContentPage>

The problem is that I can't get the image called tvbild.png, to fill the whole  container in the iOS app.
I would like the image to have the same width size as the button (see attached image).

How can I accomplish this?
Thanks for help!
Peter

A: Assuming image size is known; use separate row in Grid for image and button and
set HeightRequest for Image and ColumnDefinition Width for Grid, see sample below:
Original image width is 100 and height is 50. Width of container is 300.
Find scale factor based on width of container and width of image: 300/100=3
Find HeightRequest based on scale and height of image: 3*50=150:
<ContentPage Padding="10,20"
...
<Grid>
  <Grid.RowDefinitions>
    <RowDefinition Height="Auto"/>
    <RowDefinition Height="Auto"/>
    <RowDefinition Height="Auto"/>
    <RowDefinition Height="Auto"/>
  </Grid.RowDefinitions>
  <Grid.ColumnDefinitions>
    <ColumnDefinition Width="300"/>
  </Grid.ColumnDefinitions>
  <Image Grid.Row="0" Source="100x50.png" HeightRequest="150"/>
  <Button Grid.Row="1" Text="Button 1"/>
  <Image Grid.Row="2" Source="200x100.png" HeightRequest="150"/>
  <Button Grid.Row="3" Text="Button 2"/>
</Grid>

Sample output from iPhone SE simulator with page width 320. The left and right border is from area left and right of the display:

A: Hi and thanks for answer,
Well what I want is to fill the whole conatiners width for both the button and the image.
Peter


text:
Q: Python encoding and json dumps I apologize if this question has been asked earlier. I am still not clear about encoding in python3.2.
I am reading a csv(encoded in UTF-8 w/o BOM) and I have French accents in the csv.
Here is the code to opening and reading the csv file:
csvfile = open(in_file, 'r', encoding='utf-8')
fieldnames = ("id","locale","message")
reader = csv.DictReader(csvfile,fieldnames,escapechar="\\")
for row in reader:
        if row['id'] == id and row['locale'] == locale:
            out = row['message'];

I am returning the message(out) as Json
jsonout = json.dumps(out, ensure_ascii=True)
return HttpResponse(jsonout,content_type="application/json; encoding=utf-8")

However when I preview the result I get the accent e(French) being replaced by \u00e9 .
Can you please advice on what I am doing wrong and what should I do so that the json output shows the proper e with accent.
Thanks

A: You're doing nothing wrong (and neither is Python).
Python's json module simply takes the safe route and escapes non-ascii characters. This is a valid way of representing such characters in json, and any conforming parser will resurrect the proper Unicode characters when parsing the string:
>>> import json
>>> json.dumps({'Crêpes': 5})
'{"Cr\\u00eapes": 5}'
>>> json.loads('{"Cr\\u00eapes": 5}')
{'Crêpes': 5}

Don't forget that json is just a representation of your data, and both "ê" and "\\u00ea" are valid json representations of the string ê. Conforming json parsers should handle both correctly.
It is possible to disable this behaviour though, see the json.dump documentation:
>>> json.dumps({'Crêpes': 5}, ensure_ascii=False)
'{"Crêpes": 5}'

A: In respect to this answer, setting ensure_ascii=False renders the special characters in your printouts. On the other hand, marcelm's answer is still correct, as no information is lost in those encodings.


text:
Q: How to update existing job firing time? I have created a list of job which is executing as per there schedule time but what i need to do if job schedule time is changed so how the scheduled job's firing time will get changed?
Thanks in advance.

A: You will need to reschedule the job with a new trigger that has the new fire times you want. It's not possible to update a trigger's fire times. How to do this depends on the version of Quartz.Net you're running, as the API has changed significantly between V1 and V2

A: You will need to reschedule the
job with a new trigger that has
the new fire times you want. It's
not possible to update a trigger's
fire times. How to do this
depends on the version of
Quartz.Net you're running, as the
API has changed significantly
between V1 and V2


text:
Q: Running for loop in "parallel" using async/await promises I currently have a for loop like this:
async myFunc() {
    for (l of myList) {
        let res1 = await func1(l)
        if (res1 == undefined) continue

        let res2 = await func2(res1)
        if (res2 == undefined) continue

        if (res2 > 5) {
            ... and so on
        }
    }
}

The thing is that func1, func2 are network calls which return promises, and I don't want them to block my for loop while waiting for them. So I don't mind working in parallel with myList[0] and myList[1], nor do I care about the order in which the items of the list are processed.
How can I achieve this?

A: I'd do it by writing a function that handles the one value that you're handling sequentially:
async function doOne(l) {
    let res1 = await func1(l);
    if (res1 == undefined) {
        return /*appropriate value*/;
    }

    let res2 = await func2(res1);
    if (res2 == undefined) {
        return /*appropriate value*/;
    }

    if (res2 > 5) {
        // ... and so on
    }
}

Then I'd use Promise.all with map to start all of those and let them run in parallel, getting the results as an array (if you need the results):
function myFunc() {
    return Promise.all(myList.map(doOne)); // Assumes `doOne` is written expecting to be called via `map` (e.g., won't try to use the other arguments `map` gives it)
    // return Promise.all(myList.map(l => doOne(l))); // If we shouldn't make that assumption
}

If myList is (or may be) a non-array iterable, use Array.from to get an array to use map on:
function myFunc() {
    return Promise.all(Array.from(myList.map(doOne)));
}

(Or use a for-of loop pushing to an array.)
If you don't want a failure to handle one entry in the list to prevent seeing the results from handling others in the list, use Promise.allSettled rather than Promise.all. (Note that they'll all be started either way, the only difference is whether you see the successful results when at least one of them fails.)


text:
Q: text overflow make 2 text hidden (multi line ellipsis) how to make my text like this in css

I tried this code :
height: 60px;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;

The result was like this

Please help me sir, thanks before


text:
Q: ProgrssBar doesn't display on screen I want to set visible progress bar on my screen while uploading data to DB. But when I put VISIBLE, it doesn't display on my screen. What is wrong?
Here is my Activity class.
 public class MainActivity extends AppCompatActivity {

        private CountryService countryService = new CountryServiceImpl();
        private static final String INSERT_DATA_ITEM_MESSAGE = "Insert data item selected";
        private static final String EXIT_ITEM_MESSAGE = "Exit. Bye, bye";
        private static final String ERROR_DURING_CONVERTING_JSON_TO_MAP_MESSAGE = "Error during converting JSON to Map. ";
        private static final String JSON_FILE_NAME = "countries";
        private static final String ASSET_FOLDER = "raw";
        private static final String DATA_ARE_ALREADY_UPLOADED = "Data are already uploaded";
        private static final String DATA_UPLOADED_SUCCESSFUL = "Data uploaded successful";
        private static final String KEYWORD = "search";
        private SQLiteDatabase sqLiteDatabase;
        private SQLiteConnector sqLiteConnector;
        private Spinner countryListSpinner;
        private ListView listView;
        private List<CountryWithCitiesDto> listCountryiesAndCities;
        private ProgressBar progressBar;

        private Map<String, String[]> getParsedMapFromJSONFile() {
            InputStream inputStream = getResources().openRawResource(
                    getResources().getIdentifier(JSON_FILE_NAME,
                            ASSET_FOLDER, getPackageName()));
            byte[] byteArrayFromJSONFile = JSONReader.getByteArrayFromJsonFile(inputStream);
            if (byteArrayFromJSONFile != null) {
                return buildMapFromByteArrayJSONFile(byteArrayFromJSONFile);
            }
            return Collections.emptyMap();
        }

        private Map<String, String[]> buildMapFromByteArrayJSONFile(byte[] jsonByteArray) {
            try {
                ObjectMapper mapper = new ObjectMapper();
                return mapper.readValue(jsonByteArray, new TypeReference<Map<String, String[]>>() {
                });
            } catch (IOException e) {
                Log.e(ClassNameTags.MAIN_ACTIVITY, ERROR_DURING_CONVERTING_JSON_TO_MAP_MESSAGE + e.getMessage());
                return Collections.emptyMap();
            }
        }

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            initDatabase();
            countryListSpinner = (Spinner) findViewById(R.id.countryListSpinner);
            progressBar = (ProgressBar) findViewById(R.id.progressBar);
            listView = (ListView) findViewById(R.id.cityListView);
            progressBar.setVisibility(View.VISIBLE);
            setAdapterToSpinner(setCountryListSpinner());
            progressBar.setVisibility(View.INVISIBLE);
            countryListSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> arg0, View arg1,
                                           int position, long arg3) {
                    List<String> cityList = new ArrayList<>();
                    for (int i = 0; i < listCountryiesAndCities.get(position).getCityList().size(); i++) {
                        cityList.add(listCountryiesAndCities.get(position).getCityList().get(i).getNameCity());
                    }
                    setAdapterToCityList(cityList);
                }

                @Override
                public void onNothingSelected(AdapterView<?> arg0) {

                }
            });

            listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position,
                                        long id) {
                    Intent intent = new Intent(MainActivity.this, WikiActivity.class);
                    intent.putExtra(KEYWORD, listCountryiesAndCities.get((int) countryListSpinner.getSelectedItemId()).getCityList().get(position).getNameCity());
                    startActivity(intent);
                }
            });
        }

        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            getMenuInflater().inflate(R.menu.main_menu, menu);
            return super.onCreateOptionsMenu(menu);
        }

        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            switch (item.getItemId()) {
                case R.id.insert_data_menu:
                    if (listCountryiesAndCities.isEmpty()) {
                        progressBar.setVisibility(View.VISIBLE);
                        uploadFromJsonToDatabase();
                        setAdapterToSpinner(setCountryListSpinner());
                        progressBar.setVisibility(View.INVISIBLE);
                        Toast.makeText(this, DATA_UPLOADED_SUCCESSFUL, Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(this, DATA_ARE_ALREADY_UPLOADED, Toast.LENGTH_SHORT).show();
                    }
                    Log.i(ClassNameTags.MAIN_ACTIVITY, INSERT_DATA_ITEM_MESSAGE);
                    break;
                case R.id.exit_menu:
                    Log.i(ClassNameTags.MAIN_ACTIVITY, EXIT_ITEM_MESSAGE);
                    break;
            }
            return super.onOptionsItemSelected(item);
        }

        private void initDatabase() {
            sqLiteConnector = new SQLiteConnector(this);
            sqLiteDatabase = sqLiteConnector.getWritableDatabase();
        }

        private void uploadFromJsonToDatabase() {
            countryService.insertCountryWithCities(getParsedMapFromJSONFile(), sqLiteDatabase);
        }

        private String[] setCountryListSpinner() {
            listCountryiesAndCities = countryService.getListCountriesWithCities(sqLiteDatabase);
            String[] outArray = new String[listCountryiesAndCities.size()];
            for (int i = 0; i < listCountryiesAndCities.size(); i++) {
                System.out.println(listCountryiesAndCities.get(i).getCountry().getNameCountry());
                outArray[i] = listCountryiesAndCities.get(i).getCountry().getNameCountry();
            }
            return outArray;
        }

        private void setAdapterToSpinner(String[] spinnerCountryArray) {
            ArrayAdapter<String> adapter = new ArrayAdapter<>(this,
                    android.R.layout.simple_spinner_item, spinnerCountryArray);
            countryListSpinner.setAdapter(adapter);
        }

        private void setAdapterToCityList(List<String> cityNames) {
            ArrayAdapter<String> adapterToCityList
                    = new ArrayAdapter<>(this,
                    android.R.layout.simple_list_item_1,
                    cityNames);
            listView.setAdapter(adapterToCityList);
            adapterToCityList.notifyDataSetChanged();

        }

    }

And here is my activity.xml file below.
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.shapoval.countryparser.MainActivity">

    <ProgressBar
        android:id="@+id/progressBar"
        style="?android:attr/progressBarStyle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        tools:layout_constraintTop_creator="1"
        android:layout_marginStart="124dp"
        android:layout_marginTop="-326dp"
        tools:layout_constraintLeft_creator="1"
        app:layout_constraintLeft_toLeftOf="@+id/cityListView"
        app:layout_constraintTop_toTopOf="@+id/cityListView"
        android:layout_marginLeft="-166dp" />

    <Spinner
        android:id="@+id/countryListSpinner"
        android:layout_width="303dp"
        android:layout_height="48dp"
        android:layout_marginEnd="47dp"
        android:layout_marginRight="47dp"
        app:layout_constraintRight_toRightOf="parent"
        tools:layout_constraintRight_creator="1"
        tools:layout_constraintTop_creator="1"
        tools:layout_constraintBottom_creator="1"
        app:layout_constraintBottom_toTopOf="@+id/cityListView"
        android:layout_marginBottom="22dp"
        app:layout_constraintTop_toTopOf="parent"
        android:layout_marginTop="25dp" />

    <ListView
        android:layout_width="0dp"
        android:layout_height="361dp"
        android:id="@+id/cityListView"
        tools:layout_constraintRight_creator="1"
        tools:layout_constraintBottom_creator="1"
        android:layout_marginStart="31dp"
        app:layout_constraintBottom_toBottomOf="parent"
        android:layout_marginEnd="31dp"
        app:layout_constraintRight_toRightOf="parent"
        tools:layout_constraintLeft_creator="1"
        android:layout_marginBottom="55dp"
        app:layout_constraintLeft_toLeftOf="parent" />
</android.support.constraint.ConstraintLayout>

A: You are using a negative marginTop, i guess your progressBar is out of screen bounds.
EDIT:
Every time you set your progressBar to View.Visible, three lines after you set it to View.Invisible again. That's why you are not seeing it. If you need to show the progressBar while your data is loading, you should have a listener to know when it is completly loaded to set your progressBar to invisible/gone


text:
Q: AWS Cloudwatch Logs to Azure Log Analytics I am aware of the HTTP Data Collector API that can be used to pull data into Azure Log analytics, my ask here is on AWS Cloudwatch data to Azure. We have Azure hosted application and an external AWS hosted Serverless Lamda functions and we want to import the logs of those 13 serverless functions into Azure. I know from the documentation and there is a python function that can be used as a AWS Lamda function and the python example is in MSFT documentation. But what I am failing to understand is what Json format that AWS cloud collector needs to create so they can send it to Azure Log Analytics. Any examples on this ? Any help on how this can be done. I have come across this blog also but that is splunk specific. https://www.splunk.com/blog/2017/02/03/how-to-easily-stream-aws-cloudwatch-logs-to-splunk.html

A: Hey never mind I was able to dig a little deeper and I found that in AWS I can STREAM the Logs from one Lambda to other Lambda function thru subscription. Once that was setthen all I did was consumed that and on the fly created the JSON and sent it to Azure Logs. In case if you or anyone is interested in it, following is the code:-
import json
import datetime
import hashlib
import hmac
import base64
import boto3
import datetime
import gzip

from botocore.vendored import requests
from datetime import datetime

Update the customer ID to your Log Analytics workspace ID
customer_id = "XXXXXXXYYYYYYYYYYYYZZZZZZZZZZ"

For the shared key, use either the primary or the secondary Connected Sources client authentication key
shared_key = "XXXXXXXXXXXXXXXXXXXXXXXXXX"

The log type is the name of the event that is being submitted
log_type = 'AWSLambdafuncLogReal'

json_data = [{
"slot_ID": 12345,
"ID": "5cdad72f-c848-4df0-8aaa-ffe033e75d57",
"availability_Value": 100,
"performance_Value": 6.954,
"measurement_Name": "last_one_hour",
"duration": 3600,
"warning_Threshold": 0,
"critical_Threshold": 0,
"IsActive": "true"
},
{
"slot_ID": 67890,
"ID": "b6bee458-fb65-492e-996d-61c4d7fbb942",
"availability_Value": 100,
"performance_Value": 3.379,
"measurement_Name": "last_one_hour",
"duration": 3600,
"warning_Threshold": 0,
"critical_Threshold": 0,
"IsActive": "false"
}]
#body = json.dumps(json_data)
#####################
######Functions######
#####################

Build the API signature
def build_signature(customer_id, shared_key, date, content_length, method, content_type, resource):
x_headers = 'x-ms-date:' + date
string_to_hash = method + "\n" + str(content_length) + "\n" + content_type + "\n" + x_headers + "\n" + resource
bytes_to_hash = bytes(string_to_hash, encoding="utf-8")
decoded_key = base64.b64decode(shared_key)
encoded_hash = base64.b64encode(
hmac.new(decoded_key, bytes_to_hash, digestmod=hashlib.sha256).digest()).decode()
authorization = "SharedKey {}:{}".format(customer_id,encoded_hash)
return authorization

Build and send a request to the POST API
def post_data(customer_id, shared_key, body, log_type):
method = 'POST'
content_type = 'application/json'
resource = '/api/logs'
rfc1123date = datetime.utcnow().strftime('%a, %d %b %Y %H:%M:%S GMT')
print (rfc1123date)
content_length = len(body)
signature = build_signature(customer_id, shared_key, rfc1123date, content_length, method, content_type, resource)
uri = 'https://' + customer_id + '.ods.opinsights.azure.com' + resource + '?api-version=2016-04-01'

headers = {
    'content-type': content_type,
    'Authorization': signature,
    'Log-Type': log_type,
    'x-ms-date': rfc1123date
}
response = requests.post(uri,data=body, headers=headers)
if (response.status_code >= 200 and response.status_code <= 299):
    print("Accepted")
else:
    print("Response code: {}".format(response.status_code))
    print(response.text)
def lambda_handler(event, context):
cloudwatch_event = event["awslogs"]["data"]
decode_base64 = base64.b64decode(cloudwatch_event)
decompress_data = gzip.decompress(decode_base64)
log_data = json.loads(decompress_data)
print(log_data)
awslogdata = json.dumps(log_data)
post_data(customer_id, shared_key, awslogdata, log_type)


text:
Q: How to make a multiple asynchronous calls using .NET? The scenario is that an ASP.NET webforms page will call a web service in an async manner to make about 8 web service calls to various providers for data. I would like to run them in parallel to speed things up.
I also need to wait for them all to come back before moving on.
What is the best way to achieve this?  Please provide some code examples (I'm from VB).
Thanks!!!

A: For ASP.Net MVC...
Use an AsyncController

*

*Using an Asynchronous Controller in ASP.NET MVC (with examples)
For good ole webforms...
If you are using .Net 4 you might consider the Task Parallel Library.  Otherwise you may need to just use the Async Pattern

*

*Task Examples

*Async Pattern to Tasks


text:
Q: Promise always undefined I'm trying to call an API and use the results but the promise result is always coming back as undefined.
I think this should be straight forward, but I'm new to promises and I've spent many hours trying to figure this out without any luck. I've tried so many versions. I want to

*

*Call an API

*

*The API will return JSON in which I am interested in an array of numbers within it

*Parse the JSON to get that array

*Use the array in another function to do something

Initially I had these two functions
//Get the references
function getReferences(articleID) {
    var request = new XMLHttpRequest();
    request.open("get", "https://eutils.ncbi.nlm.nih.gov/entrez/eutils/elink.fcgi?dbfrom=pubmed&linkname=pubmed_pubmed_refs&retmode=json&id=" + articleID + "&api_key=0&tool=my_tool2&email=my_email@example.com", false);
    request.send();

    var obj = JSON.parse(request.responseText);
    return obj.linksets[0].linksetdbs[0].links;
}

//use the references
function useReferences(startingArticleID) {
    var references = getReferences(startingArticleID);
    // do something with the array "references"
}

and this worked well except sometimes getReferences would try to parse before the API call was complete. So I modified the code to look like this (used Axios to try to help with API calling)
async function getReferences(articleID) {
    let json = await axios.get("https://eutils.ncbi.nlm.nih.gov/entrez/eutils/elink.fcgi?  dbfrom=pubmed&linkname=pubmed_pubmed_refs&retmode=json&id=" + articleID  + "&api_key=0&tool=my_tool2&email=my_email@example.com");
    return json;
}

async function useReferences(startingArticleID) {
    let references = await getReferences(startingArticleID);
    //do something with the array references
}

But references always comes back as undefined with a status of pending. I read and experimented with .then() but the value from the promise was still undefined.


text:
Q: after uninstall protobuf, use protoc command, there still protoc :error while loading shared libraries: libprotoc.so.12 I installed protobuf 3.2.0 from the source code in Ubuntu;
but now I want to install a lower  version's protobuf , so I use make uninstall
Then I verify if  protobuf is still in my computer, so I use protoc command;
the response is :
protoc: error while loading shared libraries: libprotoc.so.12: cannot open shared object file: No such file or directory
Why after I uninstall protobuf, there still this error message? How can I solve this?

A: Some of the installed files need superuser access to remove, e.g. the binary file /usr/bin/protoc.
Try 'sudo make uninstall'


text:
Q: Swift Generics - Changing Values and Passing Between View Controllers I'd like to use a variable of type Any in order to pass different classes to a child view controller. For example, I might have Table, Chair and Plate objects. In my child view controller, I'd like to change the value of one of their properties (e.g. Table.legs was 4, change that to 3), and for the parent view controller to be able to read that from the child VC. I'll use a Protocol to update the parent VC that can pop the child after reading the updated object.
In order to work out how the passing of generics might work, I wrote this code in a playground:
class Table {
    var legs: Int
    var material: String
    init(legs: Int, material: String) {
        self.legs = legs
        self.material = material
    }
}
var anObject: Any?

// set up the Table
let aTable = Table(legs: 4, material: "Oak")

// set anObject to be the Table
anObject = aTable

// get the object and change it
let bTable = anObject as! Table
bTable.legs = 3

// get the original object and cast it as a Table
let cTable = anObject as! Table

print(cTable.legs) // prints 3

I believe from this, I should be able to do what I describe above without any issues, because the original object reference (anObject) is updated whenever I update a variable referencing it.
My question is this - are there any pitfalls I should be aware of when adopting this approach? It appears that rather than creating a copy of an object, swift will always create a pointer to the original object; are there any situations when that does not hold true?
Appologies if this is seen as a fairly basic question, but this is all fairly new to me - many thanks in advance!

A: Class are reference types as you noticed, if you assign an instance of the class to a variable, it keep the reference (the pointer in memory) to the instance and not the value copy.
Struct are value types, if you copy the instance of the structure to another variable, it's just copied to the variable.


text:
Q: Rows that float up I am using Angular to create a list of checkboxes that define whether some data is visible.

  $scope.data = [
  {name: "Data1", shown: true},
  {name: "Data2", shown: true},
  {name: "Data3", shown: true},
  {name: "Data4", shown: true},
  {name: "Data5", shown: true},
  {name: "Data6", shown: true}
  ];

This data is shown on a topbar, which has a limited height, thus not being able to fit the whole array of data.

{{item.name}}

What I want to achieve is: in case there are more than 4 visible instances of data, the last two should be put in another vertical row, on the right side of this row.
Here's a small demo plunker with this case.
http://plnkr.co/edit/vVysWYR5FLzIBh8zP8th?p=preview

A: you need to remove height from .contentBar div , because you applied static height and data comes dynamically. Please changes below changes in your style.css
.contentBar{
   margin-top: 1em;
   background-color: black;
   width: 30em;
 }

.content {
   color: red !important;
   font-weight:bold;
}

Cheers dude.

A: You can use CSS Flexbox:
.contentBar {
    display: flex;
    flex-flow: column wrap;
}

A: An elegant way how to achieve this is to use a flex box. Please, see the updated pluncker here.
The key are the last 3 CSS rules which were added to the contentBar:
.contentBar{
  margin-top: 1em;
  background-color: black;
  width: 30em;
  height: 5em;
  display: flex;
  flex-direction: column;
  flex-wrap: wrap;
}

A very good guide to flex box can be found on the CSS tricks site.


text:
Q: Scala Gatling http call return a string or access session outside of scenario I have a method which is called
 def getOAuth2Token() : HttpRequestBuilder = {
   http("Get OAuth2 Token from Token Converter")
     .post(tokenConverterTokenEndpoint)
     .header(HttpHeaderNames.ContentType, HttpHeaderValues.ApplicationFormUrlEncoded)
     .formParam("client_id", "client")
     .formParam("client_secret", "secret")
     .formParam("grant_type", "client_credentials")
     .formParam("scope", "api:service")
     .check(status.is(HttpResponseStatus.OK.code()))
     .check(jsonPath("$.access_token").saveAs("oAuth2Token"))
 }

That saves "oAuth2Token". How can I use this when not in a Scenario e.g
val request = new Request.Builder()
      .url(enrollmentUri)
      .header(HttpHeaderNames.Authorization, session => {
        "Bearer " + session("oAuth2Token").as[String]
      })
      .post(body)
      .build()

This currently gives me an error of Missing parameter sessions.
I would like to either:

*

*Use the session here so I can use the token

*Create a new method similar to the first code block that returns the token


text:
Q: Coding State Machine in C++ I'm attempting to code a state machine based on a gumball machine. I have a interface class of a basic state, while I have specific states that use this interface. I have four states, no_quarter, has_quarter, sold, and sold_out states. I also have a gumball machine class that handles these states and depending on which state my machine is in, it will go that class and do the needed action. Here is my code that is having the problem, I'll post my functions also.
Gumball_Machine.h
class Gumball_Machine
{
private:
    int gumball_count;
    State *current_state;
    No_Quarter_State *nqs;
    Has_Quarter_State *hqs;
    Sold_State *ss;
    Sold_Out_State *sos;

public:

    Gumball_Machine(int inventory)
    {
        gumball_count = inventory;
        nqs = new No_Quarter_State(this);
        hqs = new Has_Quarter_State(this);
        ss = new Sold_State(this);
        sos = new Sold_Out_State(this);
        if (gumball_count == 0)
            set_state(sos);
        else
            set_state(nqs);
    }

    void insert_quarter()
    {
        current_state->insert_quarter();
    }

    void eject_quarter()
    {
        current_state->eject_quarter();
    }

    void turn_crank()
    {
        current_state->turn_crank();
    }

    void dispense()
    {
        current_state->dispense();
    }

    void set_state(State *new_state)
    {
        current_state = new_state;
    }

    State *get_no_quarter_state()
    {
        return nqs;
    }

    State *get_has_quarter_state()
    {
        return hqs;
    }

    State *get_sold_state()
    {
        return ss;
    }

    State *get_sold_out_state()
    {
        return sos;
    }

No_Quarter_State.h
#ifndef NO_QUARTER_STATE_H_INCLUDED
#define NO_QUARTER_STATE_H_INCLUDED
#include "State.h"

class No_Quarter_State: public State
{
public:
    No_Quarter_State(Gumball_Machine *gbm);
    void insert_quarter();
    void eject_quarter();
    void turn_crank();
    void dispense();
};

#endif // NO_QUARTER_STATE_H_INCLUDED

No_Quarter_State.cpp
#include "No_Quarter_State.h"
#include "Gumball_Machine.h"

No_Quarter_State::No_Quarter_State(Gumball_Machine *machine)
{
    machine = machine;
}

void No_Quarter_State::insert_quarter()
{
    cout << "You inserted a quarter.\n";
    machine->set_state(machine->get_has_quarter_state());
}

void No_Quarter_State::eject_quarter()
{
    cout << "You must insert a quarter before you can eject one.\n";
}

void No_Quarter_State::turn_crank()
{
    cout << "You must insert a quarter before you can crank the handle.\n";
}

void No_Quarter_State::dispense()
{
    cout << "You need to pay first before you can get a gumball.\n";
}

The line I'm having an issue is in the No_Quarter_State.cpp
machine->set_state(machine->get_has_quarter_state());

This is giving me a run-time error. I've seen examples like this but I'm not completely sure if this is legal in C++. I'm attempting to switch the state of my gumball machine object.
The error I get is a generic not responding error: "test.ext has stopped working". I'm using CodeBlocks to code this.

A: In the constructor, the presumed member variable machine is hidden by the parameter.
No_Quarter_State::No_Quarter_State(Gumball_Machine *machine)
{
    machine = machine;
}

You can fix this by using initializer list syntax instead:Thanks Sneftel and NathanOliver
No_Quarter_State::No_Quarter_State(Gumball_Machine *machine)
    : machine(machine)
{
}

However, in regular method functions, you would have to use this-> if you named the method parameter the same as the member variable. A typical style used to avoid that issue is to prepend m_ or append _ to member names.


text:
Q: Median sort a list in unordered fashion What's the best way of sorting a python list in an unordered fashion according to the median of value positions in the list?
Suppose:
a = [1, 3 ,6, 7, 10, 12, 17]
I'm looking for this:
a = [1, 17, 7, 3, 12, 6, 10]
Meaning, the list now looks like [start, end, mid, first_half_mid, second_half_mid, ...]
edit: To clarify further, I'm looking for a way to keep bisecting the list until it covers the whole range!
edit2: Another example to illustrate the problem
input:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
desired output:
[1, 10, 6, 3, 9, 2, 5, 8, 4, 7]

A: This looks like a breadth-first task, so I used a Queue:
# from queue import Queue, Empty # python 3
from Queue import Queue, Empty   # python 2

a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
accu = []
q = Queue()
# a.sort()     # if it isn't already sorted.

def do_it(l):  # whatever a precise name might be...

    global accu
    accu = [l[0], l[-1]]
    q.put(l[1:-1])             # Add first and last element, start with rest of list.
    try:
        while True:

            l = q.get_nowait()

            if not l:
                continue

            print("working on {}".format(l))
            middle = l[len(l)//2]
            left = l[:len(l)//2]
            right = l[len(l)//2+1:]

            accu.append(middle)
            q.put(left)
            q.put(right)

            print("added {}, todo: {} // {}".format(middle, left, right))
    except Empty:
        pass

print(a)
do_it(a)
print(accu)

Result:
[1, 10, 6, 4, 8, 3, 5, 7, 9, 2]

I don't quite get why 10 is before 6 in your comment.

A: UPDATE: consider left element as a middle if the length of the list is an even numer
def f(a):
    # take left middle element for even-length lists
    mid = len(a)//2 if len(a)%2 else len(a)//2-1
    # take len(a)//2 as a middle element
    #mid = len(a)//2
    if len(a) <= 2:
        return a
    elif(len(a) == 3):
        return a[[0,-1,mid]]
    else:
        return np.append(a[[0,-1,mid]], f(np.delete(a, [0,len(a)-1,mid])))

Output:
In [153]: f(a)
Out[153]: array([ 1, 17,  7,  3, 12,  6, 10])

OLD answer:
here is one of many possible solutions:
import numpy as np

def f(a):
    if len(a) <= 2:
        return a
    elif(len(a) == 3):
        return a[[0,-1,len(a)//2]]
    else:
        return np.append(a[[0,-1,len(a)//2]], f(np.delete(a, [0,len(a)-1,len(a)//2])))

a = np.array([1, 3 ,6, 7, 10, 12, 17])

In [114]: a
Out[114]: array([ 1,  3,  6,  7, 10, 12, 17])

In [115]: f(a)
Out[115]: array([ 1, 17,  7,  3, 12, 10,  6])

PS about last two numbers in the result list/array - the question is what is the middle index for the 4-elements list?
What is the middle element for [3,6,10,12] list? In my solution it would be 10 (index: 4//2 == 2)