text:
Q: Building for macOS, but linking in object file built for free standing I am building ffmpeg and I get the following error for several files. I am not specifically building with the free standing flag, so cannot see why this is happening. What does it actually mean? Is there a problem with it, or is it an ignorable warning? If there's a problem, does anyone have any idea how to fix it?
Building for macOS, but linking in object file (~/Git/FFmpeg/FFmpegXcode/lib/libavutil.a(imgutils.o)) built for free standing

A: I know this question is for macOS, but I was getting this also for iOS and tvOS when building for the simulators (intel archs, not arm). While https://stackoverflow.com/a/59103419/1777839 certainly explains why this is happening, it doesn't provide a "fix".
This isn't a perfect fix, more of a work around, but it helped me out so I wanted to share it in case anyone else comes here with the same problem I had.
When you're building FFmpeg for the iOS or tvOS simulator, if you pass the --disable-asm flag to configure, this will make the linker error go away. Yes, it disables the optimized assembly pieces of FFmpeg for the simulators, but since it still works for ARM devices I wrote it off as being an acceptable solution. While it would be nice to use the same FFmpeg build options for both physical devices and simulators, at the very least this gets it working again.
Another option that worked was using Xcode 10 to build FFmpeg, but then you can't use the iOS/tvOS 13 SDKs (I don't think that really matters though). Besides, who wants to deal with switching Xcode just to compile a library anyways?

A: The problem is with .asm files in the FFmpeg build.
Apple Clang embeds a special load command in the object files with the target platform, system version and SDK version which it takes from -target or -mmacosx-version-min or some similar command line argument.
Linker then checks such load commands in all object files being linked and warns if it couldn't find such command or if it detects incompatibility.
Most of other compilers don't know about that load command and give no way to output it in the object file. Problems were seen at least in YASM (it manifests in this issue), in D and Go compilers, in Crystal.
Unfortunately I couldn't find a workaround to build good objects for asm sources in FFmpeg or to disable that warnings. I've created an issue for YASM but this is a long shot - first you need this feature in YASM, then you need a way to pass the required argument to FFmpeg build for the asm sources.
UPDATE
Starting with Xcode 12 it became a problem, because this warning became an error and it seems there is no way to disable or ignore this. But it looks like I've managed to hackaround that using approach suggested by tmm1. Unfortunately at the current stage it requires a lot of manual work.

*

*I've forked yasm and added padding to the output object file for the missing load command. (for building call ./autogen.sh and make)

*I've forked macho_edit and added a way to append the required load command with a command line invocation. (for building call xcodebuild build -configuration Release -project macho_edit.xcodeproj -target macho_edit)

*I've created a shell script that wraps invocation of the custom-built yasm and then custom built macho_edit with required arguments (you can set which macos version and sdk version you want to manifest as supported in this script).

*To build ffmpeg with this wrapper I copy macos_yasm_wrap.sh to the ffmpeg directory and add --x86asmexe=`pwd`/macos_yasm_wrap.sh argument to ./configure call.

This seems to work. The proper way of doing that would be adding correct command line arguments to yasm (like the ones Clang supports) and generating correct load commands in the first place. But I don't have time to do it this way right now :(


