text:
Q: Mysterious postback issues with javascript (asp.net) I show a modalpopupextender using javascript, and when I click its save button, it saves the things I have input in, and (as its a button) postsback automatically so the page refreshes.
However when it refreshes, I get an error because it says the checkbox control I define on my aspx page is null.
One of the first things I do when the page loads is create some javascript and feed in various clientIDs for my components, and the last one to be added is chkFullyBooked.ClientID.
When the page loads the first time, it is ok, but after posting back it says my checkbox is null.
Another issues is that in my save button function, while it can retreive the value of textboxes and the checkbox in code, it cannot get the text from labels that have changed... I got around this by converting my labels to textboxes though.
I just cannot figure out the reason why the checkbox control (hard-coded into my page with other textboxes) would come back as null on a page refresh.
Code at the top of my aspx page:
<% Response.Write(""); %>

Later on in my code, an excerpt:
.
.
.

    Last Edit by - <asp:TextBox ID="txtLastEditBy" ReadOnly="true" runat="server"></asp:TextBox>

<asp:CheckBox runat="server" ID="chkFullyBooked" Text="Fully Booked?" Checked="false"/>

.
.
.

Edit: This of course means I get a null reference exception on the code above as it cannot access ClientID.
Edit: As a crappy fix I did response.redirect(request.url.tostring) instead of letting the button postback itself, and this for some godforsaken reason works fine..

A: Since you're "hard coding" the values for the text/checkboxes through Javascript at runtime, the ViewState has no knowledge of these values being set and so they will remain blank after a refresh or postback.
You'll notice that the Response.Redirect does retain your values because when that server based method is called, it goes through all the form fields and gathers their values to store in the ViewState and repopulates them when it come back from the server request.
Have you tried loading the initial values through the Page_Load function the first time the user arrives at the page? This will make sure the values are stored in the ViewState when perform your actions based on the modal popup actions.


text:
Q: How to remove browser action to repeat handle event earlier? I have a registration page where I am saving some information. That is running successfully but when I press ctrl +F5 after registration. I get a message by browser to repeat event which is handled earlier. I have done blank all text values and to false viewstate of every control but It is saving 2 times.
Please suggest me. What should I do? Thanks in advance.

A: The strategy here is to call Response.Redirect("SamePage.aspx").

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I prevent event cycles with FRP (and bacon.js) I've managed to create a cycle in my bacon-powered application, so I need some advice on how to break it.
Let's say we have several properties which carry some state of the application. This state is supposed to be stored via HTML5 History API (pushState) and thus I combine those properties to an object and execute a pushState on it. However, I also need to cover popstate events,  so on every popstate (back button, etc.) I split the state object back into single properties and inject them into their original streams.
Now I've got myself a cycle: since those property streams are the same streams I got my pushState from in the first place, pushState is called again, duplicating states on the stack and making the back button useless.
This is of course my mistake, however, I don't see a good solution apart from splitting each property stream into two and combining them differently in pushState/popState-specific cases. But that seems rather unelegant -- is there any canonical way to avoid this kind of cycles?

A: The most elegant solution I come up is to check the current state before pushing new one. If they are the same, do nothing:
// state properties
var foo = ...;
var bar = ...;

// write
var history = Bacon.combineAll(makeHistoryState, foo, bar);

history.onValue(function (v) {
    if (!_.isEqual(history.state, v)) {
        history.pushState(v);
    }
});

// read
window.addEventListener("popstate", function(event.state) {
    foo.set(extractFoo(event.state));
    bar.set(extractBar(event.state));
});

Disclaimer: I didn't test this myself
EDIT: when having global state as single property, which is saved to history API as is; everything simplfies. And you can probably leverage Bacon.Model lens functionality


text:
Q: How do I use lag function in sql to display dates < sysdate If I want to display all the dates from dual which is less than sysdate using lag condition ,how do I do that
select sysdate from  Items-how do I use lag in this query?
My output should display all the dates less than sysdate using lag condition
Date
30-jun-2015
29-june-2015
28-june-2015

etc

A: Query 1 - Selecting dates from start date to today:
SELECT TRUNC(SYSDATE) - LEVEL + 1 AS "Date"
FROM   DUAL
CONNECT BY TRUNC(SYSDATE) - LEVEL + 1 >= DATE '2015-06-26'

Results:
|                   Date |
|------------------------|
| July, 01 2015 00:00:00 |
| June, 31 2015 00:00:00 |
| June, 30 2015 00:00:00 |
| June, 29 2015 00:00:00 |
| June, 28 2015 00:00:00 |
| June, 27 2015 00:00:00 |
| June, 26 2015 00:00:00 |

Query 2 - Selecting dates between multiple ranges:
WITH ranges ( start_date, end_date ) AS (
  SELECT DATE '2015-06-02', DATE '2015-06-07' FROM DUAL
  UNION ALL
  SELECT DATE '2015-06-12', DATE '2015-06-14' FROM DUAL
)
SELECT START_DATE + COLUMN_VALUE AS "Date"
FROM   ranges,
       TABLE( CAST ( MULTISET(
         SELECT LEVEL - 1
         FROM   DUAL
         CONNECT BY START_DATE + LEVEL - 1 <= END_DATE
       ) AS SYS.ODCINUMBERLIST ) )

Results:
|                   Date |
|------------------------|
| June, 02 2015 00:00:00 |
| June, 03 2015 00:00:00 |
| June, 04 2015 00:00:00 |
| June, 05 2015 00:00:00 |
| June, 06 2015 00:00:00 |
| June, 07 2015 00:00:00 |
| June, 12 2015 00:00:00 |
| June, 13 2015 00:00:00 |
| June, 14 2015 00:00:00 |


text:
Q: How can I use std::binary_search using just a key? I have some data that is stored in a sorted vector. This vector is sorted by some key. I know the STL has an algorithm for checking if an element is in this sorted list. This means I can write something like this:
struct MyData { int key; OtherData data; };
struct MyComparator
{
  bool operator()( const MyData & d1, const MyData & d2 ) const
  {
    return d1.key < d2.key;
  }
};

bool isKeyInVector( int key, const std::vector<MyData> &v )
{
   MyData thingToSearchFor;
   thingToSearchFor.key = key;
   return std::binary_search( v.begin(), v.end(), thingToSearchFor, MyComparator() );
}

However I find the construction of the "thingToSearchFor" object inelegant. Is there a better way? Something similar to this?
struct MyComparator2
{
  bool operator()( const MyData & d1, const MyData & d2 ) const
  {
    return d1.key < d2.key;
  }
};

bool isKeyInVector2( int key, const std::vector<MyData> &v )
{
   return std::binary_search( v.begin(), v.end(), key, MyComparator2() );
}

A: Do:
struct MyComparator
{
    bool operator()(int d1, const MyData & d2) const
    {
        return d1 < d2.key;
    }

    bool operator()(const MyData & d1, int d2) const
    {
        return d1.key < d2;
    }
};

The predicate is called like pred(value, ...) or pred(..., value), so just take in the value directly.


text:
Q: Get current locale of Chrome I am determining the current locale of the browser using this API:
var language = window.navigator.userLanguage || window.navigator.language;

This return "fr-FR" in IE, but it returns just "fr" in Chrome (and similarly for other locales).
Is there another API that will return "fr-FR" in Chrome as well?
We rely on this to load the appropriate culture files.

A: In the latest versions of Chrome browser,
it var language = window.navigator.userLanguage || window.navigator.language; returns 'fr-FR'.
If you are still facing the same issue, you can try var language = navigator.language;

A: Update:
As of Sept 2021 Chrome has pretty extensive support for the Intl library.
function getClientLocale() {
  if (typeof Intl !== 'undefined') {
    try {
      return Intl.NumberFormat().resolvedOptions().locale;
    } catch (err) {
      console.error("Cannot get locale from Intl")
    }
  }
}

Otherwise you can fallback to the window.navigator object:
Firefox and Chrome have a languages array on the navigator object. Normally the first element in that array is the users chosen locale (normally inherited from the OS settings)
var language;
if (window.navigator.languages) {
    language = window.navigator.languages[0];
} else {
    language = window.navigator.userLanguage || window.navigator.language;
}

The navigator.languages array in chrome for me is ["en-GB", "en-US", "en"] whereas navigator.language = "en-US", slightly different but important


text:
Q: Best practise for updating single attribute on multiple records I am writing an exporter within my current Rails3 project right now. This exporter has to mark every exported record as "exported" (bool). I know how to do this easily in a loop, but honestly, it doesn't feel very good to let Rails query the database, say, 300 times in a row, just to set one field on 300 records.
Does anyone know if there's a good way to optimize this? Should I play manually with prepared statements, or does Rails3 take care of this automagically? Is there another SQL command to do this in one step or something?
Thanks for your help

*

*Arne

A: Use update_all method on Class. From Rails API:
# Update all books with 'Rails' in their title
Book.update_all "author = 'David'", "title LIKE '%Rails%'"

A: Since ActiveRecord 4.0 that way is deprecated (Rails API), current way of doing the same is:
# Update all books with 'Rails' in their title
Book.where('title LIKE ?', '%Rails%').update_all(author: 'David')


text:
Q: How to retrieve email addresses in shipment and billing onepage checkout [magento] I was looking for solutions on how to retrieve a value from the checkout form of Magento.
I know how to get the billing email through this line of code:
{{htmlescape var=$order.getBillingAddress().getEmail()}}

but the shipment email is what I can't retrieve. Is there anyway to get it?

A: The shipment entity, or shipping address entity do not have an email field. My recommendation is to use the e-mail address from the order object like this:
{{var $order.getCustomerEmail()}}

General
When calling in an e-mail template something like {{var $object.doSomething()}} This translates into $object->doSomething(). So if you want to see what you can retrieve from the shipment object, just check the methods available in the Mage_Sales_Model_Order_Shipping class and it's parents.


text:
Q: How do I install SQLite3 while setting up Ruby on Rails? I'm new to programming and I'm trying to install Ruby on Rails for Windows 10.
I've tried several times to run the gem install bundler but there's always an error for SQLite3.
The command prompt says to install SQLite3 from http://www.sqlite.org/ but I don't know where to place it in the directory.
I looked at the mkmf.log but I can't understand what it's telling me.
When I look in RailsInstaller's 'bin' folder sqlite3.def, sqlite 3.dll sqlite3 application and sqlite3_ruby (file and batch file) are present.
If anyone knows what might be going wrong and how to fix it I'd really appreciate some help, this problem never happens on the online how-to guides.
Many thanks
Command prompt message:

An error occurred while installing sqlite3 (1.4.0), and Bundler cannot
  continue. Make sure that gem install sqlite3 -v '1.4.0' --source
  'https://rubygems.org/' succeeds before bundling.
In Gemfile:   sqlite3
C:\Sites\test_app>gem install sqlite3 -v 1.4.0 Temporarily enhancing
  PATH to include DevKit... Building native extensions.  This could take
  a while... ERROR:  Error installing sqlite3:
          ERROR: Failed to build gem native extension.
current directory: C:/RailsInstaller/Ruby2.3.3/lib/ruby/gems/2.3.0/gems/sqlite3-1.4.0/ext/sqlite3

C:/RailsInstaller/Ruby2.3.3/bin/ruby.exe -r
  ./siteconf20190317-7152-n0tljg.rb extconf.rb checking for sqlite3.h...
  no sqlite3.h is missing. Install SQLite3 from http://www.sqlite.org/
  first.
  * extconf.rb failed * Could not create Makefile due to some reason, probably lack of necessary libraries and/or headers.  Check
  the mkmf.log file for more details.  You may need configuration
  options.
Provided configuration options:
          --with-opt-dir
          --without-opt-dir
          --with-opt-include
          --without-opt-include=${opt-dir}/include
          --with-opt-lib
          --without-opt-lib=${opt-dir}/lib
          --with-make-prog
          --without-make-prog
          --srcdir=.
          --curdir
          --ruby=C:/RailsInstaller/Ruby2.3.3/bin/$(RUBY_BASE_NAME)
          --with-sqlcipher
          --without-sqlcipher
          --with-sqlite3-config
          --without-sqlite3-config
          --with-pkg-config
          --without-pkg-config
          --with-sqlcipher
          --without-sqlcipher
          --with-sqlite3-dir
          --without-sqlite3-dir
          --with-sqlite3-include
          --without-sqlite3-include=${sqlite3-dir}/include
          --with-sqlite3-lib
          --without-sqlite3-lib=${sqlite3-dir}/lib
To see why this extension failed to compile, please check the mkmf.log
  which can be found here:
C:/RailsInstaller/Ruby2.3.3/lib/ruby/gems/2.3.0/extensions/x86-mingw32/2.3.0/sqlite3-1.4.0/mkmf.log
extconf failed, exit code 1
Gem files will remain installed in
  C:/RailsInstaller/Ruby2.3.3/lib/ruby/gems/2.3.0/gems/sqlite3-1.4.0 for
  inspection. Results logged to
  C:/RailsInstaller/Ruby2.3.3/lib/ruby/gems/2.3.0/extensions/x86-mingw32/2.3.0/sqlite3-1.4.0/gem_make.ou

A: Rails tries to automatically install the latest version of the sqlite3 gem (1.4), but that new version doesn't work with Rails yet. Specify a version that works like this:
Gemfile
gem 'sqlite3', '< 1.4'

And re-run bundle install.

A: I had the same issue. Open the Gemfile that is inside your project folder and change the line gem 'sqlite3' to gem 'sqlite3', '< 1.4' like suggested by @Unixmonkey
From
gem 'sqlite3'
to gem 'sqlite3', '< 1.4'

A: *

*don't run your code on windows

*if you really have to, use gem 1.3.13

gem install sqlite3 -v 1.3.13

this will not install native extensions for windows. thus won't cause any error.


text:
Q: In Google sheet, How to get multiple 'where' including the date I have a sheet with data (named datasheet), which contains bookings/reservations. I want to create one search cell, in which I can give ´search input´  This search input can be a date DATE, ZIP code or a part of a Name.
For finding the date I use:
select (  where K = date '"&TEXT(S2;"yyyy-MM-dd")&"' OR B = ' " &S2& " ' )

Column K contains reservation dates
Cell S2  is the search input Cell
The problem is, when the input isn't a date, it comes with an Error.
I've tried to make a cell where it depends on 'ISDATE' create a what fits with the given input. However, due to the "quotes, this seems not possible  (I've tried to use char(34).
cell X1 =>    =if(isdate(date query);non date query)
=QUERY(datasheet!A1:R1500; '&X1&')

