text:
Q: Ruby on Rails - Extend Engine's Variables and Methods to Entire Application I'm using Ruby on Rails for my application, I'm using Thredded for the community aspect and Devise for the authentication aspect.
Although I believe this issue isn't specific to any of the actual Gems and more a general Ruby on Rails question.
To mount the Thredded Gem, I put this code in my route.rb file:
mount Thredded::Engine => '/community/'

This makes the Thredded gem work perfectly from /community/.
I want to use the Thredded navigation across the entire site.
I was able to link to the Thredded paths by using <%= link_to thredded.private_topics_path %> however I also need to access actions defined in the Thredded controllers.
For instance, in part of the nav there is this bit of code:
<%= link_to private_topics_path, rel: 'nofollow' do %>
    <%= inline_svg 'thredded/private-messages.svg',
                   class: 'thredded--icon',
                   title: safe_join([t('thredded.nav.private_topics'),
                                     (unread_private_topics_count if unread_private_topics_count > 0)].compact, ' ') %>
    <%= t('thredded.nav.private_topics') %>
    <% if unread_private_topics_count > 0 -%>
      <%= unread_private_topics_count %>
    <% end -%>
  <% end -%>

So I need to be able to use unread_private_topics_count throughout the application, however currently, I can only use it within the /community/ scope.
Here's where unread_price_topics_count is defined in the Thredded application controller:
def unread_private_topics_count
  @unread_private_topics_count ||=
    if signed_in?
      Thredded::PrivateTopic
        .for_user(thredded_current_user)
        .unread(thredded_current_user)
        .count
    else
      0
    end
end

Is there any way to access this outside of the /community/ scope?
Here is the Thredded Gem: https://github.com/thredded/thredded
Here is the Thredded navigation:

  <ul class="thredded--user-navigation<%= ' thredded--user-navigation-standalone' if Thredded.standalone_layout? %>">
    <% if signed_in? && Thredded.standalone_layout? %>

        <%= link_to thredded_current_user, user_path(thredded_current_user) %>

    <% end %>

    <%= render 'thredded/shared/nav/notification_preferences', messageboard: messageboard_or_nil %>
    <%= render 'thredded/shared/nav/private_topics' %>

    <% if Thredded.standalone_layout? %>
      <%= render 'thredded/shared/nav/standalone' %>
    <% end %>

    <%= yield :thredded_breadcrumbs %>
    <%= render 'thredded/search/form', messageboard: messageboard_or_nil %>

Here are the shared files the nav is rendering: https://github.com/thredded/thredded/tree/master/app/views/thredded/shared
Here is the Thredded Initializer file:
# frozen_string_literal: true
# Thredded configuration

# ==> User Configuration
# The name of the class your app uses for your users.
# By default the engine will use 'User' but if you have another name
# for your user class - change it here.
Thredded.user_class = 'User'

# User name column, used in @mention syntax and should be unique.
# This is the column used to search for users' names if/when someone is @ mentioned.
Thredded.user_name_column = :name

# The path (or URL) you will use to link to your users' profiles.
# When linking to a user, Thredded will use this lambda to spit out
# the path or url to your user. This lambda is evaluated in the view context.
Thredded.user_path = lambda do |user|
  user_path = :"#{Thredded.user_class.name.underscore}_path"
  main_app.respond_to?(user_path) ? main_app.send(user_path, user) : "#{user.to_param}"
end

# This method is used by Thredded controllers and views to fetch the currently signed-in user
Thredded.current_user_method = :"current_#{Thredded.user_class.name.underscore}"

# User avatar URL. rb-gravatar gem is used by default:
Thredded.avatar_url = ->(user) { user.profile_picture.url }

# ==> Permissions Configuration
# By default, thredded uses a simple permission model, where all the users can post to all message boards,
# and admins and moderators are determined by a flag on the users table.

# The name of the moderator flag column on the users table.
Thredded.moderator_column = :admin
# The name of the admin flag column on the users table.
Thredded.admin_column = :admin

# This model can be customized further by overriding a handful of methods on the User model.
# For more information, see app/models/thredded/user_extender.rb.

# ==> Email Configuration
# Email "From:" field will use the following
# Thredded.email_from = 'no-reply@example.com'

# Incoming email will be directed to this host
# Thredded.email_incoming_host = 'example.com'

# Emails going out will prefix the "Subject:" with the following string
# Thredded.email_outgoing_prefix = '[My Forum] '

# Reply to field for email notifications
# Thredded.email_reply_to = -> postable { "#{postable.hash_id}@#{Thredded.email_incoming_host}" }

# ==> View Configuration
# Set the layout for rendering the thredded views.
Thredded.layout = 'thredded/application'

# ==> Error Handling
# By default Thredded just renders a flash alert on errors such as Topic not found, or Login required.
# Below is an example of overriding the default behavior on LoginRequired:
#
# Rails.application.config.to_prepare do
#   Thredded::ApplicationController.module_eval do
#     rescue_from Thredded::Errors::LoginRequired do |exception|
#       @message = exception.message
#       render template: 'sessions/new', status: :forbidden
#     end
#   end
# end

Thredded Routes:
Routes for Thredded::Engine:
                  theme_preview GET    /theme-preview(.:format)                             thredded/theme_previews#show
              new_private_topic GET    /private-topics/new(.:format)                        thredded/private_topics#new
                  private_topic GET    /private-topics/:id(/page-:page)(.:format)           thredded/private_topics#show {:page=>/[1-9]\d*/}
    private_topic_private_posts POST   /private-topics/:private_topic_id(.:format)          thredded/posts#create
 new_private_topic_private_post GET    /private-topics/:private_topic_id/new(.:format)      thredded/posts#new
edit_private_topic_private_post GET    /private-topics/:private_topic_id/:id/edit(.:format) thredded/posts#edit
     private_topic_private_post PATCH  /private-topics/:private_topic_id/:id(.:format)      thredded/posts#update
                                PUT    /private-topics/:private_topic_id/:id(.:format)      thredded/posts#update
                                DELETE /private-topics/:private_topic_id/:id(.:format)      thredded/posts#destroy
                 private_topics GET    /private-topics(.:format)                            thredded/private_topics#index
                                POST   /private-topics(.:format)                            thredded/private_topics#create
             edit_private_topic GET    /private-topics/:id/edit(.:format)                   thredded/private_topics#edit
                                PATCH  /private-topics/:id(.:format)                        thredded/private_topics#update
                                PUT    /private-topics/:id(.:format)                        thredded/private_topics#update
                                DELETE /private-topics/:id(.:format)                        thredded/private_topics#destroy
             autocomplete_users GET    /autocomplete-users(.:format)                        thredded/autocomplete_users#index
           messageboards_search GET    /                                                    thredded/topics#search
            messageboard_search GET    /:messageboard_id(.:format)                          thredded/topics#search
               edit_preferences GET    /preferences/edit(.:format)                          thredded/preferences#edit
                    preferences PATCH  /preferences(.:format)                               thredded/preferences#update
                                PUT    /preferences(.:format)                               thredded/preferences#update
               new_messageboard GET    /messageboards/new(.:format)                         thredded/messageboards#new
  edit_messageboard_preferences GET    /:messageboard_id/preferences/edit(.:format)         thredded/preferences#edit
       messageboard_preferences PATCH  /:messageboard_id/preferences(.:format)              thredded/preferences#update
                                PUT    /:messageboard_id/preferences(.:format)              thredded/preferences#update
         new_messageboard_topic GET    /:messageboard_id/topics/new(.:format)               thredded/topics#new
            messageboard_topics GET    /:messageboard_id(/page-:page)(.:format)             thredded/topics#index {:page=>/[1-9]\d*/}
 categories_messageboard_topics GET    /:messageboard_id/category/:category_id(.:format)    thredded/topics#category
             messageboard_topic GET    /:messageboard_id/:id(/page-:page)(.:format)         thredded/topics#show {:page=>/[1-9]\d*/}
       messageboard_topic_posts POST   /:messageboard_id/:topic_id(.:format)                thredded/posts#create
    new_messageboard_topic_post GET    /:messageboard_id/:topic_id/new(.:format)            thredded/posts#new
   edit_messageboard_topic_post GET    /:messageboard_id/:topic_id/:id/edit(.:format)       thredded/posts#edit
        messageboard_topic_post PATCH  /:messageboard_id/:topic_id/:id(.:format)            thredded/posts#update
                                PUT    /:messageboard_id/:topic_id/:id(.:format)            thredded/posts#update
                                DELETE /:messageboard_id/:topic_id/:id(.:format)            thredded/posts#destroy
                                POST   /:messageboard_id(.:format)                          thredded/topics#create
        edit_messageboard_topic GET    /:messageboard_id/:id/edit(.:format)                 thredded/topics#edit
                                PATCH  /:messageboard_id/:id(.:format)                      thredded/topics#update
                                PUT    /:messageboard_id/:id(.:format)                      thredded/topics#update
                                DELETE /:messageboard_id/:id(.:format)                      thredded/topics#destroy
                  messageboards GET    /                                                    thredded/messageboards#index
                                POST   /                                                    thredded/messageboards#create
                           root GET    /                                                    thredded/messageboards#index

A: To access a Thredded controller's view context, render a partial via Thredded::ApplicationController.renderer.
See Thredded Wiki: Render Thredded partials outside of Thredded.


text:
Q: Running newusers util in cron to batch create users does not run I'm attempting to batch create some users from a file using the newusers util on ubuntu 18.
When running in cron as the root user, nothing happens. When I run the command manually, it works as expected and creates the users in the file. Heres my crontab, running every minute to test:
*/1 * * * * newusers /tmp/ftp_users.txt

Running it manually like this is fine newusers /tmp/ftp_users.txt.
I have no idea what I'm missing to get this command to run in cron.

A: You have to use the full path in cronjobs. So find out the full path to news users (/bin/newusers/) or whatever it is, and place that in your cronjob. You can find the full path by typing
which newusers

A: Check the mail cron sends to root containing the console output of your command.
This will tell you what went wrong.

redpajama_set_name: RedPajamaStackExchange


text:
Q: ASP.NET MVC - separating large app I've been puzzled by what I consider a contradiction in terms: ASP.NET MVC claims to be furthering and supporting the "separation of concern" motto, which I find a great idea.
However, it seems there's no way of separating out controllers, model or views into their own assembly, or separating areas into assemblies.
With the fixed Controller, Model and View folders in your ASP.NET MVC, you're actually creating a huge hodge podge of things. Is that the separation of concerns, really?? Seems like quite the contrary to me.
So what I'm wondering:

*

*how can I create an ASP.NET MVC solution that will either separate out controllers, the model, and the folders full of views, into separate assemblies?