text:
Q: jquery remove() jumps back to the top of the page I have written a popup with an overlay (not dissimilar from the usual picture displayers) where the user clicks and an overlay covers the screen which fetches the big picture for display.
The problem is, when the user clicks 'close' my function fades out the picture and overlay then removes them. When I call the .remove() function, the browser then focuses on the body tag and scrolls to the top of the page.
I have attempted a work-around by capturing the offset.top co-ords and storing them in an attribute on the element the user clicks on, and when the popup is closed and after the .remove() function has been called, I use the scrollTo() function to return the correct scroll position (which for some reason overshoots and scrolls the element to the top).
/*creating the popup layer and picture*/
function newsPopup(obj){

    /***PART ZERO - get the timestamp value of this ***/
    var itemID = $(obj).attr('itemID');
    var storyNumber = $(obj).attr('storyNumber');

    /*adding the identifier for later*/
    var offset = $(obj).offset();
    var roundedOff = Math.round(offset.top);
    $(obj).attr('scrollMeBack', roundedOff);

     /*** the script then continues to create an overlay and picture popup
}

/*function to remove popup*/
function overlayRemove(){
    //first fade out the cover and the container
    $("#NEWS_overlay").fadeOut();
    $("#NEWS_centeringContainer").fadeOut();

    //then remove it from the page completely
    setTimeout('$("#NEWS_overlay").remove();$("#NEWS_centeringContainer").remove();',400);

    /*value to scroll the element back to*/
    var scrollBack = $('[SpringCMSscrollMeBack]').attr('SpringCMSscrollMeBack');
    setTimeout('$(window).scrollTop('+scrollBack+')',401); /*notes the 1 millisecond delay here to mean the scroll ahppen after the item has been removed.*/
    $('[scrollMeBack]').removeAttr('scrollMeBack');

}

Why is the .remove() function causing the jump back to the top of the page? Even with the scrollTo work around it looks sloppy as the stuff fades out, but jumps up to the top of the screen and then back down to the element in question.

A: See How can I remove the location hash without causing the page to scroll?  ;
Alternatively, you can return false; to stop this behavior...

redpajama_set_name: RedPajamaStackExchange


text:
Q: Confused about .net MVC View Models and Models So, I've read a bit about .net and MVC. I remember reading something that suggested using ViewModels in MVC. This would help lessen the desire to have the view messing with data that should be controlled by the controller.
I thought this is what is referred to by the MVVM pattern. Evidently after looking at that, the implementation actually does away with controllers altogether. Not exactly what I want to do.
Is it still legit to use a ViewModel in my case? Is it better practice or just unnecessary work? Where would you put your ViewModels directory/namespace at? Under the Models directory?
Is it legit for Models to know about ViewModels? For example, you have a Model Return a ViewModel to the controller?

A: ViewModels are not by default in MVC projects.  It is something you need to add if you feel it benefits you to couple View to a Model "easier"
http://rachelappel.com/use-viewmodels-to-manage-data-amp-organize-code-in-asp.net-mvc-applications
The concept of the ViewModel isn't just for ASP.NET MVC, as you'll see references to ViewModels throughout the web in articles and blog posts about the MVC, MVP, and MVVM patterns. Those posts and articles can center around any number of technologies such as ASP.NET, Silverlight, WPF, or MVC... This post will investigate ViewModels as they apply to the world of ASP.NET MVC.
http://msdn.microsoft.com/en-us/magazine/ff798279.aspx

A: Design patterns in my opinion are not rigid concepts, but rather guidelines that help you architect your application better.  The Model-View-ViewModel(MVVM) design pattern stems from WPF, where there is a very robust Bata Binding framework that facilitated the pattern.  The idea is that you have business data in your model, but since there are often view specific data(i.e the currently selected item in a tree control) that didn't belong in the model, you created view model objects that wraps your model, but the view models also contained view specific state data.  So your views can bind to the view models instead of the model objects directly, thus keeping the models clean(easy to test, maintain etc).
Asp.net MVC is different in that the databinding in the Views is nowhere near as powerful as it is in WPF.  In WPF you could actually implement much of your GUI and model data interaction through databinding, which made the view models useful.  But in Asp.net MVC your controllers are designed to handle this, and since the databinding is close to non existant I just don't see the value of having view model wrappers around your model objects in Asp.net MVC.

A: Models and ViewModels are different.  Don't confuse the ViewModel with the MVVM pattern.
The use of a view model can make the interaction between model and view more simple. A model can sometimes be over complicated having other model objects as members, which could have model objects as member etc..
By using a view model you have a good way to simplify what the view deals with. This will also filter down what can be seen in intellisense, so if you have different people developing the models than those working on the views, creating a simple view model can make it much easier for those just dealing with the UI.


text:
Q: Meta/ Few-shot Learning for time series regression I am working on the calibration of low-cost air sensor data (a time series regression problem). My primary focus is to use some meta/ few-shot learning approach to solve this problem with a lesser amount of data. I have tried using MAML on top of LSTM/vanilla NN but the results are not convincing. Is there a different approach/paper for meta-regression? Anything that I should be doing differently? Things to avoid etc? Thank you in advance.

A: In this paper the authors recast MAML and Multimodal MAML for time series regression by creating "meta-windows", which are a group of rolling windows and are considered proxies for time series tasks.


text:
Q: How can I make an animation with timer? I wanted to make a method that took a timer and ascii text and changed the text when the timer hit 1 second and back again when the timer hits 2. I created this timer but didn't know how to use it to do that method. Can anyone help?
public void TimePassed()
{
    Timer t1 = new Timer(1000);
    t1.Elapsed += Timer_Elapsed;

    t1.Start();

    Console.ReadKey();

    t1.Stop();
}

public void Timer_Elapsed(object sender, ElapsedEventArgs e)
{
    timerPlayerOneAnimation++;
    Console.WriteLine(timerPlayerOneAnimation + " " + DateTime.Now);
}

A: Simply check if your counter is even or odd?
public void Timer_Elapsed(object sender, ElapsedEventArgs e)
{
    // possibly set the cursor position?
    Console.SetCursorPosition(someRow, someColumn);

    timerPlayerOneAnimation++;
    if (timerPlayerOneAnimation % 2 == 0) {
        // Display one thing
    }
    else {
        // Display something else
    }
}


text:
Q: Devise omniauth is redirecting to failure method in callback controller even after successful authentication.? I am working on devise omniauth to authenticate user using facebook. I have implemented it using the documentation https://github.com/plataformatec/devise/wiki/OmniAuth:-Overview
It is not working fine. When I login using my facebook account then it takes me to the "failure" method in the callback controller.
But the interesting thing is that when I open facebook it open without any problem means it is authenticating my account.
I have checked it so many times by login and logout from facebook. But the problem is that If it is authenticating facebook account then why it takes me to "failure method".
here is my code
callback controller.
class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController
  def facebook
    # You need to implement the method below in your model (e.g. app/models/user.rb)
    @user = User.from_omniauth(request.env["omniauth.auth"])
    if @user.persisted?
      sign_in_and_redirect @user, :event => :authentication #this will throw if @user is not activated
      set_flash_message(:notice, :success, :kind => "Facebook") if is_navigational_format?
    else
      session["devise.facebook_data"] = request.env["omniauth.auth"]
      redirect_to new_user_registration_url
    end
  end

  def failure
    render plain: params.inspect
   # redirect_to root_path
  end
end

User model
class User < ApplicationRecord
  # Include default devise modules. Others available are:
  devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable, :confirmable
  devise :omniauthable, :omniauth_providers => [:facebook]

def self.from_omniauth(auth)
    where(provider: auth.provider, uid: auth.uid).first_or_create do |user|
      user.email = auth.info.email
      user.password = Devise.friendly_token[0,20]
      user.name = auth.info.name   # assuming the user model has a name
      user.image = auth.info.image # assuming the user model has an image
      # If you are using confirmable and the provider(s) you use validate emails,
      # uncomment the line below to skip the confirmation emails.
      # user.skip_confirmation!
    end
  end

  def self.new_with_session(params, session)
    super.tap do |user|
      if data = session["devise.facebook_data"] && session["devise.facebook_data"]["extra"]["raw_info"]
        user.email = data["email"] if user.email.blank?
      end
    end
  end
end

route code
devise_for :users,  controllers: {confirmations: 'confirmations',registrations: 'users/registrations',omniauth_callbacks: 'users/omniauth_callbacks' } do
    #put "confirm_user", to: "confirmations#confirm_user"
    get "confirmation", to: "confirmations#after_confirmation_path_for"
  end

Facebook app setting screenshot is
https://www.dropbox.com/s/vn8cjpr5wyagkdp/Screenshot%202017-11-27%2017.04.28.png?dl=0
development logs after sign in are
Started GET "/users/auth/facebook" for 10.0.2.2 at 2017-11-28 14:13:37 +0000
Cannot render console from 10.0.2.2! Allowed networks: 127.0.0.1, ::1, 127.0.0.0/127.255.255.255
Started GET "/users/auth/facebook/callback?code=AQA8oLlPsMLSvZf5NqZfOA0oJxDVKczwqqMIxWPD2dJoucpJl9T7MLTmf0mMDlOhgQPAhKa2f6My4vWGZmTWhVo6S5TbSQ3ELup1iBhDHTb869pMMo-ksa1Kh1gJDG65ZJxUj5vAe8jH-DX0eBRpf_ygZACCoFYFTiZdAIzCXQI7jfLaeqH70CqAffkGZczYzhjThM_NLol3Lzo18ZX_6_5n2-p7nMC3IKhmzDEyo_toyaI1telD3QMwa0re7GIu-UXKV4DQp-ClLT452Bigp9Fhs50wYm-Kl08E7195R2mpBESpB7Gu0moDbCgi61dEEk5u8GGfmm0Cxbu9Fcw1_Eu8" for 10.0.2.2 at 2017-11-28 14:13:40 +0000
Cannot render console from 10.0.2.2! Allowed networks: 127.0.0.1, ::1, 127.0.0.0/127.255.255.255
Processing by Users::OmniauthCallbacksController#failure as HTML
  Parameters: {"code"=>"AQA8oLlPsMLSvZf5NqZfOA0oJxDVKczwqqMIxWPD2dJoucpJl9T7MLTmf0mMDlOhgQPAhKa2f6My4vWGZmTWhVo6S5TbSQ3ELup1iBhDHTb869pMMo-ksa1Kh1gJDG65ZJxUj5vAe8jH-DX0eBRpf_ygZACCoFYFTiZdAIzCXQI7jfLaeqH70CqAffkGZczYzhjThM_NLol3Lzo18ZX_6_5n2-p7nMC3IKhmzDEyo_toyaI1telD3QMwa0re7GIu-UXKV4DQp-ClLT452Bigp9Fhs50wYm-Kl08E7195R2mpBESpB7Gu0moDbCgi61dEEk5u8GGfmm0Cxbu9Fcw1_Eu8"}
  Rendering text template
  Rendered text template (0.0ms)
Completed 200 OK in 20ms (Views: 10.6ms | ActiveRecord: 0.0ms)

The result of params.inspect is as follows
<ActionController::Parameters {"code"=>"AQA8oLlPsMLSvZf5NqZfOA0oJxDVKczwqqMIxWPD2dJoucpJl9T7MLTmf0mMDlOhgQPAhKa2f6My4vWGZmTWhVo6S5TbSQ3ELup1iBhDHTb869pMMo-ksa1Kh1gJDG65ZJxUj5vAe8jH-DX0eBRpf_ygZACCoFYFTiZdAIzCXQI7jfLaeqH70CqAffkGZczYzhjThM_NLol3Lzo18ZX_6_5n2-p7nMC3IKhmzDEyo_toyaI1telD3QMwa0re7GIu-UXKV4DQp-ClLT452Bigp9Fhs50wYm-Kl08E7195R2mpBESpB7Gu0moDbCgi61dEEk5u8GGfmm0Cxbu9Fcw1_Eu8"} permitted: false>

The output of rake routes is
rake routes
                                Prefix Verb     URI Pattern                                                     Controller#Action
                      new_user_session GET      /users/sign_in(.:format)                                        devise/sessions#new
                          user_session POST     /users/sign_in(.:format)                                        devise/sessions#create
                  destroy_user_session DELETE   /users/sign_out(.:format)                                       devise/sessions#destroy
      user_facebook_omniauth_authorize GET|POST /users/auth/facebook(.:format)                                  users/omniauth_callbacks#passthru
       user_facebook_omniauth_callback GET|POST /users/auth/facebook/callback(.:format)                         users/omniauth_callbacks#facebook
       user_twitter_omniauth_authorize GET|POST /users/auth/twitter(.:format)                                   users/omniauth_callbacks#passthru
        user_twitter_omniauth_callback GET|POST /users/auth/twitter/callback(.:format)                          users/omniauth_callbacks#twitter
                     new_user_password GET      /users/password/new(.:format)                                   devise/passwords#new
                    edit_user_password GET      /users/password/edit(.:format)                                  devise/passwords#edit
                         user_password PATCH    /users/password(.:format)                                       devise/passwords#update
                                       PUT      /users/password(.:format)                                       devise/passwords#update
                                       POST     /users/password(.:format)                                       devise/passwords#create
              cancel_user_registration GET      /users/cancel(.:format)                                         users/registrations#cancel
                 new_user_registration GET      /users/sign_up(.:format)                                        users/registrations#new
                edit_user_registration GET      /users/edit(.:format)                                           users/registrations#edit
                     user_registration PATCH    /users(.:format)                                                users/registrations#update
                                       PUT      /users(.:format)                                                users/registrations#update
                                       DELETE   /users(.:format)                                                users/registrations#destroy
                                       POST     /users(.:format)                                                users/registrations#create
                 new_user_confirmation GET      /users/confirmation/new(.:format)                               confirmations#new
                     user_confirmation GET      /users/confirmation(.:format)                                   confirmations#show
                                       POST     /users/confirmation(.:format)                                   confirmations#create
                     new_model_session GET      /models/sign_in(.:format)                                       devise/sessions#new
                         model_session POST     /models/sign_in(.:format)                                       devise/sessions#create
                 destroy_model_session DELETE   /models/sign_out(.:format)                                      devise/sessions#destroy
                    new_model_password GET      /models/password/new(.:format)                                  devise/passwords#new
                   edit_model_password GET      /models/password/edit(.:format)                                 devise/passwords#edit
                        model_password PATCH    /models/password(.:format)                                      devise/passwords#update
                                       PUT      /models/password(.:format)                                      devise/passwords#update
                                       POST     /models/password(.:format)                                      devise/passwords#create
             cancel_model_registration GET      /models/cancel(.:format)                                        devise/registrations#cancel
                new_model_registration GET      /models/sign_up(.:format)                                       devise/registrations#new
               edit_model_registration GET      /models/edit(.:format)                                          devise/registrations#edit
                    model_registration PATCH    /models(.:format)                                               devise/registrations#update
                                       PUT      /models(.:format)                                               devise/registrations#update
                                       DELETE   /models(.:format)                                               devise/registrations#destroy
                                       POST     /models(.:format)                                               devise/registrations#create
                new_model_confirmation GET      /models/confirmation/new(.:format)                              devise/confirmations#new
                    model_confirmation GET      /models/confirmation(.:format)                                  devise/confirmations#show
                                       POST     /models/confirmation(.:format)                                  devise/confirmations#create
               donations_donor_history GET      /donations/donor_history(.:format)                              donations#donor_history
                donations_donor_signup GET      /donations/donor_signup(.:format)                               donations#donor_signup
                                       POST     /donations/donor_signup(.:format)                               donations#donor_signup
                 donations_sms_service POST     /donations/sms_service(.:format)                                donations#sms_service
         donations_create_user_account POST     /donations/create_user_account(.:format)                        donations#create_user_account
            donations_add_user_payroll POST     /donations/add_user_payroll(.:format)                           donations#add_user_payroll
                             donations GET      /donations(.:format)                                            donations#index
                         edit_donation GET      /donations/:id/edit(.:format)                                   donations#edit
                              donation GET      /donations/:id(.:format)                                        donations#show
                                       PATCH    /donations/:id(.:format)                                        donations#update
                                       PUT      /donations/:id(.:format)                                        donations#update
                                       DELETE   /donations/:id(.:format)                                        donations#destroy
                    campaign_donations POST     /campaigns/:campaign_id/donations(.:format)                     donations#create
                 new_campaign_donation GET      /campaigns/:campaign_id/donations/new(.:format)                 donations#new
campaign_donations_create_user_account GET      /campaigns/:campaign_id/donations/create_user_account(.:format) donations#create_user_account
                             campaigns GET      /campaigns(.:format)                                            campaigns#index
                                       POST     /campaigns(.:format)                                            campaigns#create
                          new_campaign GET      /campaigns/new(.:format)                                        campaigns#new
                         edit_campaign GET      /campaigns/:id/edit(.:format)                                   campaigns#edit
                              campaign GET      /campaigns/:id(.:format)                                        campaigns#show
                                       PATCH    /campaigns/:id(.:format)                                        campaigns#update
                                       PUT      /campaigns/:id(.:format)                                        campaigns#update
                                       DELETE   /campaigns/:id(.:format)                                        campaigns#destroy
                         organizations GET      /organizations(.:format)                                        organizations#index
                                       POST     /organizations(.:format)                                        organizations#create
                      new_organization GET      /organizations/new(.:format)                                    organizations#new
                     edit_organization GET      /organizations/:id/edit(.:format)                               organizations#edit
                          organization GET      /organizations/:id(.:format)                                    organizations#show
                                       PATCH    /organizations/:id(.:format)                                    organizations#update
                                       PUT      /organizations/:id(.:format)                                    organizations#update
                                       DELETE   /organizations/:id(.:format)                                    organizations#destroy
          admins_social_sharing_switch POST     /admins/social_sharing_switch(.:format)                         admins#social_sharing_switch
                   admins_error_detail GET      /admins/error_detail(.:format)                                  admins#error_detail
                                       GET      /admins/generate_report/:id(.:format)                           admins#generate_report
                 admins_create_company GET      /admins/create_company(.:format)                                admins#create_company
                                       POST     /admins/create_company(.:format)                                admins#create_company
                 admins_revenue_detail GET      /admins/revenue_detail(.:format)                                admins#revenue_detail
                 admins_create_account GET      /admins/create_account(.:format)                                admins#create_account
                   admins_view_account GET      /admins/view_account(.:format)                                  admins#view_account
                                       GET      /admins/view_company/:id(.:format)                              admins#view_company
              admins_donation_analysis GET      /admins/donation_analysis(.:format)                             admins#donation_analysis
                    admins_link_expiry GET      /admins/link_expiry(.:format)                                   admins#link_expiry
                   admins_edit_profile GET      /admins/edit_profile(.:format)                                  admins#edit_profile
                 admins_update_profile POST     /admins/update_profile(.:format)                                admins#update_profile
                                       POST     /admins/create_account(.:format)                                admins#create_account
                         admin_destroy GET      /admins/:id(.:format)                                           admins#destroy
                                admins GET      /admins(.:format)                                               admins#index
                                       POST     /admins(.:format)                                               admins#create
                             new_admin GET      /admins/new(.:format)                                           admins#new
                            edit_admin GET      /admins/:id/edit(.:format)                                      admins#edit
                                 admin GET      /admins/:id(.:format)                                           admins#show
                                       PATCH    /admins/:id(.:format)                                           admins#update
                                       PUT      /admins/:id(.:format)                                           admins#update
                                       DELETE   /admins/:id(.:format)                                           admins#destroy
                crons_expirylink_alert GET      /crons/expirylink_alert(.:format)                               crons#expirylink_alert
                        users_sign_out GET      /users/sign_out(.:format)                                       devise/sessions#destroy
                                  root GET      /                                                               campaigns#latest

A: After hardwork of 2 days I have finally solved it myself. Every thing was fine except the gem itself. If you just write the gem omniauth-facebook it would install version 1.4.0 which is very old. I update it to gem 'omniauth-facebook', '~> 4.0' and it is working like a charm. So if anyone face the same issue he should update the gem.


text:
Q: How to Parse JSON in Android SDK?
Possible Duplicate:
How to Parse a JSON Object In Android

i have JSON object like following .. How can i parse the Object?
{
  "0":
     {
       "productname":"Famous Amos Bite Size Chocolate Chip Cookies - 4 Pack",
       "imageurl":"http://ecx.images-amazon.com/images/I/513j-WyH1GL._SL160_.jpg",
       "producturl":"http://www.searchupc.com/rd.aspx?u=d%2bKvXQ%2fFIfa95xJ38QYLycSjbm5dt4dy3l4IYTYPM3agt4tefTNsMwzWkPWd9gCY%2fEnCdaGVMLsQD%2fO5ZUWbfJyqOuwIWqkLvouDyw5u7VWmda5dK2%2fRTmcAp3%2f1TImmZmtdaNauL74Lj8BkV0r15VeazeDf4Im4Nx%2f5TOuqBUnUXzeNkYrWvlLitV8FDFIkM77UIjZzYZqoQANt0PBNeqh94bzLqFRXpNYPyqc0fLDTHnA9TM2jsbaKVN23UA%2fH",
       "price":"5.95",
       "currency":"usd",
       "saleprice":"",
       "storename":"amazon.com"
     }
}

A: An example below demonstrates how to parse JSON. You will get a very clearcut explanation about json parsing here.
JSONObject myjson = new JSONObject("put you json string here");
JSONArray the_json_array = myjson.getJSONArray("0");
int size = the_json_array.length();
for (int i = 0; i < size; i++) {
JSONObject another_json_object = the_json_array.getJSONObject(i);
    System.out.println((String) another_json_object.get("productname"));
    System.out.println((String) another_json_object.get("imageurl"));
    System.out.println((String) another_json_object.get("producturl"));
}

A: Android provides the org.json package that can be used to parse your String to a JSONObject.
You can achieve this with this line of code:
JSONObject json = new JSONObject(myJsonString);

A: You've to use the JSONObject for this. Use of below code -
JSONParser .java
public JSONObject getJSONFromUrl(String url)  // url is your json url
{

    // Making HTTP request
    try {
        // defaultHttpClient
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);

        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        is = httpEntity.getContent();

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "n");
        }
        is.close();
        json = sb.toString();
    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }

    // try parse the string to a JSON object
    try {
        jObj = new JSONObject(json);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    // return JSON String
    return jObj;

}