My question is.
Can I create a search filter  (one cell to enter) of  'datasheet' (rows with data) on any given element in this data sheet?
`

A: Different types of data need different "string structure" in query. So if you need one input for your purpose you need to check first what kind of data was entered.
Below you have step by step approach. For explanation purpose I split this into steps - you can pack all together in one formula in your sheet.
1. Checking type of data
I assume that you only have strings, numbers and dates (if you need more, e.g. booleans - you have to expand based on this approach):

=iF(ISTEXT(E2)=TRUE;"txt";IF(AND(ISNUMBER(E2)=TRUE;ISDATE(E2)=TRUE);"date";"num"))

2. Preparing string for Query

=if(E3="txt";"'"&E2&"'";IF(E3="num";E2;" date '"&TEXT(E2;"yyyy-MM-dd")&"'"))

3. Building final Query

=QUERY(A:C;"select * where (A="&G2&" or B = "&G2&" or C="&G2&")";0)

Link to working Sheet:
Link to sheet
Is this fulfil your needs?


text:
Q: Spring Security: OAuth 2.0 Login: Bypass login page Is it possible to completely skip login page (default/custom) and directly go to authorization endpoint for authentication:
@EnableWebSecurity
public class OAuth2LoginSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .oauth2Login()
                .loginPage("/login/oauth2")
                ...
                .authorizationEndpoint()
                    .baseUri("/login/oauth2/authorization")
                    ....
    }
}

A: I could NOT remove the default/custom login page of spring security but as a work-around I added a redirect on the login page so that the end-user never know that there is a login-page in-between.
@RequestMapping(value = "/login/oauth2", method = { RequestMethod.POST, RequestMethod.GET })
public ModelAndView loginPage() {
    Map<String, Object> model = new HashMap<>();
    return new ModelAndView("redirect:/oauth2/authorization/google", "model", model);
}


text:
Q: How can I get the value of fetch async in then statement when I am using Swal? This is my source code. I am using sweetalert2.all.min.js  to use swal popup. Now I have a question, How can I access the returned value from API endpoint in then statement? I also mark it in the source code.
This is the source:
Swal.fire({
        title: 'Welcome',
        text: "Enter Username and Password",
        html:
            '<input id="username_input" class="swal2-input" placeholder="Enter Username">',
        input: 'password',
        inputPlaceholder: 'Enter Password',
        inputAttributes: {
            autocapitalize: 'off'
        },
        showCancelButton: false,
        confirmButtonText: 'Login',
        showLoaderOnConfirm: true,
        preConfirm: (passwordEntered) => {
            var usernameEntered = document.getElementById('username_input').value;
            return fetch("...my_endpoint.../checkusername/" + usernameEntered + "/" + passwordEntered)
                .then(response => {
                    response.text().then((val) => {
                        return val   // **: I need to get this value in * place
                    });
                })
                .catch(error => {
                    return "ERROR";
                })
        },
        allowOutsideClick: () => {
            !Swal.isLoading()
        }
    }).then((result) => {
        alert(result.value);  // *: I need to access the value from **
    })

So, When I log result's value, I get value of passwordEntered variable.

A: By dropping the .then() syntax and switching to async/await :
preConfirm: async (passwordEntered) => {
    var usernameEntered = document.getElementById('username_input').value;

    const response = await fetch("...my_endpoint.../checkusername/" + usernameEntered + "/" + passwordEntered);
    return await response.text();
},


text:
Q: Bash convert to pdf How can I use both ls and convert to transform all images files in a directory to a pdf ?
Also I need to put the files in a certain order for example files like AA1.png,AA11.png need to respect this logical order.
Update (ls) and (convert) are available , but how can I used them together ?

A: https://gitlab.mister-muffin.de/josch/img2pdf
In all of the proposed solutions involving ImageMagick (i.e. convert), the JPEG data gets fully decoded and re-encoded. This results in generation loss, as well as performance "ten to hundred" times worse than img2pdf.

A: To convert to a single PDF can be done in a single command:
convert -compress jpeg *.jpg my-jpegs.pdf

Remember to include the -compress jpeg flag, or it'll store the images uncompressed and result in a massive PDF.
ImageMagick (via convert) requires Ghostscript (gs) to be installed in order to process PDFs I believe.  Beware of memory issues if you are adding a lot of JPEGs at once.
As for your logical ordering, you can use ls in combination with convert to get the list in order.
Something along the lines of:
convert -compress jpeg `ls *.png` my-jpegs.pdf

See ls --help for the various sorting options available.

A: If you have a lot of files:
convert -limit memory 1 -limit map 1 *.jpg foo.pdf

see here
or with compression
convert -limit memory 1 -limit map 1 -compress jpeg -quality 85 *.jpg foo.pdf

A: for image in `ls *.png`; do
  # call convert or whatever here
  convert $image `basename $image .png`.pdf
done


text:
Q: How to display a layer over all Controls I've got a Window which opens a borderless Dialog where you select some options. Once the options are set the Dialog closes and the main Window is enabled again. Not too difficult.
But due to the changed options in the option screen I need to refresh the main window and prevent changes from beeing made before the refresh.
So now I'd like to add and extra layer with a ProgressBar in the middle to notify the user: please wait, we are refreshing.
What would be the best practices around this?

A: You could take a look at Adorners (MSDN link) which allows you to stick a rendering surface on top of other UI Elements. That would allow your existing controls to be ignorant of the refreshing stage and allow incapsulation of the progress-visualization inside the Adorner and the chunk of code that is required to show/hide the Adorner layer

A: I just learned about the Popup primitive control.  It isn't modal, but it does overlay other controls on the screen.
You could, hypothetically, open a popup that covers the entire window (you'll have to move it if the user moves the window) that has a transparent background with an opaque centered panel that displays your wait message.  Add a tinted transparent background to the popup for a dimmed UI experience.


text:
Q: How can I show a button since XAML? Let me provide you more details. The situation is I'm working on a user control and I've got a dependency object where receives a enum. Depending of the value, must show a button or not.
I mean:
public enum Entradas
{
    Entero, Decimal
}

public partial class TableroUserControl : UserControl
{
    public Entradas Entrada
    {
        get { return (Entradas)GetValue(EntradaProperty); }
        set { SetValue(EntradaProperty, value); }
    }

    public static readonly DependencyProperty EntradaProperty =
        DependencyProperty.Register("Entrada", typeof(Entradas), typeof(TableroUserControl));
}

When EntradaProperty receives Entradas.Entero, it must show a button in the user control, and when put Decimal, must disappears the button. Although, the property must contain a default value too.
I don't know if a must declare a PropertyMetadata object in EntradaProperty or use a IValueConverter.
How can I do that? Thanks in advance.

A: You can create an IValueConverter implementation to do what you need.  The result will be a System.Windows.Visibility object;
class EntradasToVisibilityConverter : IValueConverter
{
    public Object Convert(
    Object value,
    Type targetType,
    Object parameter,
    CultureInfo culture )
    {
        // error checking, make sure 'value' is of type
        // Entradas, make sure 'targetType' is of type 'Visibility', etc.

        return (((Entradas)value) == Entradas.Entero)
                ? Visibility.Visible
                : Visibility.Collapsed;
    }

    public object ConvertBack(
    object value,
    Type targetType,
    object parameter,
    CultureInfo culture )
    {
        // you probably don't need a conversion from Visibility
        // to Entradas, but if you do do it here
        return null;
    }
}

Now, in XAML...
<SomeParentControl.Resources>
    <myxmlns:EntradasToVisibilityConverter x:key="MyEntradasToVisConverter" />
</SomeParentControl.Resources>
<Button
    Visibility="{Binding MyEnumValue, Converter={StaticResource MyEntradasToVisConverter}}"
/>

A: You can do this either by metadata or by a ValueConverter. THe examples for the valueConverter are already given. Here an example for doing it by metadata.
public static readonly DependencyProperty EntradaProperty =
        DependencyProperty.Register("Entrada", typeof(Entradas), typeof(TableroUserControl), new UIPropertyMetadata((d,e)=> { ((TableroUserControl)d).EntradaPropertyChanged(e); }));

private EntradaPropertyChanged(DependencyPropertyChangedEventArgs e){
  Entradas entrada=(Entradas)e.NewValue ;
  if(entrada=Entradas.Entero)
     // Show your control
  }else{
     // Hide your control
  }
}

A: You can use your custom IValueConverter or declare DataTrigger in TableroUserControl's XAML.

A: If EntradaProperty is not changed in any other way than through the property Entrada this should work:
public Entradas Entrada
{
    get { return (Entradas)GetValue(EntradaProperty); }
    set
    {
        SetValue(EntradaProperty, value);
        if (Entrada == Entradas.Entero)
            //show button
        else
            //hide button
    }
}

the default value would have to be specified elsewhere, but Entradas will start as Entero sou showing the button at the beginning should work.


text:
Q: add qt and qt mobility to my project I've been reading about qt for some time now and would like to use it to write application for Nokia devices. But there is one thing unclear for me. Let say my aplication uses qt and qt mobility so anyone who would like to install it would have to install qt and qt mobility manually first. Am I getting it right? Or maybe there is a way to add them to my project as static libraries or something...thanks for any help

A: Nokia Smart Installer eliminates the need for Symbian apps to bundle the Qt framework in distributed SIS files. When an app packaged with Smart Installer is installed, a check is made for the presence of the required Qt packages. If any Qt packages are not present Smart Installer downloads and installs them.

A: You need download the qt-mobility source code and compile it,
See QtMobility 1.2.2: Installation Guide


text:
Q: ios - force wait Alamofire response before returning in swift 4 I have a situation where I had to check the provided mobile number on both signup and login through an OTP code. I had everything setup in my Accounts calss to reuse them on the SignUpViewController and SignInViewController.
In the ViewControllers I want to send OTP first, then check if it is sent from the server response to push the VerificationViewController, I'm using Alamofire for networking and SwiftyJSON for parsing JSON responses. Now let's dig deep to the core of my problem:
Here is a part of my SignUpViewController class
var acc: Accounts = Accounts()

@IBAction func signupAction(_ sender: Any) {
        if validateFields() {
            let fname = self.firstName.text!
            let lname = self.lastName.text!
            let pnum = self.phoneNumber.text!
            self.acc.setFirstName(fn: fname)
            self.acc.setLastName(ln: lname)
            self.acc.setPhoneNumber(pn: pnum)
            let result = self.acc.sendOTP()
            if (result) {
                let targetVC = UIStoryboard.init(name: "Main", bundle: Bundle.main).instantiateViewController(withIdentifier: "signupVerfication") as? SignupVerficationViewController
                self.navigationController?.pushViewController(targetVC!, animated: true)
            }
            else {
                CustomComponents().alertWithTitle(title: "Error", message: "Unable to Verify Phone Number,Please Try again!", ViewController: self)
            }
        }
}

And here is a part of my Accounts class
func sendOTP() -> Bool {
        let conf = APIConfig()
        var returnedResult = false
        conf.setURL(url: "patient/auth/send-totp")
        conf.setHeader(head: ["Content-Type": "Application/json"])
        conf.setBody(body: ["phone_number": self.phoneNumber])
        print(self.phoneNumber)
        Alamofire.request(conf.getURL(), method: .post, parameters: conf.getBody(), encoding: JSONEncoding.default, headers: conf.getHeader()).validate(statusCode: 200..<600).responseData { response in
            let status = response.response?.statusCode
            print(status!)
            let swiftJSONVar = JSON(response.result.value!)
            print(swiftJSONVar)
            if (status == 200) {
                returnedResult = true
            }
        }
        return returnedResult
    }

I always get the alert as an output whenever I run the app, despite the fact that as you can see I debugged the response by printing it here print(status!) and here print(swiftJSONVar). The output of the print is 200 as status code and I got the rest of my response.
I had been looking into many Tutorial online like: Grand Central Dispatch Tutorial for Swift 4 and Secure Coding With Concurrency in Swift 4 and more but couldn't implement the GCD on my code blocks.
I need your help please?

A: The sendOTP method has return type Bool which returns immediately as Alamofire request is asynchronous and you are setting value of returnedResult false at top which returns immadiately without waiting for response. After the response comes from the Alamofire the returnedResult is set to true but there is no way to inform caller. As false is returned from sendOTP method it is showing error alert.
Use closure instead of returning bool from sendOTP, which takes Bool and returns void
func sendOTP(_ completion: @escaping (Bool) -> Void) {
    let conf = APIConfig()
    var returnedResult = false
    conf.setURL(url: "patient/auth/send-totp")
    conf.setHeader(head: ["Content-Type": "Application/json"])
    conf.setBody(body: ["phone_number": self.phoneNumber])
    print(self.phoneNumber)
    Alamofire.request(conf.getURL(), method: .post, parameters: conf.getBody(), encoding: JSONEncoding.default, headers: conf.getHeader()).validate(statusCode: 200..<600).responseData { response in
        let status = response.response?.statusCode
        print(status!)
        let swiftJSONVar = JSON(response.result.value!)
        print(swiftJSONVar)
        if (status == 200) {
            completion(true)
        } else {
            completion(false)
        }
    }
}

now you can call like
self.acc.sendOTP { (result) in
    if result {
        //show vc
        let targetVC = UIStoryboard.init(name: "Main", bundle: Bundle.main).instantiateViewController(withIdentifier: "signupVerfication") as? SignupVerficationViewController
        self.navigationController?.pushViewController(targetVC!, animated: true)
    } else {
        //show error alert
        CustomComponents().alertWithTitle(title: "Error", message: "Unable to Verify Phone Number,Please Try again!", ViewController: self)
    }
}

Along with GCD tutorial, I would recommend URLSession and Alamofire tutorials as well to understand how Networking works in iOS.


text:
Q: Turn off "Starting HTTP Client" from neo4j JDBC with logback/slf4j I'm using neo4j-jdbc in an application and get a lot of "Starting the Apache HTTP client" messages during connections.
For logging I'm using logback, slf4j and the bridges like jul-to-slf4j, jcl-over-slf4j and log4j-over-slf4j.
My configuration file is in the classpath and called logback.xml. If I set the root log level to "OFF" its working for every message beside the apache messages.
How can I turn off the "Starting the Apache HTTP client" output?
I tried using log4j which also did'nt work for that message.
Setting the specific package of the httpclient (wire, org.apache, org.restlet, etc.) also didn't work.
The output is generated via a getLogger call from org.restlet.ext.httpclient, so no direct System.out.println statement or something like that.
Any thoughts on that?
Edit: These are the relevant dependencies of the pom file:
  [..]
  <dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-api</artifactId>
    <version>1.7.5</version>
  </dependency>
  <dependency>
    <groupId>ch.qos.logback</groupId>
    <artifactId>logback-classic</artifactId>
    <version>1.0.12</version>
  </dependency>
  <dependency>
      <groupId>org.neo4j</groupId>
      <artifactId>neo4j-jdbc</artifactId>
      <version>2.0.2</version>
    </dependency>
  <dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>log4j-over-slf4j</artifactId>
    <version>1.7.7</version>
  </dependency>
  <dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>jul-to-slf4j</artifactId>
    <version>1.7.7</version>
  </dependency>
  <dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>jcl-over-slf4j</artifactId>
    <version>1.7.7</version>
  </dependency>
  [..]

A: As Stefan Armbruster and Michael Hunger mentioned in the comments it is fixed in the master branch.
I couldn't figure out exactly why the messages are send to the console, since it looks like a proper jcl logger is used, anyway the messages are gone in the 2.1.5-SNAPSHOT version.


text:
Q: Left Click Issue on Minecraft I can't click on anything. I can't click play. Sometimes it allows me to but after that I can't click on a world. If I get onto world then I can't place blocks. It isn't a mouse problem because I can left click on other games I have and on search browsers. Does anyone have an answer?

A: I did once, accidentally, change the buttons required to place a block in the settings. To fix this, go to settings, options, controls and make sure attack/destroy is on left click. If this does not fix it, it may be an error that is only fixable by reinstalling java and/or Minecraft.


text:
Q: Php undefined index notice when reading array from cookie OK I have a rather odd problem and I have been sitting on it for some time without success. My page structure is roughly as follows:
<?php
ob_start();
error_reporting(E_ALL);

then I create an array with user info like:
$USER = array('ID' => md5(uniqid(rand(),1)),
          'referrer' => $_SERVER['HTTP_REFERER'],
          etc.
       );

This will have like 10 entries or so.
Then I check whether the user already has my cookie set, and if they don't, I do (still before anything is output, i.e. before the <html> tag):
$data = base64_encode(serialize($USER));
setcookie('cookiename', $data, time()+86400*30, '/','mydomain.com',1,1);

So far so good. Now say the user then navigates to another page on my site. Now the cookie will already be set, so if the check returns true, I read the cookie with:
$DUMMY = unserialize(base64_decode($_COOKIE['cookiename']));

So now $DUMMY should have the same array structure that was written to the cookie previously. The really baffling thing is that when I try to access:
$uid = $DUMMY['ID'];

I get a warning in my error_log saying that:
PHP Notice:  Undefined index: ID

Which is really weird because (1) it will only read the cookie if the cookie exists, and if it exists, it should have the 'ID' element as it was written to it in the first place (and I do have double and triple checked this with print_r($DUMMY); for instance, and all the elements are there). In addition, when I then try to use $uid I can, i.e., it does have the value it should. So everything seems OK, except that my error_log file gets 1000s of these PHP warning messages. Any ideas?
I do the ob_end_flush(); at the very end of the page footer btw.
Thanks.
P.S.: Some more odd things are going on.
OK for testing purposes, I have added some IP filter, so the cookie script is only loaded if I am the one visiting the page. It seems to work, because no further entries have been made in the database. Nevertheless, the error messages keep ticking away in the error_log file. I am providing an excerpt:
[13-Dec-2017 01:04:34 Europe/Berlin] PHP Notice:  Undefined index: ID in /home/xxxxxxxx/public_html/include/usertrack.inc.php on line 51
[13-Dec-2017 01:04:35 Europe/Berlin] PHP Notice:  Undefined index: ID in /home/xxxxxxxx/public_html/include/usertrack.inc.php on line 51
[13-Dec-2017 01:05:06 Europe/Berlin] PHP Notice:  Undefined index: ID in /home/xxxxxxxx/public_html/include/usertrack.inc.php on line 51
[13-Dec-2017 01:05:07 Europe/Berlin] PHP Notice:  Undefined index: ID in /home/xxxxxxxx/public_html/include/usertrack.inc.php on line 51
[13-Dec-2017 01:05:38 Europe/Berlin] PHP Notice:  Undefined index: ID in /home/xxxxxxxx/public_html/include/usertrack.inc.php on line 51
[13-Dec-2017 01:05:39 Europe/Berlin] PHP Notice:  Undefined index: ID in /home/xxxxxxxx/public_html/include/usertrack.inc.php on line 51
[13-Dec-2017 01:06:10 Europe/Berlin] PHP Notice:  Undefined index: ID in /home/xxxxxxxx/public_html/include/usertrack.inc.php on line 51
[13-Dec-2017 01:06:11 Europe/Berlin] PHP Notice:  Undefined index: ID in /home/xxxxxxxx/public_html/include/usertrack.inc.php on line 51
[13-Dec-2017 01:06:42 Europe/Berlin] PHP Notice:  Undefined index: ID in /home/xxxxxxxx/public_html/include/usertrack.inc.php on line 51
[13-Dec-2017 01:06:43 Europe/Berlin] PHP Notice:  Undefined index: ID in /home/xxxxxxxx/public_html/include/usertrack.inc.php on line 51
[13-Dec-2017 01:07:14 Europe/Berlin] PHP Notice:  Undefined index: ID in /home/xxxxxxxx/public_html/include/usertrack.inc.php on line 51
[13-Dec-2017 01:07:15 Europe/Berlin] PHP Notice:  Undefined index: ID in /home/xxxxxxxx/public_html/include/usertrack.inc.php on line 51
[13-Dec-2017 01:07:46 Europe/Berlin] PHP Notice:  Undefined index: ID in /home/xxxxxxxx/public_html/include/usertrack.inc.php on line 51
[13-Dec-2017 01:07:47 Europe/Berlin] PHP Notice:  Undefined index: ID in /home/xxxxxxxx/public_html/include/usertrack.inc.php on line 51
[13-Dec-2017 01:08:18 Europe/Berlin] PHP Notice:  Undefined index: ID in /home/xxxxxxxx/public_html/include/usertrack.inc.php on line 51
[13-Dec-2017 01:08:20 Europe/Berlin] PHP Notice:  Undefined index: ID in /home/xxxxxxxx/public_html/include/usertrack.inc.php on line 51
[13-Dec-2017 01:08:50 Europe/Berlin] PHP Notice:  Undefined index: ID in /home/xxxxxxxx/public_html/include/usertrack.inc.php on line 51
[13-Dec-2017 01:08:51 Europe/Berlin] PHP Notice:  Undefined index: ID in /home/xxxxxxxx/public_html/include/usertrack.inc.php on line 51
[13-Dec-2017 01:09:22 Europe/Berlin] PHP Notice:  Undefined index: ID in /home/xxxxxxxx/public_html/include/usertrack.inc.php on line 51
[13-Dec-2017 01:09:23 Europe/Berlin] PHP Notice:  Undefined index: ID in /home/xxxxxxxx/public_html/include/usertrack.inc.php on line 51
[13-Dec-2017 01:09:54 Europe/Berlin] PHP Notice:  Undefined index: ID in /home/xxxxxxxx/public_html/include/usertrack.inc.php on line 51
[13-Dec-2017 01:09:55 Europe/Berlin] PHP Notice:  Undefined index: ID in /home/xxxxxxxx/public_html/include/usertrack.inc.php on line 51
[13-Dec-2017 01:10:26 Europe/Berlin] PHP Notice:  Undefined index: ID in /home/xxxxxxxx/public_html/include/usertrack.inc.php on line 51
[13-Dec-2017 01:10:27 Europe/Berlin] PHP Notice:  Undefined index: ID in /home/xxxxxxxx/public_html/include/usertrack.inc.php on line 51
[13-Dec-2017 01:10:58 Europe/Berlin] PHP Notice:  Undefined index: ID in /home/xxxxxxxx/public_html/include/usertrack.inc.php on line 51
[13-Dec-2017 01:10:59 Europe/Berlin] PHP Notice:  Undefined index: ID in /home/xxxxxxxx/public_html/include/usertrack.inc.php on line 51
[13-Dec-2017 01:11:30 Europe/Berlin] PHP Notice:  Undefined index: ID in /home/xxxxxxxx/public_html/include/usertrack.inc.php on line 51
[13-Dec-2017 01:11:31 Europe/Berlin] PHP Notice:  Undefined index: ID in /home/xxxxxxxx/public_html/include/usertrack.inc.php on line 51
[13-Dec-2017 01:12:03 Europe/Berlin] PHP Notice:  Undefined index: ID in /home/xxxxxxxx/public_html/include/usertrack.inc.php on line 51
[13-Dec-2017 01:12:03 Europe/Berlin] PHP Notice:  Undefined index: ID in /home/xxxxxxxx/public_html/include/usertrack.inc.php on line 51
[13-Dec-2017 01:12:35 Europe/Berlin] PHP Notice:  Undefined index: ID in /home/xxxxxxxx/public_html/include/usertrack.inc.php on line 51
[13-Dec-2017 01:12:35 Europe/Berlin] PHP Notice:  Undefined index: ID in /home/xxxxxxxx/public_html/include/usertrack.inc.php on line 51
[13-Dec-2017 01:13:07 Europe/Berlin] PHP Notice:  Undefined index: ID in /home/xxxxxxxx/public_html/include/usertrack.inc.php on line 51
[13-Dec-2017 01:13:07 Europe/Berlin] PHP Notice:  Undefined index: ID in /home/xxxxxxxx/public_html/include/usertrack.inc.php on line 51
[13-Dec-2017 01:13:39 Europe/Berlin] PHP Notice:  Undefined index: ID in /home/xxxxxxxx/public_html/include/usertrack.inc.php on line 51
[13-Dec-2017 01:13:39 Europe/Berlin] PHP Notice:  Undefined index: ID in /home/xxxxxxxx/public_html/include/usertrack.inc.php on line 51
[13-Dec-2017 01:14:11 Europe/Berlin] PHP Notice:  Undefined index: ID in /home/xxxxxxxx/public_html/include/usertrack.inc.php on line 51
[13-Dec-2017 01:14:11 Europe/Berlin] PHP Notice:  Undefined index: ID in /home/xxxxxxxx/public_html/include/usertrack.inc.php on line 51
[13-Dec-2017 01:14:43 Europe/Berlin] PHP Notice:  Undefined index: ID in /home/xxxxxxxx/public_html/include/usertrack.inc.php on line 51
[13-Dec-2017 01:14:43 Europe/Berlin] PHP Notice:  Undefined index: ID in /home/xxxxxxxx/public_html/include/usertrack.inc.php on line 51
[13-Dec-2017 01:15:15 Europe/Berlin] PHP Notice:  Undefined index: ID in /home/xxxxxxxx/public_html/include/usertrack.inc.php on line 51
[13-Dec-2017 01:15:15 Europe/Berlin] PHP Notice:  Undefined index: ID in /home/xxxxxxxx/public_html/include/usertrack.inc.php on line 51
[13-Dec-2017 01:15:47 Europe/Berlin] PHP Notice:  Undefined index: ID in /home/xxxxxxxx/public_html/include/usertrack.inc.php on line 51
[13-Dec-2017 01:15:47 Europe/Berlin] PHP Notice:  Undefined index: ID in /home/xxxxxxxx/public_html/include/usertrack.inc.php on line 51
[13-Dec-2017 01:16:19 Europe/Berlin] PHP Notice:  Undefined index: ID in /home/xxxxxxxx/public_html/include/usertrack.inc.php on line 51
[13-Dec-2017 01:16:19 Europe/Berlin] PHP Notice:  Undefined index: ID in /home/xxxxxxxx/public_html/include/usertrack.inc.php on line 51
[13-Dec-2017 01:16:51 Europe/Berlin] PHP Notice:  Undefined index: ID in /home/xxxxxxxx/public_html/include/usertrack.inc.php on line 51
[13-Dec-2017 01:16:51 Europe/Berlin] PHP Notice:  Undefined index: ID in /home/xxxxxxxx/public_html/include/usertrack.inc.php on line 51
[13-Dec-2017 01:17:23 Europe/Berlin] PHP Notice:  Undefined index: ID in /home/xxxxxxxx/public_html/include/usertrack.inc.php on line 51
[13-Dec-2017 01:17:23 Europe/Berlin] PHP Notice:  Undefined index: ID in /home/xxxxxxxx/public_html/include/usertrack.inc.php on line 51
[13-Dec-2017 01:17:55 Europe/Berlin] PHP Notice:  Undefined index: ID in /home/xxxxxxxx/public_html/include/usertrack.inc.php on line 51
[13-Dec-2017 01:17:55 Europe/Berlin] PHP Notice:  Undefined index: ID in /home/xxxxxxxx/public_html/include/usertrack.inc.php on line 51
[13-Dec-2017 01:18:27 Europe/Berlin] PHP Notice:  Undefined index: ID in /home/xxxxxxxx/public_html/include/usertrack.inc.php on line 51
[13-Dec-2017 01:18:27 Europe/Berlin] PHP Notice:  Undefined index: ID in /home/xxxxxxxx/public_html/include/usertrack.inc.php on line 51

Two things strike me as odd there:
1) Why am I seeing them in the first place since the script is only included with my IP, and
2) there is some odd regularity about these messages. 2 hits about every 30 seconds.
What is this? Some kind of hack attack? But even if it was some weird DDoS, why would the attacker see the cookie script? My IP filter is this:
if ($_SERVER['REMOTE_ADDR'] == 'xxx.xxx.xxx.xxx') { // the x's would be my IP
    require 'include/usertrack.inc.php';
    flush();
}

This is an absolute mistery to me.

A: oh man ... I feel bad. I just solved it.
OK, I did some recent changes to my directory structure and I am running my own cloud server (using owncloud). Due to the change in directory structure, owncloud no longer found the directory it was supposed to sync with. So basically, every 30 seconds it tried to contact the server to locate the directory. Since it came from my machine, the owncloud request did have my IP number so passed the IP filter but since it could not locate the directory it must have triggered some 404 or something.
I am not sure what kind of request owncloud makes but it must have triggered the cookie script, maybe even accepted the cookie but maybe did not allow my script to read out the cookie or deleted it the same second it was set or something. Either way, now that I pointed owncloud to the correct directory again, the error messages stop appearing and the error_log is clean .
man ... 2 days of my life I'll never get back!
Sorry about this.


text:
Q: vb.net exporting datagrid values to excel via array I am trying to export datagrid values to excel using an array..
I get an error "ComException was unhandled" in the following line:
 xlWorkSheet.Range("A1").Resize(DataGridView1.Rows.Count, DataGridView1.Columns.Count).Value = myArray

A: See this MSDN page for more info. Try the following
    Dim myRange as Excel.Range = xlWorkSheet.Range("A1", Reflection.Missing.Value)
    myRange.Resize(DataGridView1.Rows.Count, DataGridView1.Columns.Count)
    myRange.Value = myArray

This is assuming that your myArray is a two dimensional array.


text:
Q: Different ways to evaluate area partitions Given a polygon either convex or concave, suppose we generate a partition of the polygon into multiple smaller polygons. What are the existing literature sources that describe different, complex and novel ways to score one such partition? Simple ones are the average areas of smaller polygons. A complex one would be the average time taken for TSP tour of randomly sampled points in each partition. What are other involved, novel ways to score them?

A: Average perimeter of smaller polygons.
Average total length of minimal length spanning tree of randomly sampled points in each partition.
Average diameter of smaller polygons.
Maximum minimum distance between randomly sampled points in each partition.
Minimum maximum distance between randomly sampled points in each partition.


text:
Q: Double sum over i and j with i \neq j I would like to represent a double sum with i\neq j. So I want two capital sigmas with text i\neq j underneath them. How can I achieve this?

A: \mathop allows you to perform operator-related things (like sub-/superscripting underneath/over top in display style) on non-operator symbols:

\documentclass{article}
\begin{document}
\[ \mathop{\sum\sum}_{i\neq j} \]
\end{document}

Using amsmath, it is also possible to declare a new operator, say \sumsum, if you're using this notation on a more frequent basis:
\documentclass{article}
\usepackage{amsmath}% http://ctan.org/pkg/amsmath
\DeclareMathOperator*{\sumsum}{\sum\sum}
\begin{document}
\[ \sumsum_{i\neq j} x_{ij} \]
\end{document}


text:
Q: sql- exceeding variable size in a exec? I inherited some partially complete sql code that I can't get to work.
it accesses multiple databases, so it first searches for proper database using a userID number, then inserts that database name into a query. the part i'm having a problem with (extremely abbreviated) is...
DECLARE @sql AS VARCHAR(8000)
    SET @sql = 'INSERT INTO ['+@DatabaseName+'].dbo.[customer]
                  ( -- containing about 200 columns. )
                VALUES(...)'
PRINT @sql
EXEC(@sql)

i would get errors in the middle of a column name, sometimes saying it's expecting a parenthesis or quote. i started deleting white space so that, ie, [first name],[last name] were on the same line and not two different lines and that would get me a little further down the query. i don't have much more white spaces i can delete and i'm only just getting into the Values(...) portion of it. the weird thing is. i copy and pasted just the columns portion and put it into Word and it comes up as being only about 3,000 characters, including white space.
am i missing something?
if it means anything, i'm running microsoft sql server 2005, and using the sql server management studio for editing
thanks!

A: See here: SQL Server: When 8000 Characters Is Not Enough for a couple of solutions

A:
extremely abbreviated

Well, that doesn't really help since you have likely abbreviated away the cause of the issue.
If I were to guess, I have seen cases where NCHAR or CHAR variables/columns were involved.  These expand to their full length when used in string concatenation and it will cause the final statement to be too long.
For what it's worth for style or otherwise, use NVarchar(Max) always for SQL Server 2005 and onwards.  In fact, that is the expected type if you use sp_executesql.
If you check for fixed-width N/CHAR columns and switch to nvarchar(max), you may see the problem go away.
EDIT: Test showing NVarchar(Max) holding well in excess of 8000 bytes.
declare @sql nvarchar(max)

-- this CTE sets up the columns, 1 as field1, 2 as field2 etc
-- it creates 2000 columns
;with CTE(n, t) AS (
    select 1, convert(nvarchar(max),'1 as field1')
    union all
    select n+1, convert(nvarchar(max),RIGHT(n, 12) + ' as field'+RIGHT(n, 12))
    from cte
    where N < 2000)
select @sql = coalesce(@sql+',','') + t
from CTE
option (maxrecursion 2000)   -- needed, the default of 100 is not nearly enough

-- add the SELECT bit to make a proper SQL statement
set @sql = 'select ' + @sql

-- check the length : 33786
select LEN(@sql)

-- check the content
print @sql

-- execute to get the columns
exec (@sql)

A: Use an nvarchar(max) datatype for @sql.


text:
Q: ARKit & Vision frameworks – Detecting wall edges I wonder is it theoretically possible to detect wall edges/lines (like in the picture)?
All I could achieve is detecting the vertices of rectangles that are visible to Camera Preview. But we can't consider real walls as rectangles. So, is there any advanced technique (say by training with Core ML, or something else) to achieve this?

A: Have you tried edge detection? https://docs.opencv.org/3.4.2/da/d22/tutorial_py_canny.html


text:
Q: Spring Unit Test Exception I am trying to test Spring MVC Controller but i have some problems. I will copy the stack trace for more clear explanation. I think that the problem comes form applicationContext configuration but i do not know how to fix it.
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'audioCaptchaServlet': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.springframework.context.support.MessageSourceAccessor profiles.captcha.AudioCaptchaServlet.msa; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'msa' defined in class path resource [applicationContext.xml]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.context.support.MessageSourceAccessor]: No default constructor found; nested exception is java.lang.NoSuchMethodException: org.springframework.context.support.MessageSourceAccessor.<init>()
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1210)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:755)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:757)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480)
    at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:96)
    at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:44)
    at org.springframework.test.context.TestContext.buildApplicationContext(TestContext.java:198)
    at org.springframework.test.context.TestContext.getApplicationContext(TestContext.java:233)
    at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:126)
    at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:85)
    at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:231)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:95)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.invokeTestMethod(SpringJUnit4ClassRunner.java:139)
    at org.junit.internal.runners.JUnit4ClassRunner.runMethods(JUnit4ClassRunner.java:51)
    at org.junit.internal.runners.JUnit4ClassRunner$1.run(JUnit4ClassRunner.java:44)
    at org.junit.internal.runners.ClassRoadie.runUnprotected(ClassRoadie.java:27)
    at org.junit.internal.runners.ClassRoadie.runProtected(ClassRoadie.java:37)
    at org.junit.internal.runners.JUnit4ClassRunner.run(JUnit4ClassRunner.java:42)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.springframework.context.support.MessageSourceAccessor profiles.captcha.AudioCaptchaServlet.msa; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'msa' defined in class path resource [applicationContext.xml]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.context.support.MessageSourceAccessor]: No default constructor found; nested exception is java.lang.NoSuchMethodException: org.springframework.context.support.MessageSourceAccessor.<init>()
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:561)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:331)
    ... 30 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'msa' defined in class path resource [applicationContext.xml]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.context.support.MessageSourceAccessor]: No default constructor found; nested exception is java.lang.NoSuchMethodException: org.springframework.context.support.MessageSourceAccessor.<init>()
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1101)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1046)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:504)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:1120)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1044)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:942)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:533)
    ... 32 more
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.context.support.MessageSourceAccessor]: No default constructor found; nested exception is java.lang.NoSuchMethodException: org.springframework.context.support.MessageSourceAccessor.<init>()
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:85)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1094)
    ... 43 more
Caused by: java.lang.NoSuchMethodException: org.springframework.context.support.MessageSourceAccessor.<init>()
    at java.lang.Class.getConstructor0(Unknown Source)
    at java.lang.Class.getDeclaredConstructor(Unknown Source)
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:80)
    ... 44 more

applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/task
    http://www.springframework.org/schema/task/spring-task-3.2.xsd
    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
    http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.2.xsd">

    <context:component-scan base-package="com.profiles" />

    <context:annotation-config/>

    <bean id="msa"
        class="org.springframework.context.support.MessageSourceAccessor"></bean>

    <bean id="audioCaptchaServlet" class="profiles.captcha.AudioCaptchaServlet"></bean>

</beans>

A: MessageSourceAccessor is a helper class for easy access to messages from a MessageSource, providing various overloaded getMessage methods. It doesn't have default constructor with zero argument. This bean is depends on MessageSource bean, which can be register as below.
<bean id="messageSource"
    class="org.springframework.context.support.ResourceBundleMessageSource">
    <property name="basename">
        <value>#Path to properties files#</value>
    </property>
</bean>

And then inject this reference to MessageSourceAccessor through constructor injection.
<bean id="msa"
    class="org.springframework.context.support.MessageSourceAccessor">
  <constructor-arg ref="messageSource">
</bean>


text:
Q: Variable in a form won't keep its value after being used in the call to another form I have a form with a variable in it called "VigilTable."  This variable gets its value from the calling string OpenArgs property.
Among other things, I use this variable in the call string when opening other forms.
But it only works the first call.
MsgBox VigilTable before the call will always show "Spring2022" or whatever on the first call but always comes up blank on succeeding calls (and I get "invalid use of NULL" when the called form attempts to extract the value from OpenArgs).  The variable is dimmed as String in the General section of the form's VBA code.
So what's happening here?  And can I fix it?
Thanks.

A: Ok, so you delcared a variable at the form level (code module) for that given form.
and we assume that say on form load, you set this varible to the OpenArgs of the form on form load.
So, say like this:
  Option Compare Database
  Option Explicit

  Public MyTest     As String

  Private Sub Form_Load()

      MyTest = Me.OpenArgs

  End Sub

Well, I can't say having a variable helps all that much, since any and all code in that form can use me.OpenArgs.
but, do keep in mind the following:
ONLY VBA code in the form can freely use that variable. It is NOT global to the applcation, but only code in the given form.
However, other VBA code outside of the form can in fact use this variable. But ONLY as long as the form is open.
So, in the forms code, you can go;
MsgBox MyTest

But, for VBA outside of the form, then you can get use of the value like this:
Msgbox forms!cityTest.MyTest

However, do keep in mind that any un-handled error will (and does) blow out all global and local variables. So, maybe you have a un-handled error.
Of course if you compile (and deploy) a compiled accDB->accDE, then any errors does NOT re-set these local and global variables.
but, for the most part, that "value" should persist ONLY as long as the form is open, and if you close that form, then of course the values and variables for that form will go out of scope (not exist).
Now, you could consider moving the variable declare to a standard code module, and then it would be really global in nature, but for the most part, such code is not recommended, since it hard to debug, and such code is not very modular, or even easy to maintain over time.
So, this suggests that some error in VBA code is occurring, and when that does occur, then all such variables are re-set (but, the noted exception is if you compile down to an accDE - and any and all variables will thus persist - and even persist their values when VBA errors are encountered.

A: For a string variable, a more robust solution not influenced by any error, should be writing/reading in/from Registry. You can use the, let as say, variable (the string from Registry) from any workbook/application able to read Registry.

*

*Declare some Public constants on top of a standard module (in the declarations area):

Public Const MyApp As String = "ExcelVar"
Public Const Sett As String = "Settings"
Public Const VigilTable As String = "VT"

*Then, save the variable value from any module/form:

SaveSetting MyApp, Sett, VigilTable , "Spring2022" 'Save the string in Regisgtry

*It can be read in the next way:

Dim myVal as String

myVal = GetSetting(MyApp, Sett, VigilTable , "No value") 'read the Registry
 If myVal = "No value" Then MsgBox "Nothing recorded in Registry, yet": Exit Sub
Debug.print myVal

A: Actually, this proved not to be the the answer at all.
It was suggested that I declare my variables as constants in the Standard module but I declared them as variables.  It appeared at first to work, at least through one entire session, then it ceased to work and I don't know why.
If I declare as constants instead, will I still be able to change them at-will?  That matters because I re-use them with different values at different times.
I didn't do constants but declaring VigilName in the Standard module and deleting all other declarations of it fixed both problems.
While I was at it I declared several other variables that are as generally used and deleted all other declarations of them as well so that at least they'll be consistently used throughout (probably save me some troubleshooting later.
Thanks to all!


text:
Q: How to switch clients to second server during transmission when server disconnect I am creating a client/server chat, and trying to create a redundant server.
When the primary server fails, clients switch to the second server.
In the client side I have a connection method where I initiate a socket, aninput stream and an output stream. I want to make a Remote object call using RMI repeatedly and every time this object is not reachable there will be an exception thrown.
I am struggling how to implement this trick and make it work. The thing is not only when a client connects first to check the remote object, but also when the socket is connected and there is data going between through the streams the object should be checked.
If you have any clue please do not hesitate. Thank you.

A: If the target of a remote method call is down, you will get a RemoteException of some kind:

*

*a ConnectException if there wasn't already a pooled connection to reuse, or

*a MarshallException or UnmarshallException, depending on at what phase the outage was detected.
At that point you would need to look up the other registry and retry with the other stub so obtained.
You don't need sockets for any of this.


text:
Q: Why does unittest.mock.patch work with testfixtures? Why doesn't accessing unittest.mock.patch throw an attribute error when I import testfixtures in the below code?
I myself suspect that it is because testfixtures might be importing unittest.mock somewhere internally however, is there any way I could change this behavior if I want unittest.mock to always be imported explicitly and get an AttributeError otherwise?
import unittest
import sys
import os

import testfixtures

class Test(unittest.TestCase):
    @unittest.mock.patch('sys.version_info', (2,7,0))
    def test_version(self):
        assert(sys.version_info < (3,0,0))

Accessing unitest.mock without importing it should throw an AttributeError but that's not the case when testfixtures is imported.


text:
Q: django-rest-framework browsable API doesn't show login link I am currently following the django-rest-api tutorial. In my urls.py, I created the urlpatterns like this:
urlpatterns = format_suffix_patterns([
    ...
    url(r'^auth/', include('rest_framework.urls', namespace='rest_framework')),
])

Now when i call any restricted endpoint in my browser, like 127.0.0.1/rest/api/foobar, I get the Browsable API with a 403 Forbidden, which is totally fine. But there is no login link in the top right corner. Why is that? What am I doing wrong?


text:
Q: UIButton action not triggering on ViewController that is presented modally It's a pretty simple configuration I have.
There's MainController, which will present NewController. Once NewController is presented, the whole UI loads. Some of it is within a UIScrollView, some is static. I have a few UIButtons and a UIBarButtonItem in the Navigation Bar. The UIBarButtonItem functions as expected. However, my UIButtons don't do anything. If you hold down on them, they highlight, but the touchUpInside event does not seem to call my @Objc method.
The thing I don't understand is that at one point, I had NewController pushed instead of presented, and the UIButtons worked fine. Now that it is being presented, they don't work though.
Based on what I've already researched about this issue, it seemed common that the button was being pressed twice as a result of multiple instances of NewController. That is not the case for me though.
MainController presentation method:
let newController = NewController()
let navController = UINavigationController(rootViewController: newController)
navController.modalPresentationStyle = .popover
self.present(navController, animated: true, completion: nil)

My UIButton and its method in NewController:
static let star: UIButton = {
    let btn = UIButton()
    btn.setImage(UIImage(systemName: "star"), for: .normal)
    btn.setImage(UIImage(systemName: "star.fill"), for: .selected)
    btn.setTitle("  Add to Favorites", for: .normal)
    btn.setTitle("  Remove from Favorites", for: .selected)
    btn.titleLabel?.font = UIFont.systemFont(ofSize: 14)
    btn.setTitleColor(UIColor.white, for: [.normal, .selected])
    btn.setTitleColor(UIColor.r6whiteAlpha(), for: [.highlighted, .focused])
    btn.tintColor = .white
    btn.addTarget(self, action: #selector(starTapped), for: .touchUpInside)
    return btn
}()

@objc func starTapped() {
    print("star tapped") // Nothing prints to console.
}

Something I should mention is all of the UIButtons I am having problems with are static variables. They are also both inside of the UIScrollView.
UPDATE: I changed my code around to force only one instance of NewController to exist and eliminate the need for a static variables, but it did not change anything.

A: Okay I spent a few more hours on it. After countless attempts and reviewing my code, I found the problem and it is very bizarre.
On MainController, I have a UITextField. Once the return key is pressed, it presents NewController. The keyboard closes and it presents. I did not call textField.endEditing(true) before presenting and that seemed to cause my problem for some reason.
Solution:
If you have a UITextField as the first responder, you MUST call endEditing(true) before modally presenting another ViewController or you will run into this issue.


text:
Q: python 3.2 UnicodeEncodeError: 'charmap' codec can't encode character '\u2013' in position 9629: character maps to  I'm trying to make a script that gets data out from an sqlite3 database, but I have run in to a problem.
The field in the database is of type text and the contains a html formated text. see the text below

<title>Yahoo!</title>

Välkommen till Yahoo! Mail.

Ansluta och dela går snabbt och enkelt och är tillgängligt överallt.

Det är lätt som en plätt att komma igång.

1.

Lägg till alla dina kontakter på en plats.

2.

Anpassa din nya inkorg.

3.

Anslut överallt på dina mobila enheter.

Info för dig:

                            Yahoo!-ID och e-postadress:

                            Håll ditt konto och inställningar aktuella.
Mitt konto

                Yahoo! Villkor för användning   |   Yahoo! Mail –Villkor för användning   |   Yahoo! Sekretesspolicy

Var god svara inte på detta meddelande. Detta är ett servicemeddelande som rör din användning av Yahoo! Mail. Om du vill veta mer om Yahoo!s användning av personlig information, inklusive användning av webb-beacons i HTML-baserad e-post, kan du läsa vår Yahoo! Sekretesspolicy. Yahoo!s adress är 701 First Avenue, Sunnyvale, CA 94089, USA.

RefID: lp-1037111

`

