text:
Q: Should a Perl module raise exceptions (die/croak)? When writing a Perl module, is it a good practice to use croak/die inside the module?
After all, if the caller doesn't use an eval block, the module might crash the program calling it.
What is the best practice in these cases?

A: I generally prefer exceptions if you're indicating an error of some kind. Otherwise you have to spend much more time sprinkling error handling code at different levels of your codebase rather than centralising the error handling in appropriate layers of the system - amongst other reasons.
You may find this old thread on perlmonks a useful read. I'll reproduce my comment there below - since I mostly agree with what I wrote back then :-)

Some reasons I like exceptions:

*

*Robustness. I can forget to check for an returned error value. I cannot forget to check for an exception.

*Brevity. I prefer:
$o->foo->bar->fribble->ni

to
$o->foo or return(ERROR_FOO);
$o->bar or return(ERROR_BAR);
$o->fribble or return(ERROR_FRIBBLE);
$o->ni or return(ERROR_NI);

*Clarity. With exception based code the  "normal" flow of control is more explicit because it is not obscured by error handling code. I think that the first of the two code examples above shows the intent of the code more directly than the second does.

*Separation of concerns. The error condition and the error handler are different ideas.

*

*You may want an error to be handled in different ways depending on the context.

*You may also not know how the error should be handled at the point it occurs.

*You may not know how the error should be handled at the time you write the code.
With the return-error-code style you end up having to either:

*

*propogate error conditions to where the decision on how they should be handled can be made.

*propogating error handlers down to where the errors may occur
Both options rapidly become messy if there are many levels of code between the error condition and the error handler.

*No confusion between return values and error conditions.
There are probably some more ;-)

A: At least in early stages of production, I like to have plenty of throw exeptions (die early motto). So I can catch quickly any mistake (and save you a lot of time avoiding thinking in the logic and tracking return codes). Then in each release iteration I can reduce the severity of the throws associating them with a $o->debug status. So when you run your tests, die at everything, but when you run your code for real croak instead into a log and only die when unavoidable fatal conditions happens. In my humble opinion this is more flexible that the returning codes I have been using in the old times.
Also a simple 'die' exception is not very useful sometimes, so it is better to have a throw function that prints all the call stack trace (like Carp->confess()|cluck()).
And a good catching mechanism is also handy. use Try::Tiny or TryCatch.
PD: the perlmonk thread pointed by adrianh is a classic.


text:
Q: Codeigniter photo upload and use I have made a photo upload function, it cannot be uploaded to the uploads folder in the root$this->upload->do_upload('userfile') always does not work because it always goes to Material_view page.
viewer:
<?php echo form_open_multipart ('index.php/Main/do_upload'); ?>

        Title
        <?php echo form_input('title'); ?>

        Image
        <?php echo form_upload('userfile'); ?>

        <?php echo form_submit('submit', 'Save', 'class="btn btn-primary"'); ?>
        <?php echo form_close(); ?>

Controller
public function do_upload()
    {
            $config['upload_path']          = './uploads/';
            $config['allowed_types']        = 'gif|jpg|png';
            $config['max_size']             = 100;
            $config['max_width']            = 1024;
            $config['max_height']           = 768;

            $this->load->library('upload', $config);

            if ( ! $this->upload->do_upload('userfile'))
            {
                    $error = array('error' => $this->upload->display_errors());

                    $this->load->view('Material_view', $error);
            }
            else
            {
                    $data = array('upload_data' => $this->upload->data());

                    $this->load->view('upload_success', $data);
            }
    }

And can I ask that after I upload the photo, how can I use it in viewer?
Thanks a lot :)

A: I have changed my answer based on your new code:
you are calling an incorrect field (as you didn't modify the tutorial's example to suit your custom view.
Controller:
public function do_upload()
{
        $config['upload_path']          = './uploads/';
        $config['allowed_types']        = 'gif|jpg|png';
        $config['max_size']             = 100;
        $config['max_width']            = 1024;
        $config['max_height']           = 768;

        $this->load->library('upload', $config);

        if ( ! $this->upload->do_upload('pic'))
        {
                $error = array('error' => $this->upload->display_errors());

                $this->load->view('Material_view', $error);
        }
        else
        {
                $data = array('upload_data' => $this->upload->data());

                $this->load->view('upload_success', $data);
        }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Aligning jumbotron image in the same 12 column grid I just started learning HTML and CSS a week ago, and have been learning using coursera and codeacademy. I wanted to make a simple website using bootstrap, with a navigation bar on top, and a big cover pic below that.
The code looks as follows.

                    <button type="button">

                    </button>

                    <button type="button">

                    </button>

                    <button type="button">

                    </button>

When I open the html in the browser (with the style sheet), I get the image attached. enter image description here. I though the cover pic would automatically align within the 12 column grid below the navigation bar on top, cropping out the sides. My questions are:
1. Doesn't adding an image automatically fit it in the 12 grid system?
2. How do I push the 3 icons on top to the right of the navigation bar (i.e to the right of the column)?
Thanks a ton guys! I'm grateful for any advise or suggestions in advance.

A: *

*I think the jumbotron class is formatted purposely to reach the edges of the page.

If I am understanding your question correctly in that you do not want the jumbotron to extend to the edge of the screen, you may want to Place the jumbotron inside the div class="container" as W3CSchools suggests

*Bootstrap v3 is neat because it has already created tools like the nav bar. You could try using an using the "" tag and an unordered list like so:

Home

Page 1

Page 2

Page 3


text:
Q: How to make app save data I've made an app which basically you enter some text into. You can edit it but upon closing the application all data is lost.
Is there a tutorial to preserve data for the application?
How can i save the data is it by storing to a database or plist?

A: There are hundreds of tutorials - but you also need to consider which method is best for your app. For saving small simple amounts of data (such as user settings) use NSUserDefaults. For more complicated data you could use CoreData or SQLite.

*

*NSUserDefaults - NSUserDefaults - tutsplus.com

*Core Data - Core Data - raywenderlich.com

*SQLite - SQLite Tutorial - Add/Display/Delete - Xcode 4.5 - Youtube

NSUserDefaults is as simple as:

*

*To set an object:
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:@"Patrick" forKey:@"username"];
[defaults synchronize];

*To retrieve and object:
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *username = [defaults objectForKey:@"username"];

If an object has not yet been set, it will return nil so you can do if (username == nil) {. NSUserDefaults are retained by the app even after an update.
You can read the docs for it here.

A: One of the beste Core data Tutorials:
http://www.raywenderlich.com/934/core-data-on-ios-5-tutorial-getting-started

A: It depends of what data you want to save (how much, etc.)
It could be using NSUserDefault (prefered for small data, like user prefer has already opened the app once, so stop showing the tutorial), in a .plist, in a DataBase (CoreData/SQL)...


text:
Q: First product added to new cart returned with no JSON "price" This is my first time currently working with Magento. I am developing a custom web shop solution for a machine shop with React.js.
My issue is the following:
After having completed a purchase and received a new quoteID as a logged in customer, where everything functions as expected, the first item added to the new cart is returned from our Magento backend WITHOUT a "price" attribute in the received JSON...
I have already checket out the different pricing settings in the backend, and I cannot seem to find the solution. The only weird setting is the "Special Prime Promotion" date changing randomly.
I hope one of you have encountered this issue before.
Kind regards,
Nikolaj Hem

A: I don't know you use the data when check the json. But if  you need price  of item, you can use the  code:
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$cart = $objectManager->get('\Magento\Checkout\Model\Cart');

// get quote items collection
$itemsCollection = $cart->getQuote()->getItemsCollection();

// get array of all items what can be display directly
$itemsVisible = $cart->getQuote()->getAllVisibleItems();

// get quote items array
$items = $cart->getQuote()->getAllItems();

foreach($items as $item) {
    echo 'ID: '.$item->getProductId().'
';
    echo 'Name: '.$item->getName().'
';
    echo 'Sku: '.$item->getSku().'
';
    echo 'Quantity: '.$item->getQty().'
';
    echo 'Price: '.$item->getPrice().'
';
    echo ""
"";
}


text:
Q: Apache does not load/work - even with htaccess authentication I've set up my VPS, installed httpd under yum install httpd and restarted the server. When I've added a .htaccess to /var/www/html nothing works at all, which inside the htaccess file has an authentication required and does not show anything except gives me an access to the "protected" directory.
AuthType Basic
AuthName "Private"
AuthUserFile /var/www/html/.htpasswd
Require valid-user

The .htpasswd exists, but still nothing works at all. I've also tried a simple rewrite rule and that doesn't even work.
How do you get apache to work (or run properly)? Everything is just running and working fine except apache.
My server is running Centos 5 x86_64 Standard.

A: You need to allow overrides for htaccess to work.
See this http://httpd.apache.org/docs/2.0/mod/core.html  Look at "AllowOverride"


text:
Q: Microsoft.Web.WebView2 / .NET Framework 4.8 WinForms application + Published application run-time error (REGDB_E_CLASSNOTREG) We are using XenApp: 7.6. We have a .NET full framework 4.8 WinForms application as a published application within Citrix Receiver. This published application is hosted on a Windows Server 2008 R2 SP1 (64 bit) machine. Our application uses Microsoft.Web.WebView2 (1.0.824-prerelease) web browser Winforms control to provide an embedded web browser within our application.
Our application works without any issues when running as a regular desktop application on the same Windows Server 2008 R2 SP1 server used to deliver the published application. Our application also works without any issues when running as a regular desktop application on Windows 10 and Windows Server 2012.
When we launch our application as a published application via Citrix Receiver we see a REGDB_E_CLASSNOTREG error at runtime when the Microsoft.Web.WebView2 Winforms control attempts to create a webview2 environment. You can see the runtime exception below...
System.Runtime.InteropServices.COMException (0x80040154): Class not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG))
at System.Runtime.InteropServices.Marshal.ThrowExceptionForHRInternal(Int32 errorCode, IntPtr errorInfo)
at System.Runtime.InteropServices.Marshal.ThrowExceptionForHR(Int32 errorCode)
at Microsoft.Web.WebView2.Core.CoreWebView2Environment.d__28.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.Web.WebView2.WinForms.WebView2.d__14.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
The same application works without any issues when launched via the same Citrix Receiver portal using a Citrix published desktop and not a Citrix published application.

Using ProcMon on the server when launching the published application I can see our application ultimately makes a call into C:\Program Files (x86)\Microsoft\EdgeWebView\Application\89.0.774.54\EBWebView\x64\EmbeddedBrowserWebView.dll which I believe then launches the msedgewebview2.exe process. We can see the msedgewebview2.exe executable is being launched successfully for the published app. This is shown below with the command arguments passed to msedgewebview2.exe...
C:\Program Files (x86)\Microsoft\EdgeWebView\Application\89.0.774.54\msedgewebview2.exe" --embedded-browser-webview=1 --user-data-dir="C:\Users\Admin\AppData\Roaming\OurAppName\EBWebView" --no-default-browser-check --disable-component-extensions-with-background-pages --no-first-run --disable-default-apps --noerrdialogs --embedded-browser-webview-dpi-awareness=0 --disable-features=msEdgeOnRampFRE,msEdgeOnRampImport,msEdgeMGPFrev1,msEdgeSettingsImport,msEdgeSettingsImportV2,msReadAloud,msSyncEdgeCollections,msApplicationGuard,msEdgeTranslate,msEdgeReadingView,WebPayments,msSendClientDataHeader,msSendClientDataHeaderToEdgeServices,msImplicitSignin,SpareRendererForSitePerProcess --disable-popup-blocking --enable-features=ForwardMemoryPressureEventsToGpuProcess --internet-explorer-integration=none --js-flags="--harmony-weak-refs-with-cleanup-some --expose-gc" --winhttp-proxy-resolver --mojo-named-platform-channel-pipe=26740.36688.8089883041949745853
Things I have tried