it will return the JsonObject And, using this jsonbobject we can get the result as array.
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();

// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);

try {
    // Getting Array of Contacts
    contacts = json.getJSONArray(TAG_CONTACTS);

    for(int i = 0; i < contacts.length(); i++) {

        String product_name = contacts.getString("productname");
        String image_url = contacts.getString("imageurl");
        .....
        .....
        String store_name = contacts.getString("storename");
    }
}catch(JSONException e)
{
    e.printStackTrace();
}

For more just refer Android json tutorial

A: There is a working example YatayatService that uses json library and custom JsonParser.java using apache http library.
The implementation method is getAllRoutes().
String jsonString = JsonParser.parseJSON(URL);
try {
    JSONObject parentObject = new JSONObject(jsonString);
 } catch (JSONException e) {
    e.printStackTrace();
 }

A: Try This code
 // getting JSON string from URL
    JSONObject json = jParser.getJSONFromUrl(url);

    System.out.println("json is "+json);
    System.out.println("Length"+json.length());

    for (int i = 0; i < json.length(); i++) {
        try {
            String atObj = Integer.toString(i);
            System.out.println(atObj);
            JSONObject jObj = json.getJSONObject(atObj);
            System.out.println(jObj.getString("productname"));
            System.out.println(jObj.getString("imageurl"));
            System.out.println(jObj.getString("producturl"));
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }


text:
Q: Converting a String to DateTime with new format How do you convert a string such as 13.11.2017 into a DateTime with that format 13/11/2017
I tried several ways but i didn't get solution  .
string Arrival = Request.QueryString["Arrival"];//13.11.2017
DateTime datee = DateTime.ParseExact(Arrival , "dd/MM/yyyy", null);

here is updated code i split the string :
            string Arrival = Request.QueryString["Arrival"];//13.11.2017
      string year = Arrival.Split('.')[2];
                   string month = Arrival.Split('.')[1];
                        string day = Arrival.Split('.')[0];
                        string date = day + "/" + month + "/" + year;
                        DateTime datee = DateTime.ParseExact(date, "dd/MM/yyyy", null);

A: Observe:
// the input string
string inputString = "13.11.2017";

// parse the input string with a specific format to create a DateTime
DateTime dt = DateTime.ParseExact(inputString, "dd.MM.yyyy", CultureInfo.InvariantCulture);

// create a string from the DateTime using a different specific format
string outputString = dt.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture);

// output the string
Console.WriteLine(outputString);  // "13/11/2017"

Note that a DateTime itself does not have any particular format.  A format only comes into play when going to or from a string.
Also note that by using the invariant culture here, we are avoiding any issues that may arise if the current culture was one that used different date separators or a different calendar system.

A: Had the same problem with Russian locale.
Currently using ISO format everywhere to avoid incorrect DateTime understandings (like MM.dd when you mean dd.MM).
public static string ToIsoStr(this DateTime dateTime)
    {
        return dateTime.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);
    }

Your task will be solved with
return dateTime.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture);

A: using System.Text.RegularExpressions;

string Arrival = Request.QueryString["Arrival"]; // 13.11.2017
string dateString = Regex.Replace(Arrival, @"\.", "/"); // 13/11/2017
DateTime date = DateTime.ParseExact(dateString , "dd/MM/yyyy", null); // 11/13/2017 00:00:00


text:
Q: Угол между отрезком и Ox Как по двум точкам A = (x0,y0), B = (x1,y1) узнать, какой угол составляет отрезок AB с осью Ox?

A: Например
atan2(y1 - y0, x1 - x0)

A: Есть красивая формула скалярного произведения векторов:
Так что, поскольку вектор AB = (x1-x0,y1-y0), то, понятно, что косинус угла равен (x1-x0)/sqrt((x1-x0)*(x1-x0)+(y1-y0)*(y1-y0)). Поскольку точки у вас не совпадающие, деления на 0 стопроцентно не будет.
P.S. Но решение @VladD более корректное. Я забыл про atan2, помнил только atan...

A: Формулировка вопроса неоднозначна.
Геометрический угол между лучами АВ и OX следует считать по формуле
atan2(abs(y1-y0),x1-x0)


text:
Q: aptly lists snapshots that it then cannot find I'm not sure what's going on here or how to remedy. I want to delete the old snapshot. There are several more of these that are in the same state.
# aptly snapshot list  -raw | grep bionic-backports-202108131557
bionic-backports-202108131557

# aptly snapshot list -raw | grep bionic-backports-202108131557 | xargs -n1 aptly snapshot show
ERROR: unable to show: snapshot with name bionic-backports-202108131557 not found

# aptly snapshot list -raw | grep bionic-backports-202108131557 | xargs -n1 aptly snapshot drop
ERROR: unable to drop: snapshot with name bionic-backports-202108131557 not found

My expectation would be that any snapshot that aptly snapshot list lists could be found and acted upon.
(I don't have enough reputation to create the 'aptly' tag. A tag is required so I chose 'apt' though this isn't an 'apt' question.)


text:
Q: How can I segregate properties of DateTime? I would like to write: if the result of the difference of 2 DateTimes is longer than 3 hours then.... stuff in the if statement happens. But I only need properties in seconds or minutes, can I extract just that from the DateTime object?
  if(diffResult > DateTime.Hour(3))
   {
   }

I also want to know if its possible to divide DateTime by periods. Say I want to split my diffResult (which is the difference between 2 DateTimes) into 3 periods or perhaps for every 3 seconds my counter gets one added to it.

A: For the first part:
You can subtract two DateTimes to get a TimeSpan there you can get the total of various units - for example:
if ( (secondTime - firstTime).TotalMinutes > 180.0) ...

or you could use TimeSpan directly:
if (secondTime - firstTime > TimeSpan.FromHours(3)) ...

for the secondpart you have to do some calculation yourself:
var diff = secondTime - firstTime;
var period = TimeSpan.FromSeconds(diff.TotalSeconds / 3.0);
for (var time = firstTime; time < secondTime; time += period)
{ /* do your stuff */ }

A: U can compare using the follow code:
  DateTime dt = new DateTime();
                dt = DateTime.Now;
                dt.AddHours(3);
                int h = (int)DateTime.Now.Hour;
                if (dt.Hour == h )
                   //Do something
                else
                   //do otherthing

A: You can do this:
TimeSpan time = new TimeSpan(3, 0, 0);
if (date1.Subtract(date2) > time)
{
//YourCode
}

For the second, this article should be useful:
http://www.blackwasp.co.uk/TimespanMultiplication.aspx

A: The methods your asking about return integer results. What exactly is your question? DateTime.Hour(3) would not even compile.
I think you are looking for DateTime.Now.AddHours(3.0)
I should be clear, the only reason this answer is this sparse, is because of the invalid code in the author's question which.  Since I don't attempt to guess at what people actually want, its up to the author, to clarify what he wants exactly.
All he has to do is subtract two DateTime values and compare it to a TimeSpan


text:
Q: Windows 7 - Modify "advanced settings" tab of Device Manager from command line I'm in a position where I need to enable Wake on LAN for roughly 50 machines. I don't want to have to go round every one and adjust the settings for it, but it's looking increasingly like I'll have to.
The network cards have a setting in the "advanced" tab of the adapter configuration panel that needs to be toggled from "off" to on to allow the wake on LAN to take place (I can't provide a screenshot from one of the machines with that card, but here's one of the same dialog from a virtual machine so you know which one I mean).
Note that this setting isn't the same as the one on the power management tab.
I'd ideally like to change this configuration from a command line utility or script; could anyone point me to a location in the registry where device configuration is held, or a utility which could change these settings from Command Prompt?
Thus far, I've found DevCon - a command line alternative/frontend to device manager, but I don't think it has the settings I need.
Cheers in advance :)

A: It appears this can be set using WMI.  Look at the Win32_NetworkAdapterConfiguration class for the details.  Also, you can use Powershell to manipulate WMI from the command-line.

A: Since jackweirdy did not provide the exact location of the keys he modified, they can be found here:
HKLM\SYSTEM\CurrentControlSet\Control\Class\{4D36E972-E325-11CE-BFC1-08002BE10318}

You just need to simply determine the correct adapter....Vinith Menon has provided a great example of this here:
https://gallery.technet.microsoft.com/scriptcenter/Configure-iSCSI-Network-81232a5e/view/Reviews
Simply scroll down to the relevant part of the script under the following comment:

<#Below we set the advanced property #>

A: Solved this by searching in the registry for the brand name and modifying a boolean key in the HKEY_Local_Machine\system branch for the network card.


text:
Q: Rendering javascript in render_callback php Code I've got a block-based plugin that displays a leafletjs map. The map displays perfectly in a WP Post. However, in the block editor, the map fails to display. The heading2, 'Leaflet.js Map' shows, with a blank space below where the map should be.
It looks like the javascript to display the leaflet map isn't being executed in the editor.
Render_callback function to display the map
function showMap($atts) {

    $maphtml = "
Leaflet.js Map
";

    $maphtml = $maphtml . "

";

    $maphtml = $maphtml . "";
    return $maphtml;
}