and the python code that try to extract the data is as follows.
>>> import sqlite3
>>> conn = sqlite3.connect('C:/temp/Mobils/export/com.yahoo.mobile.client.android.mail/databases/mail.db')
>>> c = conn.cursor()
>>> conn.row_factory=sqlite3.Row
>>> c.execute('select body from messages_1 where _id=7')
<sqlite3.Cursor object at 0x0000000001FB78F0>
>>> r = c.fetchone()
>>> r.keys()
['body']
>>> print(r['body'])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Python32\lib\encodings\cp850.py", line 19, in encode
    return codecs.charmap_encode(input,self.errors,encoding_map)[0]
UnicodeEncodeError: 'charmap' codec can't encode character '\u2013' in position 9629: character maps to <undefined>
>>>

Does anybody have any idea of how to print/write this to a file. Yes I know that this is printed to stdout, but I get the same UnicodeEncodeError when I try to write to a file. I tried both write method of a file object and print(r['body'], file=f).

A: While Python 3 deals in Unicode, the Windows console or POSIX tty that you're running inside does not. So, whenever you print, or otherwise send Unicode strings to stdout, and it's attached to a console/tty, Python has to encode it.
The error message indirectly tells you what character set Python was trying to use:
  File "C:\Python32\lib\encodings\cp850.py", line 19, in encode