*how can I put areas of ASP.NET MVC 2 into separate assemblies?

*or how else do you manage a large ASP.NET MVC app - which has several dozen or even over a hundred controllers, lots of model and viewmodel classes, and several hundred views?

A: I think you're looking for Areas in ASP.Net MVC 2. There are some things to uncomment in the CSProj files, but after that it will copy the views over when you build. I don't think there is any requirement that the Controller or Model classes be in the same assembly as the views.
Walkthrough: Creating an ASP.NET MVC Areas Application Using Multiple Projects

A: Controllers: AFAIK you shouldn't have to do anything special to throw controllers into their own assembly.  At the very most all you'd have to do is override the GetControllerType method of your ControllerFactory.
Models: Zero restrictions on where you put your models. Although this is frowned upon I regularly use persistent objects from an Nhibernate/other ORM layer or WCF/service layer DTO thats are located in a separate assembly as my views.  This works the same way using WebForms.
Views: Views in a separate assembly must be marked as embedded resource and then you must use a custom VirtualPathProvider that knows how to get the views from an resource instead of the file system.  views from an resource instead of the file system. Again this is the exact same technique you would use for WebForm development.
Regarding mcintyre321 and his Portable Areas answer:  The linked project does barely anything custom and simply wraps up the existing MVC 2 extensibility points into an easier to use abstraction.  Its barely "custom" and more syntactic sugar.
You manage a large MVC app just like you'd manage any other large app.  I dread opening up a 500 page WebForms project because you never quite know whats in each of those code behinds.  With MVC distinct functionality is mostly within its right place.  Its not contrary at all.

A: Separating code into separate assemblies is orthogonal to separation of concerns. Where the code lives is not a "concern". Separation of concerns has to do with responsibilities and direction of dependencies of various components. For example, Views are responsible for rendering the output, and the controller knows about the views, but the views don't really have intimate knowledge of the controller.
Likewile, Models don't know anything about either views or controllers, but both views and controllers will know about the model.
However, back to your question. As jfar points out, moving controllers and models into another assembly is trivially easy and will work. Moving views into another assembly is trickier. Embedded resources with a custom virtual path provider is one way, but not one we generally recommend for a high performance site. But if it meets your needs, go for it.

A: MVC is very extensible and does not require to adhere to the Controller, View, and Model folder structure. You can place the controllers anywhere you would like, however if they are located in another assembly you will need to implement your own controller factory that knows how to locate them. Here is an example for locating your controllers with Windsor.
Your models/view models can be where ever you want. You simply need to reference their namespace in the web.config so views know where to look. (At least I  know this is true with the Spark view engine.)
You put your views in any web project. My usual strategy is to create a plain web (non-mvc) project that contains the views folder. (This could even be a legacy web app!) Then all my controllers go in a separate class library. My view models and services go in another.
As far as structuring folders, I usually center my hierarchy around domain concepts. I'd have a folder in each project for Users, Products, Orders, etc. I never have a Models or Controllers folder anywhere.

A: You need to use portable areas see http://www.lostechies.com/blogs/hex/archive/2009/11/02/asp-net-mvc-portable-areas-part-2.aspx


text:
Q: Implementation of a pure virtual function in C++ Given the following scenario, I have a base class MyBaseClass with a pure virtual function void foo() = 0; . Two classes MyClassA and MyClassB are derived from that class MyBaseClass. Both implement the function foo().
Now in a project I work on, I came across an object created from class MyBaseClass on which the function foo() is called.
Interestingly, it's the implementation from MyClassB that is used.
Where is defined that it's this implementation and not the one from MyClassA

A: The object was of type MyClassB not MyBaseClass.  MyBaseClass is abstract and cannot be instantiated.  However you probably had a pointer MyBaseClass* which was pointing to an instance of MyClassB.
You should probably read up on inheritance and polymorphism in C++ if you need some more information.
MyBaseClass base; // Compiler error, cannot instantiate abstract class
MyClassA a;
MyClassB b;

MyBaseClass* pA = &a;
MyBaseClass* pB = &b;

pA->foo(); // Uses implementation of foo in MyClassA
pB->foo(); // Uses implementation of foo in MyClassB

A:
I came across an object created from class MyBaseClass

No, you did not. Objects of type MyBaseClass can't exist. The class is abstract and cannot be instantiated.
You likely came about a pointer to a MyBaseClass, which can point to any objects of classes that inherit the base class.

Is there a way of calling the implementation of MyClassA although pA is pointing to an object of class MyClassB? Maybe with a cast?

You can call
pA->MyBaseClass::foo();

but this will only work if the function is implemented. (yes, you can provide an implementation for pure method)

A: It is important to notice the difference between these snippets:
struct X
{
    virtual void foo() = 0;
};

X x; // not valid! X has purely virtual methods

and
struct X; // as above
struct Y : X
{
    void foo() {}
    void bar() {}
};

X * x = new Y; // valid!

The second case is most likely what you have seen. In this pattern you can call x->foo(); and it will call Y::foo(). Note that you cannot, however, call x->bar() because X::bar() does not exist.


text:
Q: How to UNION ALL multiple SELECT queries in VBA, without typing SQL in VBA? I can successfully create a UNION ALL query using SQL to join multiple (7 total) SELECT queries, which were built in Design View in Access--I simply copy the SQL, create a new query, and put UNION ALL between them. Works just as I expect and quickly.
However, I'm often asked to modify certain aspects of the individual SELECT queries. Only way to recreate the query with UNION ALL is to copy the SELECT statement and paste it again.
Is there a better way to run this using DoCmd.OpenQuery or RunSQL?
I'm looking for a simple way to call a method that might look like qry_Input_1 UNION ALL qry_Input_2 without having to retype/copy/paste the SELECT query every time I make a change. I'm open to either SQL or VBA approaches.

Here is my VBA that I started based on inputs from below (thanks @Ispep Aloc). I'm having trouble with my tempTable as suggested.
Sub UnionQuery()
Dim i As Integer
Dim tempTable As String
tempTable = "tbl_P54_Union"

For i = 1 To 7
    DoCmd.RunSQL "INSERT INTO tempTable SELECT * FROM qry_P54Input_" + CStr(i)
Next i
End Sub

A: I would take a different approach to this.  Assuming your queries are named qry_Input_1, qry_Input_2, etc., I would create a for loop in VBA to populate a table with the _1, _2 be dynamic and then have a query created that simply selects from that table.  Roughly something like this
dim i as integer

for i = 1 to 7
    docmd.runsql "insert into temp table select * from qry_Input_" + CStr(i)
next i


text:
Q: Asynchronous socket callbacks do not work in Mono/Linux I'm exploring porting a .NET C# application from Windows to Linux using Mono. The problem I'm stuck with is that asynchronous TCP socket calls do not work. This means that I can send data with no problems but I'm only seem to be able to receive the very first response from the socket (via Socket.BeginReceive()). The next BeginReceive() puts the thread into a wait state.
In it possible in principle that our socket code contains a bug but as it's been working flawlessly in Windows for years.
Thank you

A: This works fine with the mono-2-10 branch (soon to be released as Mono 2.10) and master.
The Mono 2.6.7 shipped with ubuntu fails and so does Mono 2.8. I've found the problem and I am testing a fix.. The next releases in the 2.6.x series will have the fix (also 2.8.x if there's any, since we are moving to 2.10 in a few days).
Btw, you should report problems in Mono following http://mono-project.com/Bugs instead of here.

A: If you use a synchronous socket, do things work as expected?  That's a quick way to help narrow down the issue.


text:
Q: Ubuntu 16.10 - X.org not starting The main problem: startx does not start fluxbox, server disconnects, but xinit $(which xterm) works.
X.org (and EDID) problem started with installing fresh 16.10. Minimal ubuntu console, Xorg, Fluxbox.

*

*when /etc/default/grub has LINUX_COMMAND_LINE_DEFAULT="splash quiet", then I get the drm:drm_edid_block_valid] ERROR EDID has major version 0, instead of 1. This message splashes in terminal in batches of lines. Before installing xserver-xorg-legacy starting fluxbox with startx was possible despite messages and fluxbox functioned fine. After installing xserver-xorg-legacy it only returns "connection to server lost, disconnecting).

*same when LINUX_COMMAND_LINE_DEFAULT="text"

*when LINUX_COMMAND_LINE_DEFAULT="nomodeset" console works fine, xinit $(which xterm) functions fine, .xinitrc and .Xauthority both owned by user (not root), but startx does not work. Log file points out to KMS not supported and server shuts down afterwards.
Older hardware, worked excellent on 16.04 but X problems on 16.10.
Compaq Presario 2100 (2003), AMD, ATI Radeon RS-100 video card.


text:
Q: Why is animatetoRegion not working when i pass data, Map failing to animate to region when I try to pass data from API, but works when I hard-code the latitude and longitude. I tried to log the data im trying to pass and i can see it correctly, but just does not animate.
const Timeout = setTimeout(() => {
        if (mapIndex !== index) {
          mapIndex = index;
          const longitude = getListingsApi.state[index].longitude;
          console.log(longitude); //This shows the longtitude correctly.
          _map.current.animateToRegion(
            {
              latitude: getListingsApi.state[index].latitude,
              longitude: getListingsApi.state[index].longitude,
              latitudeDelta: region.latitudeDelta,
              longitudeDelta: region.longitudeDelta,
            },
            350
          );
        }
      }, 10);

Please what can I do?

A: The code looks good. The only thing that could be wrong is the _map reference. See if you've implemented the reference correctly. I got my animateToRegion working using this answer: Cannot get ref to MapView - react-native-maps

A: const mapRef =useRef()
do not provide initial params to useRef
function animated(){
 if(mapRef.current){
    mapRef.current.animateToRegion(your coordinate)
  }

}