and is registered here:
    register_block_type(
        'cgb/block-my-block', array(
            // Enqueue blocks.style.build.css on both frontend & backend.
            'style'         => 'my_block-cgb-style-css',
            // Enqueue blocks.build.js in the editor only.
            'editor_script' => 'my_block-cgb-block-js',
            // Enqueue blocks.editor.build.css in the editor only.
            'editor_style'  => 'my_block-cgb-block-editor-css',

            'render_callback' => 'showMap',
        )
    );

Loading css & js for Leafletjs
function leafletjs_load(){
    // Custom css for table containing map and data
    $cssurl = plugins_url('/styles/showfitfile.css', __FILE__);
    wp_enqueue_style('showfitfile_css', $cssurl);

    //CSS and JS for Leaflet
    $leafletcss = plugins_url('/styles/leaflet.css', __FILE__);
    $leafletjs = plugins_url('/styles/leaflet.js', __FILE__);
    wp_enqueue_style('leafletjs_css', $leafletcss);
    wp_enqueue_script('leafletjs', $leafletjs);
}

add_action('enqueue_block_assets', 'leafletjs_load');

The editor javascript code
    edit: ( props ) => {
        const { attributes, setAttributes } = props;
        // Creates a

.
        return (
            <ServerSideRender
                block = "cgb/block-my-block"
            />
        );
    },

Trying to troubleshoot this, I get the impression that it's not possible to render javascript within the render_callback php code, and I'll need to rewrite the block editor entirely in javascript. Is this correct, or have I messed up somewhere else?


text:
Q: Semantic UI Dropdown - How to set default values with Angular JS scope? I have a semantic ui multiple search dropdown and I need to set default values to it from some data from a database that is stored into the scope.
Dropdown code:

    <input type = "hidden"  >

Selecciona...

Directive code:
app.directive('dropdownSearchPersonalities', function () {
    return {
        restrict : 'A',
        link : function (scope, elem, attrs) {
            $(elem).dropdown({
                allowAdditions : true,
                'set selected' : scope.studentPersonalities,
                onAdd: function (value) {
                    scope.addPersonality(value, scope.studentId);
                },
                onRemove: function (value) {
                    scope.removePersonality(value, scope.studentId);
                }
            });
        }
    }
});

If i console.log the scope inside the directive I do get the information I want to use structured the following way:

I'm not sure if this is the correct way to set default values to the dropdown, since in the view its showing nothing.


text:
Q: Instagram Developer Key Registration Not Available I tried to apply the Instagram developer client but realize it's not available.
In the registration page,
There should be a Captcha before submitting the application. But it doesn't exist so I always get the error saying "Submission error: please fill out all required fields" while trying to submit.
Does Instagram stop providing new client key?
This screenshot shows that the Captcha is not loaded.

A: Use chrome extension Disable Content-Security-Policy. Captcha is not appearing because of cross domain issue (Instagram need to fix this it is bug on there end).


text:
Q: Постраничный вывод Вводятся значения: начальное x1 и конечное x2 с шагом dx

x1       f
x1+dx    f
x1+dx+dx f

и так далее. Выводится вся информация сразу в виде таблицы. А как организовать постраничный вывод, например, по 10 значений? Вот вывело 10 строк, далее нажал клавишу еще 10 строк и так далее.
for (x = X1; x <= X2; x += dX) {
    if ((x < 0) && (b != 0)) {
        if (10 + b == 0) {
            printf("| %0.2f |error|n", x);
        } else {
            F = a - (x / (10 + b));        //pow âîçâåäåíèå â ñòåïåíü
            printf("| %0.2f | %0.2f |n", x, F);
        }
    } else {
        if ((x > 0) && (b == 0)) {
            if ((x - c) == 0) {
                printf("| %0.2f |error|n", x);
            } else {
                F = (x - a) / (x - c);
                printf("| %0.2f | %0.2f |n", x, F);
            }
        } else {
            if (c == 0) {
                printf("| %0.2f |error|n", x, F);
            } else {
                F = 3 * x + 2 / c;
                printf("| %0.2f | %0.2f |n", x, F);
            }
        }
    }
}

A: #include <conio.h>

for (x = X1, i=0; x <= X2; x += dX, i++) {
    if(i==10) {
        puts("Press any key...");
        _getch();
        i=0;
    }

    // остальная часть цикла
}


text:
Q: how can i output the six numbers in an array because it is giving me only zero Sub Main()
    Dim Num1 As Byte
    Dim Num2 As Byte
    Dim Num3 As Byte
    Dim Num4 As Byte
    Dim Num5 As Byte
    Dim Num6 As Byte
    Dim arrValue(5) As Integer
    Dim result As String = String.Join("", arrValue)

    Randomize()
    Num1 = CInt(Math.Ceiling(Rnd() * 40))
    Console.WriteLine("Num1:" & Num1)
    arrValue(0) = Num1

    Randomize()
    Num2 = CInt(Math.Ceiling(Rnd() * 40))
    arrValue(1) = Num2
    Console.WriteLine("Num2:" & Num2)

    Randomize()
    Num3 = CInt(Math.Ceiling(Rnd() * 40))
    Console.WriteLine("Num3:" & Num3)
    arrValue(2) = Num3

    Randomize()
    Num4 = CInt(Math.Ceiling(Rnd() * 40))
    Console.WriteLine("Num4:" & Num4)
    arrValue(3) = Num4

    Randomize(Num5)
    Num5 = CInt(Math.Ceiling(Rnd() * 40))
    Console.WriteLine("Num5:" & Num5)
    arrValue(4) = Num5

    Randomize()
    Num6 = CInt(Math.Ceiling(Rnd() * 40))
    Console.WriteLine("Num6:" & Num6)
    arrValue(5) = Num6

    Console.WriteLine("" & result)
    Console.ReadLine()
End Sub

A: Carefully check the timeline in your code:

*

*when do you assign the contents to result?

*when do you assign the values to the array?

Hint: This code is executed from top to bottom.

A: Dim result As String = String.Join("", arrValue)

should be moved to before
Console.WriteLine("" & result)

becoming
Dim result As String
...
result = String.Join("", arrValue)
Console.WriteLine("" & result)

because you're creating the string from the values before you've created values for them.


text:
Q: Composition of itertools function in python How can I combine/chain itertools functions?
For example, I'd like to combine itertools.counter with itertools.repeat so as to have a function 'counter_repeat' that output twice each value of the counter.
The function would be called like that:
count_twice = counter_repeat(start=1, step=1, repeat=2)

The output would be:
>>> next(count)
<<< 1
>>> next(count)
<<< 1
>>> next(count)
<<< 2
>>> next(count)
<<< 2
>>> next(count)
<<< 3
(...)

FYI, I know how to write the function myself :
def counter_repeat(start=0, step=1, re=1):
    n = start
    while True:
        for i in range(re):
            yield n
        n += step
count_rep = counter_repeat(1, 1, 2)

What I'd like is to  know how to compose/chain the itertools functions.


text:
Q: yaml dependency in R won't update in Windows I'm on a windows machine and I'm trying  to knit an RMarkdown  document with RStudio. When I press the 'knit' button in  RStudio,  I  get a "requires an updated version of the yaml package" message. I install.packages("yaml") to find a message saying  something along the  lines of "binary source needs_compilation." I check the  CRAN page  for yaml and it seems that the Microsoft binaries are not up to date  with the the more recent Mac version (2.1.14 < 2.1.15). I think this is the reason why I can't knit an RMarkdown document, but I do not  know how to work around this.
This  error popped  up a few days ago and I'm not really sure  how to fix it.  I've been  knitting documents pretty  consistently until  now and don't really know what to do.
Any help or guidance would be  greatly appreciated.

A: @cedric's link helped out. I had to install() the yaml package using devtools


text:
Q: The truth value of an array with more than one element is ambiguous. numpy error The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
I get the above error for this code. I did not get this kind of error a couple of months ago. But I am getting it now. How can I solve this?
t = np.linspace(np.zeros((2, 2)), np.ones((2, 2)), 20)

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-19-187bbe847597> in <module>
----> 1 t = np.linspace(np.zeros((2, 2)), np.ones((2, 2)), 20)

~\Anaconda3\lib\site-packages\numpy\core\function_base.py in linspace(start, stop, num, endpoint, retstep, dtype)
    122     if num > 1:
    123         step = delta / div
--> 124         if step == 0:
    125             # Special handling for denormal numbers, gh-5437
    126             y /= div

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

A: Simply because np.zeros((2,2)) and np.ones((2,2)) create arrays with 4 values and you are trying to create an array with 20 samples.
t = np.linspace(np.zeros((2, 2)), np.ones((2, 2)), 1)
Creates no problem ,simply because the length of the array.
Result:
array([[0., 0.],
       [0., 0.]])

A: I can replicate this error in numpy versions before 1.16.  Previous to that, np.linspace did not accept ndarray inputs for stop and start.
@JHY confirmed current version is 1.14.5.  Try updating numpy

A: Update your numpy.
for python 2
pip install numpy --upgrade --user

tables needed to update too
pip install tables --upgrade

for python 3
pip3 install numpy --upgrade --user

similarly, for python 3
pip3 install tables --upgrade

For complete working of numpy after updating them you would need to update tables to.
After that run your code, the error will be removed.


text:
Q: Pass a function with a set argument I have a handleChange that takes an index and value.  I want to pass it to a component but I don't want to pass in the index as a prop. I'm trying to return a function that has index already set but not sure how. I tried using bind?
handleChange(index, value) {}

[1,2,3].map((item,index) =>
  <component onChange={()=> index => handleChange.bind(this, index)} />
)

A: Close:
[1,2,3].map((item,index) =>
  <component onChange={handleChange.bind(this, index)} />
)

Breaking down what you had before in your {}, you were passing a function that returns a function instead of just passing a direct function, which .bind(...) creates for you. An alternative that is cleaner looking, IMO, but does almost the same thing would be:
[1,2,3].map((item,index) =>
  <component onChange={value => handleChange(index, value)} />
)


text:
Q: Javascript filter array of objects by class in this array of objects
array = [
0: foo1{name: "111", energy: 0, capacity: 0, comsuption: 0, season: 0, …}
1: foo1 {name: "222", energy: 0, capacity: 0, comsuption: 0, season: 0, …}
2: foo2 {name: "3", energy: 0, capacity: 0, comsuption: 0, season: 0, …}
3: foo2 {name: "5", energy: 0, capacity: 0, comsuption: 0, season: 0, …}
4: foo3 {name: "22", energy: 0, capacity: 0, comsuption: 0, season: 0, …}
5: foo1 {name: "444", energy: 0, capacity: 0, comsuption: 0, season: 0, …}
]

exist a method to filter by class of object?.
example :
let arr = array.filter( foo => foo === foo1) ;

// expected output:
arr = [
0: foo1 {name: "111", energy: 0, capacity: 0, comsuption: 0, season: 0, …}
1: foo1 {name: "222", energy: 0, capacity: 0, comsuption: 0, season: 0, …}
2: foo1 {name: "444", energy: 0, capacity: 0, comsuption: 0, season: 0, …}
]

https://stackblitz.com/edit/js-mkeg2b
thx

A: Using instanceof

The instanceof operator tests to see if the prototype property of a
constructor appears anywhere in the prototype chain of an object. The
return value is a boolean value.

let arr = array.filter(foo => foo instanceof foo1)

let arr = []

class foo1 {
  constructor(name, value) {
    this.name = '',
      this.value = 0
  }
}