This means the charset is cp850.
You can test or yourself that this charset doesn't have the appropriate character just by doing '\u2013'.encode('cp850'). Or you can look up cp850 online (e.g., at Wikipedia).
It's possible that Python is guessing wrong, and your console is really set for, say UTF-8. (In that case, just manually set sys.stdout.encoding='utf-8'.) It's also possible that you intended your console to be set for UTF-8 but did something wrong. (In that case, you probably want to follow up at superuser.com.)
But if nothing is wrong, you just can't print that character. You will have to manually encode it with one of the non-strict error-handlers. For example:
>>> '\u2013'.encode('cp850')
UnicodeEncodeError: 'charmap' codec can't encode character '\u2013' in position 0: character maps to <undefined>
>>> '\u2013'.encode('cp850', errors='replace')
b'?'

So, how do you print a string that won't print on your console?
You can replace every print function with something like this:
>>> print(r['body'].encode('cp850', errors='replace').decode('cp850'))
?

… but that's going to get pretty tedious pretty fast.
The simple thing to do is to just set the error handler on sys.stdout:
>>> sys.stdout.errors = 'replace'
>>> print(r['body'])
?

For printing to a file, things are pretty much the same, except that you don't have to set f.errors after the fact, you can set it at construction time. Instead of this:
with open('path', 'w', encoding='cp850') as f:

Do this:
with open('path', 'w', encoding='cp850', errors='replace') as f:

… Or, of course, if you can use UTF-8 files, just do that, as Mark Ransom's answer shows:
with open('path', 'w', encoding='utf-8') as f:

A: On Windows (git bash):
chcp.com 65001
export PYTHONIOENCODING=utf-8

And then you can run your script, in my case it was flask so finally it could decode utf on my website from mysql db...

A: When you open the file you want to write to, open it with a specific encoding that can handle all the characters.
with open('filename', 'w', encoding='utf-8') as f:
    print(r['body'], file=f)

A: Maybe a little late to reply. I happen to run into the same problem today. I find that on Windows you can change the console encoder to utf-8 or other encoder that can represent your data. Then you can print it to sys.stdout.
First, run following code in the console:
chcp 65001
set PYTHONIOENCODING=utf-8

Then, start python do anything you want.

A: for me  using export PYTHONIOENCODING=UTF-8 before executing python command worked .


text:
Q: Parsing DICOM tags to an ArrayList I am using dcm4chee2 to parse through tags with their DicomInputStream and DicomObject. I am then converting the metadata into a ArrayList of type String. However, when I use the toString() method to convert the tags from DicomObject to a String, I am noticing I am not getting a full list of DICOM tags, VR Codes, and Description. Can anyone tell me if there is another DicomObject method I should be using to get a full list rather than the toString()?
Here is the code I currently have:
    ArrayList<String> dicomTags = new ArrayList<String>();
    DicomInputStream din = null;
    FileOutputStream fos = new FileOutputStream("dicomTagResults.txt");
    ObjectOutputStream oos = new ObjectOutputStream(fos);
    din = new DicomInputStream(new File(pathName));
    try {
        DicomObject dcmObj = din.readDicomObject();
        dicomTags.add(dcmObj.toString());
        for (String findMatch : dicomTags){
            System.out.println(findMatch.toString());
            oos.writeObject(dicomTags);
            oos.close();
        }

    }
    catch (IOException e)
    {
        e.printStackTrace();
        return;
    }

