text:
Q: How do I replace a function, declared inside a plugin's class, in functions.php? I want to modify a function in a plugin. It is declared in the plugin's main file like this:
class WCPGSK_Main {
  ...
  public function wcpgsk_email_after_order_table($order) {
    ...
  }
}

Add called from there like this:
add_action( 'woocommerce_email_after_order_table', array($this, 'wcpgsk_email_after_order_table') );

I guess it would be possible to replace it if had an access to the class in functions.php. Then I would be able to write something like this:
$wcpgsk = new WCPGSK_Main;

remove_action( 'woocommerce_email_after_order_table', array($wcpgsk, 'wcpgsk_email_after_order_table') );

function customized_wcpgsk_email_after_order_table($order) {
  ...
}
add_action( 'woocommerce_email_after_order_table', array($wcpgsk, 'customized_wcpgsk_email_after_order_table') );

My thought to get an access to the class in the functions.php file was to include the file where the class is declared in functions.php:
require_once('/wp-content/plugins/woocommerce-poor-guys-swiss-knife/woocommerce-poor-guys-swiss-knife.php');
$wcpgsk = new WCPGSK_Main;
...

But this does not work because the plugin's file is included when the plugin is getting initialized in WordPress, I guess.
Is there a way to rewrite the function without touching plugin's files?

A: This should work:
add_action( 'woocommerce_init', 'remove_wcpgsk_email_order_table' );
function remove_wcpgsk_email_order_table() {

    global $wcpgsk;
    remove_action( 'woocommerce_email_after_order_table', array( $wcpgsk, 'wcpgsk_email_after_order_table' ) );

}

A: If your plugin is registered like this:
class Test_Class_Parent {
  function __construct() {
    add_action('wp_head',array($this,'test_method'));
  }

  function test_method() {
    echo 'Echoed from the parent';
  }
}
$p = new Test_Class_Parent();

Then you should be able to remove the filter by accessing the global:
class Test_Class_Child extends Test_Class_Parent {
  function __construct() {
    $this->unregister_parent_hook();
    add_action('wp_head',array($this,'test_method'));
  }

  function unregister_parent_hook() {
    global $p;
    remove_action('wp_head',array($p,'test_method'));
  }

  function test_method() {
    echo 'Echoed from the child';
  }
}
$c = new Test_Class_Child();

Otherwise, you will need to crawl the $wp_filter global for the registration key:
class Test_Class_Child extends Test_Class_Parent {
  function __construct() {
    $this->unregister_parent_hook();
    add_action('wp_head',array($this,'test_method'));
  }

  function unregister_parent_hook() {
    global $wp_filter;
    if (!empty($wp_filter['wp_head'])) {
      foreach($wp_filter['wp_head'] as $cb) {
        foreach ($cb as $k => $v) {
          if (
            isset($v['function'])
            && is_a($v['function'][0],'Test_Class_Parent')
            && isset($v['function'][1])
            && 'test_method' == $v['function'][1]
          ) {
            remove_action('wp_head',$k);
          }
        }
      }
    }
  }

  function test_method() {
    echo 'Echoed from the child';
  }
}
$c = new Test_Class_Child();

This is resource intensive and should really not be done unless you have no other choice.

A: That plugin makes its init function wcpgsk_init() pluggable, so another way to override it is to define it first in a must-use plugin (as it's too late in your theme's "functions.php"). So you could put your override in "wp-content/mu-plugins/functions.php":
function wcpgsk_init() {
    global $wcpgsk, $wcpgsk_about, $wcpgsk_options, $wcpgsk_session, $wcpgsk_woocommerce_active;
    //only continue loading
    if ( $wcpgsk_woocommerce_active && version_compare( WOOCOMMERCE_VERSION, "2.0" ) >= 0 ) {
        $FILE = WP_PLUGIN_DIR . '/woocommerce-poor-guys-swiss-knife/woocommerce-poor-guys-swiss-knife.php'; // Fake __FILE__
        $dirname = dirname( $FILE ) . '/';
        $wcpgsk_options = get_option('wcpgsk_settings', true);
        require_once( $dirname . 'classes/woocommerce-poor-guys-swiss-knife.php' );
        require_once( $dirname . 'classes/woocommerce-poor-guys-swiss-knife-about.php' );
        require_once( $dirname . 'wcpgsk-af.php' );

        if ( !is_admin() ) :
            add_action( 'plugins_loaded', 'wcpgsk_load_wcsession_helper' );
        endif;

        // Your override.
        class My_WCPGSK_Main extends WCPGSK_Main {
            public function wcpgsk_email_after_order_table($order) {
                echo "O la la";
            }
        }
        define( 'WCRGSK_DOMAIN', WCPGSK_DOMAIN ); // Fix typo! (WooCommerce Rich Guys Swiss Knife?)

        //load into our global
        $wcpgsk = new My_WCPGSK_Main( $FILE );
        $wcpgsk->version = '2.2.4';
        $wcpgsk->wcpgsk_hook_woocommerce_filters();

    } elseif ( version_compare( WOOCOMMERCE_VERSION, "2.0" ) < 0 ) {
        add_action( 'admin_notices', 'wcpgsk_woocommerce_version_message', 0 ) ;
        return;
    } else {
        return;
    }
}