<MapView ref={mapRef}>
.... any marker
</MapView>```


text:
Q: Powershell -minimum doesn't seem to work Let me preface by noting this is only my third day with powershell, sorry if this is common knowledge.
This is to create a randomly generated password with requirements. I've set the minimums to 2 for each value, but it doesn't always have a minimum of 2 of each when the password is generated. I think it may be because of the Get-Random -count 10 is pulling from the pool that the rest of the string has created. I'm unsure how i would force it to create a password of 10-12 characters with a minimum of each requirement specified. Can/Should i validate the password after it's been created?
$ErrorActionPreference = "silentlycontinue"
function OnApplicationLoad {
    #Note: This function is not called in Projects
    #Note: This function runs before the form is created
    #Note: To get the script directory in the Packager use: Split-Path $hostinvocation.MyCommand.path
    #Note: To get the console output in the Packager (Windows Mode) use: $ConsoleOutput (Type: System.Collections.ArrayList)
    #Important: Form controls cannot be accessed in this func
    else{Stop-Process -name powershell.exe}
    return $true #return true for success or false for failure
}

function OnApplicationExit {
    #Note: This function is not called in Projects
    #Note: This function runs after the form is closed
    $script:ExitCode = 0 #Set the exit code for the Packager
}

#######Static Password Resources######

$caps = [char[]] "ABCDEFGHJKMNPQRSTUVWXY"
$lows = [char[]] "abcdefghjkmnpqrstuvwxy"
$nums = [char[]] "2346789"
$spl = [char[]] "#%$+<=>?"
$ofs = ""

####################Starts code############################
function Call-test_pff {
    $form1 = New-Object 'System.Windows.Forms.Form'
    $form1.ClientSize = '514, 640'
    $form1.Name = "form1"
    $form1.Text = "Password tool"
    $form1.add_Load($form1_Load)

#Add Icon to window
$Icon = [system.drawing.icon]::ExtractAssociatedIcon($PSHOME + "\powershell.exe")
$form1.icon = $Icon

#form1: Button1 "Generate password"
$button1 = New-Object system.windows.forms.button
$button1.location = "10, 25"
$button1.size = "125, 35"
$button1.text = "Generate password"
$button1.add_click({
    $first = Get-Random -Minimum 2
    $second = Get-Random -Minimum 2
    $third = Get-Random -Minimum 2
    $fourth = Get-Random -Minimum 2
    $pwd = [string](@($nums | Get-Random -Count $first) + @($lows | Get-Random -Count $second) + @($caps | Get-Random -Count $third) + @($spl | Get-Random -Count $fourth) | Get-Random -Count 10)
    $textbox1.text = $pwd
})
$form1.controls.add($button1)

#form1: Label4: "Password"
$label4 = New-Object system.windows.forms.label
$label4.location = "10, 475"
$label4.size = "200, 20"
$label4.text = "Password:"
$form1.controls.add($label4)

#form1: password box "Password"
$textbox1 = New-Object system.windows.forms.textbox
$textbox1.location = "10, 500"
$textbox1.size = "200, 30"
$textbox1.multiline = $true
$textbox1.readonly = $true
$form1.controls.add($textbox1)

#####################Stop Code Here#####################

#Save the initial state of the form
$InitialFormWindowState = $form1.WindowState
#Init the OnLoad event to correct the initial state of the form
$form1.add_Load($Form_StateCorrection_Load)
#Clean up the control events
$form1.add_FormClosed($Form_Cleanup_FormClosed)
#Show the Form
return $form1.ShowDialog()

} #End Function

#Call OnApplicationLoad to initialize
if((OnApplicationLoad) -eq $true)
{
    #Call the form
    Call-test_pff | Out-Null
    #Perform cleanup
    OnApplicationExit
}

A: Assuming that your problem is in this code:
$first = Get-Random -Minimum 2
$second = Get-Random -Minimum 2
$third = Get-Random -Minimum 2
$fourth = Get-Random -Minimum 2
$pwd = [string](@($nums | Get-Random -Count $first) + @($lows | Get-Random -Count $second) + @($caps | Get-Random -Count $third) + @($spl | Get-Random -Count $fourth) | Get-Random -Count 10)

You have two related problems:

*

*You're specifying no maximum for get-random, so you are getting very large numbers in most cases. As a result, $nums|get-random -count $first is always going to return the whole array (but in a random order) - you're asking for a random collection of (for example) 1000 selections from a list of fewer than 10.

*Because of the above, Your trailing get-random -count 10 is picking 10 random characters from the entire search space ($caps, $lows,$lows,$spl)

So, you need to do two things:

*

*Get a subset of each of your character types by limiting get-random to both a minimum and maximum.

*Ensure that you get the correct distribution of characters in that final line. This can't be done with the current final line, because in theory you could end up with 10 upper-case characters if the random distribution fell that way

To solve the first, by limiting your counts to just the length of those source arrays:
$caps = [char[]] "ABCDEFGHJKMNPQRSTUVWXY"
$lows = [char[]] "abcdefghjkmnpqrstuvwxy"
$nums = [char[]] "2346789"
$spl = [char[]] "#%$+<=>?"
$ofs = ""
$first = Get-Random -Minimum 2 -Maximum $nums.Length;
$second = Get-Random -Minimum 2 -Maximum $lows.Length;
$third = Get-Random -Minimum 2 -Maximum $caps.Length;
$fourth = Get-Random -Minimum 2 -Maximum $spl.Length;

But this still doesn't solve the second problem, because you will be passing more than 50 characters into that final get-random -count10`, very easily excluding one or more required character types.
If you can deal with a set number of each type of character (in this case, 2 numbers, 3 upper, 3 lower, 2 special), do the following:
$caps = [char[]] "ABCDEFGHJKMNPQRSTUVWXY"
$lows = [char[]] "abcdefghjkmnpqrstuvwxy"
$nums = [char[]] "2346789"
$spl = [char[]] "#%$+<=>?"
$ofs = ""

$first = $nums | Get-Random -count 2;
$second = $caps | Get-Random -count 3;
$third = $lows | Get-Random -count 3;
$fourth = $spl | Get-Random -count 2;

$pwd = [string](@($first) + @($second) + @($third) + @($fourth) | Get-Random -Count 10)
$pwd

This picks random items in the correct quantity from each group, then randomizes the order of those characters.


text:
Q: dynamic dropdown select not entering value to db on submit Im having issues with data not being entered into the db. I have a form with 5 inputs and a select The drop down select is a dynamic list fro the db. When the form is submitted nothing is entered in the db for the campaign_owner columns. I have the values="" which I think is the problem, but I also tried
<option value="<?php echo $user['username']; ?>"><?php echo $user['username']; ?></option>

yet that doesn't help.The dropdown shows the data I want and allows you to select it on the page it just doesn't submit it and I dont know why.
HTML:

  <?php echo $entry_owner; ?>
  <select name="user-list" id="user-list">
    <?php foreach ($users as $user) { ?>
    <option value="<?php echo $user['username']; ?>"><?php echo $user['username']; ?></option>
    <?php } ?>
  </select>

A: HTML forms work with the input/select/textarea etc. names. Your select is named "user-list" which means that when submitted it will be under the key user-list. You'll need to map that to the campaign_owner column.


text:
Q: Material ui Snackbar show only once and doesn't reopen I'm using the Snackbar component from the Material-UI framework but I can't make it work correctly because the Snackbar shows only the first time, from the second message the Snackbar remain closed.
Here is the code I used to wrap the Snackbar:
import Snackbar from "@material-ui/core/Snackbar";
import { useState } from "react";

export default function Notification({ message }) {

    const [value, setValue] = useState(message);

    return (
        <Snackbar
            key={Math.random()}
            anchorOrigin={{
                vertical: 'bottom',
                horizontal: 'center'
            }}
            open={value ? true : false}
            autoHideDuration={5000}
            message={value}
            onClose={() => { console.log('snackbar closed'); setValue('') }}
        />
    )
};