class foo2 {
  constructor(name, value) {
    this.name = '',
      this.value = 0
  }
}

class foo3 {
  constructor(name, value) {
    this.name = '',
      this.value = 0
  }
}

let bar1 = new foo1();
let bar2 = new foo2();
let bar3 = new foo3();

arr.push(bar1, bar1, bar1, bar1, bar2, bar3, bar2, bar1);

document.write('check in browser console')
console.log(arr.filter(foo => foo instanceof foo1))

A:

const
    array = [{ foo1: { name: "111", energy: 0, capacity: 0, comsuption: 0, season: 0 } }, { foo1: { name: "222", energy: 0, capacity: 0, comsuption: 0, season: 0 } }, { foo2: { name: "3", energy: 0, capacity: 0, comsuption: 0, season: 0 } }, { foo2: { name: "5", energy: 0, capacity: 0, comsuption: 0, season: 0 } }, { foo3: { name: "22", energy: 0, capacity: 0, comsuption: 0, season: 0 } }, { foo1: { name: "444", energy: 0, capacity: 0, comsuption: 0, season: 0 } }]

let result = array.filter(o=>o.foo1);

console.log(result);

A: You can also use constructor.name to filter the array based on constructor.
let arr = array.filter(foo => foo.constructor.name === "foo1")


text:
Q: How to append errors to a class using the 'ActiveModel::Errors' module I am using Ruby on Rails 3 and I am trying to exend a class Account in order to handle errors "a la Rails way".
In my model I have
class Users::Account
  extend  ActiveModel::Naming
  extend  ActiveModel::Translation
  include ActiveModel::Validations
  include ActiveModel::Conversion

  def persisted?
    false
  end

  attr_reader :errors

  def initialize(attributes = {})
    @errors = ActiveModel::Errors.new(self)

    @firstname = attributes[:firstname]
    @lastname = attributes[:lastname]
    ...
  end
end

I would like to "encapsulate" in the above class the following hash using the ActiveModel::Errors
---
errors:
  base: Invalid account.
  firstname: Too short.

so that I can do, after inserting the above error hash in the class, like this
@account.errors # => Hash of errors

A debug for a testing scenario is (always) the following because I don't know how to append errors to the class.
firstname: T
lastname: Test surname
errors: !omap []

How can I do that?

A: you can actually just do
somemodel_instance.errors.add(:some_attr, "some error message")

for more info, refer to here, hope this helps =)


text:
Q: Why are people repeatedly connecting to my MTA, doing nothing, and leaving? I have a sendmail server.  Periodically (ie, several times an hour) I get log entries like this:
Sep  3 10:06:49 lory sendmail[30561]: v8396nsQ030561: [37.49.226.159] did not issue MAIL/EXPN/VRFY/ETRN during connection to MTA-v6
Sep  3 10:06:49 lory sendmail[30564]: v8396nmv030564: [37.49.226.159] did not issue MAIL/EXPN/VRFY/ETRN during connection to MTA-v6
[29 very similar lines deleted]
Sep  3 10:06:50 lory sendmail[30654]: v8396or0030654: [37.49.226.159] did not issue MAIL/EXPN/VRFY/ETRN during connection to MTA-v6
Sep  3 10:06:50 lory sendmail[30657]: v8396ou3030657: [37.49.226.159] did not issue MAIL/EXPN/VRFY/ETRN during connection to MTA-v6

This particular server went on for a bit at that rate, then got bursty, notching up in total some 600 connections in 110s; others are less prolix.  They don't cause my server any problems; fail2ban gets a bit exercised, watching the mail log file for SMTP AUTH failures as it does, and having to ignore all these new entries, but it's nothing to make the server sweat.
What I'm curious about, and what I'm asking, is why anyone would do such a thing.  Are they hoping my relaying/greylisting/SPF engine has a very small brain, and after 500 connections it says to itself gosh, they're really keen to talk to me, I'd better accept anything they send now?  Are they hoping my server has no spare VM, and sendmail will bloat and invoke the OOM killer, thus DoSsing me?  I presume someone's doing this sort of thing for a reason, but does anyone have the faintest idea what that reason might be?

A: The sendmail "did not issue MAIL/EXPN/VRFY/ETRN during connection to MTA" warnings are, not unexpected, triggered by authentication attempts that get rejected, but not only when an incorrect username password combo is supplied, but you see the same error even when authentication is not supported (or at least not allowed without TLS):
telnet localhost 25
   Trying 127.0.0.1...
   Connected to localhost.
   Escape character is '^]'.
   220 hbruijn ESMTP Sendmail 8.14.4/8.14.4; Fri, 8 Sep 2017 13:06:31 +0200
AUTH LOGIN
   504 5.3.3 AUTH mechanism LOGIN not available
QUIT

This generates the type of log event you see:

Sep  8 13:06:39 hbruijn sendmail[11333]: v88B6VYg011333: localhost [127.0.0.1] did not issue MAIL/EXPN/VRFY/ETRN during connection to MTA

You don't see any actual usernames logged because the "attackers" don't even reach the stage at which they can supply a username or password.
When I connect with STARTTLS and do supply an (incorrect) username and password combo sendmail logs exactly the same error.
openssl s_client -starttls smtp -connect localhost:25
   250 HELP
AUTH LOGIN
   334 VXNlcm5hbWU6
bXl1c2VybmFtZUBkb21haW4uY29t
   334 UGFzc3dvcmQ6
d2Vha3Bhc3M=
   535 5.7.0 authentication failed
QUIT
   DONE

That generates an additional log line, but afterwards exactly the same event.

Sep  8 13:24:22 hbruijn sendmail[11648]: STARTTLS=server, relay=localhost [127.0.0.1], version=TLSv1/SSLv3, verify=NO, cipher=DHE-RSA-AES256-GCM-SHA384, bits=256/256
  Sep  8 13:24:32 hbruijn sendmail[11648]: v88BOMvW011648: localhost [127.0.0.1] did not issue MAIL/EXPN/VRFY/ETRN during connection to MTA

Never attribute to malice that which is adequately explained by stupidity:
My own domain doesn't get much mail, but sufficient internet background noise with regards to port scans and brute force attempts. I captured all SMTP traffic over the last couple of days and, in addition to quite a few unique IP-addresses triggering such log events, my server had two IP addresses that didn't back away when my sendmail responded that AUTH isn't supported (without TLS) resulting in a large number of warnings from those IP's.
At least for those two IP-addresses it was as I expected, they appear just dumb and stupid malware programs apparently working through a list of usernames/passwords  without really doing any error control and not backing away after the initial failure ( which makes me wonder if they could even detect if/when they are successful  ...)

and the associated log:

Sep 10 04:04:34 hbruijn sendmail[7558]: v8A24YLM007558: [196.196.27.126] did not issue MAIL/EXPN/VRFY/ETRN during connection to MTA
  Sep 10 04:04:34 hbruijn sendmail[7561]: v8A24Yi1007561: [196.196.27.126] did not issue MAIL/EXPN/VRFY/ETRN during connection to MTA
  Sep 10 04:04:34 hbruijn sendmail[7564]: v8A24YHM007564: [196.196.27.126] did not issue MAIL/EXPN/VRFY/ETRN during connection to MTA
  Sep 10 04:04:35 hbruijn sendmail[7567]: v8A24YSY007567: [196.196.27.126] did not issue MAIL/EXPN/VRFY/ETRN during connection to MTA
  Sep 10 04:04:35 hbruijn sendmail[7570]: v8A24ZC2007570: [196.196.27.126] did not issue MAIL/EXPN/VRFY/ETRN during connection to MTA
  Sep 10 04:04:35 hbruijn sendmail[7573]: v8A24ZYo007573: [196.196.27.126] did not issue MAIL/EXPN/VRFY/ETRN during connection to MTA
  Sep 10 04:04:35 hbruijn sendmail[7576]: v8A24ZLt007576: [196.196.27.126] did not issue MAIL/EXPN/VRFY/ETRN during connection to MTA
  Sep 10 04:04:35 hbruijn sendmail[7579]: v8A24Zva007579: [196.196.27.126] did not issue MAIL/EXPN/VRFY/ETRN during connection to MTA


text:
Q: Minimizing $\sum_{i=1}^n \frac{x_i^2}{w_i}$ subject to $\sum_{i=1}^n x_i=1$
Minimize $\displaystyle\sum_{i=1}^n \frac{x_i^2}{w_i}$ subject to $\displaystyle\sum_{i=1}^n x_i=1$.

The answer is $x_i=\displaystyle\frac{w_i}{\sum_i w_i}$ but I don't know why apart from plugging it in after finding the first derivative and setting to $0$. A hint is appreciated!
Edit: I get
$$\begin{align}
\Lambda(v_j,\lambda) &= \sigma^2\sum\frac{v_j^2}{w_j}+\lambda\left(\sum v_j-1\right) \\
\frac{d}{dv_j}\Lambda(v_j,\lambda) &= 2\sigma^2\sum\frac{v_j}{w_j}+\lambda=0 \\
\frac{d}{d\lambda}\Lambda(v_j,\lambda) &= \sum v_j-1  = 0. \end{align}$$
Then $\lambda=-2\sigma^2\sum\frac{v_j}{w_j}$.
Not sure what's supposed to happen next.

A: Without loss of generality $\sum\limits_{i=1}^nw_i=1$.
Now you can complete the squares like this
$$\sum_{i=1}^n\frac{x_i^2-2x_iw_i+w_i^2}{w_i}=\sum_{i=1}^n\frac{(x_i-w_i)^2}{w_i}$$
And note that $\sum\limits_{i=1}^n\frac{2x_iw_i}{w_i}=\sum\limits_{i=1}^n2x_i=2$ is a constant, so it's equivalent to minimizing this sum of squares.
So $x_i=w_i$ is the only minimum, because $\sum\limits_{i=1}^nx_i=\sum\limits_{i=1}^nw_i=1$ and if $x_i\ne w_i$ for any $i$, we can't have a minimum.
This is your answer as by assuming $\sum\limits_{i=1}^nw_i=1$ we just replaced each $w_i$ by $\frac{w_i}{\sum_{i=1}^nw_i}$.