But an even better way to override it is to install runkit (https://github.com/padraic/runkit) and then just replace it directly in your theme's "functions.php":
add_action( 'init', function () {
    $code = <<<'EOD'
echo "O la la";
EOD;
    runkit_method_redefine(
        'WCPGSK_Main',
        'wcpgsk_email_after_order_table',
        '$order',
        $code,
        RUNKIT_ACC_PUBLIC
    );
} );

(That's a joke, btw.)


text:
Q: Customizing ui-icon arrow of listview items I want to use my own image of arrow for items in listview. Where and how I should change jquery mobile default grey circle arrow? Should I override jquery css classes? I'm using jquery-mobile 1.1.0RC.
There's my html code for list items:

And there's my javascript code, there I'm dynamically adding list items:
var ap = "

"+
    ""+
"
Big text
"+
"
Smaller text
"+
"
 </span</div
";

$('#list_id').append(ap);
$('#list_id').listview('refresh');

As you can see I've tried to change data-icon attribute to my own image source, but it doesn't work. Sorry if question is too obvious, I'm newbie on css and jquery framework, so any help will be appreciated. Thanks!

A:
To use custom icons, specify a data-icon value that has a unique name
  like myapp-email and the button plugin will generate a class by
  prefixing ui-icon- to the data-icon value and apply it to the button:
  ui-icon-myapp-email.
You can then write a CSS rule in your stylesheet that targets the
  ui-icon-myapp-email class to specify the icon background source. To
  maintain visual consistency with the rest of the icons, create a white
  icon 18x18 pixels saved as a PNG-8 with alpha transparency.
In this example, we're just pointing to a standalone icon image, but
  you could just as easily use an icon sprite and specify the
  positioning instead, just like the icon sprite we use in the
  framework.
.ui-icon-myapp-email {
  background-image: url("app-icon-email.png");
}

Yeah check out my copy and paste skills. http://jquerymobile.com/test/docs/buttons/buttons-icons.html

A: You can either create a new class that uses your custom image and apply it to all the elements within the mobile site that will use it.
Or replace the jQuery icon image itself, I believe they're in a directory called images.
If you're still stuck after that, try reading this easy to follow tutorial by Andy Matthews.:)

redpajama_set_name: RedPajamaStackExchange


text:
Q: IE7 Responsive Image Glitch So this is a weird one.
I'm working on a Wordpress theme, and the theme is supposed to be fully responsive. I created a "gallery" of sorts that consists of multiple rows of 3 thumbnails that when clicked open in a lightbox.  I found a snippet of code online for creating responsive "square" elements; elements whose height adjusts to match their responsive width using only CSS.  This involves setting a width in percentage (say 50%), and then setting height:0px; and padding-bottom:50%;.  I went ahead and placed every image in a responsive container that resize like this, and then I set the images max width and max height so they wouldn't overflow their responsive square container.
This displays as expected in all browsers save for ie7.  In ie7, the image seems to disappear.  I've attached a fiddle (not my exact code, but still causes the issue). http://jsfiddle.net/pwGYc/
Here's the actual code:
HTML:
<a href="<? echo $photo["url"]; ?>" class="photo" title="<? echo $photo["title"]; ?>">
    <img src="<? echo $photo["url"]; ?>" alt="<? echo $photo["alt"]; ?>" title="<? echo $photo["title"]; ?>" />

CSS:
.photo{
float:left;
margin:10px;
width:30%;
height:0px;
overflow:hidden;
padding:5px 0px 30% 0px !important;
box-sizing:border-box;
position:relative;
}

.photo img{
position:absolute;
top:0px;
bottom:0px;
left:0px;
right:0px;
margin:auto;
max-height:97%;
max-width:97%;
}

A: IE7 doesn't support border-box.
And you can not mix percents with absolute px values. So don't do width 30% and margin 10px. What's this in sum? 3 x 30% + 3 x 10px = maybe 1422px?
If you say margin 3% you can be sure of 3 x 30% + 3 x 3% = 99%


text:
Q: Find and Replace don't work in any JetBrains tools Find and replace features don't work in some of JetBrains tools. If I press Ctrl + F or Ctrl + R, special bar for searching/replacing opens, but cursor doesn't appear in a search field (cursor doesn't focus on the search field, instead remains in a code editing field). If I try to press on search field, nothing happens, cursor remains in the code field.

Problem occurs in the following tools:

*

*CLion 2018.1.2

*IDEA Ultimate 2018.1.3

*PhpStorm 2018.1.2

*PyCharm Professional 2018.1.2

All tools were installed via JetBrains Toolbox.


text:
Q: Powershell read csv file, reformat into multiple lines, write to a csv file Very new to powershell.  I want to create a powershell script that will read a csv file with lines that look like this:
6120137650,6/22/2020,,304066,267.98,,6/26/2020
6120208098,6/22/2020,,304329,230.54,,6/26/2020

Then create a new csv file that has three lines for each of the input lines, that look like this.  Anything added to the lines that was not in the input is constant.
*,CHR00,6120137650,6/22/2020,,304066,30,267.98,,6/26/2020
CHR00,6120137650,2001-00,P,-267.98
CHR00,6120137650,FRT OUT,R,267.98
*,CHR00,6120208098,6/22/2020,,304329,30,230.54,,6/26/2020
CHR00,6120208098,2001-00,P,-230.54
CHR00,6120208098,FRT OUT,R,230.54

So for each input line:

*

*Write an output line that adds *,CHR00, then everything from the input line.

*Write an output line with CHR00 followed by field 1 of input line, followed by 2001-00, followed by P, followed by field negative of field 5 of input line.

*Write an output line with CHR00 followed by field 1 of input line, followed by FRT OUT, folowed by R, folwed by field 5 of input line.

A: Because you want an outputfile that is not a true CSV file, I think in this case you could simply iterate over the lines in the input file and output the newly constructed lines like this:
$inputFile  = 'D:\Test\input.csv'
$outputFile = 'D:\Test\output.txt'

Get-Content -Path $inputFile | ForEach-Object {
    # output the original line with '*,CHR00,' prepended
    "*,CHR00,$_"
    $fields = $_ -split ','

    # output second line
    $num = -[double]$fields[4]
    'CHR00,{0},2001-00,P,{1}' -f $fields[0], $num.ToString("F2", [CultureInfo]::InvariantCulture)

    # output third line
    'CHR00,{0},FRT OUT,R,{1}' -f $fields[0], $fields[4]
} | Set-Content -Path $outputFile

-f is the PowerShell Format operator


text:
Q: Anonfiles api? Webrequest https://anonfiles.com/api/help
i want to use there api but i don't know how webrequests work.:S
i have never done webreq before i have tried this and many other things can i get some help here?
  ' Create a request using a URL that can receive a post.
    Dim request As WebRequest = WebRequest.Create("https://anonfiles.com/api/")
    ' Set the Method property of the request to POST.
    request.Method = "POST"
    ' Create POST data and convert it to a byte array.
    Dim postData As String = "file=C:\Users\blaa\Documents\eng.txt"
    Dim byteArray As Byte() = Encoding.UTF8.GetBytes(postData)
    ' Set the ContentType property of the WebRequest.
    request.ContentType = "application/x-www-form-urlencoded"
    ' Set the ContentLength property of the WebRequest.
    request.ContentLength = byteArray.Length
    ' Get the request stream.
    Dim dataStream As Stream = request.GetRequestStream()
    ' Write the data to the request stream.
    dataStream.Write(byteArray, 0, byteArray.Length)
    ' Close the Stream object.
    dataStream.Close()
    ' Get the response.
    Dim response As WebResponse = request.GetResponse()
    ' Display the status.
    Console.WriteLine(CType(response, HttpWebResponse).StatusDescription)
    ' Get the stream containing content returned by the server.
    dataStream = response.GetResponseStream()
    ' Open the stream using a StreamReader for easy access.
    Dim reader As New StreamReader(dataStream)
    ' Read the content.
    Dim responseFromServer As String = reader.ReadToEnd()
    ' Display the content.
    MsgBox(responseFromServer)

    ' Clean up the streams.
    reader.Close()
    dataStream.Close()
    response.Close()

A: You could try this, it's a bit easier:

    Dim WithEvents client As New System.Net.WebClient()

    Public Sub StartUpload(ByVal targetUrl As String, ByVal filename As String)

        Dim uriString As New System.Uri(targetUrl)
        client.UploadFileAsync(uriString, filename)

    End Sub

    Sub FileUploadCompleted(ByVal sender As Object, ByVal e As System.Net.UploadFileCompletedEventArgs) Handles client.UploadFileCompleted
        Dim response As String = System.Text.Encoding.ASCII.GetString(e.Result)

        ' further process your response string
    End Sub

    Sub Main()

        Try
            StartUpload("https://anonfiles.com/api", "D:\index.html")

            Console.ReadKey()

        Catch ex As Exception
            Console.WriteLine(ex.Message)
            Console.ReadKey()

        End Try

    End Sub


text:
Q: R: Clustering - how to predict new cases? I have 4000 (continuous) predictor variables in a set of 150 patients.
First, variables with are associated with survival should be identified. I therefore use the multiple testing procedures function (http://svitsrv25.epfl.ch/R-doc/library/multtest/html/MTP.html) with the t-statistic for tests of regression coefficients in Cox proportional hazards survival models to identify significant predictors. This analysis identifies 60 parameters which are significantly associated with survival. I then perform unsupervised k-means clustering with the ConensusClusterPlus package (https://www.bioconductor.org/packages/release/bioc/html/ConsensusClusterPlus.html) which identifies 3 clusters as the optimal solution based on the CDF curve & progression graph. If I then perform a Kaplan-Meier survival analysis I see that each of the three clusters is associated with a distinct survival pattern (low / intermediate / long survival).
The question that I now have is the following:
Lets assume that I have another set of 50 patients where I´d like to predict to which of the three clusters each patient most likely belongs to. How can I achieve this? Do I need to train a classifier (e.g. with the caret-package (topepo.github.io/caret/bytag.html) where the 150 patients with the 60 significant parameters are in the training set and the algorithm knows which patient was allocated to which of the three clusters) and validate the classifier in the 50 new patients? And then perform Kaplan-Meier survival analysis to see whether the predicted clusters in the validation set (n=50) are again associated with a a distinct survival pattern?
Thanks for your help.

A: The answer is much simpler. You do have your k-means, with 3 clusters. Each cluster is identified by its centroid (a point in your 60-dimensional space). In order to "classify" new point you just measure the euclidean distance to each of these three centroids, and select cluster which is the closest one. That's all. It comes directly from the fact, that k-means gives you partitioning of the whole space, not just your training set.

A: My advice is to create a predictive model, such as random forest, using the cluster number as the outcome. It will lead to better results than predicting using the distances in the cluster.
The reasons are several, but consider that a predictive model is specialized in such a task, for example, it will keep and consider reliable variables (while in the cluster every variable will account the same).


text:
Q: What is the difference between iCloud Photo Library and My Photo Stream In my iPhone settings I have both set ON. What is the difference if I turn one or the other off?i

A: iCloud Photo Library puts all your images in the cloud, allowing access from any device you are signed into. It requires enough space on iCloud to store all of your photos.
Photo Stream just shares your new photos with your other device, but they aren't actually in the cloud. This doesn't require you to have enough storage space for your photos.


text:
Q: Marionette App not starting and there's no error! What went wrong? I was trying out David Sulc's gentle intro to Marionette.js (Backbone.js) In almost the very first exercise, I encounter a strange problem. When i run the code in chrome or firefox,i see no error in console but apparently the application has not yet started (otherwise, the text rendered by marionette should have been visible). Similarly, the "console.log" command is showing no response in the console window. Console is absolutely blank. no errors, no warnings. please help.
Here's the code. Please let me know what exactly I'm doing wrong.
<!DOCTYPE html>

    <meta charset="utf-8" >
    <title>Marionette Test Contacts</title>
    <link rel="stylesheet" href="assets/css/bootstrap.css" />
    <link rel="stylesheet" href="assets/css/application.css" />

                Contact manager

Content to hide when app starts.

A: I believe that you are mixing up the syntax for two different versions of Marionette.
If you're using start(), try:
ContactManager.on("start", function(){});

According to the docs, events are:

*

*"before:start" / onBeforeStart: fired just before the Application    starts and before the initializers are executed.

*"start" / onStart:    fires after the Application has started and after the initializers    have been executed.

https://github.com/marionettejs/backbone.marionette/blob/master/docs/marionette.application.md


text:
Q: vim todolist without clear screen I use TODO word in a comment as todolist item
" TODO this is a todolist item

and I show the items with
nn <silent><leader>tl :grep --exclude=*~ TODO % <CR> :copen <CR>

but with the first part of command (the grep section), vim clear the screen, this is very ugly.
how I can send the grep output to background and only display the copen window ?

A: Use :vimgrep instead of :grep.
:grep uses an external program, that's why it's "suspending" Vim. :vimgrep is an internal feature and, as such, doesn't "suspend" Vim.
:vimgrep can be slower than :grep when dealing with large numbers of files but it shouldn't be a problem in your case.
Did you consider /TODO<CR>?


text:
Q: Neo4j 2.0.1 enterprise edition: Performance issue I was happily using neo4j 1.8.1 community edition for a while on my system with the following configuration.
System Specs:

*

*OS: 32-bit Ubuntu 12.04.3 LTS. Kernel version 3.2.0-52-generic-pae #78-Ubuntu

*Memory: 4GB

*Swap: 8GB (swapfile - not a partition)

*Processor: Intel® Core™ i5-2430M CPU @ 2.40GHz - Quad Core

*Harddisk: 500GB Seagate ATA ST9500420AS. Dual boot - Ubuntu uses 100GB and the rest by the almighty Windows 7.

When I switched to neo4j 2.0.1 enterprise edition, my application's response time became 4x slower. So, as advised in http://docs.neo4j.org/chunked/stable/embedded-configuration.html, I started tuning my filesystem, virtual memory, I/O-schedular and JVM configurations.
Performance Tuning

*

*Started Neo4j as a server with highest scheduling priority (nice value = -20)

*Set vm.dirty_background_ratio=50 and vm.dirty_ratio=80 in /etc/sysctl.conf to reduce frequent flushing of dirty memory pages to disk.

*Increased maximum number of open files from 1024 to 40,000 as suggested in Neo4j startup.

*Set noatime,nodiratime for the neo4j ext4 partition in /etc/fstab so that inodes don't get updated every time there is a file/directory access.

*Changed I/O scheular to "noop" from "cfq" as mentioned in
http://www.cyberciti.biz/faq/linux-change-io-scheduler-for-harddisk/

*JVM parameters: In short, max heap size is 1GB and neostore memory mapped files size is 425 MB.
Xms and Xmx to 1GB.
   GC to Concurrent-Mark-Sweep.
   neostore.nodestore.db.mapped_memory=25M,
   neostore.relationshipstore.db.mapped_memory=50M
   neostore.propertystore.db.mapped_memory=90M
   neostore.propertystore.db.strings.mapped_memory=130M
   neostore.propertystore.db.arrays.mapped_memory=130M
Sadly, this didn't make any difference. I wrote a simple script which creates N nodes and M random relationships among these nodes to get a better picture.
Neo4j 1.8.1 community edition with oracle java version "1.6.0_45":
new-sys-admin@ThinkPad:~/temp$ php perftest.php
Creating 1000 Nodes with index
Time taken : 67.02s

Creating 4000 relationships
Time taken : 201.27s

Neo4j 2.0.1 enterprise edition with oracle java version "1.7.0_51":
new-sys-admin@ThinkPad:~/temp$ php perftest.php
Creating 1000 Nodes with index
Time taken : 75.14s

Creating 4000 relationships
Time taken : 206.52s

The above results are after 2 warm-up runs. 2.0.1 results seem slower than 1.8.1. Any suggestions on adjusting the relevant configurations to boost up neo4j 2.0.1 performance would be highly appreciated.
EDIT 1
All queries are issued using Gremlin via Everyman Neo4j wrapper.
http://grokbase.com/p/gg/neo4j/143w1fen8c/gremlin-plugin-extremely-slow-on-neo4j-2-0-1
In the mean time, I moved to neo4j-enterprise-edition-1.9.6 (the next recent stable release before 2.0.1) and things were back to Normal

A: From the fact that you're using PHP, and seeing that creating just a 1000 nodes is 67 seconds, I assume you're using the regular REST API (eg. POST /db/data/node). If this is correct, you may be right that 2.0.1 is some percentage point slower than 1.8 for these CRUD operations. In 2.0 we focused on optimizing Cypher and the new transactional endpoint.
As such, for best performance, I'd suggest these things:

*

*Use the new transactional endpoint, /db/data/transaction

*Use cypher, and use it to send as much work as possible in "one go" over to the server

*When possible, send multiple cypher queries in the same HTTP request, you can do this as well through the transactional endpoint.

*Make sure you re-use TCP connections if you can, I'm not sure exactly how this works in PHP, but sending "Connection: Keep-alive" header and ensuring you re-use the same tcp connection saves significant overhead, since you don't have to re-establish TCP connections over and over.
Creating a thousand nodes in one cypher query shouldn't take more than a few milliseconds. In terms of how many cypher statements you can send per second, on my laptop and from python (using https://github.com/jakewins/neo4jdb-python), I get about 10 000 cypher statements per second in a concurrent setup (10 clients).


text:
Q: Xcode 4.1 - Archiving app gives me Entitlments.plist error I am using Xcode 4.1 and MacOSX Lion 10.7. I am trying to archive my Mac app so I can upload my app to iTunes connect but it gives me this error:
ProcessProductPackaging /Developer/Platforms/MacOSX.platform/Entitlements.plist /Users/username/Library/Developer/Xcode/DerivedData/appname/Build/Intermediates/appname.build/Debug/appname.build/appname.xcent
    cd "/Volumes/Apps/iOS/Mac app store/appname"
    builtin-productPackagingUtility /Developer/Platforms/MacOSX.platform/Entitlements.plist -entitlements -format xml -o /Users/username/Library/Developer/Xcode/DerivedData/appname/Build/Intermediates/appname.build/Debug/appname.build/appname.xcent
error: error reading property list '/Developer/Platforms/MacOSX.platform/Entitlements.plist' - property list has no object
Command builtin-productPackagingUtility failed with exit code 1
This error does not occur if I don't sign the code. I was able to submit my apps properly before upgrading to Xcode 4.1. I can't seem to find any documentation on how to sign an app in xcode 4 and I have no idea what the new Enable entitlements and sandbox does.
When I somehow get it to work, I get this email from iTunes connect with the following error:
Invalid Code Signing Entitlements - The entitlements in your app bundle signature do not match the ones that are contained in the provisioning profile:
According to the provisioning profile, the bundle contains a key value that is not allowed: "appname" for the key "com.apple.application-identifier" in appname.app/Contents/MacOS/appname
What do I need to do to properly submit my app to iTunes connect?

A: Turns out, there is an issue with packaging apps if you are using a new Macbook manufactured after June of 2010. To package your app, follow these steps:
1) Build and Archive
2) Open the Organizer - Archives, find the new archive.
3) Right-click the archive "Show in Finder"
4) Right-click the archive in the finder to "Show Package Contents"
5) drill down to your app (>Products/Applications/YourApp)
6) Right-click your app, "Show Package Contents"
7) Delete the _CodeSignature directory
8) Edit Info.plist
 a) Change BuildMachineOSBuild to "11A511"

 b) Save, close

