text:
Q: How to get a user's id from mentioning (@User) For example, if the user sends the bot /text @USER how do I get @USER's id and message them?
Question different from this since the answer to that question requires said user (@USER) to already message the bot/the owner to already know the user's id.

A: There are 3 conditions:

1-@user is not subscribed to your bot before(not initiated chat with your bot before or it does block your bot after some chat with your bot: In this condition you can NEVER send any type of message to that @user.
2-@user doesn't exist or is incorrect . As you know, a telegram user subscribe with phone and first name (at least) and he/she could not have any @user id: In this condition there is no user name to send.
3-@user exists and already is your bot subscriber. In this condition you should save all subscribers chat_id and their related user_name as they sends some messages to your bot in a database because these data are part of each message you receive from users. So for send to that @user you should find related chat_id from your DB.(Non of Telegram Bot API methods use @username but they use chat_id)

This is a sample JSON response from Telegram when user send /1 command, as you see telegram always attaches sender chat_id,firs_name,last_name and username(if exists) to each message that bot receives:

UPDATED:
As users may change they @username during the time, it is better to
  update your chat_id<-->@username database with each message you
  receive.


text:
Q: RefineryCMS: routing error introduced by portfolio gallery plugin I'm using RefineryCMS as a rails CMS, it was working like a charm until I         followed the answer in this question to get a simple image gallery functionality going. Now I'm getting the same error as shown on this issue. I didn't change any of my rails code to introduce a link_to tag with a nil reference, however (there is a link_to image_tag line in the guide but I've commented that out and nothing changed), so it's happening in the autogenerated code I believe. Here's the full error I get when I login to refinery on my site:
ActionController::UrlGenerationError in Refinery::Authentication::Devise::Admin::Users#index
Showing /home/mpvoss/.rbenv/versions/2.2.1/lib/ruby/gems/2.2.0/bundler/gems/refinerycms-0a37f8090278/core/app/views/refinery/admin/_menu_item.html.erb where line #1 raised:

No route matches {:action=>"index", :controller=>"refinery/refinery/portfolio/admin/galleries", :locale=>:en}
Extracted source (around line #46):
44 message << " missing required keys: #{missing_keys.sort.inspect}"     unless missing_keys.empty?
45
46 raise ActionController::UrlGenerationError, message
47 end
48
49 def clear

Trace of template inclusion: /home/mpvoss/.rbenv/versions/2.2.1/lib/ruby/gems/2.2.0/bundler/gems/refinerycms-0a37f8090278/core/app/views/refinery/admin/_menu.html.erb, /home/mpvoss/.rbenv/versions/2.2.1/lib/ruby/gems/2.2.0/bundler/gems/refinerycms-0a37f8090278/core/app/views/layouts/refinery/admin.html.erb

Note: Just loading the website without logging into refinery works because it's not trying to load the menu code below that encounters the routing issue.
Okay, let's have a look at _menu.html.erb
<%= link_to menu_item.title, refinery.url_for(menu_item.url),
        :class => ("active" if menu_item.highlighted?(params)),
        :id => "plugin_#{menu_item.name}" %>

This code just makes a menu bar for all the plugins. It can be commented out and refinery works (the error above goes away), but I need that menu bar to make changes to the website.
What I've tried.

*

*I found a galleries_controller.rb in ~/.rbenv/versions/2.2.1/lib/ruby/gems/2.2.0/bundler/gems/refinerycms-portfolio-289b85b18771/app/controllers/refinery/portfolio/admin, which seems to be the controller the error was talking about. It didn't have an index action, so I added an empty action to see if that was the problem and nothing changed. The routes.rb for the ~/.rbenv/versions/2.2.1/lib/ruby/gems/2.2.0/bundler/gems/refinerycms-portfolio-289b85b18771/ gem is below

*Commenting out the portfolio gem in my Gemfile and running bundle install but I get the same error because the autogenerated code (referring to stuff like .rbenv/versions/2.2.1/lib/ruby/gems/2.2.0/bundler/gems/refinerycms-0a37f8090278/) is still getting executed (I use git for version control and make a clean clone of the project before these changes and it has the same problem because the autogenerated code is not part of the version control).

*gem uninstall of the refinery-photo-gallery, refinerycms-page-images and refinerycms-portfolio gems I thought might be causing the problem

*I moved all the gems in ~/.rbenv/versions/2.2.1/lib/ruby/gems/2.2.0/bundler/gems/ out of that directory to see if a bundle install would regenerate fresh, clean gems but nothing changed.

None of these ideas has made a difference.  If any clarification is needed please just let me know. I've been stumped on this for a week and my Googling skills are failing me. Any help is really appreciated!
~/.rbenv/versions/2.2.1/lib/ruby/gems/2.2.0/bundler/gems/refinerycms-portfolio-289b85b18771/routes.rb
 Refinery::Core::Engine.routes.draw do

  # Frontend routes
  namespace :portfolio, :path => Refinery::Portfolio.page_url do
    root :to => "galleries#index"
    resources :galleries, :only => [:index, :show]
  end

  # Admin routes
  namespace :portfolio, :path => '' do
    namespace :admin, :path => Refinery::Core.backend_route do
      scope :path => 'portfolio' do
        resources :galleries, :except => :show do
          get :children, :on => :member
          post :update_positions, :on => :collection
          resources :items, :except => [:show] do
            post :update_positions, :on => :collection
          end
        end
        resources :items do
          post :update_positions, :on => :collection
        end
      end
    end
  end
end

Gemfile
source 'https://rubygems.org'

# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '4.2.3'
# Use sqlite3 as the database for Active Record
group :development, :test do
  gem 'sqlite3'
end
# Use SCSS for stylesheets
# Use Uglifier as compressor for JavaScript assets
# Use CoffeeScript for .coffee assets and views
# See https://github.com/rails/execjs#readme for more supported runtimes
# gem 'therubyracer', platforms: :ruby

# Use jquery as the JavaScript library
gem 'jquery-rails'
# Turbolinks makes following links in your web application faster. Read more:     https://github.com/rails/turbolinks
gem 'turbolinks'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 2.0'
# bundle exec rake doc:rails generates the API under doc/api.
gem 'sdoc', '~> 0.4.0', group: :doc

# Use ActiveModel has_secure_password
# gem 'bcrypt', '~> 3.1.7'

# Use Unicorn as the app server
# gem 'unicorn'

# Use Capistrano for deployment
# gem 'capistrano-rails', group: :development

group :development, :test do
  # Call 'byebug' anywhere in the code to stop execution and get a debugger     console
  gem 'byebug'

  # Access an IRB console on exception pages or by using <%= console %> in views
  gem 'web-console', '~> 2.0'

  # Spring speeds up development by keeping your application running in the     background. Read more: https://github.com/rails/spring
  gem 'spring'
end

# Added by Matthew, Thin server
gem 'faye'
gem 'thin'

group :assets do
  #gem 'sass-rails', '~> 3.2.3'
  gem 'coffee-rails', '~> 4.1.0'
  gem 'sass-rails', '~> 5.0'
  #gem 'coffee-rails', '~> 3.2.1'
  gem 'bootstrap-sass','~> 3.1.1'
  gem 'uglifier', '>= 1.3.0'
  #gem 'uglifier', '>= 1.0.3'
end

  gem 'twitter-bootstrap-rails'
gem 'refinerycms', git: 'https://github.com/refinery/refinerycms', branch: 'master'
#gem 'refinerycms-page-images', '~> 2.0.0'
gem 'quiet_assets', group: :development
#gem 'refinerycms-photo-gallery', '~> 0.1.0'
# Add support for searching inside Refinery's admin interface.
gem 'refinerycms-acts-as-indexed', ['~> 2.0', '>= 2.0.0']

# Add support for Refinery's custom fork of the visual editor WYMeditor.
gem 'refinerycms-wymeditor', ['~> 1.0', '>= 1.0.6']
gem 'refinerycms-portfolio', github: 'refinery/refinerycms-portfolio', branch:     'master'
# The default authentication adapter
gem 'refinerycms-authentication-devise', '~> 1.0'

A: Looks like it was a bug in the portfolio/images plugin, tried another bundle update and the updated code worked like a charm.  <3 RefineryCMS contributors

redpajama_set_name: RedPajamaStackExchange


text:
Q: Unable to run MSpec test due to the fact that TeamCity is building test assembly wrong I am trying to run a MSpec test following the build of my solution. So, I've got my MSBuild script set up as follows:
<?xml version="1.0" encoding="utf-8"?>
    <Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
      <Target Name="Build">
        <MSBuild Projects="../MyApplication.Web.sln" />
        <Message Text="Building solution" Importance="high" />
      </Target>

      <Target Name="TeamCity" DependsOnTargets="Build">
        <Message Text="Before executing MSpec command" Importance="high" />
        <Exec Command="mspec.exe ..\Hosts\MyApplication.Hosts.Web.Specs\bin\MyApplication.Hosts.Web.Specs.dll --teamcity" />
        <Message Text="Running MSpec" Importance="high" />
      </Target>
    </Project>

I then call "TeamCity" as my target in TeamCity. When the command

"mspec.exe
  ..\Hosts\MyApplication.Hosts.Web.Specs\bin\MyApplication.Hosts.Web.Specs.dll
  --teamcity"

is executed, I get the following error:

C:\TeamCity\buildAgent\work\117e3aa3bb76aad0\Build>mspec ..\Hosts\Application.Hos
  ts.Web.Specs\bin\Application.Hosts.Web.Specs.dll
  Could not load file or assembly 'file:///C:\TeamCity\buildAgent\work\117e3aa3bb7
  6aad0\Hosts\Application.Hosts.Web.Specs\bin\Application.Hosts.Web.Specs.dll' or on
  e of its dependencies. An attempt was made to load a program with an incorrect f
  ormat.

After doing some investigation, I found out that the "MyApplication.Hosts.Web.Specs.dll" on my local machine and the build server, although both 15kb, had different md5 checksums. That might explain why the execution of the MSpec test would cause errors. In fact, if I copy the dll from my local machine to the build server, the test will run.
So my question is whether someone else has come across this same issue of the builiding of assemblies being build "badly"?
-EDIT-
Locally I'm building the solution as a 64 bit application but in TeamCity, I'm building it as 32 bits (x86). Could that be the problem?
PS:I tried building it as a 64 bit application in TeamCity but I get other errors which I would rather ignore for the moment. However, for completeness sake here it is:
Client\ProdMaster.SLCharts\ProdMaster.SLCharts.csproj
[15:11:22]: [Client\ProdMaster.SLCharts\ProdMaster.SLCharts.csproj] GetFrameworkPaths
[15:11:22]: [GetFrameworkPaths] ValidateSilverlightFrameworkPaths
[15:11:22]: [ValidateSilverlightFrameworkPaths] C:\Program Files (x86)\MSBuild\Microsoft\Silverlight\v4.0\Microsoft.Silverlight.Common.targets(104, 9): The Silverlight 4 SDK is not installed.

A: David,

*

*Which version of MSpec are you
running? If you're still on 0.3.0.0 I
encourage you to switch to the most
recent 0.4.9.0 build. This build
contains mspec.exe (AnyCPU) as well
as mspec-x86.exe (x86). You should
use the executable matching your build
environment/architecture.

*Can you please trace the assembly
binding with Fustion Log Viewer -
it's part of the Windows SDK. The
error message "An attempt was made to
load a program with an incorrect
format." indicates that MSpec is able
to find the spec DLL, but target
architectures do not match between
the MSpec executable and and spec
assembly.


text:
Q: How to control the progress of an AnimatedVectorDrawable in Android? I would like to control or bind the progress of an AnimatedVectorDrawable with a view pager.
Is it possible to control programatically the progress of the animation or bind it to a view pager like it's done with the Swipe-To-Refresh or the Navigation drawer controls?


text:
Q: How to get actual path from Uri xamarin android I want to get actual path from Uri, when I select file using intent then it will be returning URI but below line of code not working for conversion URI to string path
Open FilePicker
public static void PickFile(Activity context)
{
    Intent intent = new Intent(Intent.ActionGetContent);
    intent.SetType("*/*");
    context.StartActivityForResult(intent, PICKFILE_RESULT_CODE);
}

Get Result
protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
    if(requestCode == PICKFILE_RESULT_CODE)
    {
        string filepath = GetRealPathFromURI(MainActivity.act, data.Data);
    }
}