A: Just to give an idea of how it would look using Lagrange multipliers: define $$f(x) = \sum_{i=1}^n \frac{x_i^2}{w_i} \quad \textrm{and} \quad g(x) = \big(\sum_{i=1}^n x_i\big) - 1$$
Then the goal is to minimize $f(x)$ subject to $g(x) = 0$. We now set $\enspace \nabla f = \lambda \nabla g \enspace$ and solve the resulting system of equations; in particular, this gives $\displaystyle \frac{2x_i}{w_i} = \lambda \enspace$ for $1 \leq i \leq n$. (If you haven't done Lagrange multipliers before, it's worth observing that while there are many $x_i$'s here, there is only one $\lambda$.)
Rearranging, we get $\displaystyle x_i = \frac{\lambda w_i}{2}$ for all $i$. Since $\lambda \neq 0$ (for then $x_i = 0$ for all $i$, making it impossible to satisfy $g(x)=0$), we immediately see that the $x_i$ are proportional to the $w_i$. The constraint $g(x) = 0$ allows you to find the appropriate value for $\lambda$.
Finally, you should note that we don't yet know whether we've found a maximum or a minimum, but I'll leave that as an exercise.

A: $
\def\b{\beta}\def\l{\lambda}\def\o{{\tt1}}\def\p{\partial}
\def\LR#1{\left(#1\right)}
\def\BR#1{\Big[#1\Big]}
\def\op#1{\operatorname{#1}}
\def\trace#1{\op{Tr}\LR{#1}}
\def\Diag#1{\op{Diag}\LR{#1}}
\def\qiq{\quad\implies\quad}
\def\grad#1#2{\frac{\p #1}{\p #2}}
\def\c#1{\color{red}{#1}}
\def\CLR#1{\c{\LR{#1}}}
\def\fracLR#1#2{\LR{\frac{#1}{#2}}}
$For problems with simple constraints, a useful approach is to convert it into an unconstrained problem.
Introduce an unconstrained vector $u$ and define the variables
$$\eqalign{
x &= \frac{u}{\o:u} &\qiq \o:x=\frac{\o:u}{\o:u}=1 \\
v &= \o\oslash w &\qiq v\odot w=\o \\
V &= \Diag v  &\qiq Vw =\o \\
W &= \Diag w  &\qiq VW = I \\
\b &= v:\LR{x\odot x} \\
}$$
where $\{\,:\,\}$ denotes the Frobenius product, $\{\odot/\oslash\}$ denote the Hadamard product/quotient, $\o$ is the all-ones vector, and $\,\b\,$ is your cost function.
Calculate the gradient of $\b$ with respect to $u$ and solve for the optimal vector
$$\eqalign{
d\b &= v:\LR{2x\odot dx} \\
 &= \LR{2v\odot x}:{dx} \\
 &= 2Vx:\c{dx} \\
 &= 2Vx:\CLR{\frac{(\o:u)\,du-(\o:du)\,u}{(\o:u)^2}} \\
 &= \fracLR{2Vu}{\o:u}:\LR{\frac{(1:u)\,I-\c{u\o^T}}{(\o:u)^2}}du \\
 &= 2\LR{\frac{(\o:u)\,I-\c{\o u^T}}{(\o:u)^2}}\fracLR{Vu}{\o:u}:du \\
\grad{\b}{u}
 &= \fracLR{2V}{(\o:u)^3}\BR{(\o:u)\,u-\LR{u^TVu}w} \;\doteq\; 0 \\
u &= \fracLR{u^TVu}{\o:u}w \qiq \c{u_* = \l w} \\
}$$
Thus the optimal $u_*$ vector is a scalar multiple of $w$.
It is not necessary to determine the multiplier $\l$ to calculate the optimal $x$
$$\eqalign{
x_* &= \frac{u_*}{\o:u_*} = \frac{\l w}{\o:\l w} = \frac{w}{\o:w} \\
}$$


text:
Q: Changing default ip rule priority for main table Please, suggest how to add ip rule right after main rule.
I have the following configuration and it needed to be restored on boot.
32766:  from all lookup main
32766:  from all lookup upstream01
32766:  from all lookup upstream02
32767:  from all lookup default

The challenge is to add rules for tables upstream 01 & 02 in correct order right after main. The priority for main & default don't have any gap to inject rules between them. I can only use the same priority of rule to main table to add it as I show above.
So, I see multiple options:
a. change default priority rule for main table to make a gap between rules to have ability define a priority in required order. But I don't know how to do this.
b. Found a way how to inject rules between "main" and "upstream01".

A: The pref keyword allows to override the priority.
ip rule add pref 32000 from all lookup main
ip rule del pref 32766 from all lookup main
ip rule add pref 32010 from all lookup upstream01
ip rule add pref 32020 from all lookup upstream02

A: You can delete the existing "default" rule and replace it with rules that suit your situation:
# delete the existing default rule
ip rule del from all lookup default    priority 32767

# add your custom rules
ip rule add from all lookup upstream01 priority 32767
ip rule add from all lookup upstream02 priority 32768

# replace the "default" rule
ip rule add from all lookup default    priority 32769

The result should look like this:
0:  from all lookup local
32766:  from all lookup main
32767:  from all lookup upstream01
32768:  from all lookup upstream02
32769:  from all lookup default


text:
Q: Master Page and Jquery Problem? I have a page called AddNews.aspx and in codebehind a web method called AddNews(Parameters)..
AddNews.aspx page is inherited from a master page.. So i used contentplaceholder.
I have a button..It's id is btnSave.
Here is jquery code:
$(function() {
    $("[id$='_btnSave']").click(function() {
        $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            data: $.toJSON(veriler),
            url: "AddNews.aspx/AddNews",
            dataType: "json",
            success: function(result) {
                $("#result").html('News added');
            },
            error: function() {
                alert('Problem');
            }
        });
    });
});
</script>

Button click dont trigger.. What can i do? Thanks.