I use this component to show the result when the user submit a form. For example when the submit is succesful the message 'operation completed' is shown, but if the server doesn't validate the submission a message error is shown. Here is the code:
function InnerForm({ mode, detail, entity }) {

  const isCreateMode = mode === 'create';
  const schema = createSchema(entity);

  const {
    handleSubmit,
    formState: { errors },
    control,
    setValue
  } = useForm({
    defaultValues: detail,
    resolver: yupResolver(schema)
  });

  const [submitResponse, setSubmitResponse] = useState();

  const onSubmit = async data => {

    const operation = isCreateMode ?
      entity.Client.create(data) :
      entity.Client.update(data);

    const response = await operation;

    setSubmitResponse(response);
    console.log(response);

    if (response.success) {

      if (isCreateMode) {
        const autoField = entity.Fields.find(({ auto }) => auto);

        if (autoField) {
          setValue(autoField.id, response.content[autoField.id]);
        }
      }
    }
  };

  return (
    <>
      {
        submitResponse ?
          submitResponse.success ?
            <Notification message='operation completed' /> :
            submitResponse.problem ?
              <Notification message={submitResponse.problem} /> :
              <Notification message='operation failed' />
          : null
      }
      <form onSubmit={handleSubmit(onSubmit)}>
        {
          entity.Fields.map(field => {
            const props = {
              control,
              id: field.id,
              label: field.label,
              error: errors[field.id]?.message,
              multiline: field.type === 'text',
              loadOptions: field.loadOptions,
              getOptionLabel: field.getOptionLabel,
              readonly: submitResponse?.success || field.auto || (field.key && !isCreateMode)
            };

            const Component =
              field.type === 'string' ? TextInput :
                field.type === 'datetime' ? DatetimeInput :
                  field.type === 'text' ? TextInput :
                    field.type === 'entity' ? SelectInput :
                      field.type === 'bool' ? CheckboxInput :
                        TextInput;

            return <Component {...props} />
          })
        }

        <SubmitButton isCreateMode={mode === 'create'} readonly={submitResponse?.success} />
      </form>
    </>

The test I do is the following:

*

*First, I compile the form with invalid data and execute the submit => Ok, the snackbar appear with an error message.

*Second, I correct the data and execute a new submit => The submit is succesful, but the success message is not shown

A: It does not look like you're updating state once it receives new props, only initializing the state the first time it's created.
You could try to update state when it's called a second time.
You could also keep the open state inside the InnerForm component, and add  a callback function as a parameter to Notification that would be called in onClose that would update the state of the Snackbar inside InnerForm
Example of the second suggestion:
In InnerForm
const [isOpen, setIsOpen] = useState(false);
const [message, setMessage] = useState(message);

const callback = () => {
    setValue(false)
}

// In render() you need to add this line.
<Notification message={message} isOpen={isOpen} onClose={callback}/>

In Notification
export default function Notification({ message, isOpen, onClose }) {

return (
    <Snackbar
        key={Math.random()}
        anchorOrigin={{
            vertical: 'bottom',
            horizontal: 'center'
        }}
        open={isOpen}
        autoHideDuration={5000}
        message={message}
        onClose={onClose}
    />
)
};

Finally, you just have to update message and isOpen in InnerForm where you currently call the Notification function


text:
Q: JScrollPane: How to move the scroll bar to the left and have the viewport align on the right If I put the JScrollPane scroll bar on the left side, the left part of the viewport is placed under the scrollbar.
jScrollPane.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);

How to align the viewport to the right of the scrollbar?

A: Found the answer here : http://forums.codeguru.com/
Thanks to Rafke.
It works fine.
jScrollPane.setLayout(new ScrollPaneLayout() {
    @Override
    public void layoutContainer(Container parent) {
        JScrollPane scrollPane = (JScrollPane) parent;
        scrollPane.setComponentOrientation(
            ComponentOrientation.RIGHT_TO_LEFT);
            super.layoutContainer(parent);
            scrollPane.setComponentOrientation(
                ComponentOrientation.LEFT_TO_RIGHT);
    }
});


text:
Q: Should I put the datatype of a class attribute in its name? Most of my system's class attributes are just text, but in this case it makes more sense to place this particular class's attributes into one single hash (from a "keep the source code pretty" aspect). Basically, a list of attributes is returned, and instead of writing a bunch of static attributes for each one, I just loop over them and collect them into a hash.
Is it a good idea to name this particular attribute @contents_hash, as opposed to @contents? I assume that users may figure out pretty quickly that @contents.split ' ' will return a NoMethodError: undefined method 'split' for Hash, but on first glance of the code, is it useful to know right away that this is a hash? Do you think it will make the implementation redundant to say @contents_hash.keys?

A: I would only put the datatype in an identifier if it clearly adds value and clarity.
Nowadays, intellisense (or "on-the-fly code analysis," as Jetbrains calls it) and type inference has pretty much eliminated the need for identifying types in your variable names.  Write clear code in the first place, so that you don't need to identify the type.

A: Ruby (and other dynamic-typed languages) don't generally put the type in the name of variable, largely because that type could potentially change. That type of naming convention is generally seen more in statically-typed languages (namely, Visual Basic), because it's a safer environment in which to do that (the variables can't change types as easily), but it's falling out of favor even there.
What happens if somewhere you have content = 'some string'? Well, now, had you used content_hash, the variable would be lying about its type. This makes things confusing.
Instead, think about naming things in a way that makes it more clear that the type is likely to be a hash. "contents" is pretty generic, and could mean either a string or a hash, but maybe "settings" or "attributes" would be a better choice, because "settings"/"attributes" has a connotation of being a collection of key-value pairs (a hash), or at least an array of values, without actually being tied to the exact type.
See also:

*

*Ruby style guide

*Duck Typing (technically applies to inheritance, but the idea applies here - if it looks and acts like a hash, then it's probably a hash)


text:
Q: Which command should I use to open an MP3 file? Which command should I use to open an MP3 file? For example, "abcd.mp3"
hamza@ubuntu:/media/hamza/Elements/mmc$ cd abcd.mp3
bash: cd: abcd.mp3: Not a directory

A: cd means "change directory". A file is not a directory so a cd will not work on your mp3. To open a `.mp3 you need to start a music or video player. The method @heemayl uses will open the player you have set as the default.
If you want you can also use aplay. The command
aplay abcd.mp3

will play the mp3 from command line and stop when it is done playing. "aplay" is probably the lightest music player around since it does not have a GUI (and can also work on a server >:-D )

A: If you want to use the App set as preferred, from the directory containing the MP3 file, use xdg-open:
xdg-open abcd.mp3

From man xdg-open:
xdg-open - opens a file or URL in the user's preferred application

If you know the application you want the MP3 file to be opened with, for example, rhythmbox:
rhythmbox abcd.mp3

or VLC media player:
vlc abcd.mp3

A: If you want to run an MP3  file with a particular application, then run it like:
 application_name audio_file_name

For example, if you want to run in the MPlayer application then install it using:
 sudo apt-get install mplayer

Then run the audio file using the command:
 mplayer  abcd.mp3

or
 sudo apt-get install mpg123
 mpg123 abcd.mp3

or
 sudo apt-get install sox
 play abcd.mp3

or
sudo apt-get install vlc
vlc abcd.mp3


text:
Q: C# Sharepoint Get current user under whitch code running I have code from tutorial, code running on WCF service under DOMAIN\AppPoolAccount
But code except that Access Denied, how determinate user?
using (SPSite site = new SPSite("http://portal.local"))
            {
                SPServiceContext serviceContext = SPServiceContext.GetContext(site);

                UserProfileManager userProfileMgr = new UserProfileManager(serviceContext);
                ProfilePropertyManager profilePropMgr = new UserProfileConfigManager(serviceContext).ProfilePropertyManager;

                // Retrieve all properties for the "UserProfile" profile subtype,
                // and retrieve the property values for a specific user.
                ProfileSubtypePropertyManager subtypePropMgr = profilePropMgr.GetProfileSubtypeProperties("UserProfile");
                UserProfile userProfile = userProfileMgr.GetUserProfile(accountName);
                IEnumerator<ProfileSubtypeProperty> userProfileSubtypeProperties = subtypePropMgr.GetEnumerator();
                while (userProfileSubtypeProperties.MoveNext())
                {
                    string propName = userProfileSubtypeProperties.Current.Name;
                    ProfileValueCollectionBase values = userProfile.GetProfileValueCollection(propName);
                    if (values.Count > 0)
                    {

                        // Handle multivalue properties.
                        foreach (var value in values)
                        {
                            Console.WriteLine(propName + ": " + value.ToString());
                        }
                    }
                    else
                    {
                        Console.WriteLine(propName + ": ");
                    }
                }
                Console.WriteLine("Press Enter to change the values.");
                Console.Read();

                // Change the value of a single-value user property.
                userProfile[PropertyConstants.Department].Value = "SDDDD";
                userProfile.Commit();

            }

How determinate user?

A: Use SPWeb.CurrentUser property to determine the current user:
using (var site = new SPSite(siteUrl))
{
    using (var web = site.OpenWeb())
    {
        var currentUser = web.CurrentUser;
        //..

    }
}


text:
Q: nested Sqlite Query not working properly In this code outer sqlite query first finish its work then it goes to inner sqlite query
 Please explain me why it happen and also give the solution of my requirment.
/*Outer Sqlite Query*/
 db.transaction(function(transaction){
 transaction.executeSql('SELECT * FROM OuterTable;', [],
 function(transaction,results){
   if (results != null && results.rows != null) {
     for (var i = 0; i < results.rows.length; i++) {
      /*My work is going here*/

       /*Inner Sqlite Query   Inside lor loop*/
       db.transaction(function(transaction){
   transaction.executeSql('SELECT * FROM MyInnerTable;',[],
   function(transaction, result){
   if (result != null && result.rows != null)  {
         for (var j = 0; j < result.rows.length; j++) {
              /* My Work is Going here */
           }
            }
     },errorHandler);
     } ,errorHandler,nullHandler);
       /*Inner Sqlite End Here*/
                        }
                      }
                   },errorHandler);
                  }
                  ,errorHandler,nullHandler);
           /*Outer Sqlite End Here*/

The Problem is That here
  First---> Outer Sqlite Work is Executing then Inner Sqlite work is executing but my Requirment is as like
 for each value of Outer Sqlite Inner Sqlite will be work
for Example:--
for(int i=0;i<=10;i++){
     for(int j=0;j<=10;j++){
   // here inner for loop will work for every value of outer for loop

   }
 }

Thanks In Advance

A: Your requirement to perform the inner query for every outer query cannot be achieved like this. Since the SELECT queries are async calls.
Even the outer for loop doesn't wait for your the query at previous index to be completed. It will continue execution and simultaneously fire SELECT queries.
However, to achieve that you can use recursion.
Where each outer loop calls the select query, the success callback implements the inner query and the success callback of the inner query recursively calls the inner query for the required number of times with the required index and post the number of times (inner loop for condition) it would call the outer query implementer with an incremented index.
Hope that helps.


text:
Q: Aspose Markup fields too wide I'm using the reporting engine for aspose and everything is working fine.
The issue I have is that my document model has some larger names in it. I didn't build the model and I would rather not create a new one just for reporting, but if that's my only option I will. Thought I'd check here first.
Example:
<<[NatureOfInjury]>><<[NatureOfInjuryOptionA]>>
Hurt   Hit thumb with hammer
The markup for <<[NatureOfInjury]>> is wider on the word document than the value that will end up going in there, and it's making formatting the document difficult.
Is there any way other than changing the object model to make the markup smaller, independent of the actual text values that will go in there?
Thanks very much in advance.

A: Unfortunately, there is no other way to populate template tag with data source field name using LINQ Reporting. You need to use the same name in template document and data source.
I work with Aspose as Developer Evangelist.


text:
Q: Sheet.Activate is not working in Office 2010 - 64 bit I have created a Macro which is working just perfect in my machine (Windows 64 bit & Office 32 bit)
But client is facing issue. He is having Windows 64 bit & Office 64 bit.
Don't know why but Sheet.Activate is not working on his machine. Refer below screen prints.

A: Based on your input, I cannot find back a declaration of "Recordsheet".
Since you input this code in the event routine "Workbook_open", I doubt that you did the declaration anywhere.
If you want to apply
RecordSheet.Activate

The least thing you should do is:
Set oRecordSheet = thisworkbook.sheets("Records")
oRecordSheet.activate

I strongly doubt that your version of Office / Windows has anything to do with it.
Vba is not supported by Microsoft anymore and no further developments to the language are made.
If it's a client, take into account the possibility that this client might have changed the name of the sheet.
In case you properly set the sheet object, this may also be the source of the problem.
Edit:
After looking at your file received by mail, I confirm that the above solution fixed the bug.
Replace the entire
UserForm_Initialize

Subroutine with:
Private Sub UserForm_Initialize()

    Dim oRecordSheet As Excel.Worksheet

    Set oRecordSheet = ThisWorkbook.Sheets("Expense Report")
    oRecordSheet.Activate
    EnableDisableConrols (False)
    Call FillDropDowns
    Navigator.Max = RecordSheet.UsedRange.Rows.Count
    If RecordSheet.UsedRange.Rows.Count = 1 Then
        RowNumber = 1
    Else
        RowNumber = 2
        Call FillDataIntoControls
    End If

End Sub

Edit 2:
The above solution is correct, BUT, if indeed the codename of your sheet is set to RecordSheet, you can use this solution too. However, note that the codename can only be used with the workbook.

A: I would think there may be missing references.
go to Tools -> References, and see if any are listed as missing

Remove the checkmarks there, and the basic stuff like date will start working again. If those references are critical to the code you are running, you will have to search out the 64 bit equivalents
More about references - normally resolving "Missing" fixes it, but, from here
What you're describing is typical of corrupted references. This can
be caused by a referenced file being a different version or in a different
location between the machine on which the code was developed, and the
client machines. Our company also tries to keep all the machines configured
the same way, but I've found it's essentially impossible to manage.
Open any code module (or open the Debug Window, using Ctrl-G, provided you
haven't selected the "keep debug window on top" option). Select Tools |
References from the menu bar. Examine all of the selected references.
If any of the selected references have "MISSING:" in front of them, unselect
them, and back out of the dialog. If you really need the reference(s) you
just unselected (you can tell by doing a Compile All Modules), go back in
and reselect them.
If none have "MISSING:", select an additional reference at random, back out
of the dialog, then go back in and unselect the reference you just added. If
that doesn't solve the problem, try to unselect as many of the selected
references as you can (Office may not let you unselect them all), back out
of the dialog, then go back in and reselect the references you just
unselected. (NOTE: write down what the references are before you delete
them, because they'll be in a different order when you go back in)
(as a side note, disambigulating as VBA.xxxx will work, since Excel no longer has to
look through all of the references.)

A: The first line of your code shows a UserForm. Some widely-used form controls (those defined in the ComCtl library) don't exist in the 64-bit version of Office so it's highly likely that the UserForm is the problem.
There's no easy solution unless you can convince the client to use 32-bit Office instead or alter your UserForm so as not to use the affected controls.
Affected controls are: ImageCombo, ImageList, ListView, ProgressBar, Slider, StatusBar, TabStrip (although there is an alternative version of TabStrip in the normal MSForms library), Toolbar, Treeview
Details of the problem are discussed in this thread and confirmed here


text:
Q: The number of ways of having 3 aces of hearts among 5 ordered cards My combinatorial reasoning will appreciate some help with this:
From a deck of $52$ cards John $5$ times does the following:

*

*Picks one card from the deck.

*He writes on a sheet of paper
    which card was drawn. He does so by ordering them. (That is, if the
    he picked 10 of heart, $5$ of spades, $3$ of clubs, ... in that order,
    then he writes $1º\  10$ of heart, $2º\ 5$ of spades and so on).

*He put
    back the drawn card.
Question: In how many different way can 3 aces of hearts appear written on the paper?
My attempt:
Suppose John already wrote the numbers $1º,\ 2º,\ 3º,\ 4º$ and $5º$ on the paper. Then
1) There are  ${52 \choose 1}$ ways of picking one card from $52$.
2) John does that $5$ times.
3) Now place the 5 cards in some arbitrary order, say $AAANN$ (where $A$ denotes the aces of hearts and $N$ the no aces of hearts). Let ''put'' the places on them. This can be done in $5!$ (since, say, the 3rd place can only go to one card). Moreover, because the order among the $A$'s themselves doesn't matter and the same for the $N$'s we have $\frac{5!}{3!2!}$.
Then by the product rule we have
$$5{52 \choose 1} \frac{5!}{3!2!} = 2600\ \text{different ways.}$$
But the correct answer is $26010$ ]:. I'm way off it. I'v been thinking for a while but I don't know what combinations I haven't taken into account.

A: If you want exactly three aces of hearts, there are ${5 \choose 3}=10$ ways to choose where the aces appear.  Each of the other cards has $51$ choices, so the total is $10 \cdot 51^2=26010$

A: $5\binom{52}{1}$ is not the count of picking any card five times.  $\binom{52}1^5$ is.
However, John does not do that.
He picks 3 ace-of-hearts and two other cards.  That's $\binom{51}2$ ways to pick 2 different cards, and $\binom{51}1$ ways to pick the same card twice.
Then arrange them.  $\binom{51}2\binom{5}{3,1,1}+\binom{51}{1}\binom{5}{3}=26010$

PS: $\binom{5}{3,1,1}=\frac{5!}{3!~1!~1!}$ is a multinomial coefficient.


text:
Q: Google spreadsheet =IMPORTXML result is blank I am trying to import the buy price on https://www.zebpay.com/#chart site
I tried following different cell formulas but result is blank:
=IMPORTXML("https://www.zebpay.com/#chart",".//*[@id='buy']")
=IMPORTXML("https://www.zebpay.com/#chart","//a/span[2]")
=IMPORTXML("https://www.zebpay.com/#chart","//span[@id='buy']")
=IMPORTXML("https://www.zebpay.com/#chart","//div[@id='bitlabel']/a/span[2]")

I also tried above things removing #chart.
Can someone help with solution?
Also is there easy tool to find Xpath with works with sheet, I used selenium IDE in above case.

A: for locateing webElement you can use ranorex chrome extension link to download

A: found Bypass solution:
=IMPORTDATA("https://www.zebapi.com/api/v1/market/ticker/btc/inr")
Zebpay hav provided API: https://www.zebapi.com/api/v1/market/ticker/btc/inr
After getting data then it can be processed further to get exact value for calculation.


text:
Q: Django form not saving to DB I tired using the formset to create a form but the form is not saving. The form is imported from my model and four forms has foreign key to the main form. My terminal looks like this: [12/Jun/2017 22:26:20] "POST /model_form/ HTTP/1.1" 200 25267
My view:
    def careerForm(request):

        if request.method == 'POST':
            form1 = ModelForm(request.POST or None, request.FILES or None)
            formset1 = ModelFormSet(request.POST or None, request.FILES or None)
            formset2 = ModelFormSet(request.POST or None, request.FILES or None)
            formset3 = ModelFormSet(request.POST or None, request.FILES or None)
            formset4 = ModelFormSet(request.POST or None, request.FILES or None)
            if form1.is_valid() and formset1.is_valid() and formset2.is_valid() and formset3.is_valid() and formset4.is_valid():
                message = "Thank you"
                career.vacancy =  get_object_or_404(Vacancy, pk = request.POST.get('vacancy'))

                form1.save()
                formset1.save()
                formset2.save()
                formset3.save()
                formset4.save()

                return HttpResponseRedirect('successful')

            else:
                message = "Something went wrong"

            context = { 'message': message }
            return render(request, 'library/careerForm.html', context)
        else:
            form1 = ModelForm()
            formset1 = ModelFormSet()
            formset2 = ModelFormSet()
            formset3 = ModelFormSet()
            formset4 = ModelFormSet()
        context = { 'form1': form1, 'formset1': formset1, 'formset2': formset2, 'formset3': formset3, 'formset4': formset4 }
return render(request, 'library/careerForm.html', context)

form.py
    class ModelForm(forms.ModelForm):
        class Meta:
            model = Model
            fields = '__all__'
            exclude = ['is_visible']

    ModelFormSet = inlineformset_factory(Model, Model_formset, fields = '__all__', exclude = ['is_visible'])
    ModelFormSet = inlineformset_factory(Model, Model_formset, fields = '__all__', exclude = ['is_visible'])
    ModelFormSet = inlineformset_factory(Model, Model_formset, fields = '__all__', exclude = ['is_visible'])
    ModelFormSet = inlineformset_factory(Model, Model_formset, fields = '__all__', exclude = ['is_visible'])

templete
    <form method="POST" action="{% url 'peruse:careerForm' %}" enctype="multipart/form-data">
            {% csrf_token %}
    </form>

output result on my browser
    [output result on my browser][1]


text:
Q: Importar datos de XLS a SQL problema con el tipo de datos Hola soy nuevo en la programación, tengo problemas para importar datos desde excel a SQL, esta vez una de las columnas del archivo xls que tiene contenido alfanumérico, relacionado a modelos de autos puntualmente.
Tras algunas pruebas me di cuenta que SQL toma la primer celda de la columna y acorde al tipo de dato de esa celda asigna al resto de la columna, es decir: si el primer dato de la celda es "500" va a leer todas las celdas como numéricas y va a pasar nulas aquellas celdas que tengan texto y viceversa, si la celda arranca con "a500" pasa nulas las celdas que tengan números.
Explicado de otra forma si hablamos de datos fuentes y datos recibidos en relación a los datos recibidos puedo elegir el mapping, es decir donde van a "aterrizar" esos datos fuentes, en que tabla que columna de excel para que columna de tabla en SQL.
El problema es que SQL al leer el tipo de datos de los datos fuentes pareciera que anula las celdas numericas o de texto de la columna tomada dependiendo el tipo de datos de la primer celda de excel.
Entonces la pregunta es cuestión es:
¿Como podría hacer para transportar todos los datos de esa columna sin nulos? ¿Hay alguna forma de elegir como tiene que leer los datos SQL?

A: Parece que el comportamiento de la importación es bastante particular, efectivamente define la columna en función de la primer fila. Una posibilidad podría haber sido agregar una primer fila dummy para forzar la evaluación de la columna a una cadena, algo como esto:

Pero, lo que ocurre en estos casos, es que importa, correctamente las cadenas pero ignora los números, porj: el 500 de la tercer fila no lo transforma en cadena, lo ignora.
Modificar la definición de las columnas de la tabla tampoco sirve. La solución que encontré, pasa por "decirle" al Excel que un determinado número lo considere un texto, el metódo clásico es agregar una comilla simple delante del número:

Y ahora sí:


text:
Q: Make a Google Docs link that makes a copy and automatically shares it into a shared folder? I want a user to share a URL to a Google Doc. When another user follows the link, they must make a copy and that copy is available in a shared folder. Are their parameters I can add to the URL to do this?
The users are students and teachers. Users share the same Google Workspace domain. The students have major digital literacy gaps so any steps I can remove to sharing to their teachers is significant.

A: Given the url of your google docs file, you need to replace edit with copy and use &copyDestination=[Drive_FolderID] (optional) to redirect the copied file to a specific folder.
As for the share to a shared folder, I can't find any parameter for it. The copyDestination might still work in your case.
From:

*

*https://docs.google.com/document/d/[Doc_FileID]/edit?resourcekey=[Resource_Key]
To:

*

*https://docs.google.com/document/d/[Doc_FileID]/copy?resourcekey=[Resource_Key]&copyDestination=[Drive_FolderID]
After confirming to "Make a copy", it opens the copied file and will show on the Drive folder.
Output:


text:
Q: Erlang: List Comprehension to an Existing List I am trying to create a new list via a list comprehension but want those new values to be included in an existing list.
More specifically, I am try to create a string out of the date and will have some string formatting between the values ( a dash - ).  The existing list will be a template if you will with the dash.
Here is what I have so far:
{Date, Time} = erlang:universaltime().
DateList = tuple_to_list(Date).
DateListString = [ integer_to_list(X) || X < DateList ].
DateListStringConcatenate = lists:flatten(DateListString).

The result should be something along
"20101121"
But, what I want is
"2010-11-21"
So I am thinking about the DateListString comprehension "comprehending" to an existing list with "-" after the first and second element.
Any suggestions accompanied with concrete code samples much appreciated.

A: 1> {{Y,M,D},_} = erlang:universaltime().
{{2010,11,21},{16,42,56}}
2> lists:flatten(io_lib:format("~p-~p-~p", [Y,M,D])).
"2010-11-21"

A: If you really want it in a list comprehension then you could do the following:
{Date, Time} = erlang:universaltime().
DateList = tuple_to_list(Date).
DateListString = [ [$- | integer_to_list(X)] || X <- DateList ].
[_ | DateListStringConcatenate] = lists:flatten(DateListString).

Roberto's is a better/more efficient solution to this but in case you wondered how you might do it with a list comprehension this would be one way.

A: This is a possible solution, but I feel that it is not an elegant one. Also, it does not use list comprehension.
1> {Date, Time} = erlang:universaltime().
{{2010,11,21},{14,51,23}}
2> DateList = tuple_to_list(Date).
[2010,11,21]
3> DateListString = lists:zipwith(fun(X,Y) -> integer_to_list(X) ++ Y end, DateList, ["-","-",""]).
["2010-","11-","21"]
4> DateListStringConcatenate = lists:flatten(DateListString).
"2010-11-21"


text:
Q: Retain Count in Copy property please read the following code::
AddressCard *card1 = [[AddressCard alloc] init];
AddressCard *card2 = [[AddressCard alloc] init];

[card1 setName:[NSMutableString stringWithString:@"Deepak"] andEmail:[NSMutableString stringWithString:@"deepak@paymate"]];

NSMutableString * temp = [NSMutableString stringWithString:@"Deepak"];
r1 = [temp retainCount];
r2 = [card1.name retainCount];

//[card2 setName:card1.name];//retain count 2
//OR//
[card2 setName:temp];// retain count 1

r1 = [card2.name retainCount];

this is some think confusing because in both cases input type is string.
Thanks in advance.
d

A: You as a programmer dont need to worry about the exact value of the retain count (mostly). You need to keep a track of which objects are owned by others.
In your code where you get the retain counts r1 & r2....
Nothing owns temp , it was created with a class method (+ method) so it will get released at next autorelease pool flush .
card1 owns its "name"
when you set [card2 setName:temp]; thats when card2 owns temp. It is no longer under threat of being detroyed at next pool release.

A: I think you seem to be missing the point of mutable and immutable objects. When you invoke setName:andEmail: is there any logical reason why this method expects mutable strings? For example, does this method change the values of these strings by inserting or removing characters? They only need to be mutable if you intend to change the contents of the string. If you are only assigning the strings to another variable and not modifying the string's actual content, then they should be immutable NSStrings instead.
Also, if you are confused about when to retain and when to release objects, please make sure that you have read and understood the Cocoa Memory Management Programming Guide. This will likely answer any questions that you have about what methods/properties will retain objects and also when you should release objects.


text:
Q: script doesn't work in the server, but working on localhost So the problem is that I got a mistake - Cannot modify header information - headers already sent by.... There is a millions of solution on the website that told exactly what is the problem, and the question is not about it. But the problem that I don't get that mistake during test on my localhost, everything work fine without mistake, but as soon I upload the scrip on the server it gave me this mistake. So the question what is the diferent between server and localhost?

A: open your file with text editor like notepad++, then from encoding tab choose "UTF8 without BOM" then your code should work.BOM character is a character that you cant see but will be sent to header and and cause your this problem.

A: There is actually little or no difference. It depends on the OS both are running on and configuration settings of both. Some rules are enforced on linux which are not enforced on windows for example. The best is to try to understand the OS so you'll be able to configure them very well.

A: My best bet is that the error reporting level is different in php.ini.
On your localhost you may have notices and warnings turned off, while they are enabled on the server.
In that case, an additional unwanted output will be produced, and this output generates the unwanted headers.


text:
Q: The noun for when no individual in a community is doing wrong but the net result of those actions is evil? I hope this question is legitimate under the strict rules of this forum?
It is possible that the accumulated effect of a number of good people's actions can be evil, not just in a discrete situation, but as the result of a change of one social more without awareness of its consequential effect? Is there a word for this?

A: A few terms come to mind, though they do not follow your definition precisely:

*

*Tragedy of the Commons - the idea that when individuals share a common resource, they end up acting contrary to the common good.

*Diffusion of Responsibility - the idea that people are not responsible for the outcome of their actions because the outcome is the collective result of multiple people's actions.

*Little Eichmanns - these are the individuals who are doing actions that are not evil per se, but contribute to evil by being complicit in a larger evil system.

*The Banality of Evil - describes the phenomenon of the "Little Eichmanns".

A: A very general analytic term for this is the "horizon effect" or "horizon problem".
Wikipedia does a decent job explaining the origins and use of the term, so I'll go ahead and quote it -

The horizon effect, also known as the horizon problem, is a problem in artificial intelligence where, in many games, the number of possible states or positions is immense and computers can only feasibly search a small portion of it, typically a few plies down the game tree. Thus, for a computer searching only five plies, there is a possibility that it will make a detrimental move, but the effect is not visible because the computer does not search to the depth of the error (i.e. beyond its "horizon").
When evaluating a large game tree using techniques such as minimax
  with alpha-beta pruning, search depth is limited for feasibility
  reasons. However, evaluating a partial tree may give a misleading
  result. When a significant change exists just over the horizon of the
  search depth, the computational device falls victim to the horizon
  effect.
Hans Berliner named this phenomenon in 1973, "The Horizon Effect",[1]
  which he and other researchers had observed. He split the effect into
  two, the Negative Horizon Effect is when it "results in creating
  diversions which ineffectively delay an unavoidable consequence or
  make an unachievable one appear achievable." For the "largely
  overlooked" Positive Horizon Effect, "the program grabs much too soon
  at a consequence that can be imposed on an opponent at leisure,
  frequently in a more effective form."

The term is now applied freely to matters where the horizon takes very different forms than in the original use. It this case, the horizon may be time scales, where the full accounting of the effects over time is not realized. Or it may be spacial, where the full span of the effected area is not taken into account. Or it may be due to a non-egalitarian approach to weighting values which causes the score to change depending on your perspective. Often, the closer you are to some local optima, the less likely you are to find the global optimum.

CEO Horizon, Optimal Pay Duration and the Escalation of Short-Termism∗
  Ivan Marinovic† Felipe Varas‡, June 12, 2017
   Abstract
   This paper
  studies optimal CEO contracts when managers can manipulate their
  performance measure, sometimes at the expense of firm value. Optimal
  contracts defer compensation. The manager's incentives vest over time
  at an increasing rate and compensation becomes increasingly sensitive
  to short-term performance. This process generates an endogenous CEO
  horizon problem whereby managers intensify performance manipulation in
  the final years in office. Contracts are designed to foster effort
  while minimizing the adverse effects of manipulation. We characterize
  the optimal mix of short and long-term compensation along the
  manager's tenure, the optimal vesting period of incentive pay, and the
  resulting dynamics of managerial short-termism over the CEO's tenure.

While this example happens to involve an exploitative situation (it's based on the assumption that the manager will exploit the situation), It's intended to show the free use of the term outside of game algorithms in ordinary writing.
Another technical, model related paper, but far distant from the game engine origin.

The investment horizon problem: A resolution
  Knut K. Aase ∗
  Abstract
  In the canonical model of investments, the optimal fractions in
  the risky assets do not depend on the time horizon. This is against
  empirical evidence, and against the typical recommendations of portfolio managers. We demonstrate that if the intertemporal coefficient
  of relative risk aversion is allowed to depend on time, or the age of
  the investor, the investment horizon problem can be resolved.

finally, a very generic and relevant example.

Horizon Effects, Sustainability, Education and Ethics: Toward an Economics of
  Foresight
    Frederic B. Jennings, Jr., Ph.D.  22 June 2007
  Abstract: Horizon Effects, Sustainability, Education and Ethics
   The core of an ecological economics is interdependence: substitution
  and
  complementarity. Yet orthodox economics stands on substitution
  assumptions as the universal human relation. A theory so founded does
  not apply to a complementary realm. The optimal organizational form in
  a world of substitution is competition among our resources. Where
  complementarity rules, however, this is precisely wrong: cooperation
  is sought instead.  Interdependence is also the basis for bounded
  rationality theories. If consequences sweep outward forever, our
  prior anticipation of those outcomes shall be contained. The range of
  our understanding  –   called the planning horizon in choice  –   sets
  the boundedness of our rationality into an ordinal frame. Especially
  in the presence of complementarity, impacts grow as they spread,
  displacing competition for cooperation as our welfare ideal.  Examples
  are found in ecology, education and ethical culture: none are well
  served by competition. The health of ecology lies in complementarities
  sundered by competition. The educational system in its intangible
  information may be our clearest case of complementarity: it is a good
  illustration of failure. The ethical manifestation of this  problem is
  short horizons, a culture ruled by myopic concerns. Such conclusions
  are framed within a horizonal theory of foresight, to be explained
  below. Prices, economic growth and most of our ecological losses are
  tied to planning horizons, which extend through learning and trust.
  Longer planning horizons transform substitutes into complements, a
  shift of interdependence calling for institutional change. Without
  adapting incentives to cooperation, progress is slowed: horizon
  effects show why. A horizonal economics of complementarity is
  introduced and discussed.  KEYWORDS interdependence, complementarity,
  cooperation, planning horizon,  conscience, ecology, economics,
  education, ethics   1   This paper was presented at the INFER 2006
  Workshop on "Bounded Rationality in Economics and Finance" in
  Loughborough, Englan d.


text:
Q: HikariCP not releasing active MySql connections I have recently updated from JDK 8 to JDK 11 (issue not exists in JDK 8) and in the process updated the app Hikari dependency to 'com.zaxxer:HikariCP:3.3.1' and I am using springBootVersion = '2.1.3.RELEASE'.  The app has 2 data sources, 1 postgres and 1 MySql.  Postgres is fine but MySql is not.  As the Pool expires connections and adds new connections the active connections are created and never released, from the hikari perspective.  When querying the DB it only shows the 5 idle connections that I expect to see.  This continues until I reach the max pool size and then the app starts to sporadically fail to connect.
Has anyone seen anything like this and/or does anyone know something that could help me get to the bottom of this?
The limited logs I could get for this issue:
mysql-17 - After cleanup stats (total=12, active=7, idle=5, waiting=0)
mysql-17 - Before cleanup stats (total=12, active=7, idle=5, waiting=0)
at com.mysql.cj.protocol.a.NativeProtocol.readMessage(NativeProtocol.java:562)
... 89 more
at com.mysql.cj.jdbc.StatementImpl.executeQuery(StatementImpl.java:1186)
at batch.processor.Processor.processRequest(Processor.java:50)
at batch.processor.Processor.checkinStaleAssignedTransaction(Processor.java:76)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:153)
at org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:61)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:527)
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:275)
SQL Error: 0, SQLState: 08S01
mysql-17 - After cleanup stats (total=11, active=6, idle=5, waiting=0)
mysql-17 - Before cleanup stats (total=11, active=6, idle=5, waiting=0)
at java.base/sun.security.ssl.Alert.createSSLException(Alert.java:117)
at java.base/sun.security.ssl.Alert.createSSLException(Alert.java:133)
javax.net.ssl.SSLException: closing inbound before receiving peer's close_notify
STACKTRACE:
MESSAGE: closing inbound before receiving peer's close_notify
javax.net.ssl.SSLException
** BEGIN NESTED EXCEPTION **
EXCEPTION STACK TRACE:
Thu Jul 25 14:52:55 UTC 2019 WARN: Caught while disconnecting...
mysql-17 - Closing connection com.mysql.cj.jdbc.ConnectionImpl@79447870: (

The MySql Config is:
# MySql Properties
mysql.datasource.type=com.zaxxer.hikari.HikariDataSource
mysql.datasource.jdbcUrl=${DB_URL}
mysql.datasource.username=${SECRET_DB_USERNAME}
mysql.datasource.password=${SECRET_DB_PASSWORD}
mysql.datasource.driver-class-name=com.mysql.jdbc.Driver

mysql.datasource.connection-timeout=7000
mysql.datasource.maximum-pool-size=30
mysql.datasource.minimum-idle=5
mysql.datasource.idle-timeout=300000
mysql.datasource.max-lifetime=600000
mysql.datasource.connection-test-query=SELECT 1
mysql.datasource.leak-detection-threshold=3000
mysql.datasource.pool-name=mysql-${node.id}

mysql.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQLDialect

The MySql Spring Java config is:
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(entityManagerFactoryRef = "mySqlEntityManagerFactory", transactionManagerRef = "mySqlTransactionManager", basePackages = {"mysql.dao", "models"})
public class MySqlConfiguration {
    @Value("${mysql.jpa.properties.hibernate.dialect}")
    private String dialect;

    @Primary
    @Bean(name = "mySqlTransactionManager")
    public PlatformTransactionManager mySqlTransactionManager() {
        return new JpaTransactionManager(mySqlEntityManagerFactory().getObject());
    }

    @Primary
    @Bean(name = {
        "entityManagerFactory", "mySqlEntityManagerFactory"
    })
    public LocalContainerEntityManagerFactoryBean mySqlEntityManagerFactory() {
        LocalContainerEntityManagerFactoryBean factoryBean = new LocalContainerEntityManagerFactoryBean();
        HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        Properties props = new Properties();
        props.put("hibernate.dialect", dialect);

        factoryBean.setPersistenceUnitName("mysql");
        factoryBean.setJpaProperties(props);
        factoryBean.setDataSource(mysqlDataSource());
        factoryBean.setJpaVendorAdapter(vendorAdapter);
        factoryBean.setPackagesToScan("models", "mysql.entity");

        return factoryBean;
    }

    @Primary
    @Bean(name = "mysqlDataSource")
    @ConfigurationProperties(prefix = "mysql.datasource")
    public DataSource mysqlDataSource() {
        return DataSourceBuilder.create().type(HikariDataSource.class).build();
    }
}

**** EDIT ****
Some additional logging that may help:
org.springframework.jdbc.CannotGetJdbcConnectionException: Failed to obtain JDBC Connection; nested exception is com.mysql.cj.jdbc.exceptions.CommunicationsException: Communications link failure

The last packet successfully received from the server was 417 milliseconds ago.  The last packet sent successfully to the server was 417 milliseconds ago.
    at org.springframework.jdbc.datasource.DataSourceUtils.getConnection(DataSourceUtils.java:81)
    at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:324)
    at org.springframework.boot.actuate.jdbc.DataSourceHealthIndicator.getProduct(DataSourceHealthIndicator.java:122)
    at org.springframework.boot.actuate.jdbc.DataSourceHealthIndicator.doDataSourceHealthCheck(DataSourceHealthIndicator.java:109)
    at org.springframework.boot.actuate.jdbc.DataSourceHealthIndicator.doHealthCheck(DataSourceHealthIndicator.java:104)
    at org.springframework.boot.actuate.health.AbstractHealthIndicator.health(AbstractHealthIndicator.java:84)
    at org.springframework.boot.actuate.health.CompositeHealthIndicator.health(CompositeHealthIndicator.java:98)
    at org.springframework.boot.actuate.health.CompositeHealthIndicator.health(CompositeHealthIndicator.java:98)
    at org.springframework.boot.actuate.health.HealthEndpoint.health(HealthEndpoint.java:50)
    at org.springframework.boot.actuate.health.HealthEndpointWebExtension.health(HealthEndpointWebExtension.java:54)
    at jdk.internal.reflect.GeneratedMethodAccessor206.invoke(Unknown Source)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:567)
    at org.springframework.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:246)
    at org.springframework.boot.actuate.endpoint.invoke.reflect.ReflectiveOperationInvoker.invoke(ReflectiveOperationInvoker.java:76)
    at org.springframework.boot.actuate.endpoint.annotation.AbstractDiscoveredOperation.invoke(AbstractDiscoveredOperation.java:61)
    at org.springframework.boot.actuate.endpoint.web.servlet.AbstractWebMvcEndpointHandlerMapping$ServletWebOperationAdapter.handle(AbstractWebMvcEndpointHandlerMapping.java:294)
    at org.springframework.boot.actuate.endpoint.web.servlet.AbstractWebMvcEndpointHandlerMapping$OperationHandler.handle(AbstractWebMvcEndpointHandlerMapping.java:355)
    at jdk.internal.reflect.GeneratedMethodAccessor205.invoke(Unknown Source)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:567)
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:189)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:102)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:895)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:800)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1038)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:942)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1005)
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:897)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:645)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:882)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:750)
    at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:867)
    at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1623)
    at org.eclipse.jetty.websocket.server.WebSocketUpgradeFilter.doFilter(WebSocketUpgradeFilter.java:214)
    at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1610)
    at org.springframework.boot.actuate.web.trace.servlet.HttpTraceFilter.doFilterInternal(HttpTraceFilter.java:90)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1610)
    at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:209)
    at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:178)
    at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:357)
    at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:270)
    at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1610)
    at org.springframework.boot.actuate.metrics.web.servlet.WebMvcMetricsFilter.filterAndRecordMetrics(WebMvcMetricsFilter.java:117)
    at org.springframework.boot.actuate.metrics.web.servlet.WebMvcMetricsFilter.doFilterInternal(WebMvcMetricsFilter.java:106)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1610)
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:200)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1610)
    at tracing.shadow.io.opentracing.contrib.web.servlet.filter.TracingFilter.doFilter(TracingFilter.java:140)
    at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1610)
    at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:540)
    at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:146)
    at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:548)
    at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:132)
    at org.eclipse.jetty.server.handler.ScopedHandler.nextHandle(ScopedHandler.java:257)
    at org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:1588)
    at org.eclipse.jetty.server.handler.ScopedHandler.nextHandle(ScopedHandler.java:255)
    at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1345)
    at org.eclipse.jetty.server.handler.ScopedHandler.nextScope(ScopedHandler.java:203)
    at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:480)
    at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:1557)
    at org.eclipse.jetty.server.handler.ScopedHandler.nextScope(ScopedHandler.java:201)
    at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1247)
    at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:144)
    at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:132)
    at org.eclipse.jetty.server.Server.handle(Server.java:502)
    at org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:364)
    at org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:260)
    at org.eclipse.jetty.io.AbstractConnection$ReadCallback.succeeded(AbstractConnection.java:305)
    at org.eclipse.jetty.io.FillInterest.fillable(FillInterest.java:103)
    at org.eclipse.jetty.io.ChannelEndPoint$2.run(ChannelEndPoint.java:118)
    at org.eclipse.jetty.util.thread.strategy.EatWhatYouKill.runTask(EatWhatYouKill.java:333)
    at org.eclipse.jetty.util.thread.strategy.EatWhatYouKill.doProduce(EatWhatYouKill.java:310)
    at org.eclipse.jetty.util.thread.strategy.EatWhatYouKill.tryProduce(EatWhatYouKill.java:168)
    at org.eclipse.jetty.util.thread.strategy.EatWhatYouKill.run(EatWhatYouKill.java:126)
    at org.eclipse.jetty.util.thread.ReservedThreadExecutor$ReservedThread.run(ReservedThreadExecutor.java:366)
    at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:765)
    at org.eclipse.jetty.util.thread.QueuedThreadPool$2.run(QueuedThreadPool.java:683)
    at java.base/java.lang.Thread.run(Thread.java:835)
Caused by: com.mysql.cj.jdbc.exceptions.CommunicationsException: Communications link failure

The last packet successfully received from the server was 417 milliseconds ago.  The last packet sent successfully to the server was 417 milliseconds ago.
    at com.mysql.cj.jdbc.exceptions.SQLError.createCommunicationsException(SQLError.java:174)
    at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:64)
    at com.mysql.cj.jdbc.StatementImpl.executeQuery(StatementImpl.java:1218)
    at com.mysql.cj.jdbc.DatabaseMetaData.getUserName(DatabaseMetaData.java:4036)
    at tracing.shadow.io.opentracing.contrib.spring.cloud.jdbc.JdbcAspect.getConnection(JdbcAspect.java:44)
    at jdk.internal.reflect.GeneratedMethodAccessor201.invoke(Unknown Source)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:567)
    at org.springframework.aop.aspectj.AbstractAspectJAdvice.invokeAdviceMethodWithGivenArgs(AbstractAspectJAdvice.java:644)
    at org.springframework.aop.aspectj.AbstractAspectJAdvice.invokeAdviceMethod(AbstractAspectJAdvice.java:633)
    at org.springframework.aop.aspectj.AspectJAroundAdvice.invoke(AspectJAroundAdvice.java:70)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:175)
    at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:93)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:688)
    at com.zaxxer.hikari.HikariDataSource$$EnhancerBySpringCGLIB$$8dfc4e21.getConnection(<generated>)
    at org.springframework.jdbc.datasource.DataSourceUtils.fetchConnection(DataSourceUtils.java:157)
    at org.springframework.jdbc.datasource.DataSourceUtils.doGetConnection(DataSourceUtils.java:115)
    at org.springframework.jdbc.datasource.DataSourceUtils.getConnection(DataSourceUtils.java:78)
    ... 83 common frames omitted
Caused by: com.mysql.cj.exceptions.CJCommunicationsException: Communications link failure

The last packet successfully received from the server was 417 milliseconds ago.  The last packet sent successfully to the server was 417 milliseconds ago.
    at jdk.internal.reflect.GeneratedConstructorAccessor201.newInstance(Unknown Source)
    at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.base/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:500)
    at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:481)
    at com.mysql.cj.exceptions.ExceptionFactory.createException(ExceptionFactory.java:61)
    at com.mysql.cj.exceptions.ExceptionFactory.createException(ExceptionFactory.java:105)
    at com.mysql.cj.exceptions.ExceptionFactory.createException(ExceptionFactory.java:151)
    at com.mysql.cj.exceptions.ExceptionFactory.createCommunicationsException(ExceptionFactory.java:167)
    at com.mysql.cj.protocol.a.NativeProtocol.readMessage(NativeProtocol.java:562)
    at com.mysql.cj.protocol.a.NativeProtocol.checkErrorMessage(NativeProtocol.java:732)
    at com.mysql.cj.protocol.a.NativeProtocol.sendCommand(NativeProtocol.java:671)
    at com.mysql.cj.protocol.a.NativeProtocol.sendQueryPacket(NativeProtocol.java:986)
    at com.mysql.cj.protocol.a.NativeProtocol.sendQueryString(NativeProtocol.java:921)
    at com.mysql.cj.NativeSession.execSQL(NativeSession.java:1154)
    at com.mysql.cj.jdbc.StatementImpl.executeQuery(StatementImpl.java:1186)
    ... 99 common frames omitted
Caused by: java.io.EOFException: Can not read response from server. Expected to read 4 bytes, read 0 bytes before connection was unexpectedly lost.
    at com.mysql.cj.protocol.FullReadInputStream.readFully(FullReadInputStream.java:67)
    at com.mysql.cj.protocol.a.SimplePacketReader.readHeader(SimplePacketReader.java:63)
    at com.mysql.cj.protocol.a.SimplePacketReader.readHeader(SimplePacketReader.java:45)
    at com.mysql.cj.protocol.a.TimeTrackingPacketReader.readHeader(TimeTrackingPacketReader.java:52)
    at com.mysql.cj.protocol.a.TimeTrackingPacketReader.readHeader(TimeTrackingPacketReader.java:41)
    at com.mysql.cj.protocol.a.MultiPacketReader.readHeader(MultiPacketReader.java:54)
    at com.mysql.cj.protocol.a.MultiPacketReader.readHeader(MultiPacketReader.java:44)
    at com.mysql.cj.protocol.a.NativeProtocol.readMessage(NativeProtocol.java:556)
    ... 105 common frames omitted

A: MySQL Connector isn't supporting Java 11, only up to 8

Connector/J 8.0 is a Type 4 pure Java JDBC 4.2 driver for the Java 8 platform.
JRE Supported  1.8.x

There was a question in MySQL forum answered simply to report a bug (which I didn't find any)

We don't have any plans to do so at the moment.
I would suggest you to file a feature request in https://bugs.mysql.com/report.php providing all details you can so that we can start analyzing it.


text:
Q: UserControl background become transparent in C# Winform App I use User Control in panel. When I use white as BackColor of something it becomes transparent automatically even all kind of operation can be done over my app.

A: What if you try to set BackColor to 'Grey'? does it work?
And could you add screenshoot from User Control properties?


text:
Q: PHP JSON Check if value exists Ok so I have a JSON string looks like this.
{
    "1": [
        "a",
        "ab",
        "ac"
    ],
    "3": [
        "v",
        "aw",
        "ea"
    ],
    "4": [
        "ffg",
        "sd"
    ]
}

I decoded it with json_decode($string, true); Now, I need to find a way to check, for example, is a exists? If it exists, I want to know the name of its parent value(e.g. 1). The keys and values aren't always the same, they will keep changing. Can anyone provide me an example code on how can I do this? Thanks in advanced ;)

A: That string is gives me back null, if i tried to convert it to JSON, so i've just built an array to you for example. I've just create a function, and loop through on all the key of that. After that, in the sub array, loop through again to check the first occurence of the searched string. If you need all the results, then you can strore the keys in an array, and return with that.
//The string we search
$searchString = "aw";

//The array where we search
$array = array(
    "1" => array("a", "ab", "ac"),
    "3" => array("v", "aw", "ea"),
    "4" => array("ffg", "sd")
);

$result = getArrayIndex($array, $searchString);
if (empty($result)) {
    "I did not find your string: " . $searchString;
} else {
    echo "The index of your main array, where  '" . $searchString . "' found is: " . $result;
}

function getArrayIndex($array, $searchString) {
    if (count($array)) {
        foreach (array_keys($array) as $key) {
            if (is_array($array[$key])) {
                foreach ($array[$key] as $item) {
                    if ($item === $searchString) {
                        return $key;
                    }
                }
            }
        }
    }
    return false;
}


text:
Q: Conditional to detect a drive I am having a lot of trouble trying to make a conditional to detect whether a drive (flash drive e: ) is connected to the computer. If it is not, I just want to send it to the c drive.
Here is my code:
        StreamWriter sw;
        sw = File.AppendText ("E:\\SignIn.txt");
        sw.WriteLine ("Date and Time: " + label5.Text + " | Name: " + Name_Box.Text + " | Company: " + Company_Box.Text + " | Visiting: " + Visiting_Box.Text + " |");
        sw.Close ();

I need that to be sent to the flash drive (E:) and then if the flash drive is not connected I would need t shoot it over to the c: drive.
Thank you.

A: Check if (Directory.Exists(@"E:\")).

A: You can do a simple if/else and choose where you would like it to go
if (Directory.Exists(@"E:\")){

StreamWriter sw;
sw = File.AppendText ("E:\\SignIn.txt");
sw.WriteLine ("Date and Time: " + label5.Text + " | Name: " + Name_Box.Text + "Company: " + Company_Box.Text + " | Visiting: " + Visiting_Box.Text + " |");
sw.Close ();
}

else{
StreamWriter sw;
sw = File.AppendText ("C:\\SignIn.txt");
sw.WriteLine ("Date and Time: " + label5.Text + " | Name: " + Name_Box.Text + "Company: " + Company_Box.Text + " | Visiting: " + Visiting_Box.Text + " |");
sw.Close ();
}


text:
Q: How do I tell sendmail to say it's localhost instead of using its FQDN to combat spam? When I started using sendmail to receive mail for my domain the server's FQDN wasn't set up right so it would appear to be localhost when other MTA connected to it.
This seems to work fine. i.e. something like:
My Server: 220 localhost.localdomain ESMTP
Client: EHLO example.com
My Server: 250 localhost.localdomain

I could also send mail fine since I masqueraded as the correct domain.
I have never received a spam message at this domain. I believe spammers typically scan the internet looking for replies to port 25 and when they find it connect, take the domain name from either the greeting or the domain name after the 250 response and then try random usernames at that domain.
Since they only get localhost as the domain name they can't try this and so only genuine people who know the domain name (having got the mail server address from the mx records in the DNS for the domain) can send mail to the domain. (My reverse DNS does not match my domain so they can't get the domain from this either).
Unfortunately I have now set up the server with a proper FQDN which is now being shown.
Now it goes something like this:
My server: 220 (My reverse DNS which is not my domain name)
(I set this using confSMTP_LOGIN_MSG,'(My reverse DNS) Sendmail; $b')
C: EHLO example.com
My Server: 250 (My FQDN) oh no:(

How do I change the bit after 250 to be something else other than my FQDN without getting rid of the FQDN on the server?
Also are there any bad consequences to this apart from breaking the relevant RFC?

A: I have added the line
DjMyReverseDNS
to sendmail.mc
where MyReverseDNS is whatever I want it to show
i.e. setting j (which is the variable for the FQDN AFAIK) to what I want. This seems to work in a basic test, although i will need to test this more later.
Ty


text:
Q: IIS doesn't render the ASP.net MVC view. It lists down all files and folders inside the physical path I'm trying to host ASP.net MVC application on IIS 10 (Windows Server 2016 Datacenter - Azure)
I hosted a default ASP.net MVC project on it. But when I request the page, It's listing down all the files and folders in the browser.
I tried by disabling Directory Browsing then it gives 403.14 error.
the same project is working fine on IIS version 8.5 (Windows Server 2012 R2)
How can I resolve this issue?
are there any special configurations to be done on IIS or the project?
Thanks in advance

A: On the server role and features, can you check if these options on the image below are selected?

A: Try to set the below code in your web.config file:
<system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>

also, make sure you enable the iis .net feature and the application pool is using the right version of .net.


text:
Q: are "Look directly into his eyes" and "Look direct into his eyes" the same? direct(a) happening or done without involving other people, actions, etc. in between
and we can form it into an adverb "directly"
Ex: look directly into his eyes
but "directly" is also an adverb
direct(adv): without involving other people
are "Look directly into his eyes" and "Look direct into his eyes" the same?
I would think "Look direct into his eyes" is not common or strange but I am not sure although you can see 800 results when googling "Look direct into his eyes"

A: Not everybody knows the difference between an adverb and an adjective. For some words like fast, everybody agrees that the same word works as both adjective or adverb- it's called a flat adverb. For other words, the distinction is not so clear. In informal American English, many more words are used as flat adverbs:

I'm doing really well. - formal AmE, all BrE
  I'm doing real good. - informal AmE

According to this definition of direct, the adjectival meaning would have an appropriate meaning in this context but the adverbal meaning would not: the adverb directly has the appropriate meaning.
direct into his eyes is therefore using an adjective where an adverb should be used. This NGram shows that the adverbal form is quite common but finds no instances of the adjectival form.

A: Patrick took Jane by the elbows and looked directly into her eyes.
When you look straight at someone/something or into someone's eyes, you usually use the adverb directly. It's not common to use the "direct" in this sense, though it can also be used as an adverb.


text:
Q: how to create a method who can be called by another class with dot notation explaining what i want to do with an example is easier
my method:
private void Update<T>(IInterface<T> provider, IEnumerable<T> models)
    {
        foreach (var model in models)
            provider.Update(model);
    }

how i call it
Update<ModelType>(_provider,models);

i want to use the dot notation like that but the method must be declared in this class and not in the provider class
_provider.Update<ModelType>(models);

thanks

A: You can achieve this with extensions methods. Method should be declared as public static in public static class and have first parameter preceded by the this modifier:
public static class MyExt
{
    public static void Update<T>(this IInterface<T> provider, IEnumerable<T> models)
    {
        foreach (var model in models)
            provider.Update(model);
    }
}

A: You're looking for an extension method.
Something like this should work:
public static class IInterfaceExtensions
{
    public static void Update<T>(this IInterface<T> provider, IEnumerable<T> models)
    {
        foreach (var model in models)
            provider.Update(model);
    }
}

A: As already answered this is achieved using extension methods. I know the technique as Extension Method Chaining.
Extension Method Chaining Tutorial