public static string GetRealPathFromURI(Activity act, Android.Net.Uri contentURI)
{
    try
    {
        ICursor cursor = act.ContentResolver.Query(contentURI, null, null, null, null);
        cursor.MoveToFirst();
        string documentId = cursor.GetString(0);
        documentId = documentId.Split(':')[1];
        cursor.Close();

        cursor = act.ContentResolver.Query(
        MediaStore.Images.Media.ExternalContentUri,
        null, MediaStore.Images.Media.InterfaceConsts.Id + " = ? ", new[] { documentId }, null);
        cursor.MoveToFirst();
        string path = cursor.GetString(cursor.GetColumnIndex(MediaStore.Images.Media.InterfaceConsts.Data));
        cursor.Close();

        return path;
    }
    catch(Exception e)
    {
        Log.Debug("TAG_DATA",e.ToString());
        return "";
    }
}

Error

System.IndexOutOfRangeException: Index was outside the bounds of the
  array.

can anyone explain to me, what's wrong think I am doing in this code.

A: Read this article, you will get exactly simple answer.
https://commonsware.com/blog/2016/03/15/how-consume-content-uri.html
My code as below:
            var targetPath = $"{FileDir}{Path.DirectorySeparatorChar}{FileName}";

            const int bufferSize = 1024;
            using (var inputStream = Activity.ContentResolver.OpenInputStream(audioFileUri))
            {
                using (var outputStream = File.Create(targetPath))
                {
                    var buffer = new byte[bufferSize];
                    while (true)
                    {
                        var count = inputStream.Read(buffer, 0, bufferSize);
                        if (count > 0)
                        {
                            outputStream.Write(buffer, 0, count);
                        }

                        if (count < bufferSize) break;
                    }
                }
            }

A:
How to get actual path from Uri xamarin android

I note that you are using MediaStore.Images.Media.ExternalContentUri property,  what you want is getting the real path of Gallery Image?
If you want implement this feature, you could read my answer : Get Path of Gallery Image ?

private string GetRealPathFromURI(Android.Net.Uri uri)
{
    string doc_id = "";
    using (var c1 = ContentResolver.Query(uri, null, null, null, null))
    {
        c1.MoveToFirst();
        string document_id = c1.GetString(0);
        doc_id = document_id.Substring(document_id.LastIndexOf(":") + 1);
    }

    string path = null;

    // The projection contains the columns we want to return in our query.
    string selection = Android.Provider.MediaStore.Images.Media.InterfaceConsts.Id + " =? ";
    using (var cursor = ContentResolver.Query(Android.Provider.MediaStore.Images.Media.ExternalContentUri, null, selection, new string[] { doc_id }, null))
    {
        if (cursor == null) return path;
        var columnIndex = cursor.GetColumnIndexOrThrow(Android.Provider.MediaStore.Images.Media.InterfaceConsts.Data);
        cursor.MoveToFirst();
        path = cursor.GetString(columnIndex);
    }
    return path;
}

Update :
Here is a solution :
private string GetActualPathFromFile(Android.Net.Uri uri)
{
    bool isKitKat = Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.Kitkat;

    if (isKitKat && DocumentsContract.IsDocumentUri(this, uri))
    {
        // ExternalStorageProvider
        if (isExternalStorageDocument(uri))
        {
            string docId = DocumentsContract.GetDocumentId(uri);

            char[] chars = { ':' };
            string[] split = docId.Split(chars);
            string type = split[0];

            if ("primary".Equals(type, StringComparison.OrdinalIgnoreCase))
            {
                return Android.OS.Environment.ExternalStorageDirectory + "/" + split[1];
            }
        }
        // DownloadsProvider
        else if (isDownloadsDocument(uri))
        {
            string id = DocumentsContract.GetDocumentId(uri);

            Android.Net.Uri contentUri = ContentUris.WithAppendedId(
                            Android.Net.Uri.Parse("content://downloads/public_downloads"), long.Parse(id));

            //System.Diagnostics.Debug.WriteLine(contentUri.ToString());

            return getDataColumn(this, contentUri, null, null);
        }
        // MediaProvider
        else if (isMediaDocument(uri))
        {
            String docId = DocumentsContract.GetDocumentId(uri);

            char[] chars = { ':' };
            String[] split = docId.Split(chars);

            String type = split[0];

            Android.Net.Uri contentUri = null;
            if ("image".Equals(type))
            {
                contentUri = MediaStore.Images.Media.ExternalContentUri;
            }
            else if ("video".Equals(type))
            {
                contentUri = MediaStore.Video.Media.ExternalContentUri;
            }
            else if ("audio".Equals(type))
            {
                contentUri = MediaStore.Audio.Media.ExternalContentUri;
            }

            String selection = "_id=?";
            String[] selectionArgs = new String[]
            {
                split[1]
            };

            return getDataColumn(this, contentUri, selection, selectionArgs);
        }
    }
    // MediaStore (and general)
    else if ("content".Equals(uri.Scheme, StringComparison.OrdinalIgnoreCase))
    {

        // Return the remote address
        if (isGooglePhotosUri(uri))
            return uri.LastPathSegment;

        return getDataColumn(this, uri, null, null);
    }
    // File
    else if ("file".Equals(uri.Scheme, StringComparison.OrdinalIgnoreCase))
    {
        return uri.Path;
    }

    return null;
}

public static String getDataColumn(Context context, Android.Net.Uri uri, String selection, String[] selectionArgs)
{
    ICursor cursor = null;
    String column = "_data";
    String[] projection =
    {
        column
    };

    try
    {
        cursor = context.ContentResolver.Query(uri, projection, selection, selectionArgs, null);
        if (cursor != null && cursor.MoveToFirst())
        {
            int index = cursor.GetColumnIndexOrThrow(column);
            return cursor.GetString(index);
        }
    }
    finally
    {
        if (cursor != null)
            cursor.Close();
    }
    return null;
}

//Whether the Uri authority is ExternalStorageProvider.
public static bool isExternalStorageDocument(Android.Net.Uri uri)
{
    return "com.android.externalstorage.documents".Equals(uri.Authority);
}

//Whether the Uri authority is DownloadsProvider.
public static bool isDownloadsDocument(Android.Net.Uri uri)
{
    return "com.android.providers.downloads.documents".Equals(uri.Authority);
}

//Whether the Uri authority is MediaProvider.
public static bool isMediaDocument(Android.Net.Uri uri)
{
    return "com.android.providers.media.documents".Equals(uri.Authority);
}

//Whether the Uri authority is Google Photos.
public static bool isGooglePhotosUri(Android.Net.Uri uri)
{
    return "com.google.android.apps.photos.content".Equals(uri.Authority);
}

Get the actual path in  OnActivityResult :
protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
    base.OnActivityResult(requestCode, resultCode, data);
    if (requestCode == 0)
    {
        var uri = data.Data;
        string path = GetActualPathFromFile(uri);
        System.Diagnostics.Debug.WriteLine("Image path == " + path);

    }
}

A: Here is the full solution for Xamarin.Android API 21+:
https://gist.github.com/IlyaLavrov97/a76063a49515764b60d5fba3ebbb2662
Its include updates for files from privite download folders and google disk.
The main part of the solution below:
    /// <summary>
    /// Main feature. Return actual path for file from uri.
    /// </summary>
    /// <param name="uri">File's uri</param>
    /// <param name="context">Current context</param>
    /// <returns>Actual path</returns>
    private static string GetActualPathForFile(global::Android.Net.Uri uri, Context context)
    {
        bool isKitKat = Build.VERSION.SdkInt >= BuildVersionCodes.Kitkat;

        if (isKitKat && DocumentsContract.IsDocumentUri(context, uri))
        {
            // ExternalStorageProvider
            if (IsExternalStorageDocument(uri))
            {
                string docId = DocumentsContract.GetDocumentId(uri);

                char[] chars = { ':' };
                string[] split = docId.Split(chars);
                string type = split[0];

                if ("primary".Equals(type, StringComparison.OrdinalIgnoreCase))
                    return global::Android.OS.Environment.ExternalStorageDirectory + "/" + split[1];
            }
            // Google Drive
            else if (IsDiskContentUri(uri))
                return GetDriveFileAbsolutePath(context, uri);
            // DownloadsProvider
            else if (IsDownloadsDocument(uri))
            {
                try
                {
                    string id = DocumentsContract.GetDocumentId(uri);

                    if (!TextUtils.IsEmpty(id))
                    {
                        if (id.StartsWith("raw:"))
                            return id.Replace("raw:", "");

                        string[] contentUriPrefixesToTry = new string[]{
                                "content://downloads/public_downloads",
                                "content://downloads/my_downloads",
                                "content://downloads/all_downloads"
                        };

                        string path = null;

                        foreach (string contentUriPrefix in contentUriPrefixesToTry)
                        {
                            global::Android.Net.Uri contentUri = ContentUris.WithAppendedId(
                                    global::Android.Net.Uri.Parse(contentUriPrefix), long.Parse(id));

                            path = GetDataColumn(context, contentUri, null, null);

                            if (!string.IsNullOrEmpty(path))
                                return path;
                        }

                        // path could not be retrieved using ContentResolver, therefore copy file to accessible cache using streams
                        string fileName = GetFileName(context, uri);
                        Java.IO.File cacheDir = GetDocumentCacheDir(context);
                        Java.IO.File file = GenerateFileName(fileName, cacheDir);

                        if (file != null)
                        {
                            path = file.AbsolutePath;
                            SaveFileFromUri(context, uri, path);
                        }

                        // last try
                        if (string.IsNullOrEmpty(path))
                            return global::Android.OS.Environment.ExternalStorageDirectory.ToString() + "/Download/" + GetFileName(context, uri);

                        return path;
                    }
                }
                catch
                {
                    return global::Android.OS.Environment.ExternalStorageDirectory.ToString() + "/Download/" + GetFileName(context, uri);
                }
            }
            // MediaProvider
            else if (IsMediaDocument(uri))
            {
                string docId = DocumentsContract.GetDocumentId(uri);

                char[] chars = { ':' };
                string[] split = docId.Split(chars);

                string type = split[0];

                global::Android.Net.Uri contentUri = null;
                if ("image".Equals(type))
                    contentUri = MediaStore.Images.Media.ExternalContentUri;
                else if ("video".Equals(type))
                    contentUri = MediaStore.Video.Media.ExternalContentUri;
                else if ("audio".Equals(type))
                    contentUri = MediaStore.Audio.Media.ExternalContentUri;

                string selection = "_id=?";
                string[] selectionArgs = new string[] { split[1] };

                return GetDataColumn(context, contentUri, selection, selectionArgs);
            }

        }
        // MediaStore (and general)
        else if ("content".Equals(uri.Scheme, StringComparison.OrdinalIgnoreCase))
        {
            // Return the remote address
            if (IsGooglePhotosUri(uri))
                return uri.LastPathSegment;

            // Google Disk document .legacy
            if (IsDiskLegacyContentUri(uri))
                return GetDriveFileAbsolutePath(context, uri);
            return GetDataColumn(context, uri, null, null);
        }
        // File
        else if ("file".Equals(uri.Scheme, StringComparison.OrdinalIgnoreCase))
            return uri.Path;

        return null;
    }