9) Go back to the Products/Applications/YourApp directory in the finder
10) Open Keychain Access.app
 a) Find your certificate "3rd Party Mac Developer Application: Your Name"

 b) double click to inspect it

 c) Copy the full Common Name "3rd Party Mac Developer Application: Your Name"

11) Open a terminal and enter the following:
 codesign -s "<paste your cert common name here>" -fv <drag the archived app from the finder to the terminal window here>

12) verify the output:
 "...path to app...: replacing invalid existing signature"

 "...path to app...: signed bundle with Mach-O universal (i386 x86_64)"

13) Close all them windows.
14) Open the Organizer - Archives in XCode
15) Validate... yep.
16) Submit... yay!

A: This method actually worked for me too!
This was my error, iTunes Connect kept kicking it out, not rejecting...just almost instant kick-out.
So anyway...this method worked for me!  now app is sitting In Review.  As he said Yay!

Invalid Code Signing Entitlements - Your application bundle's signature contains code signing entitlements that are not supported on Mac OS X;
this may happen if your Mac OS X project was ported from iOS.
Please check your Xcode project's code signing entitlements configuration, and remove any unneeded entitlements.
Specifically, key "keychain-access-groups" in [YourAppName] is not supported.
Invalid Code Signing Entitlements - Your application bundle's signature contains code signing entitlements that are not supported on Mac OS X;
this may happen if your Mac OS X project was ported from iOS.
Please check your Xcode project's code signing entitlements configuration, and remove any unneeded entitlements.
Specifically, key "application-identifier" in [YourAppName] is not supported.

Just want to add in there...that I also had a black MacBook, that was manufactured BEFORE 2010...I still went ahead and added the key "BuildMachineOSBuild to "11A511" like the instructions said.  :)


text:
Q: How to turn hundreds of text URLs in Excel into clickable hyperlinks? How do I turn a column of urls into hyperlinks, so that users can click on the url in a cell and have it open in a browser?
I pasted 100 urls and each went into its own cell. When I double-click in the cell and then leave it, Excel turns the text blue and makes a link out of it. I don't want to double-click a hundred times, but still want to format all the cells into links.

A: Hard to believe there isn't an optional setting to tell Excel to treat URLs as live links. After all Outlook automatically does this.  But then again - this is a Microsoft product, sigh.
I have a column of links in Excel. I selected the column and pasted it into an email to myself.  When I got the mail (Excel column still selected) I pasted the live links back into the column.  Done!
Alternatively, you could save the email as a draft and open the saved draft again. There's no need to actually send and receive the email.

A: From here: Convert URLs to Clickable Links In Excel
Public Sub Convert_To_Hyperlinks()
  Dim Cell As Range
  For Each Cell In Intersect(Selection, ActiveSheet.UsedRange)
    If Cell <> "" Then
      ActiveSheet.Hyperlinks.Add Cell, Cell.Value
    End If
  Next
End Sub

Creating the Macro

*

*Open your Excel doc

*Open the macro editor by pressing ALT+F11.

*In the Tools Menu, left-click View and select Project Explorer.

*Look for the folder called 'Modules', right-click it, select 'Insert', then select 'Module'.

*Paste the code into the project module you have selected.

*Press ALT+F11 to return to your Excel workbook (or click on its icon in the Windows taskbar).

Run the Macro

*

*To execute the macro, select the unclickable text links you want to convert to clickable hyperlinks.

*Press ALT+F8 to open the Macro selector window and click on the macro you just created.

*Your Links are now all Clickable! Saving you time and data entry fatigue :)

A: The function in Excel for doing a hyperlink is =Hyperlink("http://www.techonthenet.com","Tech on the Net") where "http://www.techonthenet.com" is the internet address and "Tech on the Net" is the title that appears in the Excel cell.
Thus when you are writing the urls into the Excel file just wrap this function around each url. If you don't want to come up with a dynamic name you can always put the url as the name too.
If you aren't inserting the values programmatically then this site mentions using the HYPERLINK worksheet function. Though a even better reference is this which walks you through how to add a macro to excel and they supply the code for the macro. Thus when after you add this macro you can select the column of urls and run the macro and it converts the whole column into hyperlinks

A: The easy way to do this is simply save the Excel file as an HTML page. Then reopen the HTML page in Excel and the links will be clikable.
UPDATE
Sometimes this does not work. But this seems to always work. Right click selected column URLs are located in. Then Click Hyperlink, then click "Place in this Document" This seems to always work

A: The following will create clickable links in one formula
=CONCAT("<",HYPERLINK(M28,M28),">")

If you want to overwrite the formula and clean up the <> then:
Copy and paste over the formula with the value.
use Ctrl+H to replace < and > individually with nothing.

A: Kyra's answer points you here which essentialy gives you this, and was a good direction. Allows you to do a large selection as you request and will convert them all.
Sub addHypers()

For Each cell In Intersect(Selection, ActiveSheet.UsedRange)
    If cell <> "" Then
    ActiveSheet.Hyperlinks.Add cell, "http://" + cell.Value
    End If
    Next cell
End Sub

Sub removeHypers()
Intersect(Selection, ActiveSheet.UsedRange).Hyperlinks.Delete
End Sub

A: See how to convert url text to clickable hyperlink in Excel  for easy how-to instructions.
In Excel, click on the column you want to convert to clickable hyperlinks.
Follow the first option: Convert URL text to clickable hyperlink with VBA code
Go through the steps and after you've pressed F5, close the Microsoft Visual Basic application to return to your Excel file. Your URLs will now be clickable!

A: In newer versions of Excel (2018 onwards), just open up the "Styles" dropdown in the Home menu bar and select "hyperlink" as the style. This will format a text hyperlink as a clickable hyperlink for the range you have selected.

A: The answer by Niall Flynn above (dated 6-Jan-2012, edited by nixda), is indeed the superior way to convert text to hyperlinks. In Excel 2016, the set up is different. Based on N. Flynn's answer, for the benefit of those who are not familiar with creating macros in VBA, the procedure is as follows:
To create the macro

*

*Enter the VBA macro editor via Alt+F11

*In the View menu, select Project Explorer

*Right-click the worksheet to be modified (under Microsoft Excel Objects)

*Select Insert, then select Module

*Paste in the code provided in N. Flynn's answer

*Alt+F11 to return to the Excel workbook

To run the macro:

*

*Select the text that is to be converted

*Go to the View menu, select Macros

*Select View Macros

*Run the new macro that appears (Convert_To_Hyperlinks)

A: If you don't want to make a macro and as long as you don't mind an additional column, then just create a new column alongside your column of URLs.
In the new column type in the formula =HYPERLINK(A1) (replacing A1 with whatever cell you are interested in). Then copy the formula down the rest of the entries.


text:
Q: React client side componentDidMount not working properly (server side rendering) Hello Stackoverflow community
sorry in advance if my explanation is not clear enough
when a user types a url directly. the server makes a request, fetch the corresponding data and renders to screen. and this works perfectly
when a user clicks on a link, the page is suppose to switch and render new component and fetch corresponding data from server via componentDidMount and save to state but for some reason the data does not appear on page
when i run the code below, console.log('2') comes before console.log('1') meaning that state is first rendered undefined before populated with fetched data
it looks like a async problem but i dont know my way around it and this should not be the case because it works on normal client side applications
but even though the order of events is distorted the app should re-render when state change which does not happen.
News.js
import React from 'react';
import NewsList from './newslist';
import 'es6-promise'
import 'isomorphic-fetch';

class News extends React.Component {
  constructor(props){
    super(props)

    let initialData;

    if(props.staticContext){
      initialData = props.staticContext.initialData

    } else if (typeof window !== 'undefined') {
      initialData = window.__initialData__
      delete window.__initialData__
    }

    this.state = {news: initialData }
  }

  componentDidMount() {
    News.requestInitialData().then(data => {
      console.log('1 ' + data)                           <------- console log 1
    return this.setState({ news: data })
    });
    console.log('2 ' + this.state)                       <------- console log 2
  }

  static requestInitialData() {
    return fetch('http://localhost:3000/api/data')
    .then(response => response.json())
    .catch(err => console.log(err))
  }

  render() {
    return (

        <NewsList news={this.state.news} />

    );
  }
}

module.exports = News

NewsList.js
import React, { Component } from "react";

export default class NewsList extends Component {
  constructor(props){
    super(props)

    // const data = (this.props.news) ? this.props.news : '';
    this.state = {news : this.props.news,
                  sortOrder: 'ascending'}
  }

  sortOrder(order, event) {
    event.preventDefault();
    const data = Object.assign([], this.state.news)
    let data2;

    if (order === 'ascending') {
      data.sort( (a,b) => a.id - b.id )
      data2 = 'ascending'
    }
    else if (order === 'descending') {
      data.sort( (a,b) => b.id - a.id )
      data2 = 'descending'
    }

    this.setState({
      news: data,
      sortOrder: data2
    });
  }