A: ASP.NET often changes the ID of a server control, so hard-coding the control ID in your Javascript is not ideal. In the cast of Master Pages, ASP.NET prepends the ID with the Master Page's ContentPlaceholder ID (i.e. MainContent_btnSave).
What you can do is use server code inline with the javascript: <%=btnSave.ClientId%> instead of btnSave.
If the Javascript is in the .ASPX file:
$("#<%=btnSave.ClientId%>").click(function() {
   /* ... */
}

If the JS is in a separate file, just declare the button as a variable and call the variable in your JS code.
.ASPX:
var btnSave = $("#<%=btnSave.ClientId%>");

.JS:
$(btnSave).click(function() {
   /* ... */
}

By the way, if you're using C#, you may need to use <%=btnSave.ClientId()%> instead of VB's <%=btnSave.ClientId%>.

A: .NET Framework 4 added the property "ClientIDMode" to controls.
Setting ClientIDMode="Static" to enables you to use the exact ID you defined in the control tag.
function alertClicked(me) { alert("My ID is: " + me.id); }

<asp:Button ID="btnAlert" runat="server" Text="Alert"  OnClientClick="alertClicked(this)"/>

--display bodycontaint_btnAlert

<asp:Button ID="btnAlert" runat="server" Text="Alert" ClientIDMode="Static" OnClientClick="alertClicked(this)" />

--display btnAlert

A: Don't let the master page confuse you.  It's just:
$('#btnSave').click(function() {
  //ajax call like you had
});

A: If you are using a ContentPlaceHolder in the head section, make sure it is below the line where you load jQuery.
Master Page:
<head runat="server">
<script src="<%=ResolveUrl("~/Scripts/jquery-1.4.2.min.js") %>"></script>
<asp:ContentPlaceHolder ID="head" runat="server">
    </asp:ContentPlaceHolder>
</head>

You may also want to look at your generated markup and see what the ID is for your button.  If it is in a nested master page or a control it may not end with btnSave.
    <asp:Content ID="HeadContent" ContentPlaceHolderID="head" runat="server">
<script>
        $(function(){
             $('input[id*="btnSave"]').click(function(){
                  ....
             });
        });
</script>
    </asp:Content>

A: I think you've probably encountered a very common problem with using .NET master pages with jQuery -- .NET changes your element's id when it is part of a page generated with a master page so as to avoid name collisions.  If you look at the generated source code of your page your button's id is probably something more like ct100_panel1_btnSave.  If you want to use an id call you'll need to use that id.  Otherwise, add a class to the button select the button by that class (.NET doesn't munge classes).

A: Is the button  a WebForm controll? If it is then the scripts that post the form might kick in before your javascript is run.
In this case use an Html element that has no runat="server" attribute.
If you are unshure about the id of the button just look at the rendered HTML.

A: Try
$("input[id$='btnSave']")...

to make sure it is identifying your control.
In the jQuery documentation for the square-bracket selectors, they always scope it with something else.  input[selector], div[selector], etc.  I've always used them that way too, so it's possible that jQuery simply doesn't know what to do with an unscoped attribute selector.

A: $(document).ready(function() {
    $("#btnSubmit").click(function(event) {

        //
    });
});


text:
Q: menu asp.net renders fine offline but online have problems I'm new in the asp.net world and im trying to use the menu control (instead of use a CSS one).
Orientation="Horizontal" menu with some sub-menu items.
When i run the website local it seems right, but when i upload it is absolutely different:
- Chrome renders sub-menus not as vertical pop-up.
- Mozzilla and IE9 dont take the CssClass and not the HorizontalPadding and VerticalPadding.
the link to see how it work online: http://www.symbols.it/prof/default.aspx
Really thanks,
Lionel

A: Yes, it looks something messy overriding your CSS as said above and try to check with yout target Framework in web.config file with your hosting provider configuration.
In projects that target the .NET Framework 4 or later versions, the compilation element of the Web.config file contains a targetFramework attribute, as shown:
<configuration>
  <configSections>...</configSections>
  <appSettings/>
  <connectionStrings/>
  <system.web>
    <compilation debug="false"
        targetFramework="4.0">
    ...
    </compilation>
  </system.web>
  ...
</configuration>


text:
Q: Bug In ASP.Net With ID Selectors between Css And JQuery For fadeOut Attributes During the testing the Asp.Net Web Application I have realized that the JQuery  "fadeIn/Out/Toggle/To attributes are supported in html layer(layout) but not supported to asp: layer(layout) like Panel.
For details you have to follow my below code:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs"    Inherits="Animated1._Default" %>

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

 <title>Untitled Page</title>

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

        <asp:Panel ID="pnl1" runat="server">
        </asp:Panel>
        <asp:Button  ID="Btn" runat="server" Text="Mytext" />

    </form>

Now as per above code the asp controls like panel is not support fadeout attribute. Why?.
Now take a look to the same example with html code as below:Just Change the Css ID Selectors and Jquery with above code.
Here is Css/Text Code look like:
#div1
{
  width:100px;
  height:150px;
  background-color:red;
  border-style:solid;
  border-color:black;
  border-width:3px;
 }
     //And Jquery Function:

 //Rest Of Body Code is here.

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

       <input type="button" value="fade the div" id="Btn"/>

   </form>

Now the div is support to fadeout attributes and works well.
1.My question is  why the fadeout works at html not with asp:controls?.
2.Is Jquery not support to asp:controls?.
3.Or there are conclusion of ID selectors between Css/JQuery and Asp: Controls?.
And last the solution of above problem. How to handle Selectors of  Asp Controls ID between Css And Jquery as it would works perfect.

A: It Should be like this:
$(document).ready(function(){
$("#"+"<%=Btn.ClientID%>").click(function(){
$("#"+"<%=pnl1.ClientID %>").fadeOut(3000);});
});

A: It's working there is nothing wrong with the code.

    <input type="Button" value="click" id="Btn"></input>

I have created a fiddle http://jsfiddle.net/gqBWv/

The problem could be the class(css) which you have created.
As you have created css class for ID (#pnl1) and if the id changes at runtime it won't apply on your panel.
So you can use ClientIdMode="static" it won't change the id of the controls.

A: Change your scriptag, it should be like this:

Or simply:


text:
Q: Trying to take which radio button is selected and when is put it through code is returns undefined Hello I'm new to JavaScript and trying to get a radio button to be registered on variable and then have that variable return another var but it just keeps being returned undefined. If I'm just doing something overtly wrong please tell me.
The radio buttons
Fighter:<input type="radio" id="fig" value="1"/>
 Cleric:<input type="radio" id="cleric" value="2"/>
 Sorcerer:<input type="radio" id="wiz" value="3"/>
my js
var lvl
var bab
if (document.getElementById('fig').checked) {
var cass = document.getElementById('fig').value;
if (cass == 1){
bab = 1;
}
else if (cass == 2){
bab = 2;
}
else{
bab = 3;
}
}

function show(){
var txtOutput = document.getElementById("txtOutput");
txtOutput.value = bab;
}

And my final place its supposed to be submitting.
<input id="txtOutput">
    </input>

A:
Add change event listener for all radio inputs and on change of the input, set the value of the textbox.

Document.querySelectorAll Returns a list of the elements within the document that match the specified group of selectors.
Try this:

var elems = document.querySelectorAll('[name="name"]');
Array.prototype.forEach.call(elems, function(elem) {
  elem.addEventListener('change', function() {
    document.getElementById("txtOutput").value = this.value;
  });
});
Fighter:
<input type="radio" id="fig" value="1" name='name' />Cleric:

<input type="radio" id="cleric" value="2" name='name' />Sorcerer:

<input type="radio" id="wiz" value="3" name='name' />

<br>

<input id="txtOutput">

A: I think this will give you clarity.

var lvl = "";
var bab = "";

function getValues() {
  if (document.getElementById('fig').checked) {
    bab = "1 : " + document.getElementById('fig').value + "\n";
  }
  if (document.getElementById('cleric').checked) {
    bab += "2 : " + document.getElementById('cleric').value + "\n";
  }

  if((document.getElementById('wiz').checked)){
    bab += "3 : " + document.getElementById('wiz').value;
  }

  show();
}

function show(){
  var txtOutput = document.getElementById("txtOutput");
  txtOutput.innerHTML = bab;
}

/* or you can call it when you click on it */
function consoleIt(obj) {
  console.log(obj.id + " : " + obj.value);
 }
Fighter  : <input type="radio" onclick="consoleIt(this);" id="fig" value="1"/>
Cleric   : <input type="radio" onclick="consoleIt(this);" id="cleric" value="2"/>
Sorcerer : <input type="radio" onclick="consoleIt(this);" id="wiz" value="3"/>
<button onclick="getValues();">Get Radio Data</button>
<textarea id="txtOutput"> </textarea>


text:
Q: JS Удалить все символы в строке после последнего числа Есть стройка вида 100-200,,,,,
Нужно удалить все после 200, при этом строка может быть 100-200,200-300,,,, и т.д.
Т.е. нужно взять последнее число (можно определить что это 0) и убрать все что после него
У меня же получается только убрать все кроме цифр
Спасибо!

A: Чтобы удалить и до, и после:

console.log(
  ',,100-200,200-300,,'.replace(/^\D+|\D+$/g, '')
);

A: Подсказали
str.replace(/\D+$/, '');

Только вот еще вопрос
Как убрать все до первого числа?
,,100-200,200-300,, превратить в 100-200,200-300


text:
Q: How can I use a updated list in other if-else block? I am a beginner and working with IntelijIDEA configurations first time.
Conditions of a task is:

*

*When starting the program with the -c parameter, the program should add a person with the given parameters to the end of the allPeople list, and display the id (index) on the screen.

*When starting the program with the -r parameter, the program should display data about a person with the given id according to the format specified in the task.

The current code:
public class Solution{

    public static List<Person> allPeople = new ArrayList<Person>();

    static
    {
        allPeople.add(Person.createMale("Иванов Иван", new Date()));  //сегодня родился    id=0
        allPeople.add(Person.createMale("Петров Петр", new Date()));  //сегодня родился    id=1
    }

    public static void main(String[] args) throws ParseException
    {
        if (Objects.equals(args[0], "-c"))
        {
            SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy", Locale.ENGLISH);
            Date date = sdf.parse(args[3]);
            Person artman = Person.createMale(args[1], date);
            allPeople.add(artman);
            //trying to create a new list for updated allPeople list
            //List<Person> allPeopleUpd = new ArrayList<Person>(allPeople);
        }
        if (Objects.equals(args[0], "-r"))
        {
            List<Person> allPeopleUpd = new ArrayList<Person>(allPeople); //it's not an updated list
            String name = allPeopleUpd.get(Integer.parseInt(args[1])).getName();
            String sex = String.valueOf(allPeopleUpd.get(Integer.parseInt(args[1])).getSex());
            String bd = String.valueOf(allPeopleUpd.get(Integer.parseInt(args[1])).getBirthDate());
            System.out.println(name + " " + sex + " " + bd);
        }
    }
}

How to do a first condition I understood, but the problem is that the second if statement (with a "-r" parameter) don't see a changes that I made in the first if statement. What should I do to make a updated list visible for the second if statement?
P.S. createMale() and getters are from another Person class, never mind


text:
Q: Asp.Net MVC 4 Automatically bind model from array of objects in form post I have built an array of objects in JavaScript and want to post them back to the server via Ajax (Im using jQuery)
The JavaScript object array looks like this:
var columns = [
    { name: 'col 1', source: 'whatever', hidden: false, width: 50 },
    ...
];

Im posting it back like this:
$.post('/MyController/MyAction', { 'columns': columns });

On the controller action Im currently getting this:

I have a c# object called JqColumn that I want to bind the post into, it looks like this:
public class JqGridColumn
{
    public string name;
    public string source;
    public int width;
    public bool hidden;
}

So I thought that adding a parameter in the controller action of type JqGridColumn[] columns would automatically bind the posted data, but it doesn't (it generates a array, with the correct number of elements, but each item in the array has blank values)
Can anyone tell me what Im doing wrong? Thanks!
UPDATE
At present, I am manually binding the items in my controller action as follows:
    public void ColumnChooser(JqGridColumn[] columns)
    {
        for (int i = 0; i < columns.Length; i++)
        {
            columns[i].hidden = bool.Parse(Request.Form["columns[" + i + "][hidden]"]);
            columns[i].width = int.Parse(Request.Form["columns[" + i + "][width]"]);
            columns[i].name = Request.Form["columns[" + i + "][name]"];
            columns[i].source = Request.Form["columns[" + i + "][source]"];
        }
        return;
    }

...which works fine, but I'd really like to know the .Net MVC (correct) way to do it!

A: Since you didn't register a specific ModelBinder for the JqGridColumn type, the DefaultModelBinder will be used. But:

*

*It won't bind Fields, only public Properties.

*The expected format for Array binding is columns[0].name while you're actually posting columns[0][name].
The problem could be solved easily if you'll simply send your columns in JSON format instead of Name-Value-Pairs:
$.ajax({
    url: '/MyController/MyAction',
    method: 'POST',
    contentType: 'application/json',
    data: JSON.stringify({ columns: columns })
});

Yet, if you don't like to change your class, you could register a ModelBinder specific for JqGridColumn and have it working even with Fields and current jQuery serialization:
public class JqGridColumnBinder : DefaultModelBinder
{
    protected override object CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType)
    {
        string name = bindingContext.ValueProvider.GetValue(bindingContext.ModelName + "[name]").AttemptedValue;
        string source = bindingContext.ValueProvider.GetValue(bindingContext.ModelName + "[source]").AttemptedValue;
        int width = (int)bindingContext.ValueProvider.GetValue(bindingContext.ModelName + "[width]").ConvertTo(typeof(int));
        bool hidden = (bool)bindingContext.ValueProvider.GetValue(bindingContext.ModelName + "[hidden]").ConvertTo(typeof(bool));

        return new JqGridColumn
        {
            name = name,
            source = source,
            width = width,
            hidden = hidden
        };
    }
}

Then register it in App_Start/ModelBindingConfig.cs:
binders.Add(typeof(JqGridColumn), new JqGridColumnBinder());

A: It's because your JqGridColumn object needs properties, not fields. see this question for reference:
ASP.net MVC - Model binding excludes class fields?

A: try post back with the traditional : true setting
and dataType: json
$.ajax({
    url: '/MyController/MyAction',
    method: 'POST',
    traditional: true,
    dataType: json
    data: columns ,
    sucess: function () { alert('Success'); }
});


text:
Q: Why "resizeTo" doesn't works My code works for "open" and "close" the new window, but why not for resizeTo?
<button id='modifier'>Modifier la fenêtre</button>

var modifier = document.getElementById('modifier');
var fenetre = '';

modifier.addEventListener('click', fModifier);

function fOuvrir(){
  fenetre = window.open('http://pierre-giraud.com','blank','width = 500, height = 600');
}

function fModifier(){
  fenetre.resizeTo(300, 300);
}
function fFermer(){
  fenetre.close();
}

A: I think that you didn't call the fOuvrir().
            function fModifier(){
fOuvrir();
                fenetre.resizeTo(300, 300);
            }

A: You are calling fmodifier() without calling fouvrir() first.
You can't resize a window/tab that hasn't been created by window.open.
Consider adding fOuvrir(); to your fmodifier() function.


text:
Q: Change WSDL definition generated by JBoss from JAX-WS annotations in my code? I am developing a Web services in Java using JbossWS.
The WS is pretty simple. Something like this:
@WebService(targetNamespace="http://www.huawei.com/schema/syncorder/v1-0/", name="SyncOrderRelationExt")
public interface ISyncOrderRelation {

  @WebMethod
  public int SyncOrderRelationExt(String SPID, String productID, String serviceID);

And implementation
@WebService(portName="SyncOrderRelationExtHttpPort", serviceName="SyncOrderRelationExt", targetNamespace="http://www.huawei.com/schema/syncorder/v1-0/")
    public class SyncOrderRelation implements ISyncOrderRelation
    {

       public int SyncOrderRelationExt(String SPID, String productID, String serviceID)
       {
            return 0;
       }

    }

Everything seems to work fine.. but now calling this WS from .NET proyect, I have to make someting like this:
 SyncOrderRelationExt syncNTS = new SyncOrderRelationExt();

 var params= new SyncOrderRelationExt1()
 {
        arg1 = "a",
        arg2 = "b",
        arg3 = "c",
 };

 var res = syncNTS.CallSyncOrderRelationExt(params);

 int x = res.@return;

Buy I would like to call the WS in this way (requirements):
SyncOrderRelationExt sync = new SyncOrderRelationExt();

int res2 =  sync.CallSyncOrderRelationExt("a", "b", "c");

is there any way to change the definition in Java for get the client call different?
Thank you very much in advance.


text:
Q: if $g(x)=\lim_{n→∞}\frac{\{x\}^{2n}-1}{\{x\}^{2n}+1}$ where $\{x\}=$fractional part of $x$, then find g(x). if $g(x)=\lim_{n→∞}\frac{\{x\}^{2n}-1}{\{x\}^{2n}+1}$
where $\{x\}=$fractional part of $x$,
then find $g(x)$.
My answer is coming out to be $g(x)=-1$. But I'm not sure since it's a constant function...Do i have to approximate the value a $g(x)$ as $x\to \infty$ and how to do so?

A: Let $x=y+t$, where $y\to \infty$ and $t\in[0,1]$.
Then
$$L=\lim_{y\to\infty}\frac{\{y+t\}^{2n}-1}{\{y+t\}^{2n}+1}=\frac{t^{2n}-1}{t^{2n}+1}$$
for any $t$ since $n$ is not specified.
But, as $n\to\infty$,
Then $$L=\lim_{n\to\infty}\frac{t^{2n}-1}{t^{2n}+1}=\frac{0-1}{0+1}=-1$$

A: I really think the answer depends on n more than x. As it involves frac(x) the value of that doesn't change even if x->infinity.
Before giving an answer take a look at this, maybe it gives you a hint. Sometimes graphing can actually help a lot.
https://www.desmos.com/calculator/ixvutwqnvz
As now it's edited in the question that it's n->infinity:
{x} will tend to zero as n->infinity due to the fact that {x}<1. And hence you did get the right answer.


text:
Q: Where to start, implement long-polling in Faye for iOS I'm using MZFayeClient (https://github.com/m1entus/MZFayeClient) using built in WebSocket.
I need to implement long-polling technique.
How to do it? Where to start?
There isn't information (or enough information) on how to do it or if there an Faye library with long-polling.

A: I am not a IOS developer but one of my project I was helping to my IOS team for integrating the Faye server.
On my application we had a faye-server already running on rails framework for sending notification then we decide to sending notification to IOS device using same faye-server.
IOS team just follow the instruction of: https://github.com/pcrawfor/FayeObjC
self.client = [[MZFayeClient alloc] initWithURL:[NSURL URLWithString:@"ws://198.128.0.1:9292/faye"]];

ws://198.128.0.1:9292/faye // this URL is same which is used on web-app.

subscribeToChannel & other methods are same like we are using on web-app.

Simple Faye Setup for Rails application .

How can I push to Faye Server from Rails Controller?
It will work for me I hope will also for you ..
sorry for my bad english ;)

A: 1. Server up and running:
sudo rackup faye.ru -E production -s thin to start the Faye server
Thin web server (v1.6.4 codename Gob Bluth) Maximum connections set to
1024 Listening on localhost:9292, CTRL+C to stop

Check if server is working
curl http://localhost:9292/faye -d 'message={"channel":"/server", "data":"hello"}'

Response
[{"channel":"/server","successful":true}]

Server log:
[Faye::RackAdapter] Received message via HTTP POST:
"{\"channel\":\"/server\", \"data\":\"hello\"}" [Faye::Server]
Processing messages: [{"channel":"/server","data":"hello"}] (local:
false) [Faye::Server] Passing through incoming extensions:
{"channel":"/server","data":"hello"} [Faye::Server] Handling message:
{"channel":"/server","data":"hello"} (local: false)
[Faye::Engine::Proxy] Publishing message
{"channel":"/server","data":"hello"} [Faye::Server] Processing reply:
{"channel":"/server","successful":true} [Faye::Server] Passing through
outgoing extensions: {"channel":"/server","successful":true}
[Faye::Server] Returning replies:
[{"channel":"/server","successful":true}] [Faye::RackAdapter] HTTP
response: "[{\"channel\":\"/server\",\"successful\":true}]"

2. Work with client:
Download MZFayeClient
cd FayeObjC-master/examples
pod install
open FayeObjC.xcworkspace

MZViewController.m
- (void)viewDidLoad
{
    [super viewDidLoad];

    self.client = [[MZFayeClient alloc] initWithURL:[NSURL URLWithString:@"http://localhost:9292/faye"]];
    [self.client subscribeToChannel:@"/server" success:^{
        NSLog(@"ok");
    } failure:^(NSError *error) {
        NSLog(@"Server %@",error);
    } receivedMessage:^(NSDictionary *message) {
        NSLog(@"Server %@",message);
    }];

    self.client.delegate = self;
}

3. Build example:
Touch on connect:
[Faye::RackAdapter] Received message via WebSocket[hybi-13]:
"{\"supportedConnectionTypes\":[\"long-polling\",\"callback-polling\",\"iframe\",\"websocket\"],\"channel\":\"\\/meta\\/handshake\",\"minimumVersion\":\"1.0beta\",\"version\":\"1.0\"}"
[Faye::Server] Processing messages:
[{"supportedConnectionTypes":["long-polling","callback-polling","iframe","websocket"],"channel":"/meta/handshake","minimumVersion":"1.0beta","version":"1.0"}]
(local: false) [Faye::Server] Passing through incoming extensions:
{"supportedConnectionTypes":["long-polling","callback-polling","iframe","websocket"],"channel":"/meta/handshake","minimumVersion":"1.0beta","version":"1.0"}
[Faye::Server] Handling message:
{"supportedConnectionTypes":["long-polling","callback-polling","iframe","websocket"],"channel":"/meta/handshake","minimumVersion":"1.0beta","version":"1.0"}
(local: false) [Faye::Engine::Proxy] Created new client
"f68nwz5foyf1brczhmutdhclhnbtth5" [Faye::Engine::Proxy] Ping
"f68nwz5foyf1brczhmutdhclhnbtth5", 45 [Faye::Server] Processing reply:
{"channel":"/meta/handshake","successful":true,"version":"1.0","supportedConnectionTypes":["long-polling","cross-origin-long-polling","callback-polling","websocket","eventsource","in-process"],"clientId":"f68nwz5foyf1brczhmutdhclhnbtth5","advice":{"reconnect":"retry","interval":0,"timeout":45000}}
[Faye::Server] Passing through outgoing extensions:
{"channel":"/meta/handshake","successful":true,"version":"1.0","supportedConnectionTypes":["long-polling","cross-origin-long-polling","callback-polling","websocket","eventsource","in-process"],"clientId":"f68nwz5foyf1brczhmutdhclhnbtth5","advice":{"reconnect":"retry","interval":0,"timeout":45000}}
[Faye::Server] Returning replies:
[{"channel":"/meta/handshake","successful":true,"version":"1.0","supportedConnectionTypes":["long-polling","cross-origin-long-polling","callback-polling","websocket","eventsource","in-process"],"clientId":"f68nwz5foyf1brczhmutdhclhnbtth5","advice":{"reconnect":"retry","interval":0,"timeout":45000}}]
[Faye::RackAdapter] Received message via WebSocket[hybi-13]:
"{\"channel\":\"\\/meta\\/connect\",\"clientId\":\"f68nwz5foyf1brczhmutdhclhnbtth5\",\"connectionType\":\"websocket\"}"
[Faye::Server] Processing messages:
[{"channel":"/meta/connect","clientId":"f68nwz5foyf1brczhmutdhclhnbtth5","connectionType":"websocket"}]
(local: false) [Faye::Server] Passing through incoming extensions:
{"channel":"/meta/connect","clientId":"f68nwz5foyf1brczhmutdhclhnbtth5","connectionType":"websocket"}
[Faye::Server] Handling message:
{"channel":"/meta/connect","clientId":"f68nwz5foyf1brczhmutdhclhnbtth5","connectionType":"websocket"}
(local: false) [Faye::Engine::Proxy] Accepting connection from
"f68nwz5foyf1brczhmutdhclhnbtth5" [Faye::Engine::Proxy] Ping
"f68nwz5foyf1brczhmutdhclhnbtth5", 45 [Faye::RackAdapter] Received
message via WebSocket[hybi-13]:
"{\"channel\":\"\\/meta\\/subscribe\",\"clientId\":\"f68nwz5foyf1brczhmutdhclhnbtth5\",\"subscription\":\"\\/server\"}"
[Faye::Server] Processing messages:
[{"channel":"/meta/subscribe","clientId":"f68nwz5foyf1brczhmutdhclhnbtth5","subscription":"/server"}]
(local: false) [Faye::Server] Passing through incoming extensions:
{"channel":"/meta/subscribe","clientId":"f68nwz5foyf1brczhmutdhclhnbtth5","subscription":"/server"}
[Faye::Server] Handling message:
{"channel":"/meta/subscribe","clientId":"f68nwz5foyf1brczhmutdhclhnbtth5","subscription":"/server"}
(local: false) [Faye::Engine::Proxy] Subscribed client
"f68nwz5foyf1brczhmutdhclhnbtth5" to channel "/server" [Faye::Server]
Processing reply:
{"clientId":"f68nwz5foyf1brczhmutdhclhnbtth5","channel":"/meta/subscribe","successful":true,"subscription":"/server"}
[Faye::Server] Passing through outgoing extensions:
{"clientId":"f68nwz5foyf1brczhmutdhclhnbtth5","channel":"/meta/subscribe","successful":true,"subscription":"/server"}
[Faye::Server] Returning replies:
[{"clientId":"f68nwz5foyf1brczhmutdhclhnbtth5","channel":"/meta/subscribe","successful":true,"subscription":"/server"}]

Type "hello" then send
[Faye::RackAdapter] Received message via WebSocket[hybi-13]:
"{\"data\":{\"text\":\"hello\"},\"clientId\":\"f68nwz5foyf1brczhmutdhclhnbtth5\",\"channel\":\"\\/browser\",\"id\":\"MQ==\"}"
[Faye::Server] Processing messages:
[{"data":{"text":"hello"},"clientId":"f68nwz5foyf1brczhmutdhclhnbtth5","channel":"/browser","id":"MQ=="}]
(local: false)
[Faye::Server] Passing through incoming extensions:
{"data":{"text":"hello"},"clientId":"f68nwz5foyf1brczhmutdhclhnbtth5","channel":"/browser","id":"MQ=="}
[Faye::Server] Handling message:
{"data":{"text":"hello"},"clientId":"f68nwz5foyf1brczhmutdhclhnbtth5","channel":"/browser","id":"MQ=="}
(local: false)
[Faye::Engine::Proxy] Publishing message
{"data":{"text":"hello"},"clientId":"f68nwz5foyf1brczhmutdhclhnbtth5","channel":"/browser","id":"MQ=="}
[Faye::Server] Processing reply:
{"id":"MQ==","clientId":"f68nwz5foyf1brczhmutdhclhnbtth5","channel":"/browser","successful":true}
[Faye::Server] Passing through outgoing extensions:
{"id":"MQ==","clientId":"f68nwz5foyf1brczhmutdhclhnbtth5","channel":"/browser","successful":true}
[Faye::Server] Returning replies:
[{"id":"MQ==","clientId":"f68nwz5foyf1brczhmutdhclhnbtth5","channel":"/browser","successful":true}]

Hope this help.


text:
Q: Angular lite-server results in viewing a blank page I have a Single page application and I want to run my application with a lite-server.
This is my bs-config

The problem is as follows when I run the lite-server and browse to my localhost:3000; the only thing I see is a blank page.
It looks like the lite-server loads my index page but can't seem to find my routing to the home page etc.
I know my application works perfectly when I start with npm start.
But I want to use a lite server for some test purposes.
This is how I start my server: "lite-server": "lite-server" (npm run lite-server)
What I've tried:

*

*Use other paths.

*Add a specific index HTML page.

Can anybody tell me what I am doing wrong here?

A: Build the application using ng build and run lite-server on dist/<project-name> folder because that contains final index.html.


text:
Q: Password InputField Censored (****) - Logging and Registration I am planning to do logging and registration. But I have a problem. I can't make the password InputField became like ***** (censored).
And maybe it wouldn't affect your answers but my game will be on the android platform.

Thank you.

A: now you have a property in unity than you can change directly change . you select content type in Input field text and your value is change

A: Just use a EditText and set its inputType="textPassword
Herr is also an example to do so:
http://www.mkyong.com/android/android-password-field-example/

A: Try something like
public string thePassword = "12345";
void OnGUI()
{
    passwordToEdit = GUI.PasswordField(new Rect(10, 10, 200, 20),
                                       passwordToEdit, "*"[0], 25);
}

PasswordField Parameter List

*

*Where you would like the box.

*Your password to mask.

*The character to mask the password characters with.

*(Optional) Max masking length.

*(Optional) The textfield style.

Source: Unity Scripting API

A: What about using InputField of the new UI ?
You can set the content to Password:
Doc:
http://docs.unity3d.com/es/current/Manual/script-InputField.html


text:
Q: Setting up a network for VM guests I have 4 windows VMs and a Mikrotik router vm  as guest on an ESXI 5 host server. I want to set up a network so that i can assign private IPs on the windows VM and make the Mikrotik router VM their default gateway. I know how to create a virtual switch for the physical NICs on the ESXI host. How do I create a network of the VMs where the windows VMs will sit behind the Mikrotik router.

A: *

*Use the same vmware network for windows VMs and router's LAN interface. Set vmware dhcp off on this network and use dhcp from router.

*Use another vmware network for router WAN interface. On this network set vmware nat or bridge to allow external network access for router.