A: In short, this can simply help.
public static string GetRealPathFromURI(Activity act, Android.Net.Uri contentURI)
{
    try
    {
        Android.Database.ICursor cursor = act.ContentResolver.Query(contentURI, null, null, null, null);
        cursor.MoveToFirst();
        string documentId = cursor.GetString(0);
        documentId = documentId.Split(':')[1];
        cursor.Close();

        cursor = act.ContentResolver.Query(
        MediaStore.Images.Media.ExternalContentUri,
        null, MediaStore.Images.Media.InterfaceConsts.Id + " = ? ", new[] { documentId }, null);
        cursor.MoveToFirst();
        string path = cursor.GetString(cursor.GetColumnIndex(MediaStore.Images.Media.InterfaceConsts.Data));
        cursor.Close();

        return path;
    }
    catch (Exception e)
    {
        Console.WriteLine(e.ToString());
        return "";
    }
}


text:
Q: Adding group in Legend in QGIS Map composer? There is a Map composer with created map. I want to "Add group" to Legend - it appears in the Legend Properties, but not in Legend on the map.

I am using QGIS 2.18.8. This problem was also in 2.16 version. Am I missing something?

A: You can just drag and drop your layers into groups, than just refresh legend item by clicking itnto print composer canvas or any map item.

A: The Group will not be shown until you drag any of the layers inside the new group:
Before adding anything inside the group:

After drag anything inside the group:


text:
Q: How to make a factory constructor that returns as const value Is it possibly to return a different implementation of as const?
abstract class Foo<T> {
  factory Foo(T thing) => const FooImpl(thing); // <= Arguments of a constant creation must be constant expressions
  T get thing;
}

class FooImpl<T> implements Foo<T>{
  final T thing;
  const FooImpl(this.thing);
}

A: Dart has a delegating factory constructor to allow this
abstract class Foo<T> {
  const factory Foo(T thing) = FooImpl;
  T get thing;
}

class FooImpl<T> implements Foo<T>{
  final T thing;
  const FooImpl(this.thing);
}

see also
https://groups.google.com/a/dartlang.org/forum/#!topic/misc/cvjjgrwIHbU and
https://groups.google.com/a/dartlang.org/forum/#!topic/misc/cvjjgrwIHbU


text:
Q: Endless failures of Firebase authentication My app fails on authentication new users while registering. The application is connected to Google Firebase and nothing seems to be done wrong with it. Code seems also alright, it displays no errors and I checked everything 10000000 times. Everything needed is already imported. When I try to register new user an error appears which says: "An internal error has occured. [Access Not Configured. Google Identity Toolkit API has not been used in project (here is 12-digit project number) before or it is disabled. Enable it by visiting console.developers.google.com/apis/api/… project number) then retry. If you enabled this API recently, wait a few minutes for the action to propagate to our systems and retry.] I set up authentication yesterday so I don't know what to do...
public class RegisterUserActivity extends AppCompatActivity {
    //DECLARE FIELDS
    EditText userEmailCreateEditText, userPassWordCreateEditText;
    LinearLayout createAccountBtn;
    //FIREBASE AUTHENTICATION ID
    FirebaseAuth mAuth;
    FirebaseAuth.AuthStateListener mAuthListener;
    //PROGRESS DIALOG
    ProgressDialog mProgressDialog;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register_user);
        //ASSIGN ID'S
        userEmailCreateEditText = ( EditText ) findViewById(R.id.emailRegisterEditText);
        userPassWordCreateEditText = (EditText) findViewById(R.id.passwordRegisterEditText);
        createAccountBtn = ( LinearLayout) findViewById(R.id.createAccountSubmitBtn);
        //PROGRESS DIALOG INSTANCE
        mProgressDialog = new ProgressDialog(this);
        //FIREBASE INSTANCE
        mAuth = FirebaseAuth.getInstance();
        mAuthListener = new FirebaseAuth.AuthStateListener() {
            @Override
            public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
                //CHECK USER
                FirebaseUser user = firebaseAuth.getCurrentUser();
                if( user != null )
                {
                    Intent moveToHome = new Intent(RegisterUserActivity.this, Home.class);
                    moveToHome.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivity( moveToHome );
                }
            }
        };
        mAuth.addAuthStateListener(mAuthListener);
        //CREATE ON CLICK LISTENER
        createAccountBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mProgressDialog.setTitle("Create Account");
                mProgressDialog.setMessage("Wait while the account is being created..");
                mProgressDialog.show();
                createUserAccount();
            }
        });
    }
    @Override
    protected void onStart() {
        super.onStart();
        mAuth.addAuthStateListener(mAuthListener);
    }
    @Override
    protected void onStop() {
        super.onStop();
        mAuth.removeAuthStateListener(mAuthListener);
    }
    //LOGIC FOR CREATING THE USER ACCOUNT
    private void createUserAccount() {
        String emailUser, passUser;
        emailUser = userEmailCreateEditText.getText().toString().trim();
        passUser = userPassWordCreateEditText.getText().toString().trim();
        if( !TextUtils.isEmpty(emailUser) && !TextUtils.isEmpty(passUser))
        {
            mAuth.createUserWithEmailAndPassword(emailUser, passUser).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    if( task.isSuccessful() )
                    {
                        Toast.makeText(RegisterUserActivity.this, "Account created Success", Toast.LENGTH_LONG).show();
                        mProgressDialog.dismiss();
                        Intent moveToHome = new Intent(RegisterUserActivity.this, Home.class);
                        moveToHome.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        startActivity( moveToHome );
                    }else
                    {
                        Toast.makeText(RegisterUserActivity.this, task.getException().getMessage(), Toast.LENGTH_LONG).show();
                        mProgressDialog.dismiss();
                        task.getException().getMessage();
                    }
                }
            });
        }
    }
}

A: The project_id in your Android app's google-services.json file should be the same as the Firebase Console project for which you enabled Google Sign In Authentication. Try re-download google-services.json from Firebase Console, and re-build your Android app.


text:
Q: Count pattern and matching lines simultaneously I want to count the occurrence of a pattern per line and also get the last matching line number
So for counting patterns I would use
grep -c pattern file

and for last matching line number
grep -n pattern file | cut -d : -f 1 | tail -1

Is there any way by which I get both the results by greping only once? The file I am working with is large and I need to iterate this for several patterns, so I would like to avoid greping twice.

A: You could use awk instead of grep:
awk '/pattern/ {last = NR; count++}
     END {printf "Last: %s\nCount: %d\n", last, count}' < file

Beware that awk patterns are extended regular expressions (with slight differences with grep -E ones wrt backslash).
You could also use only one awk invocations for all your patterns:
awk '!patterns_finished{patterns[$0]; next}
     {
       for (p in patterns) if ($0 ~ p) {
         last[p] = NR
         count[p]++
       }
     }
     END {
       for (p in patterns)
         printf "%s: count=%d last=%s\n", count[p], last[p]
     }' patterns.txt patterns_finished=1 file

(assuming patterns.txt contains the list of patterns, one per line).


text:
Q: Multiple User Types in Laravel 4 - Login Issues I am doing a project for school and I need more than one user type : User, Registrar and Teacher.
I followed Laravel documentation and got the user working perfectly (login/register).
Then I tried adding another user: Registrar. I got the registration working and it's even adding the user in the "registrar" table.
But when I'm trying to log in it is using the "users" table, not the "registrar" one, and giving me a controller method "not found" error.
Model: Registrar.php
<?php

use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;

class Registrar extends Eloquent implements UserInterface, RemindableInterface {
    protected $table = 'registrar';
    protected $hidden = array('password');
    public function getAuthIdentifier() {
        return $this->getKey();
    }
    public function getAuthPassword() {
        return $this->password;
    }
}

Routes:
Route::get('/', array('uses' => 'HomeController@AuthenticateUser'));

Route::get('/student/member', array('uses' => 'UsersController@getStudent'));

Route::get('logout', array('uses' => 'UsersController@doLogout'));

Route::controller('users', 'UsersController');

Route::controller('password', 'RemindersController');

Route::controller('registrar', 'RegistrarController');

Route::get('/registrar/member', array('uses' => 'RegistrarController@getRegistrar'));