  render() {
    const news = this.state.news

    return (

              Ascending
            |

              Date

        {news && news.map(post =>

                {post.id}. ▲ {post.title}{" "}
                (by {post.author})

                {post.upvotes} upvotes

        )}

    );
  }
}

thanks in advance for your help

A: You code looks fine. The following is happening:
In componentDidMount you request initial data. This is async operation meaning that componentDidMount will finish without waiting for it to complete and console.log('2 ' + this.state) will be executed, and after that initial render will be called without any data present.
Then requestInitialData gets completed and you see console.log('1 ' + data) logged. After that you update state (note that setState is also async) and News gets rendered again with data.
The reason for ui not being updated could be that NewsList implement shouldComponentUpdate and do not re-render itself upon some conditions.
I would suggest put logging inside render methods for both News and NewsList and see how they get called. And that you do fetch data from requestInitialData method.


text:
Q: How to use WebView to detect dynamic html updates? Trying to monitor and control some projectors, each with a web server built in. The status of the projectors is updated to a page dynamically through javascript.
I managed to retrieve the html and zero in on the status I was looking for using a WebView object. However, when the status changes, I will need to refresh my values, but I can't' seem to find any event that would detect such changes.
For example, when I first access the power on/off status, it's shown as Unknown and won't be updated to on/off until several seconds after the - (void)webView:(WebView *)sender didFinishLoadForFrame:(WebFrame *)frame event.
I can setup a timer to poll the values, but I would prefer to have it trigger by some sort of an event (or observe any value change). Are there such events? I looked in into WebView, WebFrame, but can't seem to find any.
Or is there a way to observe a javascript variable? The values I'm looking for are stored in javascript variables.
Or perhaps any other ways to do this?

A: If you can find any JS hooks / dom events that are fired when your content changes you can open a URL with a custom scheme (e.g. "refresh://content") from JS and implement the webView:shouldStartLoadWithRequest:navigationType: in which you can check the scheme.
If you can't find any proper events you should really just poll the JS variable values every 5-10 seconds via [webView stringByEvaluatingJavaScriptFromString:@"js_variable_name"]

A: If you are not in control of the JavaScript I doubt you can raise an event in response to an AJAX call. I guess you'll have to periodically look for changes using NSTimer scheduledTimerWithTimeInterval:. Example, to get the value of varName run the following:
NSString *value = [webView stringByEvaluatingJavaScriptFromString:@"varName"];


text:
Q: How to fix 500 internal server error while using Django and React I'm trying to create a simple shopping cart with django and react. When I click on the add-to-cart button I get 500 Internal Server Error from react. The error it's displaying in django is:
ValueError: Cannot assign "<django.contrib.auth.models.AnonymousUser object at 0x00000268F76AEFA0>": "order_product.user" must be a "User" instance. I have tried every means I know but I'm still not able to fix it. Below is the programme:
DJANGO
urls.py
path('add-to-cart/', add_to_cart_view.as_view(), name='add-to-cart'),
views.py

class add_to_cart_view(APIView):
    permission_classes = []
    def post(self, request, *args, **kwargs):
        id = request.data.get('id', None)
        if id is None:
            return Response({"message": "Invalid request"}, status=HTTP_400_BAD_REQUEST)

        product = get_object_or_404(Product, id=id)

        requested_product = order_product.objects.create(
                product=product,
                user=request.user,
                ordered=False
            )

        order_qs = Order.objects.filter(user=request.user, ordered=False)
        if order_qs.exists():
            order = order_qs[0]
            if not order.products.filter(product__id=requested_product.id).exists():
                order.products.add(requested_product)

                return Response(status=HTTP_200_OK)

        else:
            ordered_date = timezone.now()
            order = Order.objects.create(
            user=request.user, ordered_date=ordered_date)
            order.products.add(order_product)
            return Response(status=HTTP_200_OK)

REACT
export const AddToCartURL = "http://127.0.0.1:8000";

const handleAddToCartURL = async (id) => {
            try {
                const res = await axios.post(`${AddToCartURL}/add-to-cart/`, {id});
                setProduct(res.data);
                console.log(res.data)
            }
            catch (err) {

            }
        };

    return(
        <Box sx={{ flexGrow: 1 }} m={4}>
            <Grid container spacing={3}>
                <Grid item xs={9}>
                    <Item>

{product.description}

{product.label}

{product.price}

                       <button color='primary' onClick={() => handleAddToCartURL(product.id)}>
                            <AddShoppingCartIcon />
                        </button>
                    </Item>
                </Grid>
                <Grid item xs>
                    <Item>Similar Products</Item>
                </Grid>
            </Grid>

      </Box>
    )
}
export default ProductDetails

I really dont't understand why it is returning anonymous user from django. Please how do I fix it?

A: You have this error because the user you try to assign is not authenticated.
Add a permission to your view like this :
from rest_framework import permissions

class add_to_cart_view(APIView):
    permission_classes = [permissions.IsAuthenticated]

    # Rest of the code here

NB : You will need to authenticate the user before make a post request.
UPDATE : If you want to test with non authenticated user.
You can create a generic user for that :
# Create a user with a name unauthenticated_user in the admin

# In the view :
if request.user.is_authenticated:
    # Do something for authenticated users.
    # Your code previous code here
else:
    # retrieve the unauthenticated_user you create
    # use your custom user here


text:
Q: Why my program using switch always go to default My program always outpout test which should not happen. Its like the program is skipping the case to go to default right away. I don't understand why it does that. I've spent 30 mins to find a solution but I can't understand why it does that.
Thanks for helping me !
var ani;
let ans;
let prix;
var total;
var arm1;
var arm2;
let nombrearmure;
nombrearmure = 0;
ani = prompt("Entrez votre type d'animal : ");
switch (ani.toLowerCase) {
case 'c' :
    ans = prompt('Voulez vous acheter une épée pour 100$ ? : ');
    if (ans.toLowerCase() === 'o'){
        prix = 100;
        nombrearmure = 1;
    } else {
        if (ans.toLowerCase() === 'n') {
            console.log('Épée refusé');
        } else {
            console.log('Réponse non valide');

        }

    }
    ans = prompt('Voulez vous acheter une corne de licorne pour 500 $ ? : ');
    if(ans.toLowerCase() === 'o'){
        prix = prix+500;
        nombrearmure = nombrearmure + 2;
    } else {
        if (ans.toLowerCase() === 'n'){
            console.log('Corne de licorne refusé');
        } else {
            console.log('Réponse invalide');

        }
    }

    break;
case 'l' :
    ans = prompt('Voulez vous acheter un casque(100-200$) : ');
    if (ans.toLowerCase() === 'o'){
        ans = parseInt(prompt('Appuyez sur 1 pour un casque noir (100$) ou 2 pour un casque multicolore (200$) : '));
        switch(ans){
            case 1 :
                prix = 100;
                nombrearmure = 1;
                break;
            case 2 :
                prix = 200
                nombrearmure = 2;
                break;
            default :
            console.log('Réponse invalide')
            return 1;
        }
    } else {
        if(ans.toLowerCase === 'n'){
            console.log('Casque refusé');
        } else {

        }
    }
default:
    console.log('test');
}

A: You are doing ani.toLowerCase. It should be ani.toLowerCase(). Also remove the return 1.

A: You didn't call the lowerCase function, invoke it.
Also, remove the return statement,
Now if you try to enter 'l' or 'c' letter it will work

var ani;
let ans;
let prix;
var total;
var arm1;
var arm2;
let nombrearmure;
nombrearmure = 0;
ani = prompt("Entrez votre type d'animal : ");
switch (ani.toLowerCase()) {
  case 'c':
    ans = prompt('Voulez vous acheter une épée pour 100$ ? : ');
    if (ans.toLowerCase() === 'o') {
      prix = 100;
      nombrearmure = 1;
    } else {
      if (ans.toLowerCase() === 'n') {
        console.log('Épée refusé');
      } else {
        console.log('Réponse non valide');

      }

    }
    ans = prompt('Voulez vous acheter une corne de licorne pour 500 $ ? : ');
    if (ans.toLowerCase() === 'o') {
      prix = prix + 500;
      nombrearmure = nombrearmure + 2;
    } else {
      if (ans.toLowerCase() === 'n') {
        console.log('Corne de licorne refusé');
      } else {
        console.log('Réponse invalide');

      }
    }

    break;
  case 'l':
    ans = prompt('Voulez vous acheter un casque(100-200$) : ');
    if (ans.toLowerCase() === 'o') {
      ans = parseInt(prompt('Appuyez sur 1 pour un casque noir (100$) ou 2 pour un casque multicolore (200$) : '));
      switch (ans) {
        case 1:
          prix = 100;
          nombrearmure = 1;
          break;
        case 2:
          prix = 200
          nombrearmure = 2;
          break;
        default:
          console.log('Réponse invalide')

      }
    } else {
      if (ans.toLowerCase === 'n') {
        console.log('Casque refusé');
      } else {

      }
    }
  default:
    console.log('test');
}


text:
Q: MBR: How does BIOS decide if a drive is bootable or not? While trying to answer this question on askubuntu: How do I Uninstall GRUB I read the Wikipedia article on MBR and also the perfect answer on a somewhat related question here on Superuser, however, one thing is still not clear to me:
What exactly makes BIOS decide if a drive is bootable or not? How does the boot sequence skip from drive #1 and proceed trying to boot from drive #2 if more than one drive is installed in the system?
My understanding is that the only thing BIOS normally checks on an MBR is its signature at the very end of the 512-byte sector, and then it just transfers control to the initial bootloader situated in the first 446 bytes of the boot sector.
Does it imply that the first 446 bytes of the boot sector MUST contain some meaningful bootloader code even if the disk is not bootable?
After BIOS transferred control to the bootloader on drive #1 which happened to have no "bootable" partitions - how exactly is the bootloader on the second drive invoked?
Sorry if this is too technical :) Short question is: "How exactly does BIOS skip a drive and proceed to try to boot from the next one?"

A: I have read the accepted answer by @Breakthrough but I think it's wrong. Or at least for the hardware I have here it does not apply (Mainboard MSI MS-6340).
In the answer by @Breakthrough he says booting is by partition.
So you can have one disk with many bootable partitions.
But in the BIOS of my mainboard I can only select disks. Not partitions.

As you can see on the screenshot of the manual you can say "Third Boot device is HDD-0".
Booting is by disk and not by partition as said by @Breakthrough.
The partition table of the MBR is completely ignored by the BIOS.
This matches the description at osdev.org.
So instead the BIOS only looks at the last two bytes of the MBR and sees if they match 0x55 0xAA. Then it loads the MBR and executes the bootstrap at the very beginning.
The partition table in the MBR is only used by the Windows OS and not by the BIOS.
Also note if you format a disk (for example an USB pen drive) with FAT32 then it will have a MBR! Although it is not bootable! Don't ask me what the MBR bootstrap code of this disk will do. It probably simply aborts and goes to the next boot option.

A:
What exactly makes BIOS decide if a drive is bootable or not?