A: You can use
toStringBuffer(StringBuffer sb, DicomObjectToStringParam param)

and define a different DicomObjectToStringParam object (I suspect that it is not providing all of the attributes because the defaults are too small for your dataset).
If you truly want to loop through all of the attributes, you're probably better off using
Iterator<DicomElement> data = dcmObj.datasetIterator();

and handling the sequence elements appropriately as you loop through the iterator.


text:
Q: Visual Studio, Nodes in Projectexplorer for Partialclasses Is it Possible to set Nodes in the Projectexplorer for each Partialclass in Visual Studio?
Example:
Creating a Class-File in Visual Studio with 2 Classes inside, leads to a node for every class.

Creating a Class-File in VS with a Partial class, doesn't result in a new Node for each Partial class.

Is it Possible to have somehting like MurderAllHumans.Constructors and a MurderAllHumans.Methods Node?
I know it is possible to Achieve something simmular with Folders and multiple .cs files, but i am looking for a way to do this in one file.
Thanks in advance

A: No, this is not possible. The Class view will only show one entry for each class and as two files with a partial class is still only one class, there will only be one entry.
Generally it is advised to have only one class per file, and I am not sure I understand why you want to declare the same class partially twice in the same file either.
Maybe you could solve part of your wish but making one region for constructors and another for the methods etc. like this:

This will however not be reflected in the Class View.


text:
Q: How can I position my image to be in the centre while combining PHP and HTML elements using bootstrap? QUESTION
How can I add this icon above my browser name and version in my program using bootstrap version 4? In order for the layout to be fully responsive.
I know from doing research the below code will enable me to centre the icon I want. However, the part where I'm getting confused is how to place it above the browser name and version.

MODIFIED CODE
    <?php
   function getBrowser()
   {
       $u_agent = $_SERVER['HTTP_USER_AGENT'];
       $bname = 'Unknown';
       $platform = 'Unknown';
       $version= "";

       //First get the platform?
       if (preg_match('/linux/i', $u_agent)) {
           $platform = 'linux';
       }
       elseif (preg_match('/macintosh|mac os x/i', $u_agent)) {
           $platform = 'mac';
       }
       elseif (preg_match('/windows|win32/i', $u_agent)) {
           $platform = 'windows';
       }

       // Next get the name of the useragent yes seperately and for good reason
       if(preg_match('/MSIE/i',$u_agent) && !preg_match('/Opera/i',$u_agent))
       {
           $bname = 'Internet Explorer';
           $ub = "MSIE";
       }
       elseif(preg_match('/Firefox/i',$u_agent))
       {
           $bname = 'Mozilla Firefox';
           $ub = "Firefox";
       }
       elseif(preg_match('/Chrome/i',$u_agent))
       {
           $bname = 'Google Chrome';
           $ub = "Chrome";
       }
       elseif(preg_match('/Safari/i',$u_agent))
       {
           $bname = 'Apple Safari';
           $ub = "Safari";
       }
       elseif(preg_match('/Opera/i',$u_agent))
       {
           $bname = 'Opera';
           $ub = "Opera";
       }
       elseif(preg_match('/Netscape/i',$u_agent))
       {
           $bname = 'Netscape';
           $ub = "Netscape";
       }

       // finally get the correct version number
       $known = array('Version', $ub, 'other');
       $pattern = '#(?<browser>' . join('|', $known) .
       ')[/ ]+(?<version>[0-9.|a-zA-Z.]*)#';
       if (!preg_match_all($pattern, $u_agent, $matches)) {
           // we have no matching number just continue
       }

       // see how many we have
       $i = count($matches['browser']);
       if ($i != 1) {
           //we will have two since we are not using 'other' argument yet
           //see if version is before or after the name
           if (strripos($u_agent,"Version") < strripos($u_agent,$ub)){
               $version= $matches['version'][0];
           }
           else {
               $version= $matches['version'][1];
           }
       }
       else {
           $version= $matches['version'][0];
       }

       // check if we have a number
       if ($version==null || $version=="") {$version="?";}

       return array(
           'userAgent' => $u_agent,
           'name'      => $bname,
           'version'   => $version,
           'platform'  => $platform,
           'pattern'    => $pattern
       );
   }

   $ua=getBrowser();
?>

      <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.5.2/animate.css">
      <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous">

      <?php
      $ua=getBrowser();
      $yourbrowser= "Your browser: " . $ua['name'];
      $version= "Version of the browser  you're using is : " . $ua['version'];
      echo "
".$yourbrowser."
".$version."
";
      ?>

A: Why would it be a problem? You can do it like that

      <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.5.2/animate.css">
      <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous">

          <?php
          $ua=getBrowser();
          $yourbrowser= "Your browser: " . $ua['name'];
          $version= "Version of the browser  you're using is : " . $ua['version'];
          echo "
".$yourbrowser."
".$version."
";
          ?>

A:

                    <?php
                       $ua=getBrowser();
                    ?>

                       <?php echo "Your browser: {$ua['name']}"; ?>

                       <?php echo "Version of the browser you're using is : {$ua['version']}"; ?>


text:
Q: c# autocad set ucs z axis my google-fu is weak concerning setting the autocad ucs z axis. i've seen many examples online for defining a ucs though none that set the z axis. i can manually set the z axis by command line typing 'ucs' then 'za' and picking 2 point to define the z axis.
i tried this:
Align the UCS to an entity
which did not work as i need it to. i also tried modifying this but i am obviously missing some knowledge of C# to do it. Any help is appreciated.
Thanks

A: Here's an extension method:
public static class EditorExtension
{
    public static void SetZAxisUcs (this Editor ed, Point3d basePoint, Point3d positiveZaxisPoint)
    {
        Plane plane = new Plane(basePoint, basePoint.GetVectorTo(positiveZaxisPoint));
        Matrix3d ucs = Matrix3d.PlaneToWorld(plane);
        ed.CurrentUserCoordinateSystem = ucs;
    }
}


text:
Q: Junit test for @RequestPart Here I want to write a test for following controller method for a spring-boot application, on executing method of the test class I'm getting an error Bad Request: Required request part 'formData' is not present, I've tried finding a solution for testing an object having 'RequestPart' annotation but no luck
//method needs to be tested
@PostMapping("/user")
public ResponseEntity<UserDTO> createUser(@RequestPart(value = "files", required= false) MultipartFile[] files,
@RequestPart("formData") UserDTO userDTO) throws URISyntaxException {
    userService.save(userDTO, files);
}

// Inside testclass
@BeforeEach
public void initTest()
{
    user = createEntity(em);// inside this method I've set all the properties of user object
}

public void createUser() throws Exception {
    UserDTO userDTO = userMapper.toDto(user);
    mockMvc
        .perform(post("/api/user")
            .contentType(TestUtil.APPLICATION_JSON_UTF8)
            .content(TestUtil.convertObjectToJsonBytes(userDTO)))
        .andExpect(status().isCreated());
}