*

*I've used ProcMon to identify all CLSIDs being loaded when launching our application as a published Citrix application and verified all 32-bit & 64-bit CLSIDs exist. I've also attempted to re-register a number of DLL's using RegSvr32 in both System32 & SysWOW64 folders

*I've used ProcMon to identify all dependencies being loaded and verified these dependencies exist. I used a combination of ProcMon and dependency walker to verify all DLLs are present.

*I've veriried all COM permissions are correct via "dcomcnfg" & "mmc comexp.msc /32"

*Attempted all steps here https://support.microsoft.com/en-us/topic/-access-denied-errors-and-applications-with-com-activation-fail-after-installing-july-2018-security-and-quality-rollup-updates-for-net-framework-fd3d7a3f-ca2f-6e87-c409-a5652175cf40 (Diasymreader.dll CLASSNOTREG)

*Attempted to install several windows updates including August 2018 security & quality rollup - The Windows Server 2008 R2 SP1 (64 bit) operating system running the published applications appears up to date.

*Attempted different screen resolutions, color depths on the endpoint/client machine

*Attempted setting various compatibility modes for our executable on the server, disabled high DPI, direct composition, etc

*Attempted both x64 & x86 release builds with debugging flags disabled - no PDBs

*Added checks to ensure our application is running in an elevated administrator context

*Attempted useLegacyV2RuntimeActivationPolicy="true" within app.config configuration/startup element

*Attempted runtime/loadFromRemoteSources element within app.config element

*Ensured app. manifest exists to work correctly with UAC