RegistrarController, Sign-In method:
public function postSignin() {
    if (Auth::attempt(array('email'=>Input::get('login_input')) {
        return Redirect::to('registrar/member')->with('status', 'You are now logged in!');
    } else {
        return Redirect::to('registrar/login')
            ->with('error', 'Your username/password combination was incorrect')
            ->withInput();
    }
}

Other functions inside:
class RegistrarController extends BaseController {
    public function __construct() {
        $this->beforeFilter('csrf', array('on'=>'post'));
        $this->beforeFilter('auth', array('only'=>array('getRegistrar')));
    }
    public function getRegister() {
        return View::make('registrar.register');
    }
    public function getRegistrar() {
        return View::make('registrar.member');
    }

login.blade.php
{{ Form::open(array('url'=>'registrar/signin', 'class'=>'form-signin' , 'id'=>'login-form')) }}
.
.
.
.
-- form close--

I'm wondering if this line is not the problem in the signin function:
if (Auth::attempt(array('email'=>Input::get('login_input')) {
        return Redirect::to('registrar/member')->with('status', 'You are now logged in!')

As I'm not sure how the system checks which database table to use, or its default on the "users".

A: You can do this to swap the model during runtime:
$provider = new \Illuminate\Auth\EloquentUserProvider(app('hash'), 'Registrar');

Auth::setProvider($provider);


text:
Q: Openlayers2 transition effect The OpenLayers TransitionEffect='resize' property is not working while using GeoWebcache service of GeoServer
var demolayer = new OpenLayers.Layer.WMS(
    "Eg", "http://localhost:8080/geoserver/gwc/service/wms",
    {
             layers: 'Eg',
             format: 'image/gif' ,
             tiled: true,
             tilesorigin: [29.06213671874999, 28.912181118327]
            },
            {attribution: '©copy rights',
             tileSize: new OpenLayers.Size(256,256)},
            { transitionEffect: 'resize'
            }

          );

A: You didn't include properties in the right place. Then again, you also didn't include working code, so perhaps this isn't your actual code, but the four args to WMS are:

*

*name

*URL

*Properties (sent to server)

*Options (used on the client)

So your code should look something like this:
var demolayer = new OpenLayers.Layer.WMS( "Eg",
  "http://localhost:8080/geoserver/gwc/service/wms",
  { layers: 'Eg', format: 'image/gif' , tiled: true, tilesorigin: [29.06213671874999, 28.912181118327] },
  {attribution: '©copy rights', transitionEffect: 'resize', tileSize: new OpenLayers.Size(256,256),//} );


text:
Q: Does iostream header file just contain declarations? I am learning programming in C++. I was writing a program to implement the calculator functionality:
As can be seen, I am including iostream header file.
#include <iostream>
#include "calculator.h"
int main()
{
    //This program is meant to mimic the functionality of a calculator which
    //support basic arithmetic operations.

    //we will ask the user to input the desired operation and operands
    getUserInput();

    //We perform the mathematical operation and return the result
    computeResult();

    //We will print the output to the screen
    printResult();

    return 0;
}

Now I am writing a separate cpp file for getUserInput function.
#include<iostream>
int getUserInput()
{
    int a;
    std::cout << "enter your input " << std::endl;
    std::cin >> a;
    return (a);

}

Here also I am including iostream. Is it okay to do so?

Because , I suspect if iostream contains definitions, this can lead to
  a linking error related to  multiple defintions.

A: You're right that a header that contains definitions of global names can't be included in more than one source file without causing link errors. Standard headers don't do that.

A:
Does iostream header file just contain declarations?

No. It also contains definitions. For example, it is specified to include <ios> which among other things defines class templates such as std::basic_istream.

Here also I am including iostream. Is it okay to do so?
  Because , I suspect if iostream contains definitions, this can lead to a linking error related to multiple defintions.

<iostream> as well as all other standard headers will be protected by header guards or similar mechanism to ensure that the content is included only once despite multiple inclusion macros. Furthermore, they won't contain any definition that wouldn't be allowed to be in more than one translation unit according to the one-definition-rule.
So, Yes: It is okay to include standard headers multiple times. Both within a translation unit as well as from multiple separate translation units.


text:
Q: Rename mulitple special characters in filenames I always have problems with special characters and Ä, Ö, Ü in the filenames of files. So far I have collected and replaced the characters. But there are always new ones and it is simply not automated
e.g filenames:
testç.txt
aaaä.txt
gggggggç.txt
rrérr.txt
-Î¥tr.pdf

e.g. here:
def rename():
    [os.rename(os.path.join(dirpath, f), os.path.join(dirpath, f).replace('ç', 'c')) for f in os.listdir(dirpath)]
    [os.rename(os.path.join(dirpath, f), os.path.join(dirpath, f).replace('ä', 'ae')) for f in os.listdir(dirpath)]
    [os.rename(os.path.join(dirpath, f), os.path.join(dirpath, f).replace('ç', 'c')) for f in os.listdir(dirpath)]
    [os.rename(os.path.join(dirpath, f), os.path.join(dirpath, f).replace('ä', 'ae')) for f in os.listdir(dirpath)]
    [os.rename(os.path.join(dirpath, f), os.path.join(dirpath, f).replace('Ä', 'ae')) for f in os.listdir(dirpath)]
    [os.rename(os.path.join(dirpath, f), os.path.join(dirpath, f).replace('Ö', 'oe')) for f in os.listdir(dirpath)]
    [os.rename(os.path.join(dirpath, f), os.path.join(dirpath, f).replace('ö', 'oe')) for f in os.listdir(dirpath)]
    [os.rename(os.path.join(dirpath, f), os.path.join(dirpath, f).replace('Ü', 'ue')) for f in os.listdir(dirpath)]
    [os.rename(os.path.join(dirpath, f), os.path.join(dirpath, f).replace('ü', 'ue')) for f in os.listdir(dirpath)]
    etc....

Is there a simple possibility to replace all special characters and and Ä, Ö, Ü in all files in the directory?

A: You can use unicodedata module
Ex:
import unicodedata
os.rename(os.path.join(dirpath, f), os.path.join(dirpath, unicodedata.normalize('NFKD', f).encode('ascii', 'ignore').decode())) for f in os.listdir(dirpath)]

Demo:
import unicodedata
s = ['testç.txt', 'aaaä.txt', 'gggggggç.txt', 'rrérr.txt', '-Î¥tr.pdf']

for i in s:
    print(unicodedata.normalize('NFKD', i).encode('ascii', 'ignore').decode())

Output:
testc.txt
aaaa.txt
gggggggc.txt
rrerr.txt
-Itr.pdf

A: The module unicodedata gives you some internal list of changes. But, as far as I can see, some of the changes are not that you want. For example ä will be changed with a, not with ae, etc. Perhaps it can be tweaked somehow, I don't know.
So if you prefer to stick to your personal change list you sill need to write down the list explicitly but your code can be much shorter at least:
from pathlib import Path

changes = {"ä":"ae", "ö":"oe", "ç":"c", "ü":"u", "é":"e", "î":"i"} # etc

folder = Path.cwd() / "files"       # subfolder with files in current folder
files  = Path.glob(folder, "*")     # get all files from the subfolder

def replace(name):
    name = name.lower()             # convert all to lower case: ÄÖ --> äö
    for char in name:
        if char in changes:
            name = name.replace(char, changes[char])
    return name

for f in files:
    new_name = replace(f.name)
    print(f"{f.name :20} --> {new_name}")
    f.rename(folder/new_name)

Output:
...\files\

-Î¥tr.pdf            --> -i¥tr.pdf
aaaä.txt             --> aaaae.txt
gügggÖggüügç.txt     --> gugggoegguugc.txt
rrérr.txt            --> rrerr.txt
testç.txt            --> testc.txt

And your list can be about two times shorter if you will convert the filenames in lower case. You won't need to make two replaces Ö --> oe and ö --> oe, etc.


text:
Q: How to search an array of strings using wildcard I'm trying to write a simple program that will search an array of string and output all the value which first sets of letters starts with what is in JTextfield
String[] words= {"apples", "applets", "ash", "bass", "banana", "cat", "chat", "coke"};

what I want is when my textfield contains nothing all of the words would appear, if "app" then only apples and applets will be displayed.

A: Just iterate over the strings an evaluate each one with startsWith:
private static String[] filterWords(String[] words, String prefix) {
    List<String> filtered = new LinkedList<String>();
    for (String word : words) {
        if (prefix == null || prefix.lenght() == 0 || word.startsWith(prefix)) {
            filtered.add(word);
        }
    }
    return filtered.toArray(new String[filtered.size()]);
}

A: You need to iterate your array element one by one, use String.startsWith(prefixText) function to check your string is start with search text, add your search element in one List and convert that list into array return that array.
For Example :
public String[] searchText(String[] strArray,String searchTxt)
{
    if(searchTxt == null || searchTxt.length()==0)
        return strArray;

    List<String> resultArray = new LinkedList<String>();
    for (String word : strArray) {
        if (word.startsWith(searchTxt)) {
            resultArray.add(word);
        }
    }
   return resultArray.toArray(new String[resultArray.size()]);
}

If your search string's length is zero than return you original array without iterating your array.

A: A little more efficient solution especially with large arrays would be:
private static String[] filterWords(String[] words, String prefix) {
    List<String> filtered = new LinkedList<String>();

if (prefix == null || prefix.lenght() == 0){
    return words;
}
else{
    for (String word : words) {
         if(word.startsWith(prefix)) {
            filtered.add(word);
        }
    }
    return filtered.toArray(new String[filtered.size()]);
}

A: This can be done very efficiently and concisely with Java 8 Lambdas:
    String[] words = {"apples", "applets", "ash", "bass", "banana", "cat", "chat", "coke"};
    String searchText = "app"; //Coming from the TextArea

    String[] results = Arrays.stream(words)
            .filter(item -> item.startsWith(searchText))
            .toArray(size -> new String[size]);


text:
Q: How to download multiple files bundled into one zip files in Node js? I am working on node project, In my project I have two images in the images folder. Now my goal is I have to zip those two images and download. For this I am using this npm zip-downloader.
But I am getting these kind of errors
Error: Cannot find module 'babel-runtime/core-js/object/assign'
This is my code, server.js
const express = require('express');
const app = express();
const cors = require('cors');
const bodyParser = require('body-parser');
const multer = require('multer');
const upload = multer({dist:'./uploads'});
const jimp = require('jimp');
const zip = require('file-zip');
const downloader = require('zip-downloader')

app.post('/api/images',upload.single('profilepic'), (req, res) =>{
    console.log(req.file)
    res.json({'message':'file upload successfully'})
});

jimp.read('images/one.jpeg')
  .then(one => {
    return morng
      .resize(100, 100) // resize
      .quality(60) // set JPEG quality
      .greyscale() // set greyscale
      .write('images/two.jpg'); // save
  })
  .catch(err => {
    console.error(err);
  });

zip.zipFile(['images/one.jpeg','images/two.jpg'],'out.zip',function(err){
    if(err){
        console.log('zip error',err)
    }else{
        console.log('zip success');
    }
})

const assets = [
  {
      'src': 'images/one.jpeg'
  },
  {
    'src': 'images/two.jpg'
  }
];

const options = {
  downloadFolderName: 'images',
  statusCallback: function(downloadedTillNow){
      console.log('Download status:' + ((downloadedTillNow * 100)/assets.length));
  },
  onComplete : function(downloadedSummary){
      console.log('Assets downloaded:' + downloadedSummary.numberOfDownloadedAssets);
      console.log('Assets failed:' + downloadedSummary.numberOfFailedAssets);
      console.log('Large Assets downloaded(over maxZIPSize):' + downloadedSummary.numberOfLargeUnZippedAssets);
      console.log('Number of zip files downloaded:' + downloadedSummary.numberOfDownloadedZIPFiles);
      console.log('Array of failed assets:');
      console.log(downloadedSummary.failedAssetList);
  },
};

downloader(assets, options);

This is package.json file
{
  "name": "file",
  "version": "1.0.0",
  "description": "",
  "main": "server.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node server.js"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "body-parser": "^1.19.0",
    "cors": "^2.8.5",
    "express": "^4.17.1",
    "file-zip": "^1.0.1",
    "files-download-zip": "^3.1.1",
    "jimp": "^0.9.3",
    "jszip": "^3.2.2",
    "multer": "^1.4.2",
    "zip-downloader": "^1.0.2"
  }
}

Need a solution to overcome this error.

A: Since you're defining an object const options = {}, all of the properties which are defined inside the bracket {} should follow by :
The error in this case:

SyntaxError: Invalid shorthand property initializer

means you're trying to create a property with invalid syntax.
You can fix it by:
const options = {
  downloadFolderName: 'images',
  statusCallback: function(downloadedTillNow){
      console.log('Download status:' + ((downloadedTillNow * 100)/assets.length));
  },
  onComplete: function(downloadedSummary){
      console.log('Assets downloaded:' + downloadedSummary.numberOfDownloadedAssets);
      console.log('Assets failed:' + downloadedSummary.numberOfFailedAssets);
      console.log('Large Assets downloaded(over maxZIPSize):' + downloadedSummary.numberOfLargeUnZippedAssets);
      console.log('Number of zip files downloaded:' + downloadedSummary.numberOfDownloadedZIPFiles);
      console.log('Array of failed assets:');
      console.log(downloadedSummary.failedAssetList);
  }
};


text:
Q: Syntax error when trying to pass in multiple parameters for a SELECT from Python to SQLite I'm getting an error from the second half of the SELECT execution claiming it's about a ,. Around (K[0], K[1], K[2], K[3], K[4], K[5], K[6],))
Instead of (list) = (?,?,?) I've tried L0 = ? AND L1 =? which gave a different error
    K = [Loc.L[0], Loc.L[1], Loc.L[2], Loc.L[3],
        Loc.L[4], Loc.L[5], Loc.L[6],]
    c.execute("SELECT * FROM LocationTable WHERE (L0,L1,L2,L3,L4,L5,L6) = (?,?,?,?,?,?,?)", (K[0], K[1], K[2], K[3], K[4], K[5], K[6],))
    if c.fetchall() is not None:
        print('Error. Location already exists')
    else:
        c.execute('INSERT INTO LocationTable VALUES(?,?,?,?,?,?,?,?)',
                      (None, K[0], K[1], K[2], K[3], K[4], K[5], K[6],))
       conn.commit()

it says

sqlite3.OperationalError: near ",": syntax error


text:
Q: SoapUI load test terminates when limit is reached and then run again after which never stops I have a load test:

It was originally designed on version 5.0.1 of SoapUI (maybe 5.0.0) and later modified and currently used on 5.2.1.
When I run it from SOAP GUI it runs well and terminates in 30 seconds as is set in its limit.
But when I run it from Jenkins (shell script) or console it terminates in 30 seconds and then immediately re-runs. The second run is never got terminated Does anyone know how can I solve this issue? Maybe I do not understand some settings correctly?
Functional tests run without any issues.
Extract from the log which shows the moment when first run terminates and then test starts again:
[root@jenkins-cip cip-soapui-load-dev]# export SOAPUI_HOME=/opt/progs/SmartBear/SoapUI-5.2.1
[root@jenkins-cip cip-soapui-load-dev]# path=`pwd`
[root@jenkins-cip cip-soapui-load-dev]# $SOAPUI_HOME/bin/loadtestrunner.sh  -r -f/opt/progs/SmartBear/SoapUI-5.2.1/loadteststatistics -Doracle.jdbc.timezoneAsRegion=false  -Gsoapui.properties=${path}/cip.dev.properties  CIP-smoke-test-load.xml
================================
=
= SOAPUI_HOME = /opt/progs/SmartBear/SoapUI-5.2.1
=
================================
12:28:26,753 INFO  [SoapUILoadTestRunner] Running LoadTest [LoginLoadTest]
Progress: 1 - Creating Virtual User 1
Progress: 1 - Creating Virtual User 2
Progress: 1 - Creating Virtual User 3
Progress: 1 - Creating Virtual User 4
Progress: 1 - Creating Virtual User 5
Progress: 1 - Creating Virtual User 6
Progress: 1 - Creating Virtual User 7
Progress: 1 - Creating Virtual User 8
Progress: 1 - Creating Virtual User 9
Progress: 1 - Creating Virtual User 10
Progress: 1 - Started thread 1
Progress: 1 - Started thread 2
Progress: 1 - Started thread 3
Progress: 1 - Started thread 4
Progress: 1 - Started thread 5
Progress: 1 - Started thread 6
Progress: 1 - Started thread 7
Progress: 1 - Started thread 8
Progress: 1 - Started thread 9
Progress: 1 - Started thread 10
12:28:26,802 INFO  [SoapUILoadTestRunner] LoadTest [LoginLoadTest] progress: 4.6666668E-4, 10
12:28:27,673 DEBUG [HttpClientSupport$SoapUIHttpClient] Attempt 1 to execute request
12:28:27,673 DEBUG [SoapUIMultiThreadedHttpConnectionManager$SoapUIDefaultClientConnection] Sending request: POST /cip/kn-BusinessPartner-V6 HTTP/1.1
12:28:27,688 DEBUG [HttpClientSupport$SoapUIHttpClient] Attempt 1 to execute request
12:28:27,688 DEBUG [SoapUIMultiThreadedHttpConnectionManager$SoapUIDefaultClientConnection] Sending request: POST /cip/kn-BusinessPartner-V6 HTTP/1.1
12:28:27,752 DEBUG [HttpClientSupport$SoapUIHttpClient] Attempt 1 to execute request
12:28:27,752 DEBUG [SoapUIMultiThreadedHttpConnectionManager$SoapUIDefaultClientConnection] Sending request: POST /cip/kn-BusinessPartner-V6 HTTP/1.1
12:28:27,776 DEBUG [HttpClientSupport$SoapUIHttpClient] Attempt 1 to execute request
12:28:27,776 DEBUG [SoapUIMultiThreadedHttpConnectionManager$SoapUIDefaultClientConnection] Sending request: POST /cip/kn-BusinessPartner-V6 HTTP/1.1
12:28:27,802 INFO  [SoapUILoadTestRunner] LoadTest [LoginLoadTest] progress: 0.0338, 10
12:28:27,830 DEBUG [HttpClientSupport$SoapUIHttpClient] Attempt 1 to execute request
12:28:27,830 DEBUG [SoapUIMultiThreadedHttpConnectionManager$SoapUIDefaultClientConnection] Sending request: POST /cip/kn-BusinessPartner-V6 HTTP/1.1
12:28:27,882 DEBUG [SoapUIMultiThreadedHttpConnectionManager$SoapUIDefaultClientConnection] Receiving response: HTTP/1.1 200 OK
12:28:27,882 DEBUG [SoapUIMultiThreadedHttpConnectionManager$SoapUIDefaultClientConnection] Receiving response: HTTP/1.1 200 OK
12:28:27,901 DEBUG [HttpClientSupport$SoapUIHttpClient] Connection can be kept alive indefinitely
12:28:27,901 DEBUG [HttpClientSupport$SoapUIHttpClient] Connection can be kept alive indefinitely
12:28:27,908 DEBUG [SoapUIMultiThreadedHttpConnectionManager$SoapUIDefaultClientConnection] Receiving response: HTTP/1.1 200 OK
12:28:27,908 DEBUG [HttpClientSupport$SoapUIHttpClient] Connection can be kept alive indefinitely
12:28:27,923 DEBUG [SoapUIMultiThreadedHttpConnectionManager$SoapUIDefaultClientConnection] Receiving response: HTTP/1.1 200 OK
12:28:27,924 DEBUG [HttpClientSupport$SoapUIHttpClient] Connection can be kept alive indefinitely
12:28:27,972 DEBUG [HttpClientSupport$SoapUIHttpClient] Stale connection check
12:28:27,973 DEBUG [HttpClientSupport$SoapUIHttpClient] Attempt 1 to execute request
12:28:27,973 DEBUG [SoapUIMultiThreadedHttpConnectionManager$SoapUIDefaultClientConnection] Sending request: POST /cip/kn-BusinessPartner-V6 HTTP/1.1
12:28:27,977 DEBUG [SoapUIMultiThreadedHttpConnectionManager$SoapUIDefaultClientConnection] Receiving response: HTTP/1.1 200 OK
12:28:27,977 DEBUG [HttpClientSupport$SoapUIHttpClient] Connection can be kept alive indefinitely
12:28:27,979 DEBUG [HttpClientSupport$SoapUIHttpClient] Stale connection check
12:28:27,981 DEBUG [HttpClientSupport$SoapUIHttpClient] Attempt 1 to execute request
12:28:27,981 DEBUG [SoapUIMultiThreadedHttpConnectionManager$SoapUIDefaultClientConnection] Sending request: POST /cip/kn-BusinessPartner-V6 HTTP/1.1
12:28:27,992 DEBUG [HttpClientSupport$SoapUIHttpClient] Stale connection check
12:28:27,997 DEBUG [HttpClientSupport$SoapUIHttpClient] Attempt 1 to execute request
...
...
...
12:28:56,947 DEBUG [SoapUIMultiThreadedHttpConnectionManager$SoapUIDefaultClientConnection] Receiving response: HTTP/1.1 200 OK
12:28:56,947 DEBUG [HttpClientSupport$SoapUIHttpClient] Connection can be kept alive indefinitely
12:28:57,810 INFO  [SoapUILoadTestRunner] LoadTest [LoginLoadTest] finished with status FINISHED
12:28:57,810 INFO  [SoapUILoadTestRunner] Exporting log and statistics for LoadTest [LoginLoadTest]
12:28:57,813 INFO  [SoapUILoadTestRunner] Exported 2 log items to [/opt/progs/SmartBear/SoapUI-5.2.1/loadteststatistics/LoginLoadTest-log.txt]
12:28:57,813 INFO  [SoapUILoadTestRunner] Exported 0 error results
12:28:57,814 INFO  [SoapUILoadTestRunner] Exported 3 statistics to [/opt/progs/SmartBear/SoapUI-5.2.1/loadteststatistics/LoginLoadTest-statistics.txt]
12:28:57,814 INFO  [SoapUILoadTestRunner] Running LoadTest [LoadTest]
Progress: 1 - Creating Virtual User 1
Progress: 1 - Creating Virtual User 2
Progress: 1 - Creating Virtual User 3
Progress: 1 - Creating Virtual User 4
Progress: 1 - Creating Virtual User 5
Progress: 1 - Creating Virtual User 6
Progress: 1 - Creating Virtual User 7
Progress: 1 - Creating Virtual User 8
Progress: 1 - Creating Virtual User 9
Progress: 1 - Creating Virtual User 10
Progress: 1 - Started thread 1
Progress: 1 - Started thread 2
Progress: 1 - Started thread 3
Progress: 1 - Started thread 4
Progress: 1 - Started thread 5
Progress: 1 - Started thread 6
Progress: 1 - Started thread 7
Progress: 1 - Started thread 8
Progress: 1 - Started thread 9
Progress: 1 - Started thread 10
12:28:57,841 INFO  [SoapUILoadTestRunner] LoadTest [LoadTest] progress: 2.5E-5, 10
12:28:58,613 DEBUG [HttpClientSupport$SoapUIHttpClient] Stale connection check
12:28:58,614 DEBUG [HttpClientSupport$SoapUIHttpClient] Attempt 1 to execute request
12:28:58,614 DEBUG [SoapUIMultiThreadedHttpConnectionManager$SoapUIDefaultClientConnection] Sending request: POST /cip/kn-BusinessPartner-V6 HTTP/1.1
12:28:58,658 DEBUG [HttpClientSupport$SoapUIHttpClient] Stale connection check
12:28:58,659 DEBUG [HttpClientSupport$SoapUIHttpClient] Attempt 1 to execute request
12:28:58,659 DEBUG [SoapUIMultiThreadedHttpConnectionManager$SoapUIDefaultClientConnection] Sending request: POST /cip/kn-BusinessPartner-V6 HTTP/1.1
12:28:58,699 DEBUG [HttpClientSupport$SoapUIHttpClient] Stale connection check
12:28:58,701 DEBUG [HttpClientSupport$SoapUIHttpClient] Attempt 1 to execute request

The same behaviour when run from a command line:
export SOAPUI_HOME=/opt/progs/SmartBear/SoapUI-5.2.1
path=`pwd`

$SOAPUI_HOME/bin/loadtestrunner.sh  -r -f/opt/progs/SmartBear/SoapUI-5.2.1/loadteststatistics -Doracle.jdbc.timezoneAsRegion=false  -Gsoapui.properties=${path}/cip.dev.properties  CIP-smoke-test-load.xml


text:
Q: How To Have Multiple Divs On One Line With Even Spacing Trying to get multiple divs on the same line with even spacing. So they nicely fit the whole container.
Here is what i have got so far. Tried to set margin right and left equal to the same on all the boxes, but it is still tricky to make it even and sometimes the final box will go on a new line.
HTML

 Heading 1

Information

Heading 2

 Information

Heading 3

Information

Heading 4

Information

CSS
#serviceBox
{
    width:100%;
    margin: 0 auto;
    margin-top:75px;
    height:250px;
    border:1px solid black;
}
.serviceBox1, .serviceBox2, .serviceBox3, .serviceBox4 {
    float:left;
    width:20%;
    height: 250px;
    background-color: white;
    border: 1px solid #bdbdbd;
    -webkit-border-radius: 5px;
    border-radius: 5px;
    -moz-box-shadow: 0 0 10px #bdbdbd;
    -webkit-box-shadow: 0 0 10px #bdbdbd;
    box-shadow: 0 0 10px #bdbdbd;
}

https://jsfiddle.net/ruJ2R/3/

A: I would suggest adding a new element inside each serviceBox, in this example the div with class box
CSS:
#serviceBox
{
    width:100%;
    margin: 0 auto;
    margin-top:75px;
    height:250px;
    border:1px solid black;
}
.serviceBox1, .serviceBox2, .serviceBox3, .serviceBox4 {
    float:left;
    width:25%;
}

.box{
    height: 250px;
    background-color: white;
    border:1px solid #bdbdbd;
    -webkit-border-radius: 5px;
    border-radius: 5px;
    -moz-box-shadow: 0 0 10px #bdbdbd;
    -webkit-box-shadow: 0 0 10px #bdbdbd;
    box-shadow: 0 0 10px #bdbdbd;
}

HTML

 Heading 1

Information

Heading 2

 Information

Heading 3

Information

Heading 4

Information

This way the service boxes are nicely a quarter of the container and inside service box you can add the border and shading to the new box element

A: UPDATE: because of the borders , either apply box-sizing:border-box to your style, or put your div with borders inside one more div.
There are at least 4 different ways of doing it.

*

*using float layout

*using display:table-cell

*using display:inline-block

*using absolute positioning
.serviceBox {
  box-sizing:border-box;
  margin-right:4%;
  float:left;
  width:20%;
  height: 250px;
  background-color: white;
  border: 1px solid #bdbdbd;
  -webkit-border-radius: 5px;
  border-radius: 5px;
  -moz-box-shadow: 0 0 10px #bdbdbd;
  -webkit-box-shadow: 0 0 10px #bdbdbd;
  box-shadow: 0 0 10px #bdbdbd;

}

.serviceBox:first { margin-left:4%; }

see updated fiddle

A: Your problem is that the boxes have a border, so giving them width and margin in percentages that sum to 100% don't work: each box has an extra 2 pixels from the border, pushing the last one off the row.  But you can solve this problem by giving them negative margins to compensate for the border:
width:25%;
margins:0 -1px;

A: try this,
.serviceBox {

margin-left:4%;

float:left;
width:20%;
height: 250px;
background-color: white;
border: 1px solid #bdbdbd;
-webkit-border-radius: 5px;
border-radius: 5px;
-moz-box-shadow: 0 0 10px #bdbdbd;
-webkit-box-shadow: 0 0 10px #bdbdbd;
box-shadow: 0 0 10px #bdbdbd;

}


text:
Q: External Object general error message on login When logging into an org as a System Admin, I receive the following error:

The text of the error message: "Developer error in file apex://Order__x at line number -1"
Stack trace error message: "Unfortunately, there was a problem. Please try again. If the problem continues, get in touch with your administrator with the error ID shown here and any other related details.
Error ID: 334194590-82559 (116521520)"
Any idea why this error may be being thrown? What does this error mean for an external object? It looks like the Order__x external object is behaving as expected in all other contexts.
Upon refreshing, now the error is no longer appearing, even when logging out and logging back in. I have not made any changes to resolve this error and can no longer reproduce at all.

A: That message "Error ID: 334194590-82559 (116521520)" is a GACK reference.
It's basically an internal Salesforce error code for something they didn't expect to occur.
The standard way to handle a GACK is to raise a support case. Make sure you include the Error ID clearly and identify it as a GACK.


text:
Q: Error in creating own package while doing exactly what instruction says I have a problem with creating my own package in R. I deem that it's very strange because I'm doing exactly when the instruction says.
I've done what was in the instruction :

*

*Create functions I want in my package

*Open new project -> R package

*Create description and put them info 'man' folder

*Press Ctr+Shift+B

I have problem, because I get this massage :
'UNC paths are not supported.  Defaulting to Windows directory.
Warning: invalid package 'mynewpackage'
Error: ERROR: no packages specified'
I tried to find the solution in internet. It seem's that this is often problem, but I couldn't find the answer in this specific problem. Do you have any idea's how can I fix it ?


text:
Q: How to remove date format I have the following content in the file. I would like to remove dates and the underlines from the file using sed. let me know if this would be possible to do with grep either.
03-02-2016
===========

<exp2://Ticket/26727777> Splunk Onboarding for SSO Components (UAT)

<exp2://Ticket/25709048> <SERVER-SETUP>Splunk Setup 14xMDN, 10xPRN Prod

<exp2://Ticket/26716590> Logs not populated properly from all servers -  SPLUNK TEST

<exp2://Ticket/23995808> Prod: Create summary index summary_rover_lifecycle in DS cluster

05-02-2016
===========

<exp2://Ticket/26781310> Request for on-boarding on Splunk -Employee Systems Logs

<exp2://Ticket/26781558> Splunk setup for Apple Learn UAT hosts

A: If you have access to GNU grep:
grep -vP '^(\d+-\d+-\d+|=+)$' file

And, if you don't:
grep -vE '^([0-9]+-[0-9]+-[0-9]+|=+)$' file

Both commands use grep's -v flag which means "print lines that don't match the pattern and look for lines consisting of either 3 groups of digits separated by dashes or one or more = from the beginning (^) to the end ($) of the line.
You can do the same thing in sed with:
sed -E '/([0-9]+-[0-9]+-[0-9]+|=+)/d' file


text:
Q: Can memcpy be used for type punning? This is a quote from the C11 Standard:

6.5 Expressions
...
6  The effective type of an object for an access to its stored value is the declared type of the object, if any. If a value is stored into an object having no declared type through an lvalue having a type that is not a character type, then the type of the lvalue becomes the effective type of the object for that access and for subsequent accesses that do not modify the stored value. If a value is copied into an object having no declared type using memcpy or memmove, or is copied as an array of character type, then the effective type of the modified object for that access and for subsequent accesses that do not modify the value is the effective type of the object from which the value is copied, if it has one. For all other accesses to an object having no declared type, the effective type of the object is simply the type of the lvalue used for the access.
7 An object shall have its stored value accessed only by an lvalue expression that has one of the following types:
— a type compatible with the effective type of the object,
— a qualified version of a type compatible with the effective type of the object,
— a type that is the signed or unsigned type corresponding to the effective type of the object,
— a type that is the signed or unsigned type corresponding to a qualified version of the effective type of the object,
— an aggregate or union type that includes one of the aforementioned types among its members (including, recursively, a member of a subaggregate or contained union), or
— a character type.

Does this imply that memcpy cannot be used for type punning this way:
double d = 1234.5678;
uint64_t bits;
memcpy(&bits, &d, sizeof bits);
printf("the representation of %g is %08"PRIX64"\n", d, bits);

Why would it not give the same output as:
union { double d; uint64_t i; } u;
u.d = 1234.5678;
printf("the representation of %g is %08"PRIX64"\n", d, u.i);

What if I use my version of memcpy using character types:
void *my_memcpy(void *dst, const void *src, size_t n) {
    unsigned char *d = dst;
    const unsigned char *s = src;
    for (size_t i = 0; i < n; i++) { d[i] = s[i]; }
    return dst;
}

EDIT: EOF commented that The part about memcpy() in paragraph 6 doesn't apply in this situation, since uint64_t bits has a declared type.  I agree, but, unfortunately, this does not help answer the question whether memcpy can be used for type punning, it just makes paragraph 6 irrelevant to assess the validity of the above examples.
Here here is another attempt at type punning with memcpy that I believe would be covered by paragraph 6:
double d = 1234.5678;
void *p = malloc(sizeof(double));
if (p != NULL) {
    uint64_t *pbits = memcpy(p, &d, sizeof(double));
    uint64_t bits = *pbits;
    printf("the representation of %g is %08"PRIX64"\n", d, bits);
}

Assuming sizeof(double) == sizeof(uint64_t), Does the above code have defined behavior under paragraph 6 and 7?

EDIT: Some answers point to the potential for undefined behavior coming from reading a trap representation.  This is not relevant as the C Standard explicitly excludes this possibility:

7.20.1.1 Exact-width integer types
1 The typedef name intN_t designates a signed integer type with width N, no padding bits, and a two's complement representation. Thus, int8_t denotes such a signed integer type with a width of exactly 8 bits.
2 The typedef name uintN_t designates an unsigned integer type with width N and no padding bits. Thus, uint24_t denotes such an unsigned integer type with a width of exactly 24 bits.
These types are optional. However, if an implementation provides integer types with widths of 8, 16, 32, or 64 bits, no padding bits, and (for the signed types) that have a two's complement representation, it shall define the corresponding typedef names.

Type uint64_t has exactly 64 value bits and no padding bits, thus there cannot be any trap representations.

A: You propose 3 ways which all have different problems with C standard.

*

*standard library memcpy
double d = 1234.5678;
uint64_t bits;
memcpy(&bits, &d, sizeof bits);
printf("the representation of %g is %08"PRIX64"\n", d, bits);

The memcpy part is legal (provided in your implementation sizeof(double) == sizeof(uint64_t) which is not guaranteed per standard): you access two objects through char pointers.
But the printf line is not. The representation in bits is now a double. it might be a trap representation for an uint64_t, as defined in 6.2.6.1 General §5

Certain object representations need not represent a value of the object type. If the stored
  value of an object has such a representation and is read by an lvalue expression that does
  not have character type, the behavior is undefined. If such a representation is produced
  by a side effect that modifies all or any part of the object by an lvalue expression that
  does not have character type, the behavior is undefined. Such a representation is called
  a trap representation.

And 6.2.6.2 Integer types says explicitely

For unsigned integer types other than unsigned char, the bits of the object
  representation shall be divided into two groups: value bits and padding bits ... The values of any padding bits are unspecified.53

With note 53 saying:

Some combinations of padding bits might generate trap representations,

If you know that in your implementation there are no padding bits (still never seen one...) every representation is a valid value, and the print line becomes valid again. But it is only implementation dependant and can be undefined behaviour in the general case

*union
union { double d; uint64_t i; } u;
u.d = 1234.5678;
printf("the representation of %g is %08"PRIX64"\n", d, u.i);

The members of the union do not share a common subsequence, and you are accessing a member which is not the last value written. Ok common implementation will give expected results but per standard it is not explicitely defined what should happen. A footnote in 6.5.2.3 Structure and union members §3 says that if leads to same problems as previous case:

If the member used to access the contents of a union object is not the same as the member last used to
  store a value in the object, the appropriate part of the object representation of the value is reinterpreted
  as an object representation in the new type as described in 6.2.6 (a process sometimes called "type
  punning"). This might be a trap representation.

*custom memcpy
Your implementation only does character accesses which is always allowed. It is exactly the same thing as the first case: implementation defined.
The only way that would be explicitely defined per standard would be to store the representation of the double in an char array of the correct size, and then display the bytes values of the char array:
double d = 1234.5678;
unsigned char bits[sizeof(d)];
memcpy(&bits, &d, sizeof(bits));
printf("the representation of %g is ", d);
for(int i=0; i<sizeof(bits); i++) {
    printf("%02x", (unsigned int) bits[i]);
}
printf("\n");

And the result will only be useable if the implementation uses exactly 8 bits for a char. But it would be visible because it would display more than 8 hexa digits if one of the bytes had a value greater than 255.

All of the above is only valid because bits has a declared type. Please see @EOF's answer to understand why it would be different for an allocated object

A: I read paragraph 6 as saying that using the memcpy() function to copy a series of bytes from one memory location to another memory location can be used for type punning just as using a union with two different types can be used for type punning.
The first mention of using memcpy() indicates that if it copies the specified number of bytes and that those bytes will have the same type as the variable at the source destination when that variable (lvalue) was used to store the bytes there.
In other words if you have a variable double d; and you then assign a value to this variable (lvalue) the type of the data stored in that variable is type double. If you then use the memcpy() function to copy those bytes to another memory location, say a variable uint64_t bits; the type of those copied bytes is still double.
If you then access the copied bytes through the destination variable (lvalue), the uint64_t bits; in the example, then the type of that data is seen as the type of the lvalue used to retrieve the data bytes from that destination variable. So the bytes are interpreted (not converted but interpreted) as the destination variable type rather than the type of the source variable.
Accessing the bytes through a different type means the bytes are now interpreted as the new type even though the bytes have not actually changed in any way.
This is also the way a union works. A union does not do any kind of conversion. You store bytes into a union member which is of one type and then you pull the same bytes back out through a different union member. The bytes are the same however the interpretation of the bytes depends on the type of the union member that is used to access the memory area.
I have seen the memcpy() function used in older C source code to help divide up a struct into pieces by using struct member offset along with the memcpy() function to copy portions of the struct variable into other struct variables.
Because the type of the source location used in the memcpy() is the type of the bytes stored there the same kinds of problems that you can run into with the use of a union for punning also apply to using memcpy() in this way such as the Endianness of the data type.
The thing to remember is that whether using a union or using the memcpy() approach the type of the bytes copied are the type of the source variable and when you then access the data as another type, whether through a different member of a union or through the destination variable of the memcpy() the bytes are interpreted as the type of the destination lvalue. However the actual bytes are not changed.

A: CHANGED--SEE BELOW
While I have never observed a compiler to interpret a memcpy of non-overlapping source and destination as doing anything that would not be equivalent to reading all of the bytes of the source as a character type and then writing all of the bytes of the destination as a character type (meaning that if the destination had no declared type, it would be left with no effective type), the language of the Standard would allow obtuse compilers to make "optimizations" which--in those rare instances where a compiler would be able to identify and exploit them--would be more likely to break code which would otherwise work (and would be well-defined if the Standard were better written) than to actually improve efficiency.
As to whether that means that it's better to use memcpy or a manual byte-copy loop whose purpose is sufficiently well-disguised as to be unrecognizable as "copying an array of character type", I have no idea.  I would posit that the sensible thing would be to shun anyone so obtuse as to suggest that a good compiler should generate bogus code absent such obfuscation, but since behavior that would have been considered obtuse in years past is presently fashionable, I have no idea whether memcpy will be the next victim in the race to break code which compilers had for decades treated as "well-defined".
UPDATE
GCC as of 6.2 will sometimes omit memmove operations in cases where it sees that the destination and source identify the same address, even if they are pointers of different types.  If storage which had been written as the source type is later read as the destination type, gcc will assume that the latter read cannot identify the same storage as the earlier write.  Such behavior on gcc's part is justifiable only because of the language in the Standard which allows the compiler to copy the Effective Type through the memmove.  It's unclear whether that was an intentional interpretation of the rules regarding memcpy, however, given that gcc will also make a similar optimization in some cases where it is clearly not allowed by the Standard, e.g. when a union member of one type (e.g. 64-bit long) is copied to a temporary and from there to a member of a different type with the same representation (e.g. 64-bit long long).  If gcc sees that the destination will be bit-for-bit identical to the temporary, it will omit the write, and consequently fail to notice that the effective type of the storage was changed.

A: There are two cases to consider: memcpy()ing into an object that has a declared type, and memcpy()ing into an object that does not.
In the second case,
double d = 1234.5678;
void *p = malloc(sizeof(double));
assert(p);
uint64_t *pbits = memcpy(p, &d, sizeof(double));
uint64_t bits = *pbits;
printf("the representation of %g is %08"PRIX64"\n", d, bits);

The behavior is indeed undefined, since the effective type of the object pointed to by p will become double, and accessing an object of effective type double though an lvalue of type uint64_t is undefined.
On the other hand,
double d = 1234.5678;
uint64_t bits;
memcpy(&bits, &d, sizeof bits);
printf("the representation of %g is %08"PRIX64"\n", d, bits);

is not undefined. C11 draft standard n1570:

7.24.1 String function conventions
  3 For all functions in this subclause, each character shall be interpreted as if it had the type
  unsigned char (and therefore every possible object representation is
  valid and has a different value).

And

6.5 Expressions
  7 An object shall have its stored value accessed only by an lvalue expression that has one of the following types: 88)

— a type compatible with the effective type of the object,
    — a qualified version of a type compatible with the effective type of the object,
    — a type that is the signed or unsigned type corresponding to the effective type of the object,
    — a type that is the signed or unsigned type corresponding to a qualified version of the
    effective type of the object,
    — an aggregate or union type that includes one of the aforementioned types
    among its members (including, recursively, a member of a subaggregate or contained union), or
    — a character type.

Footnote 88) The intent of this list is to specify those circumstances in which an object may or may not be aliased.

So the memcpy() itself is well-defined.
Since uint64_t bits has a declared type, it retains its type even though its object representation was copied from a double.
As chqrlie points out, uint64_t cannot have trap representations, so accessing bits after the memcpy() is not undefined, provided sizeof(uint64_t) == sizeof(double). However, the value of bits will be implementation-dependent (for example due to endianness).
Conclusion: memcpy() can be used for type-punning, provided that the destination of the memcpy() does have a declared type, i.e. is not allocated by [m/c/re]alloc() or equivalent.

A: It might give the same result, but the compiler does not need to guarantee it. So you simply cannot rely on it.


text:
Q: No se procesan correctamente los nuevos valores de 3 select dependientes En el formulario IngresoType tengo 3 select dependientes: salaDeIngreso, cubiculoDeIngreso y camaDeIngreso. La entidad Ingreso relacionada al formulario tambien tiene una relación con la entidad UnidadDeIngreso, y a partir de ahí es donde comienza la dependencia: Cuando se va a registrar un ingreso en una unidad de ingreso el select salaDeIngreso solo carga las salas de esa unidad que estén disponibles, y así sucecivamente con las entidades cubiculo y cama. El problema lo tengo en el evento PRE_SUBMIT del formulario, que al ocurrir un error de validación en el formulario, carga todos los registros existentes en los 3 select y no los registros asociados a la unidad de ingreso, así como los disponibles.
Esta es mi clase del formulario ingreso:
class IngresoType extends AbstractType {

    private $em;
    private $uuidEncoder;

    public function __construct(EntityManagerInterface $em, UuidEncoder $uuidEncoder) {
        $this->em = $em;
        $this->uuidEncoder = $uuidEncoder;
    }

    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options) {

        $builder->addEventListener(FormEvents::PRE_SET_DATA, function(FormEvent $event) {
            $form = $event->getForm();
            $data = $event->getData();

            if ($data->getId() === null) {
                $form->add('embarazada', EntityIdType::class, array(
                    'data_class' => Embarazada::class,
                    'empty_data' => null
                ));

                $form->add('fechaIngreso', DateType::class, array(
                    'widget' => 'single_text',
                    'input' => 'datetime',
                    'format' => 'dd/MM/yyyy',
                    'html5' => false,
                    'compound' => false,
                    'label' => 'Fecha de Ingreso',
                    'attr' => array('class' => 'js-datepicker')
                ));

                $form->add('nombre_embarazada', TextType::class, array(
                    'label' => 'Nombre Embarazada',
                    'mapped' => false,
                    'attr' => array('readonly' => true)
                ));
                $form->add('numeroIdentidad', TextType::class, array(
                    'mapped' => false,
                    'label' => 'Número de Identidad',
                    'attr' => array('maxlength' => '11'),
                ));

                $form->add('motivoDelIngreso', TextareaType::class, array(
                    'label' => 'Motivo del Ingreso',
                ));

                $unidadIngreso = $data->getUnidadDeIngreso();
                $salas = $this->em->getRepository(EstructuraOrganizativa::class)->obtenerSalasDisponiblesParaIngreso($unidadIngreso);
//                foreach ($salas as $s) {
//                    $s->setIdPublico($this->uuidEncoder->encode($s->getIdPublico()));
//                }
                $form->add('salaDeIngreso', EntityType::class, array(
                    'label' => 'Sala:',
                    'class' => SalaDeIngresos::class,
                    'choice_label' => 'nombre',
                    'choice_value' => 'id',
                    'empty_data' => null,
                    'choices' => $salas,
                ));
            }
            else {
                $form->add('id', HiddenType::class, array(
                    'data_class' => Ingreso::class,
                    'mapped' => false
                ));
                $form->add('fechaEgreso', DateType::class, array(
                    'widget' => 'single_text',
                    'input' => 'datetime',
                    'format' => 'dd/MM/yyyy',
                    'html5' => false,
                    'compound' => false,
                    'label' => 'Fecha de Ingreso',
                    'attr' => array('class' => 'js-datepicker'),
                ));

                $form->add('nombre_embarazada', TextType::class, array(
                    'label' => 'Nombre Embarazada',
                    'mapped' => false,
                    'data' => $data->getEmbarazada()->getNombre(),
                    'empty_data' => $data->getEmbarazada()->getNombre(),
                    'attr' => array('readonly' => true)
                ));

                $form->add('anotacionAlEgresar', TextareaType::class, array(
                    'label' => 'Nota del Egreso',
                ));

                $form->add('ingresoFinalizadoPorFuga', CheckboxType::class, array(
                    'label' => 'Abandono'
                ));

                $form->add('ingresoFinalizadoPorParto', CheckboxType::class, array(
                    'label' => 'Parto'
                ));

                $form->add('ingresoFinalizadoPorMuerteMaterna', CheckboxType::class, array(
                    'label' => 'Muerte Materna'
                ));

                $form->add('ingresoFinalizadoPorPerdidaEmbarazo', CheckboxType::class, array(
                    'label' => 'Pérdida del Embarazo'
                ));

                $form->add('criterioUbicacionNuevo', EntityType::class, array(
                    'label' => 'Criterio de Ubicación',
                    'class' => CriterioUbicacion::class,
                    'empty_data' => $data->getEmbarazada()->getUbicacion(),
                    'mapped' => false
                ));
            }
        });

        $builder->addEventListener(FormEvents::PRE_SET_DATA, function(FormEvent $event) {
            $form = $event->getForm();
            $data = $event->getData();
            if (is_null($data->getId())) {
                $cubiculos = $this->em->getRepository(Cubiculo::class)->obtenerDisponiblesParaIngreso($data->getSalaDeIngreso());
//                foreach ($cubiculos as $c) {
//                    $c->setIdPublico($this->uuidEncoder->encode($c->getIdPublico()));
//                }
                $form->add('cubiculoDeIngreso', EntityType::class, array(
                    'label' => 'Cubículo:',
                    'class' => Cubiculo::class,
                    'choice_label' => 'nombre',
                    'choice_value' => 'id',
                    'empty_data' => null,
                    'choices' => $cubiculos,
                ));
            }
        });

        $builder->addEventListener(FormEvents::PRE_SET_DATA, function(FormEvent $event) {
            $form = $event->getForm();
            $data = $event->getData();

            if (is_null($data->getId())) {
                $camas = $this->em->getRepository(Cama::class)->obtenerDisponiblesParaIngreso($data->getCubiculoDeIngreso());
//                foreach ($camas as $c) {
//                    $c->setIdPublico($this->uuidEncoder->encode($c->getIdPublico()));
//                }
                $form->add('camaDeIngreso', EntityType::class, array(
                    'label' => 'Cama:',
                    'class' => Cama::class,
                    'choice_label' => 'numero',
                    'choice_value' => 'id',
                    'empty_data' => null,
                    'choices' => $camas,
                    'placeholder' => '-- Seleccione --'
                ));
            }
        });

        $builder->addEventListener(FormEvents::PRE_SUBMIT, function(FormEvent $event) {
            $form = $event->getForm();
            $data = $event->getData();

            if (false === array_key_exists('id', $data)) {

                $sala = $this->em->getRepository(SalaDeIngresos::class)->find($data['salaDeIngreso']);
//                $sala = $this->em->getRepository(SalaDeIngresos::class)->findOneBy(array('idPublico' => $this->uuidEncoder->decode($data['salaDeIngreso'])));
                $form->add('salaDeIngreso', EntityType::class, array(
                    'label' => 'Sala:',
                    'class' => SalaDeIngresos::class,
                    'choice_label' => 'nombre',
                    'choice_value' => 'id',
                    'empty_data' => null,
                    'data' => $sala,
                ));

                $cubiculo = $this->em->getRepository(Cubiculo::class)->find($data['cubiculoDeIngreso']);
//                $cubiculo = $this->em->getRepository(Cubiculo::class)->findOneBy(array('idPublico' => $this->uuidEncoder->decode($data['cubiculoDeIngreso'])));
                $form->add('cubiculoDeIngreso', EntityType::class, array(
                    'label' => 'Cubículo:',
                    'class' => Cubiculo::class,
                    'choice_label' => 'nombre',
                    'choice_value' => 'id',
                    'empty_data' => null,
                    'data' => $cubiculo,
                ));

                $cama = $this->em->getRepository(Cama::class)->find($data['camaDeIngreso']);
//                $cama = $this->em->getRepository(Cama::class)->findOneBy(array('idPublico' => $this->uuidEncoder->decode($data['camaDeIngreso'])));
                $form->add('camaDeIngreso', EntityType::class, array(
                    'label' => 'Cama:',
                    'class' => Cama::class,
                    'choice_label' => 'numero',
                    'choice_value' => 'id',
                    'empty_data' => null,
                    'data' => $cama,
                    'placeholder' => '-- Seleccione --'
                ));
            }
        });
    }

    /**
     * @param OptionsResolver $resolver
     */
    public function configureOptions(OptionsResolver $resolver) {
        $resolver->setDefaults(array(
            'data_class' => Ingreso::class,
            'attr' => array('autocomplete' => 'off'),
        ));
    }

El código anterior se puede refactorizar al máximo, pero lo que deseo es entender el trabajo con los enventos PRE_SET_DATA y PRE_SUBMIT.

A: Para hacer un poco más sencilla la solución, separé en dos formularios la apertura y el cierre de un ingreso. Los tres select dependientes solamente aparecen en el formulario de apertura de ingreso, denominado IngresoType.
class IngresoType extends AbstractType {

    private $em;
    private $uuidEncoder;

    public function __construct(EntityManagerInterface $em, UuidEncoder $uuidEncoder) {
        $this->em = $em;
        $this->uuidEncoder = $uuidEncoder;
    }

    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options) {

        $builder->add('unidadDeIngreso', EstructuraOrganizativaIdPublicoType::class);

        $builder->add('embarazada', EntityIdPublicoType::class, array(
            'data_class' => Embarazada::class,
            'empty_data' => null
        ));

        $builder->add('fechaIngreso', DateType::class, array(
            'widget' => 'single_text',
            'input' => 'datetime',
            'format' => 'dd/MM/yyyy',
            'html5' => false,
            'compound' => false,
            'label' => 'Fecha de Ingreso',
            'attr' => array('class' => 'js-datepicker')
        ));

        $builder->add('nombre_embarazada', TextType::class, array(
            'label' => 'Nombre Embarazada',
            'mapped' => false,
            'attr' => array('readonly' => true)
        ));

        $builder->add('numeroIdentidad', TextType::class, array(
            'mapped' => false,
            'label' => 'Número de Identidad',
            'attr' => array('maxlength' => '11'),
        ));

        $builder->add('motivoDelIngreso', TextareaType::class, array(
            'label' => 'Motivo del Ingreso',
        ));

        $builder->addEventListener(FormEvents::PRE_SET_DATA, array($this, 'onPreSetData'));
        $builder->addEventListener(FormEvents::PRE_SUBMIT, array($this, 'onPreSubmit'));

        $builder->addEventListener(FormEvents::PRE_SET_DATA, array($this, 'onPreSetDataCubiculo'));
        $builder->addEventListener(FormEvents::PRE_SUBMIT, array($this, 'onPreSubmitCubiculo'));
    }

    protected function addElements(FormInterface $form, SalaDeIngresos $salaDeIngresos = null, EstructuraOrganizativa $unidadDeIngresos = null) {
        $salas = (null === $unidadDeIngresos) ? array() : $this->em->getRepository(EstructuraOrganizativa::class)->obtenerSalasDisponiblesParaIngreso($unidadDeIngresos);
        $form->add('salaDeIngreso', EntityType::class, array(
            'label' => 'Sala de Ingreso:',
            'class' => SalaDeIngresos::class,
            'choice_label' => 'nombre',
            'choice_value' => 'id',
            'empty_data' => null,
            'choices' => $salas,
            'placeholder' => '-- Seleccione --'
        ));

        $cubiculos = (null === $salaDeIngresos) ? array() : $this->em->getRepository(Cubiculo::class)->obtenerDisponiblesParaIngreso($salaDeIngresos);
        $form->add('cubiculoDeIngreso', EntityType::class, array(
            'label' => 'Cubículo:',
            'class' => Cubiculo::class,
            'choice_label' => 'nombre',
            'choice_value' => 'id',
            'empty_data' => null,
            'choices' => $cubiculos,
            'placeholder' => '-- Seleccione --'
        ));
    }

    function onPreSubmit(FormEvent $event) {
        $form = $event->getForm();
        $data = $event->getData();
        $unidadDeIngresos = $this->em->getRepository(EstructuraOrganizativa::class)->findOneJoinTipoEstructuraOrganizativa($this->uuidEncoder->decode($data['unidadDeIngreso']));
        $salaDeIngresos = $this->em->getRepository(SalaDeIngresos::class)->find($data['salaDeIngreso']);
        $this->addElements($form, $salaDeIngresos, $unidadDeIngresos);
    }

    function onPreSetData(FormEvent $event) {
        $ingreso = $event->getData();
        $form = $event->getForm();
        $unidadDeIngresos = $ingreso->getUnidadDeIngreso();
        $this->addElements($form, $ingreso->getSalaDeIngreso(), $unidadDeIngresos);
    }

    protected function addElementsCamas(FormInterface $form, Cubiculo $cubiculoDeIngresos = null) {
        $camas = (null === $cubiculoDeIngresos) ? array() : $this->em->getRepository(Cama::class)->obtenerDisponiblesParaIngreso($cubiculoDeIngresos);
        $form->add('camaDeIngreso', EntityType::class, array(
            'label' => 'Camas disponible:',
            'class' => Cama::class,
            'choice_label' => 'numero',
            'choice_value' => 'id',
            'empty_data' => null,
            'choices' => $camas,
            'placeholder' => '-- Seleccione --'
        ));
    }

    function onPreSubmitCubiculo(FormEvent $event) {
        $form = $event->getForm();
        $data = $event->getData();
        $cubiculoDeIngresos = $this->em->getRepository(Cubiculo::class)->find($data['cubiculoDeIngreso']);
        $this->addElementsCamas($form, $cubiculoDeIngresos);
    }

    function onPreSetDataCubiculo(FormEvent $event) {
        $ingreso = $event->getData();
        $form = $event->getForm();
        $this->addElementsCamas($form, $ingreso->getCubiculoDeIngreso());
    }

    /**
     * @param OptionsResolver $resolver
     */
    public function configureOptions(OptionsResolver $resolver) {
        $resolver->setDefaults(array(
            'data_class' => Ingreso::class,
            'attr' => array('autocomplete' => 'off'),
        ));
    }

En la definición del formulario empleé dos eventos PRE_SET_DATA y 2 eventos PRE_SUBMIT, que se encargarán de "popular" el widget "salaDeIngreso" y a la vez "crear en cadena" los widget dependientes cubiculoDeingreso y camaDeIngreso.
Por úlitmo en la vista del formulario el código javascript que manejará los eventos changede los widgets salaDeIngreso y cubiculoDeIngreso.


text:
Q: How to open the camera app on ios react native Tell me how to open the camera app on react-native ios. The below code is not working
Linking.openURL("camera://")

A: You can open the camera in expo using expo image picker library
here's the documentation for u.
https://docs.expo.dev/versions/latest/sdk/imagepicker/#ios
Image picker library is also used in cli but with different imports and package installation command is different. Here's the link for u. https://www.npmjs.com/package/react-native-image-picker


text:
Q: How to copy a sub node structure from one XML file to another XML file (merge two XML files) using Omni XML as DOMVendor I asked how to copy a sub node structure from one XML file to another XML file (merge the two XML files) in this question:
How to copy a sub node structure from one XML file to another XML file (merge two XML files)?
The useful and detailed answers from Remy Lebeau and Olivier work fine when I do not set the DOMVendor.
However, when I set the DOMVendor to 'Omni XML', I get an EXMLException error when the cloned node is added to the ChildNodes list:

NewChild was created from a different document than the one that created this node.

The exception is raised in unit Xml.Internal.OmniXML in
function OmniTXMLNode.appendChild(const NewChild: OmniIXMLNode): OmniIXMLNode;
var
  Node: OmniIXMLNode;
  SPrefix: string;
  URIIDCh, URIIDPa: TDicId;
begin
  // NewChild should be created from the same document than the one that created this node
  if (Self.OwnerDocument <> nil) and (NewChild.OwnerDocument <> nil) and (NewChild.OwnerDocument <> Self.OwnerDocument) then
    raise EXMLException.CreateParseError(WRONG_DOCUMENT_ERR, MSG_E_WRONG_DOCUMENT, []);

Target platform is 64-bit Windows. I would like to use 'Omni XML' because it seems to be much faster than 'MSXML'.
How to solve this problem?


text:
Q: How to redirect mobile users to mobile style and Back to the original style on PHP i used this code on http://mobiledetect.net, to redirect users to mobile style
// Include and instantiate the class.
require_once 'Mobile_Detect.php';
$detect = new Mobile_Detect;

// Any mobile device (phones or tablets).
if ( $detect->isMobile() ) {

}

// Any tablet device.
if( $detect->isTablet() ){

}

// Exclude tablets.
if( $detect->isMobile() && !$detect->isTablet() ){

}

// Check for a specific platform with the help of the magic methods:
if( $detect->isiOS() ){

}

if( $detect->isAndroidOS() ){

}

But , i want to put a link or Button on mobile style to return users to the original Style , without turning them Automatically again to Mobile Style , how i do that ?

A: You could pass a variable from the link, like ?mob=false and then check for it at the top while you're doing the mobile check.
$mob = true;
if(isset($_GET['mob'])){
    $mob = $_GET['mob'];
}
if ( $detect->isMobile() && mob !== false ) {
   //mobile stuff
}


text:
Q: Questrade.emit error I am trying to use a package for Questrade which is a financial company. When I run my app.js file I get the error:
Error: Unhandled "error" event. ([object Object])
    at Questrade.emit (events.js:185:19)

Now I get the error is not handled but looking at the docs I can not find out where or how I should include error handling. I used just the code from the section below the install to see if I could get it to work and nope not working at all. I have tried adding it on and can't figure out the right place or how. I'm a bit lost after a few hours of pounding my head.
 // Wait to login
qt.on('ready', error, () => {
    if (error) {
        return console.log(error);
    }
  // Access your account here
  qt.getAccounts();
  qt.getBalances();
});

A: It's simple, you have to add the error event to your file.
qt.on('error', function(err){
   console.log(err);
})

Also, while getting items, you can also have a callback function.
qt.on('ready',  () => {
    if (error) {
        return console.log(error);
    }
  // Access your account here
  qt.getAccounts(function(err, accounts){
     //handler
  });
  qt.getBalances(function(err, balances){
     //handler
  });
});