A: You have to build a multipart request using MockMultipartFile with something like this:
    MockMultipartFile api = new MockMultipartFile (
        "file",
        "foo.zip",
        "application/zip", "foo".bytes)

and then use it like this:
    mvc.perform (
        multipart ('/api/foo')
            .file (api))
       .andExpect(...)

This is for a file upload (groovy code), so you have to adjust it a little bit.


text:
Q: What is the best way substracting weeks from a given date with moment.js? What is the best way to substract weeks from a given date with moment.js?
Let's say I am getting a date from the user with dd-mm-yyyy format. I would like to display date - 10weeks.
For example, let's say the user input is: 18042013
The result should be: 18042013 - 10weeks
I am playing with momentjs but cannot figure out how to achieve this. Any idea?

A: You may try like this:
var week = moment().subtract('week', 10);
alert(week);

JSFIDDLE

A: You can do this without need of any libraries...
var MS_PER_MINUTE = 60000;
var MS_PER_HOUR = MS_PER_MINUTE*60;
var MS_PER_DAY = MS_PER_HOUR*24;
var MS_PER_WEEK = MS_PER_DAY*7;

var _DATE_ = new Date()-MS_PER_WEEK*NUM_WEEKS;

JSFIDDLE


text:
Q: Visual Studio 2012 undocumented warning C4447 dllmain.cpp(16): warning C4447: 'main' signature found without threading mode
l. Consider using 'int main(Platform::Array<Platform::String^>^ args)'.

Above is a warning I got from building a Windows Store App DLL project. I didn't change anything in that default dllmain.cpp file except for including my own version of pch.
The documentation for this warning (along with many VS2012 errors/warnings) is nowhere to be found on MSDN and here is the only relevant link I can find:
http://social.msdn.microsoft.com/Forums/en-US/vssetup/thread/6daa9587-fe54-4e84-a8b9-0e5c52c2f6e8/
and the op there didn't get an answer.
If anyone knows what it means and how to fix it, it would be great!

A: As far as I can tell, you can safely ignore the warning. The compiler cribs when it sees a Win32-style DllMain being compiled using the /ZW flag (Consume Windows Runtime Extensions). However, the function gets called as you'd normally expect.
Alternatively, you can work around the warning by compiling dllmain.cpp without /ZW. You might need to adjust the PCH settings for this to properly work. This is the path taken by the DLL (Windows Store apps) C++/CX project template in Visual Studio.
Incidentally, the reason you do not get the warning when you're trying to build a Windows Runtime Component project (which builds everything using /ZW) is that a Windows Runtime Component doesn't declare a DllMain. This is not to say that it can't; it just picks up the dummy DllMain that the CRT defines (which basically turns off per-thread initialization and reports success).


text:
Q: Use an array in an array All,
I've got the following code:
array(
        'id'        => 'tweet_slider',
        'name'      => __( 'Slide', TB_GETTEXT_DOMAIN ),
        'desc'      => __( 'Select the icon you\'d like shown before the Tweet.', TB_GETTEXT_DOMAIN ),
        'type'      => 'select',
        'std'       => 'twitter_display_option',
        'options'   => array(
            'single_twitter'    => __( 'Show Single Tweet', TB_GETTEXT_DOMAIN ),
            'slider_twitter'    => __( 'Show Twitter Slider', TB_GETTEXT_DOMAIN ),
        )
    ),

This works fine but I'd basically like to add options to my options array dynamically. I tried to do something like this:
$menus = wp_get_nav_menus();
foreach ( $menus as $menu ) :
    $menu_options =  'single_twitter'   => __( 'Show Single Tweet', TB_GETTEXT_DOMAIN ),
endforeach;
$menu_options = (array)$menu_options;

array(
        'id'        => 'menu_options',
        'name'      => __( 'Enter in your Menu Options', TB_GETTEXT_DOMAIN ),
        'desc'      => __( 'Enter in your menu options.', TB_GETTEXT_DOMAIN ),
        'std'       => '',
        'type'      => 'select',
        'options'   =>  $menu_options,
    ),

This gives me the error:

Parse error: syntax error, unexpected T_DOUBLE_ARROW

Is there a way to go about doing something like this?? Thanks

A: Try this:
$menu_options = array();
foreach ( $menus as $menu ) :
    $menu_options[] = array( 'single_twitter' => __( 'Show Single Tweet', TB_GETTEXT_DOMAIN));
endforeach;

Edit: Per the comment, you could try something like:
foreach ( $menus as $menu ) :
    $menu_options[] = array( $menu->menu_id => __( $menu->name, TB_GETTEXT_DOMAIN));
endforeach;

A: You are getting a syntax error because you cannot use the => symbol in that position. You can add an item to an array using:
$menu_options['single_twitter'] = __( 'Show Single Tweet', TB_GETTEXT_DOMAIN );

or, in general:
$menu_options = array();
foreach ($menus as $menu) {
    $key = ...
    $value = ...
    $menu_options[$key] = $value;
}

where $key and $value are obtained using $menu. In the main array, you can then write:
'options' => $menu_options

A: The way to build an array from scratch is
$myArray = array();
$myArray['some_key'] = some_value ;
$myArray['some_other_key'] = some_other_value ;

Try and apply that to your situation in your foreach loop.


text:
Q: How to make links in a textview not clickable except the chosen one I have a textview like following (Just an example the text is dynamic)
<TextView
        android:id="@+id/msgtext"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:autoLink="web"
        android:text="hi visit: www.abc.com  or http://www.cde.com or efg.com or www.mywebsite.com or mywebsite.com/privacy.php"
        />

How is it possible to make links from mywebsite.com only clickable.
Means In the above textview www.mywebsite.com and mywebsite.com/privacy.php only be the clickable links.
Any help?

A: you can try something like below.
view.setText(Html.fromHtml("This is a link"));

A: Before you do setText(stuff)
Parse it to find out the indicies start/end of where your url is.
Then you will need to use SpannableString and ClickableSpan
Followed by something like this:
span.setSpan(clickableSpan, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
Now go ahead setText and setMovementMethod

A: Try
 TextView textView= (TextView) findViewById(R.id.msgtext);

 textView.setText(Html.fromHtml("hi visit:" +
                "www.abc.com "+"the rest of your text"));
 textView.setMovementMethod(LinkMovementMethod.getInstance());


text:
Q: SQL select by qualifying multiple strings I have to find student names who are enrolled in a class AND also in another class. But when I do a WHERE statement it cuts out out all the other lines that have the other classes.
So my question is: How would I go about doing it so that it compares the entire group and only selects students that are both in CLASSA and CLASSB.
Some of the students are in CLASSA and some of them are in CLASSB and some are in both. How do I get the one that is in both?
For example:

*

*John Smith is in CLASSA

*BETTY WHITE is in CLASSB

*Timmy Edwards is in CLASSA

*Timmy Edwards is in CLASSB

If I use an OR, it will select all of the names. But I only want a student that is in BOTH classes. So Timmy Edwards is the one I want selected.
WHERE C.DESCRIPTION LIKE 'Systems Analysis%'

AND C.DESCRIPTION LIKE 'Project Management%'

A: You can do use group by and having:
select student
from enrollments
where class in ('CLASSA', 'CLASSB')
group by student
having count(*) = 2;

This version assumes that a student can be enrolled only once for a given class.

A: No individual row will every have information for both classes. That means that AND and OR as you're using them are useless. You need to check for the existence of such rows using the EXISTS keyword.
select distinct
  student
from
  enrollments
where
  exists (
    select
      1
    from
      enrollments e1
    where
      e1.student   = enrollments.student
      and e1.class = 'CLASSA'
  ) and exists (
    select
      1
    from
      enrollments e2
    where
      e2.student   = enrollments.student
      and e2.class = 'CLASSB'
  )

Note:
Each row will have the student name in it, so I've added the DISTINCT keyword to remove the duplicates.

A: You could try something like this, (although im not sure what exactly your schema is like...)
    WITH a AS
    (
        SELECT
        S.FIRST_NAME||' '||S.LAST_NAME [Student]
        ,C.DESCRIPTION
        FROM STUDENT S
        JOIN ENROLLMENT E ON (E.STUDENT_ID = S.STUDENT_ID)
        JOIN SECTION SE ON (SE.SECTION_ID = E.SECTION_ID)
        JOIN COURSE C ON (C.COURSE_NO = SE.COURSE_NO)

        WHERE C.DESCRIPTION  = 'CourseA'
    )
    ,b AS
    (
        SELECT
        S.FIRST_NAME||' '||S.LAST_NAME [Student]
        ,C.DESCRIPTION
        FROM STUDENT S
        JOIN ENROLLMENT E ON (E.STUDENT_ID = S.STUDENT_ID)
        JOIN SECTION SE ON (SE.SECTION_ID = E.SECTION_ID)
        JOIN COURSE C ON (C.COURSE_NO = SE.COURSE_NO)

        WHERE C.DESCRIPTION  = 'CourseB'
    )

    Select a.Student, a.Description [DescA], b.Description [DescB]
    from a join b on a.Student = b.Student

    --optional where to just get students in both classes...
    where a.Description is not null and b.Description is not null

Hope this assists...

A: You can always try the neat trick of joining a SELECT result with itself and then selecting from that result.
SELECT A.NAME
FROM (SELECT S.FIRST_NAME||' '||S.LAST_NAME as NAME,
             S.STUDENT_ID as S_ID,
             C.DESCRIPTION as DESC
        FROM STUDENT S
        JOIN ENROLLMENT E ON (E.STUDENT_ID = S.STUDENT_ID)
        JOIN SECTION SE ON (SE.SECTION_ID = E.SECTION_ID)
        JOIN COURSE C ON (C.COURSE_NO = SE.COURSE_NO)) A

JOIN (S.STUDENT_ID as S_ID, C.DESCRIPTION as DESC
        FROM STUDENT S
        JOIN ENROLLMENT E ON (E.STUDENT_ID = S.STUDENT_ID)
        JOIN SECTION SE ON (SE.SECTION_ID = E.SECTION_ID)
        JOIN COURSE C ON (C.COURSE_NO = SE.COURSE_NO)) B

ON A.S_ID = B.S_ID
WHERE A.DESC LIKE 'Systems Analysis%'
  AND B.DESC LIKE 'Project Management%'
GROUP BY A.NAME