*Checked local security policies on the server (I can't see any obvious issues)

*Attempted embedded WebView2 run-time (both x64 & x86)

*Attempted install & downloadd of the dedicated WebView2 run-time from https://developer.microsoft.com/en-us/microsoft-edge/webview2/ (both x86 & x64 versions)

*Installed the latest version of Edge on the server running the published application

*Added msedge.exe,msedgewebview2.exe,msedgewebview2 to each of the following registry keys to disable Citrix hooks...

*

*HKEY_LOCAL_MACHINE\SOFTWARE\Citrix\CtxHook\ExcludedImageNames

*HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Citrix\CtxHook64\ExcludedImageNames

*HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\CtxUvi\UviProcessExcludes

Key Differences
When launching our application as a published application via the Citrix Receiver portal as opposed to a regular desktop application, we see the following key differences via ProcMon...

*

*We see calls into the registry to locate the following CLSIDs (we don't see these calls when launched via a regular desktop app)...

*

*60A417CA-F1AB-4307-801B-F96003F8938B - Host Object Helper

*9BA05972-F6A8-11CF-A442-00A0C90A8F39 - Shell Folder View Router

*0A29FF9E-7F9C-4437-8B11-F424491E3931 - NDP SymBinder CorSymBinder_SxS / Dia based SymReader (diasymreader.dl / mscoree.dll)l

*FAE3D380-FEA4-4623-8C75-C6B61110B681\Instance - WindowsCodecs.dll

*

*0E25DC18-9F5E-48B1-80B3-D124E81B773B ColourTransformer (%SystemRoot%\system32\windowscodecsext.dll)

*05AF94D8-7174-4CD2-BE4A-4124B80EE4B8

*7835EAE8-BF14-49D1-93CE-533A407B2248

*7ED96837-96F0-4812-B211-F13C24117ED3

*ABE3B9A4-257D-4B97-BD1A-294AF496222E

*AC757296-3522-4E11-9862-C17BE5A1767E

*I've verified the DLLs referenced in the above CLSIDs are present within System32 & SysWOW64

*We see the PDB symbol reader at C:\Windows\Microsoft.NET\Framework64\v4.0.30319\diasymreader.dll being loaded.

*Before any file is accessed we see calls into the registry at HKU.Default\Software\Citrix\SessionSfr\10

*Our application runs under the WFICA32.EXE process on the endpoint which is a 32-bit process. We see our application launch on the server as a regular 64-bit process running under a domain user who belongs to the local administrator's group.

Notes

*

*Whilst we have full admin privileges and our Winforms application is running under the context of a local administrator the Windows Server 2008 R2 SP1 server hosting the published application is on a domain and various group policies are applied.

*Windows Firewall is completely disabled on the Windows Server 2008 R2 SP1 server hosting the published application

At this stage, I'm not sure what to try next. I would sincerely welcome any suggestions from the Citrix experts here within the community.
Thank you in advance for any suggestions or assistance you can provide.
Best wishes for now,
Ryan


text:
Q: Content type 'application/json;charset=UTF-8' not supported, when i try send JSON to Spring When i send JSON package from jQuery to Spring RestController i have many errors:
In Spring:

Resolved [org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/json;charset=UTF-8' not supported]

in Chrome:

POST http://localhost/post 415
(anonymous)   @   main.js:11

My jQuery code:
$(document).ready(function() {

$('#go').on('click', function() {

    var user = {
        "name" : "Tom",
        "age" : 23
    };

    $.ajax({
        type: 'POST',
        url: "http://localhost/post",
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify(user),
        dataType: 'json',
        async: true
    });

   });

 });

My Spring RestController code:
@RestController
public class mainController {
@RequestMapping(value = "/post", method = RequestMethod.POST,
        consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE,
        produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
public ResponseEntity<Object> postUser(@RequestBody User user){
System.out.println(user);
return new ResponseEntity<>("Success", HttpStatus.OK);
}

@RequestMapping(value = "/get", method = RequestMethod.GET)
public User getStr(){
    System.out.println("-------------------------");
    return new User("Tom", 56); //'Get' Check
}

}

Entity User:
@Data
@ToString
@NoArgsConstructor
@AllArgsConstructor
public class User {
  private String name;
  private int age;
}

A: you are using wrong mediatype i.e APPLICATION_FORM_URLENCODED_VALUE for consume in rest conttroller. Use MediaType.APPLICATION_JSON_UTF8_VALUE as you are passing json request.
@RestController
public class mainController {
@RequestMapping(value = "/post", method = RequestMethod.POST,
        consumes = MediaType.APPLICATION_JSON,
        produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
public ResponseEntity<Object> postUser(@RequestBody User user){
System.out.println(user);
return new ResponseEntity<>("Success", HttpStatus.OK);
}

@RequestMapping(value = "/get", method = RequestMethod.GET)
public User getStr(){
    System.out.println("-------------------------");
    return new User("Tom", 56); //'Get' Check
}

}


text:
Q: Storing Cart in local storage and persisting Data on route change vue I have a cart that clears each time I change my route and I'd like to persist this cart even if I change my route. I am using watch to render the products on route change. I can successfully Add the cart product to LocalStorage, but when I change my route and add products from a different category, the localStorage clears. How can I persist my cart via localStorage?
Here is my code:
    addTocart: function (product) {
          this.cartProducts.push(product)
          console.log(this.cartProducts)
          this.showCart = true
// successfuly added to localStorage
          window.localStorage.setItem('cart', JSON.stringify(this.cartProducts))
        },

Loading the products on url change
watch: {
    '$route.params.categoryId': function (id) {
      this.getProducts()
// I am trying to get the cart from localStorage at this point
      this.cartProducts = window.localStorage.getItem('cart')
      console.log(this.cartProducts)
    }
  },

How can I access my cart from local storage even when I add products from a different route?


text:
Q: mysqlslap: [ERROR] mysqlslap: Option 'debug-info' used, but is disabled When I use the command mysqlslap like:
mysqlslap --concurrency=50,100,200 --iterations=1 --number-int-cols=5 --number-char-cols=5 --auto-generate-sql --auto-generate-sql-load-type=mixed --engine=innodb --number-of-queries=100 --auto-generate-sql-guid-primary --debug-info
the system gives out the error:
mysqlslap: [ERROR] mysqlslap: Option 'debug-info' used, but is disabled
If I move the option "--debug-info", then everything goes well.
How do I fix this problem?
basic info:
mysql 5.7
redhat el7
I log in the Linux server with SSH protocol.

A: I just ran into this myself - It's strangely/frustratingly difficult to get a definitive answer, but about 98% sure you have to have a version compiled with debugging enabled.
From https://dev.mysql.com/doc/refman/5.7/en/compiling-for-debugging.html

If you have some very specific problem, you can always try to debug
  MySQL. To do this you must configure MySQL with the -DWITH_DEBUG=1
  option. You can check whether MySQL was compiled with debugging by
  doing: mysqld --help. If the --debug flag is listed with the options
  then you have debugging enabled. mysqladmin ver also lists the mysqld
  version as mysql ... --debug in this case.

https://dev.mysql.com/doc/refman/5.7/en/porting.html for the overview.


text:
Q: Weird profiling result on keras models: the more complex the faster So I am currently trying to figure out which deep learning framework is best to handle fourier transforms. So far I was using keras with a tensorflow backend, but I noticed the fft was kinda slow (cf this issue on Github).
So recently I tried to compare the speed directly with pytorch. Since I want to do more than simply do a fourier transform, I tried adding some operations to do a more comprehensive benchmark, and I noticed that for keras, adding operations was decreasing the compute time.
Here is the minimal working example (basically doing an inverse fourier transform in 2D, finished by taking the module of the image, and in between potentially "decomplexification" and "recomplexification"):
import os
os.environ["CUDA_VISIBLE_DEVICES"]="-1"
from keras.layers import Input, Lambda, concatenate
from keras.models import Model
import numpy as np
import tensorflow as tf
from tensorflow.signal import ifft2d
import time

def concatenate_real_imag(x):
    x_real = Lambda(tf.math.real)(x)
    x_imag = Lambda(tf.math.imag)(x)
    return concatenate([x_real, x_imag])

def to_complex(x):
    return tf.complex(x[0], x[1])

def complex_from_half(x, n, output_shape):
    return Lambda(lambda x: to_complex([x[..., :n], x[..., n:]]), output_shape=output_shape)(x)

def weird_model(conc_then_com=False):
    input_size = (320, None, 1)
    kspace_input = Input(input_size, dtype='complex64', name='kspace_input')
    inv_kspace = Lambda(ifft2d, output_shape=input_size)(kspace_input)
    if conc_then_com:
        inv_kspace = concatenate_real_imag(kspace_input)
        inv_kspace = complex_from_half(inv_kspace, 1, input_size)
    abs_inv_kspace = Lambda(tf.math.abs)(inv_kspace)
    model = Model(inputs=kspace_input, outputs=abs_inv_kspace)
    model.compile(
        optimizer='adam',
        loss='mse',
    )
    return model

# fake data
data_x = np.random.rand(35, 320, 320, 1) + 1j * np.random.rand(35, 320, 320, 1)
data_y = np.random.rand(35, 320, 320, 1)

start = time.time()
r = weird_model(conc_then_com=True).predict_on_batch(data_x)
end = time.time()
duration = end - start
print(f'For the prediction with the complex model it took {duration}')

start = time.time()
r = weird_model(conc_then_com=False).predict_on_batch(data_x)
end = time.time()
duration = end - start
print(f'For the prediction with the simple model it took {duration}')

start = time.time()
weird_model(conc_then_com=True).fit(
    x=data_x,
    y=data_y,
    batch_size=35,
    epochs=1,
    verbose=2,
    shuffle=False,
)
end = time.time()
duration = end - start
print(f'For the fitting with the complex model it took {duration}')

start = time.time()
weird_model(conc_then_com=False).fit(
    x=data_x,
    y=data_y,
    batch_size=35,
    epochs=1,
    verbose=2,
    shuffle=False,
)
end = time.time()
duration = end - start
print(f'For the fitting with the simple model it took {duration}')

Which gives the following times (more or less):
For the prediction with the complex model it took 0.24
For the prediction with the simple model it took 3.98
For the fitting with the complex model it took 0.28
For the fitting with the simple model it took 4.01

I have no idea of what's going on.

A: Actually, this was just a typo:
inv_kspace = concatenate_real_imag(kspace_input) should be inv_kspace = concatenate_real_imag(inv_kspace)


text:
Q: Ruby not edit or saving from a collection_select Please help
The form does not save the collection_select and it does not edit
_form.html.erb

  <%= f.label :company_id %>

  <%= collection_select(:learner, :learner_id, @clients, :id, :name,    prompt: >true) %>

learners_controller.rb
def new
    @learner = Learner.new
    @clients = Client.all
    respond_to do |format|
      format.html # new.html.erb
      format.xml  { render :xml => @learner }
    end
  end
  # GET /learners/1/edit
  def edit
  @learner = Learner.find(params[:learner][:learner_id])
  end

  # POST /learners
  # POST /learners.json
  def create
    @learner = Learner.new(learner_params)

    respond_to do |format|
      if @learner.save
        format.html { redirect_to @learner, notice: 'Learner was successfully created.' }
        format.json { render :show, status: :created, location: @learner }
      else
        format.html { render :new }
        format.json { render json: @learner.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /learners/1
  # PATCH/PUT /learners/1.json
  def update
    respond_to do |format|
      if @learner.update(learner_params)
        format.html { redirect_to @learner, notice: 'Learner was successfully updated.' }
        format.json { render :show, status: :ok, location: @learner }
      else
        format.html { render :edit }
        format.json { render json: @learner.errors, status: :unprocessable_entity }
      end
    end
  end

A: I think you should do:
def edit
  @learner = Learner.find(params[:learner][:learner_id])
end

To find the record of learner.

A: From the parameters you posted in the comment, the edit route is passing in the ID as just :id, so the edit action should be:
def edit
  @learner = Learner.find(params[:id])
end

As for the form not saving your collection_select input, it looks like you are using the default strong parameters gem with Rails 4. This means that learner_id must be available in the list of whitelisted parameters. At the bottom of your controller should be the learner_params method.
def learner_params
  params.require(:learner).permit(...other parameters..., :learner_id)
end


text:
Q: What is the length of an array? What does length mean exactly in this sentence: "Each array is passed to the function along with the "length" of that array."
Does it mean the size of the array?

A: Not necessarily. The size of the array is the number of bytes located for it (or at least that what sizeof(array) will return if it knows how many elements are there in the array) the length of the array is the number of elements in the array.
For example: short arr[10]; its length is 10, but its size is 20 (each short is two bytes)

A: In C, just because you have a pointer to an array, doesn't mean you know its length (how many entries it has).  Somehow you must know to avoid array indexing errors.
There are only a small number of ways to do this:

*

*Agree on an array length.  The code just knows certain arrays have a certain length, e.g., 17.  This is generally considered bad practice, but people do it for arrays that are problem-domain specific such as translation matrices for 3D graphics, which tend to have 4 rows.

*Document the array length with a constant declaration or a macro definition, and use that symbol to control loops accessing the array.

*Implicitly associate a well-known variable containing the runtime array size with the array. The program consults the variable when it needs to know the array size.

*Pass the pointer to the array, and the length known by the caller to the callee. Now the callee knows the length, and can in turn pass it to whoever the callee calls.

*Package the array and its length in a struct, and pass a pointer to the struct.  Now the callee can consult the struct to determine the array size.

This discussion is a little confusing for the C language, because we tend in general conversation to treat array length and array size as being synonyms.  But in C, "size" has a specific meaning; it is the number of storage units occupied by an entity. It is easily computed from an array length, and sometimes programs will pass "size" rather than length.  IMHO you should pass array lengths to functions that manipulate arrays by indexing them, as length is more abstract and easier to understand.


text:
Q: Previewing Velocity Template I'm editing velocity templates. these are used to generate PDFs. The problem is that I can't preview them. I can't see how the template will look when rendered. Are there any tools that can be used for that? I've tried googling and I can't find anything.

A: Not sure if this addresses what you need, but I created a velocity-template-tester a few years ago when I worked with Velocity templates. It has a UI where you can specify a template like Hello ${user} and parameters like {"user":"test"} or user=test and it'll show you the expanded template as Hello test. But it doesn't render the output as such.
If your output will be internally HTML and you want it rendered, you could use a REST API that is also part of the tester in Postman. Postman has a Preview button in the Body tab of the response which can be used to render HTML. The API accepts both JSON and YAML input. YAML input makes it easier to manually test multi-line templates. A sample API call with YAML input looks something like below:
curl --location --request POST 'http://localhost:8080/api/expandTemplate' \
--header 'Content-Type: application/x-yaml' \
--header 'Accept: text/html' \
--data-raw 'template: |

      Hello ${user}

parameters:
  user: test'


text:
Q: Pandas df.columns running very slow for large DataFrame when interactively executed in console EDIT:
This question has been heavily edited because the original issue is not valid after running additional tests.
For a DataFrame with roughly 1million rows and only 13 columns, getting the column names by using either one of the following:
print(df.columns)
df.columns
df.columns.values

is very slow (25sec). This happens ONLY WHEN I TYPE IN ABOVE CODE IN CONSOLE. After the slow execution is complete, the next several runs will be instant.
If I save as a script and run the script then all three operations take no time to finish. Seems to be a problem of my IDE.
I'm using DataSpell 2022.2.3 with python 3.9.5 and pandas 1.4.4 on macOS Ventura.

A: That's because neither of those two print statements actually print the whole Series. They rather print a representation of it:
import numpy as np
df = pd.DataFrame(np.random.randint(0,100,size=(10000, 4)), columns=list('ABCD'))

print("This is df.column")
print(df.A)
print("This is df.column.values")
print(df.A.values)

will output
This is df.column
0       35
1       76
        ..
9998    74
9999    79
Name: A, Length: 10000, dtype: int64
This is df.column.values
[35 76 91 ... 27 74 79]

As you can see the second representation is much smaller, hence quicker to print. Also it doesn't print auxiliary data like column name, type, etc.
If you will measure performance difference when doing some simple computations, you will find that it's not that big:
%timeit [x**2 for x in df.A]
%timeit [x**2 for x in df.A.values]

3.41 ms ± 25.3 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
2.09 ms ± 6.18 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

A: I think because df.columns.values return only Numpy array and that should be faster instead of considering and scan entire the DataFrame with pandas.core.indexes.base.Index which may contain MultiIndex.


text:
Q: react: disable right click on videojs The following is my code:
I need to add a quality selector and disable the right-click option in a webpage which uses videojs. I am not sure on how to use the plugins, there weren't any examples of plugins in react. Please help
VideoPlayer.js
import videojs from "video.js";

export const VideoPlayer = (props) => {
  const videoPlayerRef = useRef(null); // Instead of ID
  const [currentTime, setCurrentTime] = useState(null);
  const videoSrc = "https://media.w3.org/2010/05/sintel/trailer_hd.mp4";

  const videoJSOptions = {
    autoplay: "muted",
    controls: true,
    userActions: { hotkeys: true },
    playbackRates: [0.5, 1, 1.5, 2],
    chromecast: {
      appId: "APP-ID",
      metadata: {
        title: "Title display on tech wrapper",
        subtitle: "Synopsis display on tech wrapper",
      },
    },
    hlsQualitySelector: {
      displayCurrentQuality: true,
    },
  };

  useEffect(() => {
    if (videoPlayerRef) {
      const player = videojs(videoPlayerRef.current, videoJSOptions, () => {
        player.src(videoSrc);
        player.on("ended", () => {
          console.log("ended");
        });
        player.on("timeupdate", () => {
          setCurrentTime(player.currentTime());
        });
        console.log("Player Ready");
      });
    }

    return () => {};
  }, []);

  return (

      <video
        style={{ width: "100%" }}
        ref={videoPlayerRef}
        className="video-js"
      />
      Current Time: {currentTime}
      {/* <GlobalStyle /> */}

  );
};```

A: To disable right click menu in videoPlayer, you can use the contextmenu synthetic event in react,
document.addEventListener("contextmenu", (event) => {
  event.preventDefault();
});

// using react synthetic events
<SomeJSXVideoDOM onContextMenu={(event)=>event.preventDefault()} />

For more information, check out this [blog on contextmenu(https://www.pluralsight.com/guides/how-to-create-a-right-click-menu-using-react).
You can find more information on react synthetic event for onContextMenu over here

A: You can use onContextMenu event prop to handle right clicks on a particular element. Something like this -
...
  return (

 e.preventDefault()} style={{ width: "100%" }}>
      <video
        style={{ width: "100%" }}
        ref={videoPlayerRef}
        className="video-js"
      />
      Current Time: {currentTime}
      {/* <GlobalStyle /> */}

  );
...

This will disable right click on the element and all the elements inside it. Also, this is only going to work with native HTML elements, unless you are forwarding the onContextMenu prop or forwarding ref for the HTML element.


text:
Q: AdMob custom events for ADs mediation on iOS (Swift) I am doing ADs mediation through AdMob, and my goal is to automatically determine the eCPM, and select the best ADs network to pull ADs from.
However, it seems the AD network I am using (FB / MoPub) can not directly be configured to attain that goal, so I'll need to use the custom events
https://developers.google.com/admob/ios/custom-events#notify_admob_mediation
But I really don't understand the sample code provided on their website...
It even contains a type called: SampleBanner, and I really don't get it!
Have anyone done this before?
It'd be a big help if anyone can provide a more detailed illustration as to how to implement the custom events for AdMob in Swift

A: I can't give detailed recommendations about implementing events in swift, but my guess is that sample code differs, because it's made for test mode to avoid manual customization in order to prevent better results from other networks. I mean AdMom thinks about itself first of all))) But what you're trying to do is called programmatic mediation and it's definitely the right way to spreading traffic. I also thought about it, but i'm not that technically skilled to implement it myself. I checked that thread on Reddit https://www.reddit.com/r/iosdev/comments/41qie7/best_app_monetization_ad_network_solution/  and I think this might be helpful for you as well, cause if you're using fb,mopub and admob, getting access to other "competitors" would provide better results. I'm using appodeal for now and it really provides around 20% more revenue from admob alone. The point is that they "automatically determine the eCPM, and select the best ADs network to pull ADs from". hope this can be useful


text:
Q: Ubuntu 21.04-21.10 Random shutdowns, no logs Hardware (hardinfo):
I hope this isn't a hardware issue...
    OS: Ubuntu 21.10
    CPU: Intel(R) Core(TM) i7-8550U CPU @ 1.80GHz, 1 physical processor; 4 cores; 8 threads
    RAM: 7858608 KiB (AKA 8GB)
    Motherboard: Lenovo YOGA 730-13IKB / LNVNB161216 (LENOVO)
    Graphics: 1920x1080 (Unknown) The X.Org foundation
    Storage: (Shows nothing for some reason, but I already opened my computer to clean it to fix this issue and i confirmed it was an NVMe SSD.
    Printers: (Irrelevant)
    Audio: USB-Audio - USB Device 0x46d

Symptoms:
What I despise.
Now, since upgrading from Ubuntu 20.04 LTS to Ubuntu 21.04, I've been experiencing some crashes, these crashes:

*

*Do not automatically reboot

*Are spontaneous

*Happen ONLY when plugged in to AC power

*Have no signs of logging anywhere

*List item

Attempts:
Things that didn't work
I tried reinstalling the system at least two times (I have somehow forgotten, but it was two or more), updating from 21.04 to 21.10 in the process. Also worth noting that I chose what programs to back up, only choosing the ones that were:

*

*Not automatically installed

*Not local (I could reinstall those debs later myself)

*All not automatically development libraries

The only notable difference from 21.04 and 21.10 in crashes is none (IIRC).
Other things I have tried:

*

*BIOS Update

*Reinstalling thermald

*Disabling c-states (and enabling them again due to not helping)

*Tried to log kernel (couldn't set it up correctly, manual crash gave no log)

*Set up persistent journal (found nothing of use in there, I can post it if necessary though)

Extra
Some extra information that may help
The last piece of information I can provide is a text file, in which I wrote a bunch of things that I tried, suspected, and failed at. It is very unorganized (especially at the end when I just got irritated and started cursing at the end of file), but I'll include it nonetheless.
Personal logging:
When I updated to Ubuntu 21.04, thing's started going wrong.
I assume schedutil is doing something, as the computer crahes sometimes, no log or anything either.
I checked /var/log/kern.log among others, and I found nothing.

I suspect it's something to do with "P-states" and "C-states".
P-states, which stand for performance states, are used to optimize power consumption during code execution. They can be changed by the OS to change the CPU voltage (in short, change CPU frequency).
C-states on the other hand, are used to optimize/reduce power consumption during idle mode (when no code is being executed).
The typical C-states are:
    C0      - CPU is actively running code (P-states)
    C1      - CPU uses HLT instruction when idle, the clock is gated off to parts of the core, but it is relatively quick to wake up
    C1E     - This is actually just C1, except when C1E is enabled, the CPU lowers the CPU's speed & voltage when it is in C1
    C2 & up - The CPU will shut off various parts of the core for greater power savings, at the cost of no longer to wake up.
Source: "Controlling Processor C-State Usage in Linux, A Dell technical white paper describing the use of C-states with Linux operating systems"

Anyways, all of this is still happening now, even in 21.10, so this has to be a kernel issue.
Although setting "intel_idle.max_cstate=0" does not stop the crashes, so maybe it's a different problem.
I already used "memtest86" and my system is fine.
I'm going to restart my computer and see if there are any c-state settings in the BIOS/UEFI (are the settings still called BIOS?).

Yeah I checked I couldn't find anything.

The Dell C-state PDF (same in source above) has this section right below the C-states one (which is the first one www) called "Checking C-State Usage". It says:
    There are several ways to see how much idle time is being spent in the various C-states.
    First check the kernel messages from boot ("dmesg |grep idle" or "grep idle /var/log/messages", for instance) to see which idle driver is in use.

This is what I got:
    sudo dmesg |grep idle
    [sudo] password for ws:
    [    0.028186] clocksource: refined-jiffies: mask: 0xffffffff max_cycles: 0xffffffff, max_idle_ns: 7645519600211568 ns
    [    0.076265] clocksource: hpet: mask: 0xffffffff max_cycles: 0xffffffff, max_idle_ns: 79635855245 ns
    [    0.100211] clocksource: tsc-early: mask: 0xffffffffffffffff max_cycles: 0x39a8208cdd2, max_idle_ns: 881590748921 ns
    [    0.104538] process: using mwait in idle threads
    [    0.128722] clocksource: jiffies: mask: 0xffffffff max_cycles: 0xffffffff, max_idle_ns: 7645041785100000 ns
    [    0.132319] cpuidle: using governor ladder
    [    0.132322] cpuidle: using governor menu
    [    0.389960] clocksource: acpi_pm: mask: 0xffffff max_cycles: 0xffffff, max_idle_ns: 2085701024 ns
    [    1.426615] clocksource: tsc: mask: 0xffffffffffffffff max_cycles: 0x396d4ffc055, max_idle_ns: 881590662783 ns
    [    4.981048] systemd-journald[323]: varlink-22: varlink: setting state idle-server
    [    4.981116] systemd-journald[323]: varlink-22: varlink: changing state idle-server → processing-method
    [    5.336734] systemd-journald[323]: varlink-22: varlink: changing state processed-method → idle-server
    [    5.339242] systemd-journald[323]: varlink-22: varlink: changing state idle-server → pending-disconnect
I don't seem to see anything here, but I remember in the BIOS/UEFI settings something said ACPI instead of RXS or whatever it's called.
I can't open the folder "/proc/acpi/processor/CPU0/power", as it doesn't exist (only reaches "acpi").

Some time later, I decided to reinstall Ubuntu, and so I did, things worked well for the first day (and second) day, and then it crashed.
After some fidling around i decided to run "watch sensors", and I discovered something; when playing osu!, my temperature spiked up to ~95ºC, reaching 99ºC!
Just want to mention that the PC's killswitch is triggered at 100ºC, I was 1 degree away from it, and most of the time, 2 away (~96-98ºC most of the time)!

Another idea, this may be a PSU problem, as I've never seen it crash unplugged..

"kernelUpdateCrash" was this file's old name, now it is "cleaningComputer", I opened up the computer and holy hell there was so much crud in the fans.
Hasn't crashes since I cleaned it! Not really elaborating because this file is so long and also i've opened another computer which will be in another story (I think I'll call it "firstUbuntuInstallation").

Update it crashed again.
It didn't while it was sideways, so I think it's a fan air conduction problem thing.
An askubuntu question had their computer shutting down due to heating, I'm not sure if it is heating in my case but a bios update helped.
Source: "https://askubuntu.com/questions/1232813/ubuntu-20-04-shutdown-after-overheating"

I did it, I had to boot into a Windows PE USB to run the program, but the program didn't work...
So instead of ticking the "Install" option, I chose the "Unpack" option, and it unpacked another executable with the same name except that all the letters were capital now!
Anyways I ran it and it was this weird sketchy setup that appeared to be using WinAPI to put text where it shouldn't be and it wouldn't run without AC power.
I proceeded to plug it in and re-run it, it had a weird and probably broken image of a mascot that was like a pencil?
I attached an 2 images I took with my phone, that's why this story is in a folder.
PC rebooted, it worked, and then the fans started whirring up as if the thing was gonna blow up, never seen it like that, probably a temporary overvoltage of the fans while the computer tried to reboot.
So yeah I changed the title of this again.

It crashed again...

The last time I modified this file was: 2021年10月26日 19時55分59秒.
Now it's:               2021年11月06日 23時10分36秒
I just reintsalled thermald, seems to work, I'm not sure, throttles well I guess.
The "setPerformanceMode.sh" and "setPowersaveMode.sh" scripts that I created (using cpufreq) no longer seem to change anything.
So lets just hope this works, even if thermald was installed by default...
PS: I have i7z on a terminal set to "Always on Top" so I can monitor Frequency, C-states, and the temperature of the CPU cores (4 physical, logical).

Bruh thermald is throttling down to 400MHz while playing.
I tab out of the program it goes back to 1GHz what?
Okay I made Osu! set the FPS cap to V-Sync (60fps) instead of double of that (120fps, which it was before) and it seems to be good even when the computer is not on it's side (it usually didn't crash when on it's side, as the fans were pointing out.

Okay so I was checking the journalctl logs and I got:
"thermald.service: Changed running -> stop-sigterm"
huh...
Oh wait this is at the end of the journal it's probably shutdown 笑.

Keywords checked with "journalctl -g ???":
    thermal
    shutting
    crash
    panic
    spark
It just crashed while searching in journalctl... Let's investigate with "journalctl -b -1". Huh, the last log is 4 minutes before the crash, okay...
Yeah that's it im asking for help in AskUbuntu, should've done that a long time ago!
Alright now I just have to copy this into the question.

Footnote
If there's any other information I could provide, please leave a comment, I'll check them
regularly and update the post accordingly.
Again, this could be a hardware issue, but it happened when I updated my system, and currently due to Wayland and several other things I can't downgrade to 20.04 LTS and work on it.


text:
Q: Python tkinter not working on chrome os (linux terminal) When i installed python3 and tkinter by using sudo apt-get install python3-tk it installed it but when i ran python3 -m tkinter it said:
Traceback (most recent call last):
  File "/usr/lib/python3.9/runpy.py", line 197, in _run_module_as_main
    return _run_code(code, main_globals, None,
  File "/usr/lib/python3.9/runpy.py", line 87, in _run_code
    exec(code, run_globals)
  File "/home/udayveer/tkinter.py", line 1, in <module>
    from tkinter import *
  File "/home/udayveer/tkinter.py", line 3, in <module>
    window = Tk()
NameError: name 'Tk' is not defined

please help!


text:
Q: F#: Why aren't option types compatible with nullable types? Why aren't option types like "int option" compatible with nullable types like "Nullable"?
I assume there is some semantic reason for the difference, but I can't figure what that is.

An option in F# is used when a value may or may not exist. An option has an underlying type and may either hold a value of that type or it may not have a value.

http://msdn.microsoft.com/en-us/library/dd233245%28VS.100%29.aspx
That sure sounds like the Nullable structure.

A: The two have different semantics.  Just to name one, Nullable is an idempotent data constructor that only works on value types, whereas option is a normal generic type.  So you can't have a
Nullable<Nullable<int>>

but you can have an
option<option<int>>

Generally, though there are some overlapping scenarios, there are also things you can do with one but not the other.

A: Because of the runtime representation choice for System.Nullable<'T>.
Nullable tries to represent the absent of values by the null pointer, and present values by pointers to those values.
(new System.Nullable<int>() :> obj) = null
|> printfn "%b" // true

(new System.Nullable<int>(1) :> obj).GetType().Name
|> printfn "%s" // Int32

Now consider strings. Unfortunately, strings are nullable. So this is valid:
null : string

But now a null runtime value is ambiguous - it can refer to either the absence of a value or a presence of a null value. For this reason, .NET does not allow constructing a System.Nullable<string>.
Contrast this with:
(Some (null : string) :> obj).GetType().Name
|> printfn "%s" // Option`1

That being said, one can define a bijection:
let optionOfNullable (a : System.Nullable<'T>) =
    if a.HasValue then
        Some a.Value
    else
        None

let nullableOfOption = function
    | None -> new System.Nullable<_>()
    | Some x -> new System.Nullable<_>(x)

If you observe the types, these functions constrain 'T to be a structure and have a zero-argument constructor. So perhaps F# compiler could expose .NET functions receiving/returning Nullable<'T> by substituting it for an Option<'T where 'T : struct and 'T : (new : unit -> 'T)>, and inserting the conversion functions where necessary..

A: Key difference is that must test the option type to see if it has a value. See this question for a good description of its semantics: How does the option type work in F#

A: Again, this is from my limited understanding, but the problem probably lies in how each gets rendered in the IL.  The "nullable" structure probably gets handled slightly different from the option type.
You will find that the interactions between various .Net languages really boils down to how the IL gets rendered.  Mostof the time it works just fine but on occasion, it causes issues.  (check out this).  Just when you thought it was safe to trust the level of abstraction. :)


text:
Q: Error in [.data.frame: undefined columns selected for worldcloud in Shiny I'm creating a simple Shiny UI that allow users to either input text or upload file to create a word cloud, the sidebar shows normal, but main panel continues to show

Error in [.data.frame: undefined columns selected'.

Avoid initial warning with default value set in textAreaInput
Key code as below:
ui <- fluidPage(
  h1("Word Cloud"),
  sidebarLayout(
    sidebarPanel(
      # Add radio buttons input
      radioButtons(
        inputId = "source",
        label = "Word source",
        choices = c(
          "Use your own words" = "own",
          "Upload a file" = "file"
        )
      ),
      conditionalPanel(
        condition = "input.source == 'own'",
        textAreaInput("text", "Enter text",value="Paste here",rows = 7)
      ),
      conditionalPanel(
        condition = "input.source == 'file'",
        fileInput("file", "Select a txt file (encoding='UTF-8')")
      ),
      colourInput("col", "Background color", value = "white"),
      # Add a "draw" button to the app
      actionButton(inputId = "draw", label = "Draw!")
    ),
    mainPanel(
      wordcloud2Output("cloud")
    )
  )
)

library(tidyverse)
library(jiebaR)
mixseg = worker()
server <- function(input, output) {
  data_source <- reactive({
    if (input$source == "own") {
      (data <- as.data.frame(table(mixseg <= input$text)))
    } else if (input$source == "file") {
      f<-read_file(input$file$datapath)
      if(is.null(f)){
        return(NULL)
      }else{
        data <- as.data.frame(table(mixseg <=f))
      }
    }
    return(data)
  })

  output$cloud <- renderWordcloud2({
    input$draw
    isolate(
      wordcloud2(data_source(), backgroundColor =input$col))
  })
}

A: There are multiple issues with your code.

*

*wordcloud2 requires a data.frame including word and frequency count in two columns. Currently you are providing data_source() as input which is a reactive structure that returns a single character string.

*You need to properly parse the textInput server-side, which means that you need to create a wordcloud2-suitable data.frame from the input provided through textAreaInput; in fact, using textAreaInput is probably not the best element to use here, as your input text is highly structured and textAreaInput is best used for unstructured text values, see ?textAreaInput. But let's continue with your textAreaInput for pedagogical purposes.

*You should also include a check that ensures that the wordcloud only gets drawn if there is actually any data to use. We can do this using validate, see code below. Not including this check will result in a Warning: Error in [.data.frame: undefined columns selected.

*Less of an issue but not helping your post in terms of clarity: You are not using input_file at all; ditto for colourInput.

Following is a minimal reproducible example (where I've removed the unnecessary parts)
library(shiny)
library(shinyjs)
library(wordcloud2)

ui <- fluidPage(
    h1("Word Cloud"),
    sidebarLayout(
        sidebarPanel(
        # Add radio buttons input
            radioButtons(
                inputId = "source",
                label = "Word source",
                choices = c(
                    "Use your own words" = "own",
                    "Upload a file" = "file")
            ),
            conditionalPanel(
                condition = "input.source == 'own'",
                textAreaInput("text", "Enter comma-separated text", rows = 7)
            ),
            conditionalPanel(
                condition = "input.source == 'file'",
                fileInput("file", "Select a file")
            )
        ),
        mainPanel(
            wordcloud2Output("cloud")
        )
    )
)

server <- function(input, output) {
    data_source <- reactive({
        if (input$text != "")
            as.data.frame(table(unlist(strsplit(input$text, "[, ]"))))
        else
            NULL
    })

    output$cloud <- renderWordcloud2({
        validate(need(data_source(), "Awaiting data"))
        wordcloud2(data_source(), backgroundColor = "white")
    })
}

This produces e.g.


text:
Q: Server local connection provider has stopped listening on [ \\.\pipe\SQLLocal\MSSQLSERVER ] Anyone know what specifically causes this error message and/or how to fix it? Thanks.

SQL Server Alert System: 'Sev 17 Error'
DESCRIPTION:  Server local connection provider has stopped listening on
  [ \.\pipe\SQLLocal\MSSQLSERVER ] due to a failure. Error: 0xe8,
  state: 4. The server will automatically attempt to re-establish
  listening.


text:
Q: Next Thursday is vacation I have read the following sentence in a language learning tool (the Italian course in Duolingo) :

Next Thursday is vacation.

What does it mean?
It sounds odd to me, either in US English or UK English. I think it might be a bad translation. I'd rather say:

*

*the holidays are next week/month (holidays = "festivities of the end of the year" or holiday = "day in which most schools, stores and offices are closed because of a public celebration" )

*the holiday is next Thursday ( holiday = "day in which most schools, stores and offices are closed because of a public celebration")

*the holiday(s) (UK) / vacation (US) start(s) next Thursday (holiday(s)/vacation = "rest period given to a specific student/worker or group of those")

A: It seems incorrect!
Vacation is a period and not a day. Generally, when you say that you are on a vacation, you mean it is more than a day. Hence, mentioning Thursday, only one day, for a vacation does not satisfy the definition we have in dictionaries.
Yes, this is a valid sentence...

Next Thursday is a holiday!

Or...

The vacation begins from next Thursday.


text:
Q: Load and save image from blob field in delphi using firebird In my Firebird database I have a Blob field that contain a Bitmap. I'll have to load and display in a TImage located on my Form. Subsequently I'll have to save in the same field the image selected by a OpenDialog.

A: Procedure LoadBitmapFromBlob(Bitmap: TBitmap; Blob: TBlobField);
var
  ms, ms2: TMemoryStream;
begin
  ms := TMemoryStream.Create;
  try
    Blob.SaveToStream(ms);
    ms.Position := 0;
    Bitmap.LoadFromStream(ms);
  finally
    ms.Free;
  end;
end;

example usage
procedure TForm4.Button1Click(Sender: TObject);
var
  bmp: TBitmap;
begin
  bmp := TBitmap.Create;
  try
    LoadBitmapFromBlob(bmp, TBlobField(Dataset.FieldByName('Image')));
    Image1.Picture.Assign(bmp);
    bmp.SaveToFile(OpenDialog.FileName);
  finally
    bmp.Free;
  end;

end;


text:
Q: Store output from purrr:map_dfr and dplyr::group_split with while loop I would like to use map_dfr and group_split to run groups of a data.frame through a while loop and store the results.
I can do this for one group like this.
# df dput below
# this code finds the closet match for DIFF for Sample.x in Sample.y, then finds the next closest match, until
df_f <- df %>% filter(grp == "AB" & VAR == "Var1")
HowMany <- length(unique(df_f$Sample.y))
i <- 1
MyList <- list()

while (i <= HowMany){
  res1 <- df_f %>%
    group_by(grp, VAR, Sample.x) %>%
    filter(DIFF == min(DIFF)) %>%
    ungroup() %>%
    mutate(Rank1 = dense_rank(DIFF))

  res2 <- res1 %>% group_by(grp, VAR) %>% filter(rank(Rank1, ties.method="first")==1)

  SY <- as.numeric(res2$Sample.y)
  SX <- as.numeric(res2$Sample.x)
  res3 <- df_f %>% filter(Sample.y != SY)
  res4 <- res3 %>% filter(Sample.x != SX)
  df_f <- res4

  MyList[[i]] <- res2

  i <- i + 1
}
df.result <- do.call("rbind", MyList)

But when trying to make a function with the while loop to use with map_dfr and group_split I am unable and/or unsure on how to store the output.
MyResult <- df %>%
      dplyr::group_split(grp, VAR) %>%
      map_dfr(fun) # fun below

df.store <- data.frame() # attempt to store results

fun <- function(df){
  HowMany <- length(unique(df$Sample.y))
  i <- 1
  MyList_FF <- list()
  ThisDF <- df
  while (i <= HowMany){

    res1 <- ThisDF %>%
      group_by(grp, VAR, Sample.x) %>%
      filter(DIFF == min(DIFF)) %>%
      ungroup() %>%
      mutate(Rank1 = dense_rank(DIFF))
    res2 <- res1 %>% group_by(grp, VAR) %>% filter(rank(Rank1, ties.method="first")==1)
    # print(res2) # when printed to screen the desired output looks correct
    SY <- as.numeric(res2$Sample.y)
    SX <- as.numeric(res2$Sample.x)

    res3 <- ThisDF %>% filter(Sample.y != SY)
    res4 <- res3 %>% filter(Sample.x != SX)

    # df.store <- rbind(df.store, res4)
    # MyList_FF[[i]] <- res2
    ThisDF <- res4
    i <- i + 1
  }
}

I've tried to rbind or use a list to store the output, but my attempts have not been correct. If I print "res2" to screen, I can see the desired output one row at a time. How do I store the output from fun from each group_split?
# df dput
df <- structure(list(Location.x = structure(c(1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L,
2L, 2L, 2L, 2L), .Label = c("A", "C", "B"), class = "factor"),
    Sample.x = c(6L, 6L, 10L, 10L, 9L, 9L, 6L, 6L, 10L, 10L,
    9L, 9L, 6L, 6L, 6L, 10L, 10L, 10L, 9L, 9L, 9L, 6L, 6L, 6L,
    10L, 10L, 10L, 9L, 9L, 9L, 1L, 1L, 1L, 9L, 9L, 9L, 1L, 1L,
    1L, 9L, 9L, 9L), VAR = c("Var1", "Var1", "Var1", "Var1",
    "Var1", "Var1", "Var2", "Var2", "Var2", "Var2", "Var2", "Var2",
    "Var1", "Var1", "Var1", "Var1", "Var1", "Var1", "Var1", "Var1",
    "Var1", "Var2", "Var2", "Var2", "Var2", "Var2", "Var2", "Var2",
    "Var2", "Var2", "Var1", "Var1", "Var1", "Var1", "Var1", "Var1",
    "Var2", "Var2", "Var2", "Var2", "Var2", "Var2"), value.x = c(56.48,
    56.48, 57.03, 57.03, 55.04, 55.04, 6, 6, 10, 10, 9, 9, 56.48,
    56.48, 56.48, 57.03, 57.03, 57.03, 55.04, 55.04, 55.04, 6,
    6, 6, 10, 10, 10, 9, 9, 9, 55.62, 55.62, 55.62, 55.65, 55.65,
    55.65, 1, 1, 1, 9, 9, 9), Location.y = structure(c(2L, 2L,
    2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L,
    3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L,
    3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L), .Label = c("A",
    "C", "B"), class = "factor"), Sample.y = c(1L, 9L, 1L, 9L,
    1L, 9L, 1L, 9L, 1L, 9L, 1L, 9L, 3L, 7L, 9L, 3L, 7L, 9L, 3L,
    7L, 9L, 3L, 7L, 9L, 3L, 7L, 9L, 3L, 7L, 9L, 3L, 7L, 9L, 3L,
    7L, 9L, 3L, 7L, 9L, 3L, 7L, 9L), value.y = c(55.62, 55.65,
    55.62, 55.65, 55.62, 55.65, 1, 9, 1, 9, 1, 9, 1.4, 111.6,
    111.8, 1.4, 111.6, 111.8, 1.4, 111.6, 111.8, 10.2, 14.4,
    20.9, 10.2, 14.4, 20.9, 10.2, 14.4, 20.9, 1.4, 111.6, 111.8,
    1.4, 111.6, 111.8, 10.2, 14.4, 20.9, 10.2, 14.4, 20.9), DIFF = c(0.859999999999999,
    0.829999999999998, 1.41, 1.38, 0.579999999999998, 0.609999999999999,
    5, 3, 9, 1, 8, 0, 55.08, 55.12, 55.32, 55.63, 54.57, 54.77,
    53.64, 56.56, 56.76, 4.2, 8.4, 14.9, 0.199999999999999, 4.4,
    10.9, 1.2, 5.4, 11.9, 54.22, 55.98, 56.18, 54.25, 55.95,
    56.15, 9.2, 13.4, 19.9, 1.2, 5.4, 11.9), grp = c("AC", "AC",
    "AC", "AC", "AC", "AC", "AC", "AC", "AC", "AC", "AC", "AC",
    "AB", "AB", "AB", "AB", "AB", "AB", "AB", "AB", "AB", "AB",
    "AB", "AB", "AB", "AB", "AB", "AB", "AB", "AB", "CB", "CB",
    "CB", "CB", "CB", "CB", "CB", "CB", "CB", "CB", "CB", "CB"
    )), row.names = c(NA, -42L), class = "data.frame")

A: The only piece missing was your mapped function fun wasn't returning a value. It was computing and building the temporary list, MyList_FF properly, you could see with the print() calls, but without a return, it was disappearing.
fun <- function(df) {
    HowMany <- length(unique(df$Sample.y))
    i <- 1
    MyList_FF <- list()
    df_f <- df
    while (i <= HowMany){
        res1 <- df_f %>%
            group_by(grp, VAR, Sample.x) %>%
            filter(DIFF == min(DIFF)) %>%
            ungroup() %>%
            mutate(Rank1 = dense_rank(DIFF))

        res2 <- res1 %>% group_by(grp, VAR) %>% filter(rank(Rank1, ties.method="first")==1)

        SY <- as.numeric(res2$Sample.y)
        SX <- as.numeric(res2$Sample.x)
        res3 <- df_f %>% filter(Sample.y != SY)
        res4 <- res3 %>% filter(Sample.x != SX)
        df_f <- res4

        MyList_FF[[i]] <- res2

        i <- i + 1
    }
    # this is the magic line
    do.call("rbind", MyList_FF)
    # this returns the list built inside of the function
}

The magic is in that last line, similar to what you did after your single example, binding up the intermediate results list. In R the return() function is only needed if you are trying to return early, because by default R functions will return the last value. So here we don't need to explicitly say return(do.call("rbind", MyList_FF)), although it wouldn't hurt anything if you did. In the non-working example there wasn't a last value since i was being assigned, so you were not getting any objects back, but were not getting any errors either.
For a full working example:
MyResult <- df %>%
    dplyr::group_split(grp, VAR) %>%
    map_df(fun)

MyResult
# A tibble: 16 x 10
# Groups:   grp, VAR [1]
   Location.x Sample.x VAR   value.x Location.y Sample.y value.y  DIFF grp   Rank1
   <fct>         <int> <chr>   <dbl> <fct>         <int>   <dbl> <dbl> <chr> <int>
 1 A                 9 Var1     55.0 B                 3     1.4  53.6 AB        1
 2 A                10 Var1     57.0 B                 7   112.   54.6 AB        1
 3 A                 6 Var1     56.5 B                 9   112.   55.3 AB        1
 4 A                 9 Var1     55.0 B                 3     1.4  53.6 AB        1
 5 A                10 Var1     57.0 B                 7   112.   54.6 AB        1
 6 A                 6 Var1     56.5 B                 9   112.   55.3 AB        1
 7 A                 9 Var1     55.0 B                 3     1.4  53.6 AB        1
 8 A                10 Var1     57.0 B                 7   112.   54.6 AB        1
 9 A                 9 Var1     55.0 B                 3     1.4  53.6 AB        1
10 A                10 Var1     57.0 B                 7   112.   54.6 AB        1
11 A                 9 Var1     55.0 B                 3     1.4  53.6 AB        1
12 A                10 Var1     57.0 B                 7   112.   54.6 AB        1
13 A                 6 Var1     56.5 B                 9   112.   55.3 AB        1
14 A                 9 Var1     55.0 B                 3     1.4  53.6 AB        1
15 A                10 Var1     57.0 B                 7   112.   54.6 AB        1
16 A                 6 Var1     56.5 B                 9   112.   55.3 AB        1

Side note if you use do.call("xbind", list) a lot you might enjoy dplyr::bind_rows(list) and dplyr::bind_cols(list).


text:
Q: Create and call member functions similar to laravel How can we create member functions in php that can be called similarly to the way laravel does?
ex:
User::with('package')->where('id', $user_id)->get();

i tried creating a static function with a member function inside:
 public static function getAll() {

     public function withJoin($join_table, $local_key, $foreign_key) {

         global $wpdb;
         $table_name = $wpdb->prefix.'qre_events';

         $query = "SELECT * from $table_name INNER JOIN $join_table ON $local_key = $foreign_key";

         try {
             $results = $wpdb->get_results($query);
         } catch(Throwable $e) {
             $results = null;
             echo($e);
             echo "Error retrieving data.";
         }

         var_dump($results);
     }

     global $wpdb;
     $table_name = $wpdb->prefix. static::$table_name;

     $query = "SELECT * from $table_name";

     try {
         $results = static::convertArrayToModelArray($wpdb->get_results($query),
 static::$attributes);
     } catch(Throwable $e) {
         $results = null;
         echo($e);
         echo "Error retrieving data.";
     }

     return $results;
 }

and tried calling it like so:
$results = Event::getAll()->withJoin($user_table, 'user_id', 'ID');

but it returned this error:

Fatal error: Uncaught Error: Call to a member function withJoin() on array

A: Try .
$results = Event::withJoin($user_table, 'user_id', 'ID')->get();

A: The method chaining is archived by returning $this for each method.
Like this:
class Event
{
    public function getAll()
    {
        // Do stuff
        return $this;
    }

    public function withJoin()
    {
        // Do stuff
        return $this;
    }
}

Now they can be called like this:
(new Event)->getAll()->withJoin();

So you have to save you parameters to properties on the class.
You can take a look inside Laravel builder to see exactly how it was archived there: https://github.com/laravel/framework/blob/6.x/src/Illuminate/Database/Eloquent/Builder.php

A: The chaining of methods works because each function returns an instance of an object that has functions on it.
// This
User::with('package')->where('id', $user_id)->get();

// Is basicly the same as
$user_query = User::with('package');
$user = $user_query->where('id', $user_id)->get();

You need to create two objects and the static function will return an instance of the other object. If you want method chaining as well, you just need to make sure that chainable functions return their own instance.
For example
class Event
{
    public static function getAll()
    {
        return new EventObject();
    }
}

class EventObject
{
    public function withJoin()
    {
        // Do stuff here.
        // return `$this` if you want to chain functions.
    }
}

In this example, using Event::getAll() will give you an EventObject instance on which you can call the withJoin function. So you can now do the following:
Event::getAll()->withJoin();


text:
Q: Incorrect syntax near the keyword 'CREATE' while creating function I am a complete newbie when it comes to MS SQL and have found this code online while searching. It seems like it would do exactly what I want, which is do a radius search based on Latitude and Latitude values.
However, I keep getting: Incorrect syntax near the keyword 'CREATE'. , which is the very first line of the code. My database is 2008 MS SQL
Here is the code:
CREATE FUNCTION CalculateDistance
            (@Longitude1 Decimal(8,5),
            @Latitude1   Decimal(8,5),
            @Longitude2  Decimal(8,5),
            @Latitude2   Decimal(8,5))
        Returns Float
        AS BEGIN
        Declare @Temp Float

        Set @Temp = sin(@Latitude1/57.2957795130823) * sin(@Latitude2/57.2957795130823) + cos(@Latitude1/57.2957795130823) * cos(@Latitude2/57.2957795130823) * cos(@Longitude2/57.2957795130823 - @Longitude1/57.2957795130823)

        if @Temp > 1
            Set @Temp = 1
        Else If @Temp < -1
            Set @Temp = -1

        Return (3958.75586574 * acos(@Temp) )

        End

        -- FUNCTION
        CREATE FUNCTION LatitudePlusDistance(@StartLatitude Float, @Distance Float) Returns Float
        AS BEGIN
            Return (Select @StartLatitude + Sqrt(@Distance * @Distance / 4766.8999155991))
        End

        -- FUNCTION
        CREATE FUNCTION LongitudePlusDistance
            (@StartLongitude Float,
            @StartLatitude Float,
            @Distance Float)
        Returns Float
        AS BEGIN
            Return (Select @StartLongitude + Sqrt(@Distance * @Distance / (4784.39411916406 * Cos(2 * @StartLatitude / 114.591559026165) * Cos(2 * @StartLatitude / 114.591559026165))))
        End

        -- ACTUAL QUERY
        -- Declare some variables that we will need.
        Declare @Longitude Decimal(8,5),
                @Latitude Decimal(8,5),
                @MinLongitude Decimal(8,5),
                @MaxLongitude Decimal(8,5),
                @MinLatitude Decimal(8,5),
                @MaxLatitude Decimal(8,5)

        -- Get the lat/long for the given id
        Select @Longitude = Longitude,
               @Latitude = Latitude
        From   qccities
        Where  id = '21'

        -- Calculate the Max Lat/Long
        Select @MaxLongitude = LongitudePlusDistance(@Longitude, @Latitude, 20),
               @MaxLatitude = LatitudePlusDistance(@Latitude, 20)

        -- Calculate the min lat/long
        Select @MinLatitude = 2 * @Latitude - @MaxLatitude,
               @MinLongitude = 2 * @Longitude - @MaxLongitude

        -- The query to return all ids within a certain distance
        Select id
        From   qccities
        Where  Longitude Between @MinLongitude And @MaxLongitude
               And Latitude Between @MinLatitude And @MaxLatitude
               And CalculateDistance(@Longitude, @Latitude, Longitude, Latitude) <= 2

Any idea what's going on?
Thank you!!!
EDIT: Thank you very much to bluefeet and Aaron Bertrand for pointing me in the right direction!

A: You should also end the each of create statements with a GO or semicolon:
Also, should add the schema to the function. For example the below uses the dbo. schema:
CREATE FUNCTION dbo.CalculateDistance
            (@Longitude1 Decimal(8,5),
            @Latitude1   Decimal(8,5),
            @Longitude2  Decimal(8,5),
            @Latitude2   Decimal(8,5))
        Returns Float
        AS BEGIN
        Declare @Temp Float

        Set @Temp = sin(@Latitude1/57.2957795130823) * sin(@Latitude2/57.2957795130823) + cos(@Latitude1/57.2957795130823) * cos(@Latitude2/57.2957795130823) * cos(@Longitude2/57.2957795130823 - @Longitude1/57.2957795130823)

        if @Temp > 1
            Set @Temp = 1
        Else If @Temp < -1
            Set @Temp = -1

        Return (3958.75586574 * acos(@Temp) )

        End
        GO

See SQL Fiddle with Demo of all functions being created.

A: Try a single function without the GO. GO is not part of T-SQL, it is a batch separator for client tools like Management Studio. ColdFusion is probably passing that along to SQL Server and it doesn't understand the GO. So either send one function at a time from ColdFusion (without the GO), or use a better tool for creating objects and sending queries (e.g. Management Studio or whatever client interface the host provides you with).
I'm not sure why you think you need to create the three functions in a single code block instead of creating them separately (since your web page obviously has no clue about batches). You only need to create the functions once. After you have created them in the database, you can reference them in subsequent queries all day/week/month/year etc.

A: You have to separate multiple CREATE FUNCTION calls with GO OR ; (or both - which one I prefer):
CREATE FUNCTION CalculateDistance
        (@Longitude1 Decimal(8,5),
        @Latitude1   Decimal(8,5),
        @Longitude2  Decimal(8,5),
        @Latitude2   Decimal(8,5))
    Returns Float
    AS BEGIN
    Declare @Temp Float

    Set @Temp = sin(@Latitude1/57.2957795130823) * sin(@Latitude2/57.2957795130823) + cos(@Latitude1/57.2957795130823) * cos(@Latitude2/57.2957795130823) * cos(@Longitude2/57.2957795130823 - @Longitude1/57.2957795130823)

    if @Temp > 1
        Set @Temp = 1
    Else If @Temp < -1
        Set @Temp = -1

    Return (3958.75586574 * acos(@Temp) )

    End;
GO

    -- FUNCTION
CREATE FUNCTION LatitudePlusDistance(@StartLatitude Float, @Distance Float) Returns Float
    AS BEGIN
        Return (Select @StartLatitude + Sqrt(@Distance * @Distance / 4766.8999155991))
    End

    -- FUNCTION
    CREATE FUNCTION LongitudePlusDistance
        (@StartLongitude Float,
        @StartLatitude Float,
        @Distance Float)
    Returns Float
    AS BEGIN
        Return (Select @StartLongitude + Sqrt(@Distance * @Distance / (4784.39411916406 * Cos(2 * @StartLatitude / 114.591559026165) * Cos(2 * @StartLatitude / 114.591559026165))))
    End;

GO

A: There are a number of CREATE statements in that SQL. They have to be separated into batches by putting GO between the statements.
This is revealed by the half of the message in SSMS:

'CREATE FUNCTION' must be the first statement in a query batch.

So to fix:
CREATE FUNCTION CalculateDistance
        (@Longitude1 Decimal(8,5),
        @Latitude1   Decimal(8,5),
        @Longitude2  Decimal(8,5),
        @Latitude2   Decimal(8,5))
    Returns Float
    AS BEGIN
    ...
    END

GO

CREATE FUNCTION LatitudePlusDistance(@StartLatitude Float, @Distance Float) Returns Float
    AS BEGIN
        Return (Select @StartLatitude + Sqrt(@Distance * @Distance / 4766.8999155991))
    End

 GO

 CREATE FUNCTION... etc


text:
Q: Dealing with conflicts when merging from development to master I begun a workflow where I aim to do all new features in a development branch and the master branch will only be for production ready code.
After doing the following:
git checkout master
git merge staging

I received a bunch of conflicts looking like this:
CONFLICT (rename/add): Rename app/assets/stylesheets/mobile.css->app/assets/stylesheets/application.css in HEAD. app/...
CONFLICT (modify/delete): app/views/organizers/mobile.html.erb deleted in HEAD and modified in staging. Version stagi...
CONFLICT (modify/delete): app/views/events/mobile.html.erb deleted in HEAD and modified in staging. Version staging of app/v...

When I now have been googling this, all I read is about reviewing each and every file, resolving the conflicts and commit the changes. But I don't see any point in doing all this, as I know the code and it's only an advancement of the same code set.
How can I merge the changes done in staging into master in a simple manner without having to review and resolve each and every change?

A: This is a complex problem because it basically means that git cannot figure out intuitively how to combine the two branches.  It appears that some files were deleted on master that are then modified in (and therefore used by) staging while another was renamed in master yet added to on staging.  The following will mostly be a shot in the dark, and you may still have to manually resolve some (but hopefully fewer) conflicts.
There are a number of different algorithms for merging that git can choose from, so we'll use the one that is simplest, easy to customize, and usually used by default: the recursive strategy.  And we'll force its use with the option -s recursive.
The first step to helping git would be to have it spend more time refining the patches, so we'll use the option -Xdiff-algorithm=histogram.  This will take the longest but it will force git-merge to produce a better diff output (which will hopefully reduce the conflicts).
The next step is to tell git-merge to spend more time on doing a correct merge.  We'll use the use the -Xpatience option to do this.
Since master will depend on the renamed/modified file, while staging will depend on the old file, we can try to trick git into thinking that the file wasn't really renamed with the option -Xrename-threshold=100% (so that the files have to be identical to be considered a rename).  Note that you may have some redundant files left over and any changes to files that need to be aware of the other file names won't record old names (just the new ones) so you may want to go back and fix those once you've completed the merge.  You could also adjust that 100% to something smaller (the default is 50% and that's currently causing a problem).
Now to include the files that are needed by staging we can use the following option to force them to be added: -Xtheirs.  WARNING: this option will silently ignore all merge conflicts and simply use the content of staging by default.  Make sure to run a full test suite to check for any inconsistencies.  If you do have problems in the test suite after the merge, undo it with git reset --hard HEAD^ and redo the merge without this option.  You will likely have a small number of merge conflicts that you'll have to settle manually, but you will know that the source of the errors is from one of those (finitely many) conflicts, which is huge leap forward from guessing in front of a debugger.
Finally, we put it all together to get
git checkout master
git merge staging -s recursive -Xdiff-algorithm=histogram -Xpatience -Xrename-threshold=100% -Xtheirs

Lastly, I suggest you play around with the options.  The extra time spent on the merge may make the last two options useless (and even make it worse).
In the future, I suggest you regularly pull any changes in master to your topic branches.  This will not only present the conflicts earlier (and thus there are fewer of them at a time) but it will also keep you up to date enough that you may even resolve the conflicts before they occur.  The other reason that this is good is because git has a feature called git-rerere that records the conflicts that you resolve manually and then learns how to resolve those same conflicts automatically for you later.  So once you resolve it once, you won't have to resolve the same/similar conflict over again.

A: Use git merge option, known as "strategy" -s ours (or theirs). That means git will prefer changes from development branch (or from master). That means if you have one code string changes differently in master and staging, it will take staging changes.
Also, I will recommend you to use --no-commit option, so you will be able to check your code once before commit merge (not for every change).

A: I use next strategy.
At first, checkout from develop branch to other:
  git checkout -b feature/resolve-conflicts

Next step, you must pull code from master into feature branch:
  git pull origin master

Next resolve conflicts and push feature branch into git:
  git add --all
  git commit -am 'resolve conflicts'
  git push -u origin feature/resolve-conflicts

Then create pull request and compare feature/resolve-conflicts with master branch. On different platforms it makes with different ways. After merge feature branch into master then create new pull request merging develop branch into master branch.
Now, changes in develop must normally merged into master branch with commits.
It works for me, hope i can help.

A: This is a very common problem and there lies an easy solution. Once you are in a merge conflict, you can do this on a file to file basis by
Keep master's file
git checkout --ours myfile.html

Keep development's file
git checkout --theirs myfile.html

Quite easily you can apply this to the entire folder
git checkout --ours ./
git checkout --theirs ./

This is better than a git merge because you get to see the conflicted files as well.
More details are here https://www.kernel.org/pub/software/scm/git/docs/git-checkout.html


text:
Q: How does this `++` implementation by `foldr` work? I am learning Haskell with programming in haskell from Channel 9 Lectures. In chapter 7, the professor implemented his own ++ operator using foldr by
(++ ys) = foldr (:) ys

and his reasoning is
  xs ++ ys = foldr (:) ys xs
= (++) ys xs = foldr (:) ys xs
= (++ ys) = foldr (:) ys

Here is the blackboard

I got confused here why xs ++ ys functions the same as (++) ys xs. And I let xs = [1,2,3] and ys = [4,5,6] and run them by runhaskell, they just produce different answers:
> main = print $ [1,2,3] ++ [4,5,6]
[1,2,3,4,5,6]
> main = print $ foldr (:) [4,5,6] [1,2,3]
[1,2,3,4,5,6]
> main = print $ (++) [4,5,6] [1,2,3]
[4,5,6,1,2,3]

So what did the professor actually mean in his reasoning?
By the way, I am trying to induce by myself like the following:
  xs ++ ys = foldr (:) ys xs
= (++) xs ys = foldr(:) ys xs

foldr(:) ys xs at the right part of the equation means for each y in this Foldable ys, apply : to y and xs, which is actually what's done on the left side. Is my reasoning right?

A: IMO, your reasoning is correct - there's an error in the video:
xs ++ ys = ...
= (++) ys xs = ...

should really be
xs ++ ys = ...
= (++) xs ys = ...

If you look at the comments to the video, you'll notice that Tom Lokhorst pointed out this error (among several others).


text:
Q: I want to use elements of an array as variables but how?  char [] abc ={a,b,c};//  The array      //   1)
    for(int i = 0; i < abc.length; i++) {  //for loop   //  2)
        String abc[i] = "yukarı";   // 3)
    }

*/
        1) I need variables for example: a, b, c. But if I put them in an array(I need to reach them with numbers) they are not variables as you can see.
2) I will assign the elements of abc array to strings automatically. But java does not accept that
               String abc[i] = "yukarı";
               abc[i] is not supported in here. Java want to see
               String x = "yukarı";
3) I need these a, b, c variables in array because I need to reach them with numbers. If ı could assign a number to a
        string value all my problems were solved.
Can you suggest another way or help?
        If Is there any fail for my explanation sorry about that. Thanks for your helps.

A: 1). In here you define the array as a char array. (can consider as a collection of chars) So you can not add a string to that. So you can write as follows,
String [] abc ={"a","b","c"};
for(int i = 0; i < abc.length; i++) {
    abc[i] = "yukarı";   // like String a = "yukarı";

It seams that you have less knowledge in java arrays.So refer this link for more details.
2). And you can use reflection to do so. please refer this link

A: try the below
String [] abc ={a,b,c};
    //abc[0] = "yukarı";  //I want to use all elements in abc like variables.
    for(int i = 0; i < abc.length; i++) {
        abc[i] = "yukarı";   // like String a = "yukarı";


text:
Q: Is the concept of spatial dimensions generalized beyound positive integers? I can only find definitions of spaces, $\mathbb{R}^p$ where $p\in\mathbb{N}$ yet I cannot convince myself that having fractions of dimensions or even irrational amount of dimensions in a space would make sense or not. I.e how a sphere would look like in $2.5$ dimensions, how would we define distances, etc. Fractal dimensions do not seem to help, because as I see, they have a very narrow usage.(cannot define shapes or angles on them, or can we?)
negative integer dimensions may be interesting too.


text:
Q: Ant - Poll REST resource to monitor remote process I'm a little bit of an Ant n00b, but I hope this question isn't too n00bish:
I have a section of an Ant script that needs to monitor a remote process and report whether it has succeeded or failed. The remote information is exposed as a REST resource. The process behind it may take several minutes, so I will likely need to poll several times before I get a result other than "in progress".
In very rough pseudo-code, I need something like this:
while(true) {
  get REST resource status
  if status='success' or status='failure'
    break;
  sleep 10
}

I know that I can (ab)use the <waitfor> task to repeatedly evaluate a condition, but I can't for the life of me figure out what that condition should be. The best I can come up with is to use a <scriptcondition>, but then I'm faced with the problem that Rhino JS (which Ant uses) has no XMLHttpRequest to send the REST query.
In other parts of the Ant script, we're using <exec> to run curl commands to interact with the REST service, but I don't see how to do that within the <waitfor>.
EDIT: I forgot to mention I'm stuck (for the time being) with Ant 1.7.1. Also, I realize it might be easier to push this to an external (bash, python, php, whatever) script, but I would prefer to keep it in the Ant script.


text:
Q: Closed form solution for least square problem subject to probability simplex Let $f(x)=||Ax-b||_2^2$ where $A \in \mathbb{R}^{N \times n}$ where $n \leq N$ and a $A$ is full column rank. Find the closed form solution of the following problem:
$$
\min_{x \in \mathbb{R}^n, x \geq 0, \sum_{i=1}^n x_i=1} ||Ax-b||_2^2\tag{1}.
$$
My try:
Problem (1) is a convex problem since $A$ is a full column rank matrix so the objective function is strongly convex. Also, the constraint is a polyhedron which is bounded so it is polygon and would be convex. Or, one could say the constraint set is the probability simplex and it is bounded and convex. Hence, it has a unique solution.
Question
Would it be possible to find the closed form solution of (1)? If so, what would it be?


text:
Q: Adding a border to my HTML div shifts my text I'm recently learning some html/css, and doing a little project to get started on my own. I came across a problem. I added a 1px solid black border to a div and it shifted my text right off of my div's background. How do I fix this?

A: Try adding the property to the div:
box-sizing: border-box;

The default value for box-sizing is content-box, which means that the width and height are the only things accounted for in a defined height and width.
In contrast, border-box makes it so that the width, height, padding, and border are all within the specified width and height.
For example, in a <div> with box-sizing: content-box; height: 400px; width: 400px, the content (i.e., the text) would be 400px by 400px. Adding border or padding would push the content over (as is your case) and make the entire box wider. On the other hand, if you change it to box-sizing with the same width and height, then the 400px would account for all of those size properties (except margin).


text:
Q: one generation away Example with a context:

Former astronaut John Grunsfeld, associate administrator for NASA's Science Mission Directorate, shared Stofan's optimism, predicting that signs of life will be found relatively soon both in our own solar system and beyond.
  "I think we're one generation away in our solar system, whether it's on an icy moon or on Mars, and one generation [away] on a planet around a nearby star," Grunsfeld said during Tuesday's event.

I'm not sure what he really means by one generation away and how we should understand it.

A: We're one generation away means we are at the distance (in time) of one generation.


text:
Q: Allow 10k+ users to reverse downvote if user deletes See Update Below
As a 10k+ user (on SO, not here), I'd like to be able to un-downvote a deleted answer. Details:
Like a lot of users who've been on the site(s) for a while, I don't downvote virtually anything right away. I comment saying what my problem is with the item and, if I'm not too busy and I'm still around later and oh look a butterfly I don't get too distracted, I'll come back to see if it's been fixed or removed and downvote if called for.
Despite that, sometimes I downvote an answer and find later that the poster deleted it. Now, they could be deleting it because they don't want more downvotes, but that's fine by me, the goal is to have high-quality content on the site. Sometimes, though, it's clear that they've simply realized that they're wrong and so they're deleting the answer because it's wrong.
And when that happens, I'd like to be able to un-downvote the answer as a means of encouraging that behavior (deleting bad answers). (Re the questions below: No, it's not about reclaiming my rep. I don't care about that, particularly.) It's not like this is a burning item or high on the priority list, but I didn't see it suggested, so I'm suggesting it.
Update: According to Grace Note, the rep they lose will eventually come back to them. And so there's probably no need for this. Sure, it would make it more immediate, and maybe there's something to that if the change is as trivial to implement as it seems, but...

A: Deleted posts, as long as they are deleted, do not count their votes for the real reputation of anyone who has had a reputation change. After a recalculation of reputation (which you can do by going to Go to https://stackoverflow.com/reputation [substitute site name as necessary], scrolling down to the bottom, and clicking Trigger Reputation Recalc), your displayed reputation will be set to your real reputation. You can revert the cost of casting your downvote, while the target can revert all of the reputation change from all votes on the deleted post.
There is no real benefit to changing the vote while the answer is still deleted. Your vote has no actual impact while it remains deleted. If the answer gets undeleted, then ideally it should be revised before you change your vote, and revision lets you change your vote.
If you had mistakenly cast a downvote on a post that otherwise didn't need it, which got subsequently deleted, then it has nothing at all to do with the deletion status.

A: If you request a reputation recalculation you will get your reputation back since the question was deleted. There isn't any need for that feature.
For more information about how to request a reputation recalculation see this question :
How can I request a reputation recalc?

A: I agree.  I hesitate to downvote for the same reasons.  If the downvotes got un-downvoted automatically, this would be even better


text:
Q: Android chroot Debian I have a armv7l embedded device with 3 usb ports and a sd card slot.
The OS of the device is android with a Debian OS in chroot.
Via the Debian I can ssh into the device and breakout the chroot to the android kernel. No screen can be attached to the device.
I want to run Debian as the main OS and delete android all together.
Installing Debian is only possible with ssh which is not installed on the android OS.
Is it possible to somehow install Debian remotely via ssh without having any physical access to the device?


text:
Q: Updating the Progress Bar achieved in the New View I want to Update the Progress bar in my application.
I have created a new view by making use of inflater and in that newly created view I want to show the Horizontal Progress Bar Updating.
How can I do that particularly?
Also I got to know that when We create a new view by Inflater, we need to add it to the Current Activity Class by addContentView(), I don't know how to do these though I have tried a lot till now.
Can anybody help me here?

A: So, as you don't provide code, let me search my crystal ball... wait... OK, there it is. You have something like this:
View someView = inflater.inflate(R.layout.view_with_progress_bar, null);

In order to access your ProgressBar, you have to use the findViewById method:
ProgressBar yourProgressBar = (ProgressBar)someView.findViewById(R.id.id_of_your_progress_bar);
// you can know modify the progress bar: yourProgressBar.setBlahBlah

In order to add the view that contains the progress bar to you current activity, you have to have a reference to the container that you previously set. So, I guess you previously did: setContentView(R.layout.something);, then you have a layout called something.xml; that layout contains a ViewGroup (LinearLayout, RelativeLayout, etc.; my crystal ball can't see that clearly). Then, you need to set an ID to that container, create a reference, and add your newly created view to it:
// in your onCreate method
setContentView(R.layout.something);

// let's suppose it's a LinearLayout
LinearLayout mainContainer = (LinearLayout)findViewById(R.id.id_you_gave_to_container);

// blha blah... the rest of your code. Keep in mind that you will
// probably have to declare the mainContainer outside the onCreate method

// here, you have already inflated your view, and want to add it to your activity
mainContainer.addView(someView);


text:
Q: How to change "Continue to Force.com" to "Contineu to " in Google SSO with Salesforce We implemented Single sign on with Google as authentication provider for Salesforce.
It is working well. However, in the Google's login page, it shows force.com and we want to see our company name.enter image description here


text:
Q: phpmyadmin dosen't work in Windows Server, extension mysqli is missing I have a problem with phpmyadmin. Throws me an error message that says the following. "The mysli extension is missing. Please chech you PHP configration ...." I do not understand why I get the error message because I in my php.ini uncomment the extension called "extension = mbstring" and "extension = mysqli ". I have tried differently and still I get the same error I don't know if I have to change something in the Apache configuration file to make it work.
Here the error message:

A: Check for the following config for extensions in php.ini file
extension=bz2
extension=curl
extension=fileinfo
extension=gd2
extension=gettext
;extension=gmp
;extension=intl
;extension=imap
;extension=interbase
;extension=ldap
extension=mbstring
extension=exif      ; Must be after mbstring as it depends on it
extension=mysqli
;extension=oci8_12c  ; Use with Oracle Database 12c Instant Client
;extension=odbc
;extension=openssl
;extension=pdo_firebird
extension=pdo_mysql
;extension=pdo_oci
;extension=pdo_odbc
;extension=pdo_pgsql
extension=pdo_sqlite
;extension=pgsql
;extension=shmop
;extension=php_gd2.dll

A: For those who still have the error, and it isn't dissapearing (it happened to me after trying everything).
I did the following:
1. Check that the "extension_dir" in "php.ini" is refering to the extension dir
"*/xamp/php/ext"
2. In the same file "php.ini" search for "extension=exif" (the one that says "Must be after mbstring as it depends on it") and under it place -> "extension=php_mysqli.dll"
After that, check that you don't have any "php_mysqli.dll" duplicated in all those extensions, if so, just comment it placing ";" in front of it.
3. After that, go to "*\xamp\phpMyAdmin\config.inc.php" and where it says:
/* Authentication type and info */ put the same login you used when creating the localhost user -> (usually) "['user'] = 'root';"  ['password'] = 'thePasswordYouUsed';
// I don't know if this  is necessary but I just deleted the "mnb" or something like that
that was appearing in "/* User for advanced features */" "['controluser']" = '';
now I have it like that -> "['controluser']" = '';"
4. After that, open your xamp control panel, stop apache service, wait, and start it again.
5. Then open a new navigator tab and go to your "localhost/phpmyadmin", in my case it is -> "http://localhost:8080/phpmyadmin/" (I previously changed the port from 80 to 8080 in the configuration files, because the port 80 was already being used)

Hope it worked for you. I'm not a pro in this things but I just persisted in trying to solve my problem, searching and searching until I found the way for me to work.
When I finnaly solved it, I wanted to share my experience, because I appreciate a lot when people do this and I can get benefit from it. So I decided to take a moment and give back to the community! ^^


text:
Q: What to parameter value from returning url in php I have a client url[www.mysite.com/page.aspx]
when we put this url in browser then it revert the automatically
with this url

[www.mysite.com/page.aspx?|&CC=121&DD=123&AA=323|&CC=321&DD=555&AA=000]

Now we want to fetch that parameter value in php page through php or jquery.
Kindly Help and give the best suggestions.

A: You can simply use GET
$cc = $_GET['CC'];
$dd = $_GET['DD'];

A: You can access those values using $_REQUEST or $_GET


text: Q: Cannot detect my AVD comes online I recently upgraded my SDK for my AVD and the files seems corrupted. It takes forever to say "waiting for target device to come online" even if my device already online. I tried that on my actual phone and saw the same issue. I tried delete and recreated the AVD, reinstall API 27 but still couldn't solve the problem. But I believe it shouldn't be the problem of my AVD because my actual phone shows the same problem as well.