The BIOS decides if a drive is bootable based on the 16-byte partition record, present after the MBR code area (held in a table starting at the 446th byte).  The first byte in each partition record represents the drive's bootable status (and is set to 0x80 if bootable, or 0x00 if not).  Some BIOSes may check other parts of the MBR (e.g. partition types, checksums), but the basic requirement is the bootable flag.

How does the boot sequence skip from drive #1 and proceed trying to boot from drive #2 if more than one drive is installed in the system?

This is implementation dependent, and is why you need to properly select a boot order.  In most cases, the BIOS will look through each storage medium in the order you set, and determine whether it can boot from that device (via the MBR data).  If it can, it does - if not, it continues looping through the other devices (again, in the order you selected).

After BIOS transferred control to the bootloader on drive #1 which happened to have no "bootable" partitions - how exactly is the bootloader on the second drive invoked?

Once a valid boot device is found (i.e. the bootable flag is set, and other additional checks pass), the BIOS copies the MBR sector into RAM.  The BIOS then relocates the instruction pointer to the beginning of this location (using a JUMP instruction), where the MBR code segment is located, and the computer then starts.
If the BIOS supports the BIOS Boot Specification, MBR code can return control to BIOS with a certain instruction, signaling it of boot failure and prompting it to try the next device. Older BIOSes just print an error message though. A good tell if you BIOS supports it is whether you can boot from USB.

My understanding is that the only thing BIOS normally checks on an MBR is its signature at the very end of the 512-byte sector, and then it just transfers control to the initial bootloader situated in the first 446 bytes of the boot sector.

This is correct, although it should be noted that most modern BIOSes will also look for a GUID Partition Table as well as the older, conventional MBR-style table.

Does it imply that the first 446 bytes of the boot sector MUST contain some meaningful bootloader code even if the disk is not bootable?

No, but the drive must have a valid MBR or GUID partition table - otherwise, it won't be detected by the computer.  While the code part of the MBR can indeed be empty, the first sector of the drive must have a well-formed MBR/GPT.


text:
Q: Better RxJava usage I'm still learning RxJava and I wanted to know if there was another way to do what I want.
I have the following code, and it works:
apiManager.getChannelListByRegion(region)
            .observeOn(scheduler)
            .map(new Func1<ChannelList, List<ChannelList.Channel>>() {
                @Override
                public List<ChannelList.Channel> call(ChannelList channelList) {

                    if (params.getGenre() == 0) {
                        return channelList.getChannels();
                    } else {
                        List<ChannelList.Channel> filteredList = new ArrayList<>();
                        for (ChannelList.Channel channel : channelList.getChannels()) {
                            if (Integer.parseInt(channel.getGenreId()) == params.getGenre())
                                filteredList.add(channel);
                        }
                        return filteredList;
                    }
                }
            })
            .subscribe(new SuccessCallback<>(callback), new ErrorCallback(callback));

Some explanantion - The ChannelList is a POJO representing some JSon from an external service. I have no control over the structure of this JSon.
ChannelList contains an embedded List which I want and I am able to get it via the map() operator quite easily assuming no filtering of the list.
If I need to filter however, I resorted to a loop over its contents and checked for the filtering condition.
Is there a way to better filter? I'm assuming I would need to create another Observable that emits the List contents and provide a function but I'm not sure how to do that.

A: I can show you how to rewrite your code using only FP and reactivex. It is rather matter of taste if it is simpler. I will use lambdas to make the code simpler to understand.
apiManager.getChannelListByRegion(region)
                .observeOn(scheduler)
                .flatMap(channelList->Observable.from(channelList.getChannels()))
                .filter(channel->params.getGenre() == 0 || Integer.parseInt(channel.getGenreId()) == params.getGenre())
                .toList()
                .subscribe(new SuccessCallback<>(callback), new ErrorCallback(callback));

As you can see, I first convert ChannelList into Observable of Channel, to later filter it and collect as list.


text:
Q: My theme is adding an unmatched end tag and outputting it to my screen I use a theme that uses WPBakery - I have a feeling WPBakery might be the culprit here. I made a few small changes, and now this is appearing at the very top of the page, above the menu:
" />

I have included a screenshot for reference.
Any help or ideas would be greatly appreciated as I'm banging my head trying to figure out why

A: It wasn't displaying before for some reason, but we did find that this exists in the original file. We went in and deleted it and it disappeared....the real mystery is why it suddenly started appearing in the first place. It's related to the char-set.
In any case, answer is solved, somewhat.


text:
Q: yii2 phpDoc- word order Why in yii2 phpDoc annotation in views we can see such word order
 * @var $width integer

and in class's methods such word order
 * @param integer $width

Why doesn't the second example have such form
 * @param $width integer

A: The correct syntax for this tag is
@param [Type] [name] [<description>]

So declaration where type declared after parameter name is incorrect, but as you see it works the same so i guess that it has no difference but better to use syntax.


text:
Q: Python: How does adding functions as input variables affect a program? So I was reading through the itertools documentation when I came across this note at the bottom of the page:

Note, many of the above recipes can be optimized by replacing global lookups with local variables defined as default values. For example, the dotproduct recipe can be written as:
def dotproduct(vec1, vec2, sum=sum, imap=imap, mul=operator.mul):
    return sum(imap(mul, vec1, vec2))

What do they mean by this? Am I to understand that adding functions as input variables makes the program run faster or more efficiently?
Could someone explain this to me like a 5 year old? :-)
Thanks in advance.

A: One problem for Python efficiency is that the language is completely dynamic. For example consider the simple loop
def myfunc():
    for i in range(10):
        foo(bar(i))

seems that the function foo will be called with the result of calling bar ten times.
However the function bar can for example change what foo is and the code of foo can in turn change what bar is. Python is thus forced to check at each iteration what foo is pointing to and what bar is pointing to. This requires looking in the module globals and, if nothing is found there in the builtin (predefined) names. At each of the 10 iterations.
The very same happens with all global lookups (and for example it's not forbidden for you to even define a function named len thus "hiding" the standard function with that name).
When using a local variable instead things are simpler
 def myfunc():
     f = foo
     b = bar
     for i in range(10):
         f(b(i))

the reason is that f and b are local variables so getting the value to be able to make the calls is much simpler. Code outside of myfunc cannot change what f and b are pointing to.
So one trick to get some speed is to write things like
def myfunc(x, sin=math.sin):
    ...

so that when using sin you don't need to look up math first and then sin inside math.
It's a kind of micro-optimization that is however considered bad style unless you really found (measured) the speed to be a problem, the fix has been measured to give a reasonable gain and that the slowness is however not serious enough to require some more radical approach.

A: There are few benefits:

*

*The default arguments are calculated when the function definition is parsed. So, when the function is actually called no such calculation is required.

*During a function call when python sees that a variable was not found in local scope it looks for it in the globals first, if still not found then it goes to the built-ins. Ultimately it'll raise the error that variable not found if it's not found anywhere.
So operator.mul will require three calls: first search operator in local scope, then in global scope. Now as it is found in global scope now search operator module for mul.
Declaring it like mul=operator.mul in function header will reduce these number of searches to 1.
Look at Byte code:
The local variables will re going to be loaded using LOAD_FAST.
While other variables like operator.itemgetter, list and list require more number of calls.
>>> def dotproduct(vec1, vec2, sum=sum, imap=imap, mul=operator.mul):
        sum(imap(mul, vec1, vec2))
        list([operator.itemgetter(1) for x in lis])
...
>>> dis.dis(dotproduct)
  2           0 LOAD_FAST                2 (sum)
              3 LOAD_FAST                3 (imap)
              6 LOAD_FAST                4 (mul)
              9 LOAD_FAST                0 (vec1)
             12 LOAD_FAST                1 (vec2)
             15 CALL_FUNCTION            3
             18 CALL_FUNCTION            1
             21 POP_TOP

  3          22 LOAD_GLOBAL              0 (list)
             25 BUILD_LIST               0
             28 LOAD_GLOBAL              1 (lis)
             31 GET_ITER
        >>   32 FOR_ITER                21 (to 56)
             35 STORE_FAST               5 (x)
             38 LOAD_GLOBAL              2 (operator)
             41 LOAD_ATTR                3 (itemgetter)
             44 LOAD_CONST               1 (1)
             47 CALL_FUNCTION            1
             50 LIST_APPEND              2
             53 JUMP_ABSOLUTE           32
        >>   56 CALL_FUNCTION            1
             59 POP_TOP
             60 LOAD_CONST               0 (None)
             63 RETURN_VALUE

A: Let me try.
I think This mean that when python will  try to find variables (functions or other objects) it will use LEGB rule
please check this question for complete description of LEGB
But this trick allows python to find variables in closest scope local one (where arguments are situated)


text:
Q: TWIG FORM input 'choice_widget', How to apply `transchoices` on choices `ChoiceView` type label? I am using SYMFONY 3 and TWIG.
I have in my translation file "[MySymfProject]\MyBundle\Resources\translations\messages.fr.yml" this:
MyBundle:
   label:
        all_saints: "Toussaint | La Toussaint"
        bastille_day: "14 juillet | Le 14 juillet"

I want my <input type="choice"> menu to display "Toussaint" (That does not work, I get "Toussaint | La Toussaint" displayed in the menu). And then it should display "La Toussaint" in another field (that works, with JS translation bundle, I use the TransChoice function and select the index corresponding to "La Toussaint" for translation word tag "all_saints").
I've tried to alter the TWIG template based on {% extends 'form_div_layout.html.twig' %}.
And do something like:
{% block form_row  %}

         {% if  (form.vars.block_prefixes.1 == "choice") %}
            {% for choice in form.vars.choices %}
                {% set choice.label = choice.label|transchoice(1) %}
            {% endfor %}

            {% block choice_widget %}
                {{ parent() }}
            {% endblock %}
        {% endif %}
{% endblock %}

But that does not work, it seems that I cannot alter values of an object that is being processed thru a loop in TWIG.
Any idea?

A: namespace AppBundle\Form\Type;

use Symfony\Component\Form\AbstractType as BaseAbstractType;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Translation\Translator;

private $translator;

public function __construct(Translator $translator)
{
    $this->translator = $translator;
}

class AbstractType extends BaseAbstractType
{
    public function configureOptions(OptionsResolver $resolver)
    {
        parent::configureOptions();
    }

    public function getParent()
    {
        return BaseAbstractType::class;
    }
}

services:
    app.form.type.abstract:
        class: AppBundle\Form\Type\AbstractType
        arguments:
            - '@translator'
        tags:
            - { name: form.type }

Then you extend all your custom forms from this new AbstractType


text:
Q: forms validationerror sends me to a ValidationerError page Ive been struggling with this problem for days now. As you se the validation error works but i want the error to show in the form and not redirect the user to the ValidationError page. What am i missing? I use django Alluth
def custom_signup(self, request, user):
    user.profile.pid = self.cleaned_data[_("pid")]
    data = User.objects.filter(profile__pid=user.profile.pid)
    if data.exists():
        raise forms.ValidationError(
            _('This user exists in our system. Please try another.'),
            code='unique_pid'
        )
    else:
        user.save()
        return user

A: Ok, so first you need to create a custom signup form, I've detailed how that is done in answer to this question
What you're seeing there is a 500 page, in debug mode (so you get all the information about what's happened). The reason that you're seeing this is that you are raising an error.
What you want to do, is to add an error to a form as part of that form's validation.
Once you've created your custom signup form, you can add your validation as part of the form's clean method;

    def clean(self):
        """
        Clean the form
        """
        cleaned_data = super().clean()
        pid = self.cleaned_data["pid"]

        if User.objects.filter(profile__pid=pid).exists():
            self.add_error(
                'pid',
                _('This user exists in our system. Please try another.'),
            )

        return cleaned_data

Please note, you're also using translation (_("")) to access the form's cleaned_data - you don't need to do this.


text:
Q: javax.servlet.ServletException: javax.servlet.jsp.JspException: In <parseDate>, value attribute can not be parsed I have a Calendar object that I'm trying to pass to the JSP and format with JSTL into my own custom format:
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<c:forEach items="${employees}" var="employee" varStatus="loop">
                <fmt:parseDate value="${employee.startDate}" var="parsedStartDate" pattern="HH:mm dd/MM/yyyy z" />
                <fmt:parseDate value="${employee.endDate}" var="parsedEndDate" pattern="HH:mm dd/MM/yyyy z" />
                var contentString = '
' +
                        '

${parsedStartDate}
 to
${parsedEndDate}

' +
                        '
' +
                        '
${employee.details}
' +
                        '
' +
                        '
';
</c:forEach>

The employee object is a standard Calendar.getInstance(); object.
edit, full exception:
java.text.ParseException: Unparseable date: "java.util.GregorianCalendar[time=1417392000000,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="Europe/London",offset=0,dstSavings=3600000,useDaylight=true,transitions=242,lastRule=java.util.SimpleTimeZone[id=Europe/London,offset=0,dstSavings=3600000,useDaylight=true,startYear=0,startMode=2,startMonth=2,startDay=-1,startDayOfWeek=1,startTime=3600000,startTimeMode=2,endMode=2,endMonth=9,endDay=-1,endDayOfWeek=1,endTime=3600000,endTimeMode=2]],firstDayOfWeek=2,minimalDaysInFirstWeek=4,ERA=1,YEAR=2014,MONTH=11,WEEK_OF_YEAR=49,WEEK_OF_MONTH=1,DAY_OF_MONTH=1,DAY_OF_YEAR=335,DAY_OF_WEEK=2,DAY_OF_WEEK_IN_MONTH=1,AM_PM=0,HOUR=0,HOUR_OF_DAY=0,MINUTE=0,SECOND=0,MILLISECOND=0,ZONE_OFFSET=0,DST_OFFSET=0]"
    at java.text.DateFormat.parse(DateFormat.java:366)
    at org.apache.taglibs.standard.tag.common.fmt.ParseDateSupport.doEndTag(ParseDateSupport.java:187)
    at org.apache.jsp.index_jsp._jspx_meth_fmt_005fparseDate_005f0(index_jsp.java:459)
    at org.apache.jsp.index_jsp._jspx_meth_c_005fforEach_005f0(index_jsp.java:405)
    at org.apache.jsp.index_jsp._jspService(index_jsp.java:142)
    at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:723)
    at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:388)
    at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:313)
    at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:260)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:723)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:646)
    at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:436)
    at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:374)
    at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:302)
    at com.example.controller.EmployeeController.doGet(EmployeeController.java:48)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:723)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293)
    at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:861)
    at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:620)
    at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
    at java.lang.Thread.run(Thread.java:745)

at com.example.controller.EmployeeController.doGet(EmployeeController.java:48) is: request.getRequestDispatcher("/index.jsp").forward(request, response);

A: parseDate is used to parse string input and convert to Date object. You should not use parseDate. Instead use formatDate
<c:forEach items="${employees}" var="employee" varStatus="loop">
   var contentString = '
' +
     '

    <fmt:formatDate type="time" value="${employee.startDate.time}" pattern="HH:mm dd/MM/yyyy z"/>
 to

    <fmt:formatDate type="time" value="${employee.endDate.time}" pattern="HH:mm dd/MM/yyyy z" />

' +
    '
' +
    '
${employee.details}
' +
    '
' +
    '
';
</c:forEach>


text:
Q: Stacking content vertically and horizontally with inline-block and float left So I'd like to stack items vertically within a div and stack multiple divs horizontally like the following illustration:

Each div is defined with a class name of floatbox

    Screening Type:
    <select></select>

For which I was applying the following css
.floatbox {
    display: inline-block;
    width: 175px;
    margin: 0;
    padding-top: 5px;
    float: left;
}

I need float because IE8 will treat it as a block level element unless you use float.  However, when I add it, the items get shifted around.  I can correct this by adding two extra
 elements, but I'm wondering if that's the best sollution
See this fiddle for an example

A: the problem is that not all the floatbox elements have the same height, so you can fix it by giving them one:
.floatbox {
    ...
    height:45px;
    ...
}

works well with your jsfiddle example.
another way to force a 'line break' with floating elements is using the css clear property:

put this after every 4th div box to ensure that it will break there. then you dont have to use a fixed height, and you can remove all
 tags from the code (for both solutions)

A: You can do the above answer but you don't need float at all really if you use display:inline-block. http://jsfiddle.net/ApKHE/10/ I only added in float with the buttons to position them under the right box but you can place them wherever you want.
.floatbox {
display: inline-block;
width: 175px;
margin: 0;
padding-top: 5px;

}
.floatbox input, select, label {
    width: 150px;
    margin: 0px;
}
.EntryFieldSet {
    width: 735px;
    padding-left: 15px;
    overflow: hidden;
}
#screeningButtons{
    float:right;
    padding-right:30px;
}


text:
Q: Red Hat subscriptions in EC2 via AWS - are they just for specific AMIs? So the docs say that if you launch a Red Hat image in AWS then you will be charged a fee for the Red Hat subscription but all of the billing will be done via AWS.
I used packer to bake a new AMI based on RHEL 7.7 with extra hardening but on any instance I launch with my new AMI, yum can't retrieve packages because it's not subscribed. Does AWS just know which instances are using the Red Hat provided community packages and allow access to their RHN repos that way? And therefore for images that I bake based on them, will I have to sort out subscriptions separately? Or is there a way to use the same subscription system?
Eventually I imagine these instances will subscribe separately via Red Hat Cloud Access anyway but I'm just interested to know if there's some weird magic under the hood in AWS or if I've maybe broken my PKI client certs for RHN.


text:
Q: How general is the statement that "the gradient points in the direction of fastest increase"? Let $V$ be an arbitrary $n$-dimensional inner product space over $\mathbb R$. Define the gradient of $f$ at $x$ as the vector such that for all $\mathbf v\in V$,
$${\displaystyle {\big \langle}\nabla f(x){\big )},\mathbf {v}\big\rangle =D_{\mathbf {v} }f(x),}$$
where $\langle,\rangle$ is the inner product on $V$ and $D_{\mathbf {v} }f(x)$ is the directional derivative of $f$ at $x$ along the tangent vector $\mathbf v\in \mathbb R^n$.
What do we need to assume to conclude that the gradient is the "steepest" direction in which to go? Does this hold for arbitrary inner products? Or just the Euclidean one?


text:
Q: SUM of array with the same variable php I have a dynamic variable a with different values
$a = (1,2,3,4,5);
$a = (2,3,4,5,6);

I want a result that will sum each index of each array
$a = (3,5,7,9,11);

while($row=mysqli_fetch_array($sql)){
   $a = explode(',',$row['array']); //array with same variable name
}

A: You could use array_map:
$a = array();
while($row=mysqli_fetch_array($sql)){
    $a = array_map(function ($x, $y) { return $x + $y; }, $a,  explode(',',$row['array']));
}
print_r($a);

Assuming your code returns rows of
$row['array'] = '1,2,3,4,5';
$row['array'] = '2,3,4,5,6';

The output will be:
Array
(
    [0] => 3
    [1] => 5
    [2] => 7
    [3] => 9
    [4] => 11
)

A: May be below code will help you out
$a = array(1,2,3,4,5,4,5);
$b = array(2,3,4,5,6,7,3);
foreach($a as $k=>$v)
{
$temp = $a[$k]+$b[$k];
$c[] = $temp;
}
print_r($c);


text:
Q: Defining Variable's Data Type While Assigning New? i'm linked a MovieClip class object to my project, and i will programatically add it to the display list.  is there a difference between defining the variable's data type and not doing so?  neither produce a runtime error.
//var datatype
var rectangle:Block = new Block();
addChild(rectangle);

//no var datatype
var rectangle = new Block();
addChild(rectangle);

A: In ActionScript, it doesn't make much of a difference, AS isn't very strict in these situations. But it is a best-practice to set the datatype, and it allows the IDE to give code-hints.


text:
Q: I am having trouble linking Css File to Django Template I just started learning django framework and i tried to add and use static files to design a template(to change the background) of webpage with simple css but my css file doesn't seem to link with html template as the background did not change.
I looked up various solutions and it doesn't seem i am doing anything wrong in the code but it still doesn't work. Please look at the code, what could i be missing?
Here is the code for the template;
{% load staticfiles %}
<link rel="stylesheet" type="text/css" href="music/style.css">

{% if all_albums %}

My Albums

    {% for album in all_albums %}

{{album.album_title}}

    {% endfor %}

{% else %}

You don't have any albums

{% endif %}

Here is the css;
body{
    background: white url("images/blackbackground.jpg");
}

I expected the background to change but it didn't. The server returned error message "Not Found: /music/music/style.css
[01/Feb/2019 12:15:26] "GET /music/music/style.css HTTP/1.1" 404 2559" guys what am i missing?

A: To make the static files work on Django you need to have a couple of variables in place.
First, in your settings.py you'll have to have your static file variables set.
Here I show you an example of the one I use:
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'staticfiles')
STATICFILES_DIRS = (
    'static',
    os.path.join(os.path.dirname(BASE_DIR), 'static')
)
STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)

This means that you will need to have a static folder in the same folder as your main app.
For example:
├── apps
│   ├── api
│   ├── blog
│   └── home
├── manage.py
├── media
│   ├── images
│   └── original_images
├── requirements
│   ├── base.txt
│   ├── development.txt
│   └── production.txt
├── src    -----> THIS IS MY MAIN FOLDER
│   ├── __init__.py
│   ├── __pycache__
│   ├── db.sqlite3
│   ├── locale
│   ├── media
│   ├── settings ------> THIS IS MY SETTINGS FOLDER
│   ├── urls.py
│   └── wsgi.py
├── static    ------> THIS IS MY STATIC FOLDER
│   ├── css
│   ├── figures
│   ├── fonts
│   ├── img
├── templates
│   └── base.html
└── utilities

Next, you'll need to add this to your main urls.py:
from django.conf.urls.static import static
from django.conf import settings

# Serve static files with Django. Normally this is for development purposes.
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

After that, the last part goes into your templates, you'll need to load static template tags and use the following syntax:
{% load staticfiles %}
<link rel="stylesheet" type="text/css" href="{% static 'music/style.css' %}">

At the end, it will render something like:
<link rel="stylesheet" type="text/css" href="/static/music/style.css">


text:
Q: Merging ifs in jQuery Hi I'm working on Datatables and I'm just a jQuery beginner. I want to merge some of the JSON output through the DT render property. I tried this:
 function ( data, type, full ) {
 return full["a"] + full["b"] + full["c"] + full["d"];}

But this doesn't work, because when there's no C or D in the data row, an "undefined" will appear. So I turned to conditionals that will check before posting the result.
function ( data, type, full ) {
      if (full["a"]) {
        return full["a"];}
      else if (full["a"] && full["b"]) {
        return full["a"] + full["b"];}

I would then go through some iteration of this until I get all the variables I need — A, B, C, and D. Plus, this doesn't work. Any shortcut?
Update: I'm now using the map function, which kind of gives me the result I was looking for, but I'm still looking for some granular control of the variables. See the fiddle.
Update 2: See here for another iteration of the same problem.

A: Here is how to loop over the object
var res = [];
for (var o in full) res.push(full[o]);
return res.length==0?"":res.join(",");

var full = {"a":"A","c":"C","d":"D"}, res = [];
for (var o in full) res.push(full[o]);
console.log(res.length==0?"":res.join(","));

Alternative if no commas needed
return (full["a"] || "") +
       (full["b"] || "") +
       (full["c"] || "") +
       (full["d"] || "");

jQuery example:

var full = {
    "type": "book",
    "title": "Title",
    "container-title": "", // empty
    "publisher": "Publisher",
    "page": "Pages X to X",
    "volume": "XXX"
  },
  res = [];
$.each(full, function(key, val) {
  if ($.trim(val) != "") res.push(val);
});
console.log(res.length == 0 ? "" : res.join(","));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

A: as full is an array, then you can use $.each on it and add the result to a variable only if the current element is not having bad data(undefined, null)


text:
Q: Python Plotly Dash : How to insert new values to filter after the callback? (Update filter) My situation is such that I get a table by user_id only after he logged in.
For example :
app = dash.Dash(__name__)

#Filter with static values
Month_Selector = dcc.Dropdown(id='month_dropdown',
                                  options=[
                                      {"label": "November 2021", "value": "November 2021"},
                                      {"label": "October 2021", "value": "October 2021"},
                                      {"label": "September 2021", "value": "September 2021"},
                                  ],
                                          placeholder="Select Month",
                                          value = datetime.today().strftime('%B %Y'),
                                          searchable=False
                                          )

app.layout = html.Div(
    children=[
    html.Div(Month_Selector, style={'width': '200px'}),
    dcc.Graph(id='chart')
    ]
)

    @dash_app.callback(
        [
        Output(component_id='chart', component_property='figure')
        ],
        [Input(component_id="submit-button-state", component_property="n_clicks"),
         Input(component_id="month_dropdown", component_property="value")]
    )
    def get_user_name(n_clicks, selected_month):

        # Can get a table only after user authorization.
        df= get_table_by_an_authorized_user_id

        #filter table by slicer value
        filtered_df= df[ (df['Month Name'] == selected_month)]

        # This new values that need to insert to slicer Month_Selector
        new_options_for_month_selector=[{'label': i, 'value': i} for i in df['Month Name'].unique()]

        fig = px.bar(filtered_df, x='Month Name', y='Sales')
        return fig
    # Run Local Server
if __name__ == '__main__':
    app.run_server(debug=True, use_reloader=False)

Therefore before @callback I can use only filter static values.
How can I update or replace filter values with dynamic values I get after a @callback ?

A: You want to update the options property of the dropdown, so you can add an Output with the new options and make the callback return them along with the updated figure :
@dash_app.callback(
    [Output(component_id='chart', component_property='figure'),
     Output(component_id='month_dropdown', component_property='options')],
    [Input(component_id="submit-button-state", component_property="n_clicks"),
     Input(component_id="month_dropdown", component_property="value")]
)
def get_user_name(n_clicks, selected_month):

    # Can get a table only after user authorization.
    df= get_table_by_an_authorized_user_id

    #filter table by slicer value
    filtered_df= df[ (df['Month Name'] == selected_month)]

    # This new values that need to insert to slicer Month_Selector
    new_options_for_month_selector=[{'label': i, 'value': i} for i in df['Month Name'].unique()]

    fig = px.bar(filtered_df, x='Month Name', y='Sales')
    return [fig, new_options_for_month_selector]


text:
Q: Writing SOAP request/responses to a log file I have a web service Client class that establishes a connection with the destination server using the wsdl url. This class uses JaxWsProxyFactoryBean and the WSS4JOutInterceptor to establish a secure connection. I would like to see the SOAP request generated by my code and response generated from the server.
I have tried including the following options when I run my jar from the command line
-Dcom.sun.xml.ws.transport.http.client.HttpTransportPipe.dump=true
-Dcom.sun.xml.internal.ws.transport.http.client.HttpTransportPipe.dump=true
-Dcom.sun.xml.ws.transport.http.HttpAdapter.dump=true
-Dcom.sun.xml.internal.ws.transport.http.HttpAdapter.dump=true

I am using log4j for logging and all the messages get written to a custom file. How can I dump the SOAP request/responses to this same file using command line options?
Do I have to make any code changes to the Client class to achieve this?
Thanks for the help.

A: I had to add the following lines to the class that creates a SOAP request:
LoggingInInterceptor loggingInInterceptor = new LoggingInInterceptor();
loggingInInterceptor.setPrettyLogging(true);
LoggingOutInterceptor loggingOutInterceptor = new LoggingOutInterceptor();
loggingOutInterceptor.setPrettyLogging(true);
factory.getInInterceptors().add(loggingInInterceptor);
factory.getOutInterceptors().add(loggingOutInterceptor);

I also had to update my cxf client to the latest version from Apache i.e. 2.7.12.
This printed out the SOAP headers to the console.


text:
Q: Is it possible to change countif to an array google sheets Below are two formulas that I use to determine if courses selected are full or if there is a vacancy.  I am wondering if it is possible to change these formulas to an array or if there is a workaround that would accomplish the same result.
=if(COUNTIF(G$2:G2,G2)<=(VLOOKUP(G2,$AC$2:$AD$50,2,0)),G2,"Full")

=if(W2="Full",if(COUNTIF({R$2:R;S$2:S;T$2:T;U$2:U;V$2:V;W$2:W},M2)

Edit: link to demo sheet  https://docs.google.com/spreadsheets/d/1nPhrEKhKwuq3YSghgJ4LFoHZqOzo67_b1qohh1NABJo/edit?usp=sharing

A: I duplicated the sheet and entered in R2
=Arrayformula(IF(LEN(G2:G), if(COUNTIF(G$2:G,G2:G)<=(VLOOKUP(G2:G,$AC$2:$AD$50,2,0)),G2:G,"Full"),))

and in S2
=ArrayFormula(if(len(R2:R), if(R2:R="Full",if(COUNTIF(R$2:R,H2:H)<VLOOKUP(H2:H,$AC$2:$AD$50,2,0),H2:H,"Full"),),))

See if that works for you?


text:
Q: How to rename all directories on a terminal I have a total of 31 directories. Every directory has a random name.
❯ ls -al
total 32
drwxr-xr-x  34 shinokada  staff   1088 Dec 28 17:16 .
drwxr-xr-x  32 shinokada  staff   1024 Dec 28 17:12 ..
-rw-r--r--@  1 shinokada  staff  14340 Dec 28 17:16 .DS_Store
drwxr-xr-x   5 shinokada  staff    160 Dec 28 17:10 05618066
drwxr-xr-x   5 shinokada  staff    160 Dec 28 17:08 0fef2d20
drwxr-xr-x   5 shinokada  staff    160 Dec 28 17:09 11ff096d
drwxr-xr-x   5 shinokada  staff    160 Dec 28 17:09 1651ff1f
drwxr-xr-x   5 shinokada  staff    160 Dec 28 17:09 2123b256
... and more

Now I'd like to rename them sample1 sample2 sample3 ...sample31.
How can I do it on a terminal(bash/zsh)?
Is there a quick way to do it rather than rename one by one?

A: This should do:
num=1; for dir in */ ; do mv "${dir}" "sample$num" ; ((num++)); done

I assume you don't want to rename the files, only directories inside your current working directory.


text:
Q: Debug Maven to find out the war file name that has been created I am getting this exception in Maven2 when i run mvn deploy
Please see the error
[INFO] An Ant BuildException has occured: Warning: Could not find file D:\bayer\service\target\${file.name}.war to copy.
I have this below line under my POM.xml file

Please tell me is it possible to see the file.name that is forming at runtime ??
I have this line under my POM.xml file
<copy file="${project.build.directory}/${file.name}.${project.packaging}" tofile="${deploy.home}/${webapps.dir}/${file.name}.${project.packaging}" />

How can we debug this ??

A: By default maven generated wars will have the following name:
${artifactId}-${version}.war

In you antrun plugin you can reference maven properties ( see http://maven.apache.org/plugins/maven-antrun-plugin/usage.html ).
So if you replace file.name property by a direct maven reference it will just work:
${project.build.directory}/${artifactId}-${version}.${project.packaging}

( above assumes that your ant script is inside the pom.xml and not externalized )
You also can override that in the build section of your pom.xml:
<build>
   <finalName>MySuperCoolApplication</finalName>
   ...
</build>

For general debug output from mvn just use the -X flag


text:
Q: rails - Best practice for creating similar routes? In my application, a User can make a Post, and a User can make Correction (think of it as a comment) on another user's post. Each User can have many Posts, and each Post can have many Corrections.
On each show page for a Post, there is a form to create a new Correction. This uses the user_post_corrections path.
On the show page for each User, I would like to display each Correction they've submitted for any Post. This requires a user_corrections path.
In order to achieve this, I have the following in my routes.rb:
resources :users do
    resources :posts do
      resources :corrections
      end
    end

    resources :users do
      resources :corrections
    end

This intuitively feels bad to me, as I've created two nested routes that are very similar to one another.
Is there a better way to do this? My code is working fine as it is but is there a best practice method for implementing this kind of model?

A: Routing concerns are an excellent but underused tool for DRYing out your routes:
concern :correctable do
  resources :corrections
end

# just an example of multiple concerns
concern :commentable do
  resources :comments
end

resources :users, concerns: :correctable
resources :posts, concerns: [:correctable, :commentable]

However you should take when creating nested routes so that you are not nesting needlessly.
Often you might want the collective actions [new, index, create] to be scoped by the parent:
GET|POST  /posts/:post_id/corrections
GET       /posts/:post_id/corrections/new

While you want the member actions to be unscoped since you can always access a record directly if it has a unique id.
GET    /corrections/:id
GET    /corrections/:id/edit
PATCH  /corrections/:id
DELETE /corrections/:id

To do this you would declare the routes like so:
resources :corrections, only: [:show, :update, :edit]

concern :correctable do
  resources :corrections, only: [:new, :index, :create]
end

resources :users, :posts, concerns: [:correctable]

The shallow: true option does something like this but does not work well when you declare the same resources several times as it adds unscoped routes for every call.


text:
Q: Insert two columns in a data frame from another data frame I am working on an election dataset, in which I want to show which party has a higher representative in each district. For this I want to show it on the map of Pakistan. The election dataset has no info about the lat/lon. I found another dataset that has this info. I do not know how to merge this dataset so I can show my result on the map of Pakistan.
df1
city       lat      lon
karachi    24.860   67.010
lahore     31.549   74.3436
sialkot    32.50    74.53

election_df2
District   Seat     ConstituencyTitle     CandidateName     Party     Votes
Karchi     Karachi    NA249               sajid abdullah     pmln     80000
lahore     lahore     NA129               firdous ashiq      pppp     50010
sialkot    sialkot    NA150               ahsan iqbal        pmln     45000

A: I would do it following way
import pandas as pd
df1 = pd.DataFrame([["karachi",24.860,67.010],["lahore",31.549,74.3436],["sialkot",32.50,74.53]],columns=["city","lat","lon"])
df2 = pd.DataFrame([["Karachi","pmln",80000],["lahore","pppp",50010],["sialkot","pmln",45000]],columns=["Seat","Party","Votes"])
df2["city"] = df2.Seat.str.lower()
df3 = df2.merge(df1,on='city')
print(df3)

output
      Seat Party  Votes     city     lat      lon
0  Karachi  pmln  80000  karachi  24.860  67.0100
1   lahore  pppp  50010   lahore  31.549  74.3436
2  sialkot  pmln  45000  sialkot  32.500  74.5300

Note: I use subset of your data for brevity sake. Disclaimer this solution assumes lat and lon is known for each Seat.


text:
Q: Calculate Workflow Custom Task Due Date without weekends? I'd like to set the value of "Due Date" on "Create Custom Task" within my workflow.
However, I want it to be "weekend aware"...i.e. (Sunday-Thursday working week)
if you create a task on Sunday to Tuesday then its due 2 days later
if you create a task on a Wednesday then its due Sunday
if you create a task on a Thursday then its due Monday
I have looked at workflow variables, but these don't have calculations.
I have looked at "Do Calculatation" but this is very restricted to "add a fixed number"
[Yet again, a simple task in SharePoint proves to be difficult]

A: Without custom code, I can see no way of doing it on with de SPD.
Best regards.

A: It's not as simple as one could wish, but you can do it by using the following actions as building blocks:

*

*Use Find Interval Between Dates to get the number of days from a know date to the create date

*Use Do Calculation (mod 7) to get the week day of the create date

*Use a series of if any value equals value togetter with Add Time to Date to calculate the due date

A: It's rather a late reply, but as a search for this still led me here 10 months later, I thought I'd give a code example of Per Jackson's response above in SPD 2013 (I haven't got an earlier version to test with I'm afraid). In my example of an IT HelpDesk, the DueDate value gets set based on the priority of the ticket raised, then changes the DueDate value if it falls on a Saturday or Sunday (to Monday or Tuesday respectively):
Step: 3 - Set "Due Date" based on Priority
    Step: 3.1 Set initial value for DueDate
        If Current Item:Priority equals (1) High
            Add 0 months, 0 days, 11 hours, 0 minutes to Today (Output to Variable: DueDate )
        If Current Item:Priority equals (2) Normal
            Add 0 months, 2 days, 11 hours, 0 minutes to Today (Output to Variable: DueDate )
        If Current Item:Priority equals (3) Low
            Add 0 months, 5 days, 11 hours, 0 minutes to Today (Output to Variable: DueDate )
    Step: 3.2 Fix DueDate for weekend values
        Set time as 0 : 0 for Variable: DueDate (Output to Variable: DueDate )
        Find days between 01/07/2013 00:00:00 and Variable: DueDate (Output to Variable: DaysBetweenMondayAndDueDate )
        Calculate Variable: DaysBetweenMondayAndDueDate mod 7 (Output to Variable: Mod7DueDate )
        If Variable: Mod7DueDate is greater than or equal to 5
            Add 0 months, 2 days, 0 hours, 0 minutes to Variable: DueDate (Output to Variable: DueDate )

Set time as 17 : 0 for Variable: DueDate (Output to Variable: DueDate )
    Update item in Current Item
    Log Due date set to [%Current Item:Due Da... to the workflow history list

Step 3.1 decides that 'If a call is logged in the afternoon, it doesn't need to be resolved until tomorrow', then sets a Date/Time variable called DueDate.
Step 3.2 sets the Time part of DueDate to 00:00 to avoid decimals in later calculations.
It then uses the "Find days between" function to find the number of days between a Monday (01/07/13 in this case, but it could be any Monday - and it's in DD/MM/YY format here due to my localisation settings). This value is then stored in a Number variable called DaysBetweenMondayAndDueDate.
It then uses the "Calculate" function to do (DaysBetweenMondayAndDueDate Mod 7), which gives us a nice round number between 0-6 where 0 represents a Monday (as that's what 01/07/13, used earlier, is and 6 represents a Sunday. This is stored as another Number variable called Mod7DueDate.
Finally, if Mod7DueDate is greater or equal to 5 (i.e. if it falls on a Saturday or Sunday), add two days to the original DueDate variable to move it to Monday or Tuesday respectively.
The last functions set the Time part of DueDate to 17.00 (which happens to be my preference in this case), then updates the List item with DueDate variable.
Hope this helps someone :)


text:
Q: Using CubeRefractionMapping with THREE.CubeCamera renders upside down If I set the renderTarget mapping for my cube camera to THREE.CubeRefractionMapping, it renders upside down.
_myCubeCamera.renderTarget.mapping = THREE.CubeRefractionMapping;

It seems related to the issue discussed in this post where the default orientation of the CubeCamera's component cameras are upside down. I tried tinkering around with these orientations in the THREE.js source code but only made things worse.
So, is there a correct way to use CubeRefractionMapping with CubeCamera? or a workaround?
r73

A: I found a workaround: When assigning the envMap to the material, use THREE.BackSide.
var sphereMaterial = new THREE.MeshBasicMaterial(
    {
        envMap: myCubeCamera.renderTarget,
        side: THREE.BackSide,
        refractionRatio: .09
     } );

A complete example is here.
Not sure why this works, but it does, and that's what the original poster (me!) wanted.


text:
Q: How to change text size and prevent text overlap in a circos plot I try to get comfortable with R and have created a circos plot but I am faced with two problems which I can't solve on my own:
1st: The text around the circos plot is too small (I want a larger letter size)
2nd: The text is partly overlapping
I have tried to change the text size using
circos.text(x=?, y=?, labels=name?, facing = dd, cex=1,  adj = aa)

but I don't know how to fill in x and y and I am not sure if lables=name is true for my code.
This is my code
Acinar_Resection<-c("Res_simple", "Res_cribriform","Res_tall", "Res_columnar", "Res_necrosis")
Bio_necrosis<-c(0,0,0,1,0)
Bio_columnar<-c(0,7,0,18,0)
Bio_tall<-c(0,1,1,0,0)
Bio_cribriform<-c(2,42,0,3,0)
Bio_simple<-c(29,14,1,1,3)
Chord_Diagram<-data.frame(Acinar=Acinar_Resection,Bio_simple=Bio_simple, Bio_columnar=Bio_columnar, Bio_tall=Bio_tall, Bio_solBio_cribriform=Bio_cribriform, Bio_simple=Bio_simple)
Chord_Diagram

circos.par(gap.after = c(rep(5, length(unique(df[[1]]))-1), 15,
                       rep(5, length(unique(df[[2]]))-1), 15))
from<-c("Bio_necrosis (n=1)", "Bio_necrosis (n=1)", "Bio_necrosis (n=1)", "Bio_necrosis (n=1)", "Bio_necrosis (n=1)", "Bio_columnar (n=25)", "Bio_columnar (n=25)", "Bio_columnar (n=25)", "Bio_columnar (n=25)", "Bio_columnar (n=25)", "Bio_tall (n=2)", "Bio_tall (n=2)", "Bio_tall (n=2)", "Bio_tall (n=2)", "Bio_tall (n=2)", "Bio_cribriform (n=47)", "Bio_cribriform (n=47)", "Bio_cribriform (n=47)", "Bio_cribriform (n=47)", "Bio_cribriform (n=47)", "Bio_simple (n=48)", "Bio_simple (n=48)", "Bio_simple (n=48)", "Bio_simple (n=48)", "Bio_simple (n=48)")
to<-c("Res_simple (n=31)", "Res_cribriform (n=64)", "Res_tall (n=2)", "Res_columnar (n=23)", "Res_necrosis (n=3)", "Res_simple (n=31)", "Res_cribriform (n=64)", "Res_tall (n=2)", "Res_columnar (n=23)", "Res_necrosis (n=3)", "Res_simple (n=31)", "Res_cribriform (n=64)", "Res_tall (n=2)", "Res_columnar (n=23)", "Res_necrosis (n=3)", "Res_simple (n=31)", "Res_cribriform (n=64)", "Res_tall (n=2)", "Res_columnar (n=23)", "Res_necrosis (n=3)", "Res_simple (n=31)", "Res_cribriform (n=64)", "Res_tall (n=2)", "Res_columnar (n=23)", "Res_necrosis (n=3)")
value<-c(0,0,0,1,0,0,7,0,18,0,0,1,1,0,0,2,42,0,3,0,29,14,1,1,3)
CD<-data.frame(from=from, to=to, value=value)
CD
chordDiagram(CD)
circos.clear()

circos.par(gap.after = c(rep(5, length(unique(df[[1]]))-1), 15,
                     rep(5, length(unique(df[[2]]))-1), 15))
grid.col = c("Bio_simple (n=48)" = "yellow", "Bio_cribriform (n=47)" = "orange", "Bio_tall (n=2)" = "red", "Bio_columnar (n=25)" = "purple", "Bio_necrosis (n=1)" = "blue",
         "Res_simple (n=31)" = "yellow", "Res_cribriform (n=64)" = "orange", "Res_tall (n=2)" = "red", "Res_columnar (n=23)" = "purple", "Res_necrosis (n=3)" = "blue")
chordDiagram(CD, grid.col = grid.col, transparency = 0.5)
title("Relationship of acinar growth between colonic cancer biopsies and resection specimens")
circos.clear()

chordDiagram(CD, grid.col = grid.col, directional = -1, annotationTrack = c("name", "grid"),
           annotationTrackHeight = c(0.01, 0.08))
title("Relationship of acinar growth between colonic cancer biopsies and resection specimens")
circos.clear()

This is how it looks like:

Who can help?
Many thanks
Janina


text:
Q: How to audit the sharepoint search? I want to audit the sharepoint searches using Sharepoint object model... how to do it?
using sharepoint object model how can i get the audited report for these searches.
Thanks in advance.

A: What specific information do you need? SharePoint already comes with Search Usage Reporting.
You can track stuff like:
- Queries per day over the previous 30 days.
- Queries per month over the previous 12 months.
- Top queries over the previous 30 days.
- Queries per search scope over the previous 30 days.

A: I think you have a slight misunderstanding over what the search webparts do when they provide search results.
All the "fetching" of documents is done when the search crawler runs over the site. This can be audited by importing the stslogs into a database and limiting them down to the username the search crawler uses.
The search results webpart doing the actual search only looks at the index the search crawler creates. Auditing the results a search brings back could be done by a customised search results webpart that stores the url's provided by searches as they are completed, but I am not sure this would provide much value.