text:
Q: Use jQuery to conditionally hide elements in Quick Edit I would like to use jQuery to conditionally hide some taxonomies from the quick edit box, based upon the checkbox status of another taxonomy.
I have a WooCommerce import store. The products fall into two basic groupings based on the Product Category Taxonomy:

*

*Product Category

*

*Fashion

*Food

But then each product has a range of different taxonomies, depending on the product category:

*Country of Origin - Fashion & Food

*Fashion Brand - Fashion

*Food Brand - Food

*Fashion Category - Fashion

*Food Category - Food

*Fashion Season - Fashion

*Gender - Fashion

Given that this is quite a lot of taxonomies, I decided to hide the taxonomies and only show them based upon whether Food or Fashion is clicked in the Product Category taxonomy.
This worked great for the product editing admin screen.
I set the css of the Taxonomy meta boxes I wished to hide to display none, and also created an altered css class for them to display block, as follows:
#fashion-categorydiv,
#fashion-branddiv,
#fashion-seasondiv,
#genderdiv,
#food-drink-categorydiv,
#food-drink-brandsdiv,
#country-of-origindiv {
    display: none;
}

#fashion-categorydiv.show,
#fashion-branddiv.show,
#fashion-seasondiv.show,
#genderdiv.show,
#food-drink-categorydiv.show,
#food-drink-brandsdiv.show,
#country-of-origindiv.show {
    display: block;
}

I loaded in the following javascript to add the .show class if the product category checkbox is already ticked, or is ticked while the edit screen is open:
(function(){

  var fashionCheckBox = jQuery('#product_catchecklist li label input#in-product_cat-46:checkbox');
  var fashionCategory = jQuery('#fashion-categorydiv');
  var fashionBrand = jQuery('#fashion-branddiv');
  var fashionSeason = jQuery('#fashion-seasondiv');
  var fashionGender = jQuery('#genderdiv');

  var foodDrinkCheckBox = jQuery('#product_catchecklist li label input#in-product_cat-45:checkbox');
  var foodDrinkCategory = jQuery('#food-drink-categorydiv');
  var foodDrinkBrands = jQuery('#food-drink-brandsdiv');
  var foodDrinkCountry = jQuery('#country-of-origindiv');

  if (fashionCheckBox.is(':checked')) {
    fashionCategory.addClass('show');
    fashionBrand.addClass('show');
    fashionSeason.addClass('show');
    fashionGender.addClass('show');
  }

  fashionCheckBox.change(function(){
    if (this.checked) {
      fashionCategory.addClass('show');
      fashionBrand.addClass('show');
      fashionSeason.addClass('show');
      fashionGender.addClass('show');

    } else {
      fashionCategory.removeClass('show');
      fashionBrand.removeClass('show');
      fashionSeason.removeClass('show');
      fashionGender.removeClass('show');

    }
  });

  if (foodDrinkCheckBox.is(':checked')) {
    foodDrinkCategory.addClass('show');
    foodDrinkBrands.addClass('show');
    foodDrinkCountry.addClass('show');
  }

  foodDrinkCheckBox.change(function(){
    if (this.checked) {
      foodDrinkCategory.addClass('show');
      foodDrinkBrands.addClass('show');
      foodDrinkCountry.addClass('show');
    } else {
      foodDrinkCategory.removeClass('show');
      foodDrinkBrands.removeClass('show');
      foodDrinkCountry.removeClass('show');
    }
  });

})();

This works great. It is purely cosmetic and just to declutter the edit product screen.
I decided to have a go at doing the same with the quick edit if possible, but I can't get it to work.
When the quick edit is open, and I load the code into the console, it all works fine, but as soon as I either refresh or go to another post to quickedit it stops working.
I understand the quick edit boxes are populated dynamically when the quick edit button is clicked, and that is the crux of the problem.
I have read innumerable tutorials now on adding custom fields and meta data to the quick edit box, but nothing on getting something like this to work.
I really hope someone can help. I know I can turn the taxonomies off from the quick edit, which is my only other option, at the moment, there are just too many for comfortable usability.
Thanks for any assistance.

A: So I worked out how to do this, with a little help from Tonya Mork @ KnowTheCode and a tutorial on adapting the quick edit by Rachel Carden.
I need to refactor the code down, there's still a lot of repetition but I'm pretty much a Javascript/jQuery novice, so please bear with me.
Anyway the solution is as follows:
My custom admin css, saved in my child theme as product-admin-quick-edit.css:
ul.fashion-category-checklist,
ul.fashion-brand-checklist,
ul.fashion-season-checklist,
ul.gender-checklist,
ul.food-drink-category-checklist,
ul.food-drink-brands-checklist,
ul.country-of-origin-checklist {
    display: none;
}

body.wp-admin span.inline-edit-categories-label {
    display: none;
}

Then I have my jQuery, saved in my child theme /js folder as product-admin-quick-edit-jquery.js:
(function($) {

  // we create a copy of the WP inline edit post function
  var $wp_inline_edit = inlineEditPost.edit;
  // and then we overwrite the function with our own code
  inlineEditPost.edit = function( id ) {

    // "call" the original WP edit function
    // we don't want to leave WordPress hanging
    $wp_inline_edit.apply( this, arguments );

    // now we take care of our business

    // get the post ID
    var $post_id = 0;
    if ( typeof( id ) == 'object' )
      $post_id = parseInt( this.getId( id ) );

    if ( $post_id > 0 ) {

      var productCategoryQuickEdit = jQuery('ul.product_cat-checklist');

      var fashionQuickEditCheckBox = jQuery('ul.product_cat-checklist li label input#in-product_cat-46:checkbox');
      var fashionCategoryQuickEdit = jQuery('ul.fashion-category-checklist');
      var fashionBrandQuickEdit = jQuery('ul.fashion-brand-checklist');
      var fashionSeasonQuickEdit = jQuery('ul.fashion-season-checklist');
      var fashionGenderQuickEdit = jQuery('ul.gender-checklist');

      var foodDrinkQuickEditCheckBox = jQuery('ul.product_cat-checklist li label input#in-product_cat-45:checkbox');
      var foodDrinkCategoryQuickEdit = jQuery('ul.food-drink-category-checklist');
      var foodDrinkBrandsQuickEdit = jQuery('ul.food-drink-brands-checklist');
      var foodDrinkCountryQuickEdit = jQuery('ul.country-of-origin-checklist');

      productCategoryQuickEdit.prev().prev().css("display", "block");

      if (fashionQuickEditCheckBox.is(':checked')) {
        fashionCategoryQuickEdit.css("display", "block");
        fashionBrandQuickEdit.css("display", "block");
        fashionSeasonQuickEdit.css("display", "block");
        fashionGenderQuickEdit.css("display", "block");
        fashionCategoryQuickEdit.prev().prev().css("display", "block");
        fashionBrandQuickEdit.prev().prev().css("display", "block");
        fashionSeasonQuickEdit.prev().prev().css("display", "block");
        fashionGenderQuickEdit.prev().prev().css("display", "block");
      }

      fashionQuickEditCheckBox.change(function(){
        if (this.checked) {
          fashionCategoryQuickEdit.css("display", "block");
          fashionBrandQuickEdit.css("display", "block");
          fashionSeasonQuickEdit.css("display", "block");
          fashionGenderQuickEdit.css("display", "block");
          fashionCategoryQuickEdit.prev().prev().css("display", "block");
          fashionBrandQuickEdit.prev().prev().css("display", "block");
          fashionSeasonQuickEdit.prev().prev().css("display", "block");
          fashionGenderQuickEdit.prev().prev().css("display", "block");
        } else {
          fashionCategoryQuickEdit.css("display", "none");
          fashionBrandQuickEdit.css("display", "none");
          fashionSeasonQuickEdit.css("display", "none");
          fashionGenderQuickEdit.css("display", "none");
          fashionCategoryQuickEdit.prev().prev().css("display", "none");
          fashionBrandQuickEdit.prev().prev().css("display", "none");
          fashionSeasonQuickEdit.prev().prev().css("display", "none");
          fashionGenderQuickEdit.prev().prev().css("display", "none");
        }
      });

      if (foodDrinkQuickEditCheckBox.is(':checked')) {
        foodDrinkCategoryQuickEdit.css("display", "block");
        foodDrinkBrandsQuickEdit.css("display", "block");
        foodDrinkCountryQuickEdit.css("display", "block");
        foodDrinkCategoryQuickEdit.prev().prev().css("display", "block");
        foodDrinkBrandsQuickEdit.prev().prev().css("display", "block");
        foodDrinkCountryQuickEdit.prev().prev().css("display", "block");
      }

      foodDrinkQuickEditCheckBox.change(function(){
        if (this.checked) {
          foodDrinkCategoryQuickEdit.css("display", "block");
          foodDrinkBrandsQuickEdit.css("display", "block");
          foodDrinkCountryQuickEdit.css("display", "block");
          foodDrinkCategoryQuickEdit.prev().prev().css("display", "block");
          foodDrinkBrandsQuickEdit.prev().prev().css("display", "block");
          foodDrinkCountryQuickEdit.prev().prev().css("display", "block");
        } else {
          foodDrinkCategoryQuickEdit.css("display", "none");
          foodDrinkBrandsQuickEdit.css("display", "none");
          foodDrinkCountryQuickEdit.css("display", "none");
          foodDrinkCategoryQuickEdit.prev().prev().css("display", "none");
          foodDrinkBrandsQuickEdit.prev().prev().css("display", "none");
          foodDrinkCountryQuickEdit.prev().prev().css("display", "none");
        }
      });

    }

  };

})(jQuery);

Then I enqueue these files in my functions.php:
add_action( 'admin_enqueue_scripts', 'load_my_custom_wp_admin_style' );
function load_my_custom_wp_admin_style() {
    wp_register_style( 'product_admin_quick_edit_css', get_stylesheet_directory_uri() . '/product-admin-quick-edit.css', false, '1.0.0' );
    wp_enqueue_style( 'product_admin_quick_edit_css' );
}

add_action( 'admin_print_scripts-edit.php', 'load_custom_quick_edit_scripts', 9999, 2 );
function load_custom_quick_edit_scripts(){
    wp_enqueue_script( 'product-admin-quick-edit-jquery', get_stylesheet_directory_uri() . "/js/product-admin-quick-edit-jquery.js", array( 'jquery', 'inline-edit-post' ), CHILD_THEME_VERSION, true );
}

Making sure to enqueue the scripts late at 9999, and making them dependent on inline-edit-post javascript from WP Core.
I'll refactor the jQuery into some sort of loop for adding and removing the css classes, it should reduce it down quite a bit.
Hope it helps someone else, I couldn't find any other material on dynamically displaying taxonomies in quick edit dependent on other taxonomies settings, so guess there isn't much need for it.


text:
Q: How should a good mobile database logic be structured? So far I've made dozens of apps which use database. I did not go too deep into database logic and how to structure it, but made it as simple as possible and by the rules.
For example, my database logic usually consists of one database class which extends SQLiteOpenHelper. Then I make CRUD methods for each table. Each time I have to deal with a database, I make a special AsyncTask and within it deal with the database. And this is it.
Talking to some developers, I was told that my logic structure should be more complex, more OOP. I tried finding samples on the net but they all were directed towards explaining how to deal with the database. I even reviewed some open source projects but they had the logic similar to mine.
Can you help me? How should I make database logic more OOP? I guess they mentioned that I should be able to reuse this logic in the future, changing only the lowest part which deals with a specific database and its tables.

A: This is a slightly subjective question, so here's a subjective answer. There is not one correct way to do it imho, I can only speak about how I personally like to work (the big project version, for small projects there's another story). For you or your team it might be different.
For the reference, I work mostly agile, e.g. requirements can change. APIs within the code can change (and do that quite often). This - of course - influences what I consider as useful and what I consider as not useful for my personal work.
Also, I like to work without big frameworks, whereever possible. That's why there is no framework in the model explained below.

I divide database work into three parts to work with: (quite some similatities with the MVC pattern)

*

*The actual database backend (which can execute SQL). Can contain own code for cross-platform work.

*The storage class(es), that takes care of storing application-specific information. Each piece of information can be read and set from storage classes, (example: interface AddressBook provides access to elements of the type interface Contact, which have getters and setters for some stuff. The implementation translates that to a single table in the backend).

*The application code, which performs actual work and is splitted up further depending on the application (example: stuff providing an address book GUI, etc.).

Why do I split that way? Well, one reason is the ease to switch to a new storage or database backend. If I discover that there could be more preformance when restructuring tables so that new requirements can be met, I update the storage classes. That way I do not have to touch any application logic (example: adding a 1:n table for email addresses to the address book. The new table and its relations do not affect any code within the application, it can recive a list of email addresses from a contact, and add or remove them with ease).
One other reason is that the application code is easy to read (as it consists of, well, application code), while storage code is also easy to read (as it only takes care of storing, caching and similar stuff).
The third reason is that in the case I wish to add another storage mechanism (for example when switching to a platform with a built-in database backend or when adding optional web services) - I can use all OOP mechanisms on the three layers; multiple storages for example can coexist within the same application, so that the user could choose between storing data locally (storage with database backend) or in the cloud.

I hope this answer gave you a little insight of some possibilities with OOP in database-related parts of your application. Again, this is not the one correct way to do it, just one I found working quite well.

A: Try ORMLite
Object Relational Mapping Lite (ORM Lite) provides some lightweight functionality for persisting Java objects to SQL databases while avoiding the complexity and overhead of more standard ORM packages. It supports a number of SQL databases using JDBC and also supports Sqlite with native calls to Android OS database APIs.
http://ormlite.com/sqlite_java_android_orm.shtml
http://sourabhsaldi.blogspot.in/2012/10/ormlite-tutorial.html

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I use a library in multiple classes w/o getting "multiple definition" errors I am starting a new c++ project and I want to use Boost.Build / bjam.
I'm getting "multiple definition" errors because, I think maybe, the jam file is not written correctly or I am not including the headers correctly or, perhaps, the library is not written well, which I have not investigated.
main.cpp uses libA.
rest.cpp uses libA.
libA is a header library. Therefore I need to include headers for libA in both main.cpp and rest.cpp of the compiler complains about namespaces etc...
I'm using gcc on debian.
Here are my jam files:
Jamroot.jam
import os ;
import modules ;

path-constant boost-root : "/home/dude/include/boost_1_48_0" ;
path-constant cgi-root : "/home/dude/include/cgi-0.7.1/libs/cgi/build" ;
path-constant BOOST_BUILD_PATH : "$(boost-root)/tools/build/v2" ;

# path-constant include-dir : /usr/local/include ;

use-project /boost/ : $(boost-root) ;
use-project /boost/cgi/ : $(cgi-root) ;

lib libsoci_core : : <file>/usr/local/lib/libsoci_core.so ;
lib libsoci_odbc : : <file>/usr/local/lib/libsoci_odbc.so ;
lib libboost_log : : <file>/usr/local/lib/libboost_log.so ;

Jamfile.jam
project hello_fcgi
: requirements
    <library>/boost/cgi/
    <library>/boost/system/
    <library>/boost/thread/
    <include>/usr/local/include/soci/
    <include>/usr/local/include/soci/odbc/
  ;

# exe rest : rest.cpp hello /boost/regex/ libboost_log libsoci_core libsoci_odbc ;
exe hello : main.cpp rest.cpp cms.cpp /boost/regex/ libboost_log libsoci_core libsoci_odbc ;

# Our install rule (builds binaries and copies them to <location>)
install install
 :
   hello
 :
   <location>/var/www/localhost/cgi-bin/
 ;

# Only install example if you use `bjam install' or equivalent
explicit install ;

The errors I get are repetitions of:
Performing configuration checks

    - has_icu builds           : yes
...patience...
...patience...
...found 3228 targets...
...updating 1 target...
gcc.link bin/gcc-4.4.5/debug/hello
bin/gcc-4.4.5/debug/rest.o: In function `basic_client':
/usr/include/c++/4.4/exception:62: multiple definition of `boost::cgi::common::basic_client<boost::cgi::common::tags::fcgi>::basic_client()'
bin/gcc-4.4.5/debug/main.o:/home/dude/include/cgi-0.7.1/boost/cgi/fcgi/client.hpp:44: first defined here

A: This defect report looks relevant: it seems this "header only" library has slipped up on a few things which aren't really just header only.


text:
Q: Convert classes that extends with JPanel into JPanel What i want do is,
I have a class named 'TestPanel' that extends from JPanel. and want to make it draggable by a method. But method returns JPanel type and shows this error when compiling.
cannot convert from JPanel to testpanel

Method cannot be make for return 'TestPanel' type because i hope to make more classes like testpanel. Here is the RegisterAsDraggable method that returns JPanel.
    public static JPanel RegisterAsDraggable(){
        final JPanel panel = new JPanel();
        ...
        return panel;
    }

Here is the class that extends from JPanel.
public class testpanel extends JPanel {
    JLabel titlelabel;

    public testpanel(){
        initsettings();

        GroupLayout layout = new GroupLayout(this);
        this.setLayout(layout);
        ...
    }
}

And here is my main class.
public class HelloWorld extends JFrame {

    public HelloWorld(){
        initcomponent();
        ...
    }

    private void initcomponent() {
        testpanel tstpan = DragsExternal.RegisterAsDraggable();
        ...
    }

    public static void main(String[] args){
        new HelloWorld().setVisible(true);
    }
}

I removed some of codes because for make this not too long.
-- Edit --
I tried to do that by casting testpanel into JPanel.( Accouding to your answers). But it showed this error
Exception in thread "main" java.lang.ClassCastException: javax.swing.JPanel cannot be cast to testpanel

Can anyone help?
Please excuse my English.

A: Please do yourself a favor: Learn and follow Java coding standards.
You just need to make one change:
 JPanel tstpan = DragsExternal.RegisterAsDraggable();

or
 testpanel tstpan = (testpanel) DragsExternal.RegisterAsDraggable();

A: you need to cast the Jpanel to a testpanel
private void initcomponent() {
    testpanel tstpan = (testpanel) DragsExternal.RegisterAsDraggable();
    ...
}


text:
Q: .NET Login and Splash Screens what to put in Application.Run In .NET (language: C#) when writing Windows Applications we start the application with a form passed to Application.Run.
But when you have an Application where you don't have a single window to keep it alive...
But rather if any of one type of forms is active you wan't the application to remain.
What I have is e.g. a Login Screen that when the user successfully log's in, I wan't to close.
However calling "Close()" obviously closes the entire app since the login screen is the one passed to the Application.Run.
The next screen has the same "fate" so can't use that either, that will be a screen where the user selects something and then it closes.
Anyways... long story short. I have a few ideas, but all involving some not so neat things.
So what I am asking for here is sort of a "Best Practice" in these cases.
This is not something with a definitive awnser, I know that, so please all good ideas are welcome and discussions around them.

A: Create a main function where you create the windows (and show them).
For this you must define that the application should not be ended when the main or the last window is closed

A: The Code Project article ended up being the basis for the solution (as it is now).
There is still some parts to sort out in the "Navigator" part, but the override of the context works perfectly.
The essence of the implementation:
public class ApplicationContextNavigator : ApplicationContext, INavigator
{
  private readonly IWindsorContainer container;
  private IView Current { ... }
  public ApplicationContextNavigator(IWindsorContainer container) {...}
  public void Start<TView>() where TView : IView { ... }
  public void Start<TView>(IViewInitializer initializer) where TView : IView
  {
    Current = InitializeView<TView>(initializer);
    Application.Run(this);
  }

  public void Navigate<TView>() where TView : IView { ... }
  public void Navigate<TView>(IViewInitializer initializer) where TView : IView
  {
    IView closing = Current;
    IView showing = InitializeView<TView>(initializer);

    showing.Location = closing.Location;
    showing.Show();

    Current = showing;
    closing.Close();
  }

  private IView InitializeView<TView>(IViewInitializer initializer) where TView : IView
  {
    IView view = container.Resolve<TView>();
    initializer.Initialize(view);
    return view;
  }

  protected override void OnMainFormClosed(object sender, EventArgs e)
  {
    if(sender == Current)
    {
      base.OnMainFormClosed(sender, e);
    }
  }
}


text:
Q: MYSQL matching one column to another in a different table via a FULLTEXT index I current have two different tables.
The first table has a list of titles and IDs associated to these titles; the second table is a list of random heading.
What I would like to know is if there is a way to match up all the titles in table 2 to the closest matching title in table 1. Is this possible?
I've tried :
SELECT    title_table .*,
          random_titles.*,
          MATCH (title_table.title) AGAINST (random_titles.title) AS relevance
FROM      title_table
ORDER BY  `relevance` DESC

But that did not work.
I know I could use this query as each title is being put in table 2 with PHP but I already have a lot of titles in the database.

A: AGAINST() only accepts a string literal or a variable containing a string -- something the optimizer can deterministically resolve to a constant.

AGAINST takes a string to search for, and an optional modifier that indicates what type of search to perform. The search string must be a string value that is constant during query evaluation. This rules out, for example, a table column because that can differ for each row.
-- http://dev.mysql.com/doc/refman/5.6/en/fulltext-search.html

This rules out any construct I can think of where an ordinary query could be used to join tables based on a fulltext index match.
...however...
You can wrap the fulltext query in a stored function:
DELIMITER $$

DROP FUNCTION IF EXISTS `best_fulltext_match` $$
CREATE FUNCTION `best_fulltext_match` (search_string TEXT) RETURNS INT
DETERMINISTIC
READS SQL DATA
BEGIN

  RETURN (SELECT id FROM title_table WHERE MATCH(title) AGAINST(search_string)
           ORDER BY MATCH(title) AGAINST (search_string) DESC LIMIT 1);

END $$

DELIMITER ;

Now...
SELECT best_fulltext_match('your title here');

...returns the id of the best match according to the fulltext index in title_table, and this function will accept a variable, no problem.
You could then use this to update your random_title_table.
UPDATE random_title
   SET title_id = best_fulltext_match(title);

The function is invoked once per row in random_title, and gives the fulltext search a static value to search with.
You could also use that same function when creating new entries in random_title.

A: The "the closest matching" constraint make me think to the MySQL function SOUNDEX.
I never used this feature but maybe it's well designed for you :)
Max.


text:
Q: Memory managment when drawing to a view on the iPhone I have a UIImage that I'm instantiating using imageWithData: (the data is loaded from the bundle using [NSData dataWithContentsOfFile:]).
I'm then drawing the image like so:
NSData *imageData =  [NSData dataWithContentsOfFile:fileLocation];
UIImage *myImage = [UIImage imageWithData:imageData];

//These lines are superfluous from what I can tell, replacing with
//UIImage *myImage = [UIImage imagedNamed:imageName]; very soon.

[myImage drawAtPoint:CGPointMake(0,0)];
//myImage will be released at the end of the run loop

My question is this: The UIImage created is autoreleased. What happens in terms of memory when the UIImage is drawn to the view and then the UIImage is deallocated out of existence. Obviously, visually, the image is still there as it has been drawn to a context.
Does the memory usage double if the UIImage is valid AND has been drawn to the view, and then return to the same amount as if only one UIImage existed after the UIImage has been deallocated?

Now going down another route.
If I used [UIImage imageNamed:] to instantiate the image, then the UIImage class has its own image cache of sorts and will only ever hold one true instance of a particular image (regardless of how many UIImage instances are created to represent that one image).
My other question is: What happens to the image in the cache if I draw it to a context and then the UIimage is released (via autorelease at the end of the run loop)? Does the image stay in the cache an consume memory? Is it removed because no other UIImage instances are using it?
Any help would be great, thanks!

A: At any point, when you "draw to context", the context does not hold a reference to the image. Instead, drawing will place the actual bits of pixels on the context, so it doesn't need the reference to UIImage (or anything drawn to it - NSString, NSPath etc).
Regarding imageNamed:, it will never be really released - what you get is a refernece that you don't (and shouldn't) release, but the cached image might still be there.

A: I really recommend starting with simple code here and then optimizing where you are actually having trouble. The kind of space optimizations you're describing are likely to create serious time problems (recreating the UIImage in -drawRect: for instance is very expensive). That said, let's look through the various questions:

*

*First, as I said, be careful with doing expensive work in -drawRect:. You have little control over how often or when it gets called, and any expensive work here (like creating a new UIImage, particularly if you have to read it from disk) can seriously impact UI performance.

*I'm assuming that there's a lot more to your -drawRect: then this, correct? UIImageView is optimized for what you've done here, both in speed and in memory. But if your view is much more complicated, then drawing the image yourself is better than creating lots of sub-views.

*As has been noted, when you call -drawAtPoint:, the copy you make is a bitmap representation (blended with any other drawing that is done). It's unrelated to the original UIImage in terms of memory usage. You cannot trade one for the other. The memory required for the bitmap representation is a function of the view size and bit depth, and you're not going to be able to change it. It doesn't care if the UIImage exists after it's been drawn.

*-imageNamed: does do caching for you and is generally a good choice. Note that it doesn't clear its cache in low-memory situations. The UIImages themselves transparently dump their underlying data if they were loaded from a file (and they dump extra representations in any case). The UIImage reference includes information about how this is done.

*If you're very concerned about performance around these images (space or time), and you don't need the functionality of UIImage, you should be working with CGImages. They are not as flexible as UIImages, and they're more complex to code, but they are more efficient. That said, UIImages are good for most purposes.

A: It really depends on where you're creating the UIImage instance itself. If this is a UIView subclass, are you creating the UIImage in -drawRect: or -initWithFrame: or somewhere else? If you load the image once (in your init or with a setter which retains, etc.) then there shouldn't be a problem. However if you're creating the image over and over again in -drawRect: then at the very least you will have a performance problem.


text:
Q: Unable to read video file using cv2.VideoCapture() function in OpenCv import numpy as np
import cv2

cap = cv2.VideoCapture("1.mp4")

while(cap.isOpened()):
    ret, frame = cap.read()
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    cv2.imshow('frame',gray)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()

Its throwing error

libv4l2: error getting capabilities: Inappropriate ioctl for device
  VIDEOIO ERROR: V4L: device 1.mp4: Unable to query number of channels
  after compiling.


text:
Q: Qt Sensors Qml compile error I am looking at the example application for the Qt Sensors that comes with qt and I've complied it on windows with no errors, but as soon as I try to put it onto my android I get this compile error.
10:41:51: Running steps for project qmlqtsensors...
10:41:51: Configuration unchanged, skipping qmake step.
10:41:51: Starting: "C:\Qt\Qt5.2.1\Tools\mingw48_32\bin\mingw32-make.exe"
mingw32-make: Nothing to be done for 'first'.
10:41:52: The process "C:\Qt\Qt5.2.1\Tools\mingw48_32\bin\mingw32-make.exe" exited normally.
10:41:52: Removing directory C:\Qt\Qt5.2.1\5.2.1\android_x86\examples\sensors\build-qmlqtsensors-Android_for_armeabi_v7a_GCC_4_8_Qt_5_2_1-Release\android-build
10:41:52: Starting: "C:\Qt\Qt5.2.1\Tools\mingw48_32\bin\mingw32-make.exe" INSTALL_ROOT="C:\Qt\Qt5.2.1\5.2.1\android_x86\examples\sensors\build-qmlqtsensors-Android_for_armeabi_v7a_GCC_4_8_Qt_5_2_1-Release\android-build" install
copy /y "libqmlqtsensors.so" "C:\Qt\Qt5.2.1\5.2.1\android_x86\examples\sensors\build-qmlqtsensors-Android_for_armeabi_v7a_GCC_4_8_Qt_5_2_1-Release\android-build\libs\armeabi-v7a\libqmlqtsensors.so"
        1 file(s) copied.
The full path of C:C:\Qt\Qt5.2.1\5.2.1\android_x86\examples\sensors\build-qmlqtsensors-Android_for_armeabi_v7a_GCC_4_8_Qt_5_2_1-Release\android-build\Qt\Qt5.2.1\5.2.1\android_armv7\examples\qtsensors\qmlqtsensors is too long.
makefile:873: recipe for target 'install_app' failed
mingw32-make: *** [install_app] Error 1
10:41:53: The process "C:\Qt\Qt5.2.1\Tools\mingw48_32\bin\mingw32-make.exe" exited with code 2.
Error while building/deploying project qmlqtsensors (kit: Android for armeabi-v7a (GCC 4.8, Qt 5.2.1))
When executing step 'Copy application data'
10:41:53: Elapsed time: 00:02.

I've looked on google with no avail. Can anyone help me with this problem please?

A: It seems the error or at least one of them is because the path to your file qmlqtsensors is too long.
The full path of C:C:\Qt\Qt5.2.1\5.2.1\android_x86\examples\sensors\build-qmlqtsensors-Android_for_armeabi_v7a_GCC_4_8_Qt_5_2_1-Release\android-build\Qt\Qt5.2.1\5.2.1\android_armv7\examples\qtsensors\qmlqtsensors is too long.

Try to compile and run your project at a different location with a shorter path.

A: I get the error on this example (and had the same on previous examples some while ago).
My problem turned out to be that when the Makefile is generated, it generates 'wrong' code.  It generates stuff like:
      mkdir C:$(INSTALL_ROOT)/........
which is fine if $(INSTALL_ROOT) evaluates to a relative path but in fact it resolved to an absolute path, that is:
      mkdir C:C:/Qt/.......
So simply edited the Makefile replacing all occurrences of 'C:$(INSTALL_ROOT)' with '$(INSTALL_ROOT)'.  It worked for me and hopefully you too.


text:
Q: How to apply $watchCollection to grid in template(html page) that is included using ng-include in another page? I am new to angularJS.
I have a page that contains a grid filled with data.

Controller code
$scope.$watchCollection('personGrid', function (newVal, oldVal) {

            console.log('Working -- New value');
            console.log(newVal);

        });

I had applied $watchCollection in controller,  when i select any single row it fires the $watchCollection event and all works fine.
I had use the above template in another new hmtl page.

And code in controller used for  new html page.
 $scope.$parent.$watchCollection('personGrid', function (newVal, oldVal) {

            console.log('Working --');
            console.log(newVal);
        });

But they event is only fired when page load first time. after that when i select any row in table grid , the event is not fired. : (
Any help, some better solution. May be we can add the data in $rootScope and apply $watch.


text:
Q: How to show timeEditor on date select using rich:calendar I want to make a calendar where you can select the date, and automatically you can select the time. I shouldn't use butons to change the time :(
So I have the next:
<rich:calendar id="currentDate" popup="true"
    datePattern="dd/MM/yyyy - HH:mm" enableManualInput="false"
    showFooter="false" required="true" resetTimeOnDateSelect="true"
    oncollapse="return timeSelected;"
    showWeeksBar="false" showWeekDaysBar="true"
    value="#{bean.currentDate}"
    ondateselected="timeSelected=false; Richfaces.getComponent('calendar',this).showTimeEditor(); return true;"
    ontimeselected="timeSelected=true; return true;"
    ontimeselect="timeSelected=true; return true;"
>
    <a4j:support event="onchange" ajaxSingle="true" />
</rich:calendar>

But it doesn't work at all.
There are two problems.
1 - When you choose a day, the popup appears. But if you press 'Accept' withouth changing the time, you can't close the calendar :(
2 - Once you have selected the date/time, but you want to change only the time, you can't do it because you can't select the current day, so you can't see the time editor.
I'm using rich faces 3.3.3
Thanks

A: The ondateselected and ontimeselected attributes are only invoked when the date or time is actually changed, not when you just click on the date or closes the time editor. There are no standard <rich:calendar> attributes which capture that. You need to override the standard calendar.js functions eventCellOnclick() (which is invoked when a date is clicked) and hideTimeEditor() (which is invoked when time editor is closed).
The following works for me with RichFaces 3.3.3 (and Mojarra 1.2_15 and Tomcat 7.0.29).
<h:form id="form">
    <rich:calendar id="currentDate" popup="true"
        datePattern="dd/MM/yyyy - HH:mm" enableManualInput="false"
        showFooter="false" required="true" resetTimeOnDateSelect="true"
        showWeeksBar="false" showWeekDaysBar="true"
        value="#{bean.currentDate}"
        oncollapse="return this.component.timeSelected;"
    >
        <a4j:support event="onchange" ajaxSingle="true" />
    </rich:calendar>
</h:form>

<script>
    var currentDateComponent = $('form:currentDate').component;

    var originalCellOnClickFunction = currentDateComponent.eventCellOnClick;
    currentDateComponent.eventCellOnClick = function() {
        this.timeSelected = false;
        originalCellOnClickFunction.apply(this, arguments);
        currentDateComponent.showTimeEditor();
    };

    var originalHideTimeEditorFunction = currentDateComponent.hideTimeEditor;
    currentDateComponent.hideTimeEditor = function() {
        this.timeSelected = true;
        originalHideTimeEditorFunction.apply(this, arguments);
    };
</script>

Note that ondateselected, ontimeselect and ontimeselected attributes are removed and that oncollapse attribute has been changed. Also note that the script must be executed after the calendar is been populated in the DOM. So the above works as-is. If you want to move the script into its own JS file (which is a good thing), make sure that it's executed on DOM ready only (i.e. put script in end of <body>, or execute it by window.onload() or jQuery.ready()).


text:
Q: .NET compression of XML to store in SQL Server database Currently our .NET application constructs XML data in memory that we persist to a SQL Server database. The XElement object is converted to a string using ToString() and then stored in a varchar(MAX) column in the DB. We dind't want to use the SQL XML datatype as we didn't need any validation and SQL doesn't need to query the XML at any stage.
Although this implementation works fine, we want to reduce the size of the database by compressing the XML before storing it, and decompressing it after retrieving it. Does anyone have any sample code for compressing an XElement object (and decompressing would be great too)? Also, what changes would I need to make to the data type of the database column so that we can fully take advantage of this compression?
I have investigated again the XML datatype SQL Server 2005 offers, and the validation overhead it offers is too high for us to consider using it. Also, although it does compress the XML somewhat, it doesn't as much compression as the .NET DeflateStream class.
I have tested the DeflateStream class by writing the XML we use to disk, and then saving the comrpessed version as a new file. The results are great, a 16kb file goes down to a 3kb file, so it's jsut a case of getting this to work in memory and saving the resulting data to the DB. Does anyone have any sample code to do the compression, and should I change the varcahr(MAX) colum to type to maybe varbinary?
Thanks in advance

A: This article may help you get a start.
The following snippet can compress a string and return a base-64 coded result:
public static string Compress(string text)
{
 byte[] buffer = Encoding.UTF8.GetBytes(text);
 MemoryStream ms = new MemoryStream();
 using (GZipStream zip = new GZipStream(ms, CompressionMode.Compress, true))
 {
  zip.Write(buffer, 0, buffer.Length);
 }

 ms.Position = 0;
 MemoryStream outStream = new MemoryStream();

 byte[] compressed = new byte[ms.Length];
 ms.Read(compressed, 0, compressed.Length);

 byte[] gzBuffer = new byte[compressed.Length + 4];
 System.Buffer.BlockCopy(compressed, 0, gzBuffer, 4, compressed.Length);
 System.Buffer.BlockCopy(BitConverter.GetBytes(buffer.Length), 0, gzBuffer, 0, 4);
 return Convert.ToBase64String (gzBuffer);
}

EDIT: As an aside, you may want to use CLOB formats even when storing XML as text because varchars have a very limited length - which XML can often quickly exceed.

A: I think you should also re-test the XML column. It stores in binary, I know, not as text. It could be smaller, and may not perform badly, even if you don't actually need the additional features.

A: Besides possibly compressing the string itself (perhaps using LBushkin's Base64 method above), you probably want to start with making sure you kill all the whitespace. The default XElement.ToString() method saves the element with "indenting". You need to use the ToString(SaveOptions options) method (using SaveOptions.DisableFormatting) if you want to make sure you've just got the tags and data.

A: I know you tagged the question SQL 2005, but you should consider upgrading to SQL 2008 and using the wonderful new compression capabilities that come with it. Is out-of-the-box, transparent for your application and will save you a huge implementation/test/support cost.


text:
Q: When a plugin is registered in joomla observer? I have done a plugin for a simple debug purpose, print some data ( avoiding the code to be delete on each update ) .
I have build a plugin following official tutorial, but code does not go there ( seen with xdebug )
THe plugin isn't registered among observers, so it's action is not thrown. I image that plugin are registered while the plugin is installed? or I can change code after being installed?
Thanks
class plgSystemVmdataprint extends JPlugin
{
function onAfterRender()
{

$data = JRequest::get('post');
            if(!($_REQUEST['option']='com_virtuemart' && $_REQUEST['view']='product' && $_REQUEST['task']='edit') )
            {
                $textFIleSave = JPATH_VM_SITE . DS . 'plugins'. DS . 'vmdataprint' . DS . 'productsaveprint'. DS . 'productsave.txt';
                file_put_contents($textFIleSave, print_r($data, true));
            }

}
}


text:
Q: Collect DLL usage data (Open Source) Is it legal to collect some usage data of a open source library?
Let's say, I would like to know Things like These:

*

*Name of the assembly, using the library

*Number of Startups of the assembly, using the library

Am I allowed to collect information like these as soon as the .net assembly loads (we're talking about Desktop applications).

A: If you do not want to get into trouble, your library should not collect this information secretly, you should ask every user of the lib for permission, and also make sure (maybe by some "terms of use") any end user of a program which includes this lib has given his permission for collecting the data and sending it back to you. The amount of trouble you get if you do not follow these rules depend surely on your local jurisdiction, if you want more info on this, ask a lawyer.
Be aware that any user who cares a little bit for his privacy won't probably give you such a permission, so expect any usage data you get to be incomplete.


text:
Q: How to create Binance test API key I'm trying to build a Binance trading bot, I generated an API key and can use it with a real money, but I need to test the bot using their test -sandbox- account
I looked in the documentation and couldn't find out how to create a testing API key
Where can I found it?

A: For futures testnet, register and login here: https://testnet.binancefuture.com/
You will see "API KEYS" tab in the panel just below the main chart panel
(the other tabs in this panel are: Positions(0) / Open Orders(0) / Order History / Trade History / Transaction History / Assets / and, finally, API Key)
I hope this will save your time

A: Try this : https://testnet.binance.vision/
Sign in with github and then press Generate HMAC_SHA256 Key


text:
Q: URL change without re rendering in React router I am working on an application where I need to change the url of the page without causing a re-render.
I am making a call to fetch all the pages inside componentDidMount like this
componentDidMount() {
    axios.get('/pages')
      .then(response => {
        this.setState({
          pages: response.data,
          slugs: response.data.pages.map(item => Slug(item.title))
        })
      })

Once I have all the pages then I want to show the individual pages.
For eg. in the url it has to be like /page/1/slug-for-page-1 and /page/2/slug-for-page-2 based on a state variable activePageNumber and the active page content will be displayed. Also the corresponding slug should be there on the url.
I tried adding a callback after setState like below, but it didn't work.
() => this.props.history.push({
          pathName: '/page',
          state: {activePageNumber : activePageNumber},
        })

I thought of adding a child component to manage the activePageNumber state, but I am not sure if its the best way to do it and whether it'll prevent the re-render.
I can implement it such that each page make a separate request to the backend, but I wish to call it only once, and then update the url based on the active page number.
I am not sure how to implement this in react.
I have the following versions

"react-router-dom": "^5.0.0"
"react": "^16.8.6"

A: If you define your /page route like this:
<Route
  path="/page/:number"
  component={({ match }) => (
    <Pages activePageNumber={match.params.number} />
  )}
/>

The Pages component method componentDidMount will be called when you switch from, for example, /home to /page/1, but will not be called when you switch from /page/1 to /page/2, because the DOM elements inside the /page/:number Route remain of the same type. I suggest you read React's documentation on reconciliation for a better explaination.
So you can safely put the call to your /pages service inside of the Pages component, and then in its render method display the page you need based on the activePageNumber prop.
class Pages extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      pages: null,
    };
  }

  componentDidMount() {
    axios.get('/pages')
      .then(response => {
        this.setState({
          pages: response.data
        })
      });
  }

  render() {
    const { pages } = this.state;
    const { activePageNumber } = this.props;

    return pages ? (
      <Page page={pages[activePageNumber]} />
    ) : (

loading...

    );
  }
}

A: We can make use of Navigate from 'react-router-dom'

const navigate = useNavigate();
<Button onClick={() => navigate('/products/addnewproduct')}>
Click Me
</Button>


text:
Q: Bold text in ObservableList breaks ChangeListener I want a header in my ObservableList that is bold. I've got it bold but it hits the exception block when it's selected because it is not a string. I can make the other items Text but then the ChangeListener wants a string. I just want the exception to go away.
Is there a way to make it not select-able OR bold and of type string?
   ListView<String> list = new ListView<>();
   ObservableList items = FXCollections.observableArrayList();
   Task curr = tasklist.head;

   items.add(TextBuilder.create().text("Done Tasks").style("-fx-font-weight:bold;").build());
   items.add(curr.name + " - " + curr.description);
   //items.add(new Text(curr.name + " - " + curr.description));

   try {
        list.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<String>() {
            public void changed(ObservableValue<? extends String> ov,
                                final String oldvalue, final String newvalue) {
                if(newvalue != "Done Tasks")
                    selectedValue[0] = newvalue.split(" - ")[0];
                else
                    selectedValue[0] = "done";
            }
        });
    } catch(Exception e)
    {
        actiontarget.setFill(Color.FIREBRICK);
        actiontarget.setText("You must select a task.");
    }

A: Quick and Dirty Answer
To directly answer your wishes "I can make the other items Text but then the ChangeListener wants a string. I just want the exception to go away.", you can change the type of the ChangeListener to accept Object rather than String:
new ChangeListener<Object>() {
    @Override
    public void changed(ObservableValue<? extends Object> observable, Object oldValue, Object newValue) {
        if(!(newvalue instanceof Text)) {
            String string = ((String) newvalue).split(" - ")[0];
            System.out.println(string);
        }
    }
}

However, I do not recommend the above approach as you lose some of the innate type safety goodness that the Java environment provides.
Coding Advice
Some advice based upon your code snippet.

*

*Use cell factories to generate ListView cell nodes from the underlying item model data for the ListView.

*Don't put nodes such as Text directly into the ListView item list.  The ListView item list is for representing model objects which are not nodes.  I know the ListView javadoc doesn't state this explicitly, but, nevertheless that is still the best recommendation I have.  Whenever you think a node would be a good fit in a ListView, your better option is usually to use a cell factory.

*When you do place items into the ListView, they should match the type of the items of the ListView (the javadoc for ListView does state this).

*For a non-trivial use case such as you have here, use a more complicated data structure to represent the items in the list, so that you can encode semantic data such as whether or not an item is a header directly into the item rather than hardcoding strings such as "Done Tasks".

*Don't use the Builder classes, such as TextBuilder, they are deprecated and will be removed from future JavaFX runtime distributions.

*Use external stylesheets and manipulate styles by setting and unsetting style classes instead of inlining style definitions in code.

Sample Incorporating Advice
Based upon the advice you could code your problem up as something like the application below (note it still isn't extracting the style info to an external stylesheet, I'll leave that part as an exercise):

import javafx.application.Application;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.stage.Stage;

public class ListDisplay extends Application {
    @Override
    public void start(Stage stage) {
        ListView<TaskItem> listView = new ListView<>(
                FXCollections.observableArrayList(
                        new TaskItem("Todo Tasks", null, true, true),
                        new TaskItem("Senility", "The Autumn Years", false, false),
                        new TaskItem("Death", "But I didn't eat the salmon mousse", false, false),
                        new TaskItem("Done Tasks", null, true, true),
                        new TaskItem("Birth", "The Miracle of Life", true, false),
                        new TaskItem("School", "Growth and Learning", true, false),
                        new TaskItem("Middle Age", "Stagnation", true, false),
                        new TaskItem("Live Organ Transplants", "The Machine that goes 'Ping'", true, false)
                )
        );

        listView.setCellFactory(param -> new ListCell<TaskItem>() {
            @Override
            protected void updateItem(TaskItem item, boolean empty) {
                super.updateItem(item, empty);

                if (!empty && item != null) {
                    if (item.isHeader()) {
                        setText(item.getName());
                        setStyle("-fx-font-weight: bold;");
                    } else {
                        setText(item.getName() + " - " + item.getDescription());
                        setStyle(null);
                    }
                } else {
                    setText(null);
                }
            }
        });

        listView.setPrefHeight(200);

        listView.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> {
            if (!newValue.isHeader()) {
                System.out.println("Selected: " + newValue.getName());
            }
        });

        stage.setTitle("Monty Python's Meaning of Life");
        stage.setScene(new Scene(listView));
        stage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }

    private static class TaskItem {
        private final String name;
        private final String description;
        private final SimpleBooleanProperty completed;
        private final boolean header;

        public TaskItem(String name, String description, boolean completed, boolean header) {
            this.name = name;
            this.description = description;
            this.completed = new SimpleBooleanProperty(completed);
            this.header = header;
        }

        public boolean isHeader() {
            return header;
        }

        public boolean isCompleted() {
            return completed.get();
        }

        public SimpleBooleanProperty completedProperty() {
            return completed;
        }

        public String getName() {
            return name;
        }

        public String getDescription() {
            return description;
        }
    }
}


text:
Q: Does Kotlin have any generic constraints other than upper bounds? https://kotlinlang.org/docs/reference/generics.html#generic-constraints says

The most common type of constraint [on a type parameter] is an upper bound

but doesn't list any others. Are there any other constraints on type parameters supported in Kotlin, or planned in future (except for type classes, which I know about)?

A: At this time (as of Kotlin 1.2) no other constraints are supported, but it's possible that other constraint types will be added in the future.


text:
Q: How can I display a text in a C# label like written in the editor I'm working on a C# label but when I use the .Text I can't write on more than one line.
But I would like to write it in Visual Studio and it should directly be formatted like that.
Is this even possible?
Is there a tag instead of the "" which is working on more lines?

A: You can append the new line in your label text with Environment.NewLine
label1.Text = "First Line"+ Environment.NewLine + "Second Line".

Also, you must set AutoSize property false

A: Try this
string strHTML = "
Hello World!
";
Label.Text = Server.HtmlDecode(strHTML);

A: Try this:
lblAdress.Text = "Hi" + "\n" + "Hello";

lblAdress is my label ID

A: You can use StringBuider to format your text to different lines:
StringBuilder sb = new StringBuilder();
sb.AppendLine("The quick");
sb.AppendLine("brown fox");
sb.AppendLine("jumps over");
sb.AppendLine("the lazy dog.");
this.label1.Text = sb.ToString();

You can also play with Label.AutoSize property if ever you need to control the container.
As a suggestion if you want to have more control on formatting, you can subscribe to a control's OnPaint event and use the e.Graphics to draw the string you want to apply the formatting/styling.

A: Try this
label1.Text = "Try"+"
"+"this";

You can append HTML
 in between your lines

A: if it is winform then i will do the following ways.
 private void button1_Click(object sender, EventArgs e)
        {
        var sampleText = "hello\nasfasd\nasdfasdfa\nsdff";
        label1.Text = sampleText;
           // the other way to do the same thing.
            sampleText =
@"hello
world
123";
            label1.Text = sampleText;

        }


text:
Q: Error when building Haxe project from Sublime Text 3 I'm getting the error:
Traceback (most recent call last):
  File "/Volumes/Sublime Text/Sublime Text.app/Contents/MacOS/sublime_plugin.py", line 549, in run_
    return self.run(edit)
  File "HaxeComplete in /Users/graphic/Library/Application Support/Sublime Text 3/Installed Packages/Haxe.sublime-package", line 338, in run
  File "HaxeComplete in /Users/graphic/Library/Application Support/Sublime Text 3/Installed Packages/Haxe.sublime-package", line 925, in run_build
TypeError: 'NoneType' object is not iterable

In the console when I try to build my project. Is this a permissions issue or something? I'm unable to find much about it online when I search. I've tried different build targets to no avail, and I got the same error in Sublime Text 2.
As an important side note, the Build option in the menu is greyed out, and when I try to run it via keyboard shortcut I get "No Build System".

A: This problem appeared to boil down to a combination of two things:

*

*I made sure to get the latest version of Haxe and Haxelib.

*When I tried to trigger a build from Sublime Text 3, I had to make sure to have the project's build XML file open and active. Once it was the active file, I'd then choose a build target and start the build. After it had built successfully, I could change the active file and still complete a build, but sometimes it would appear to "forget" and I'd have to go back to the XML file, choose a build target, and trigger the build once again from the build XML file.


text:
Q: How Come Everybody Can See My Private Files? Sorry for the newbie question...
When I go to http://www.plans4boats.com/scripts/youtubeplayer/ in Google Chrome, I can see a full listing of the files there.  What should I do if I don't want any old hacker to just come in and view/copy my source codes?  Does it have something to do with htaccess?
I discovered that putting a blank index.html file in the folder helps for THAT folder, but it still leaves all subfolders vulnerable.
What should I google for more information on how to set up my server to prevent this?

A: Just set Options -Indexes for that particular directories either in an .htaccess file or a <Directory> or <Location> container.

A: What you need to do is turn of Directory Listing for your specific server.  I don't know what server you're using so I can't walk you through it, but just google your server name and how to disable directory listing.

A: I created a file called .htaccess and put the following contents:
IndexIgnore /


text:
Q: How to add a new visitortag to the current user (Sitecore)? I'm using Sitecore 6.6. I want to add a new visitortag to the current user in programcode (C#). Does anyone know how to do this?
Thanks a lot.
Jordy

A: You can assign tags to the current analytics visitor through the Analytics API:
Sitecore.Analytics.Tracker.Visitor.Tags.Add("MyTagName", "content of my tag");

To debug, you can check the VisitorTags table in the Analytics database but keep in mind that it might take a few moments until the tags are saved down to the database as Analytics saves them asynchronously.
Also keep in mind that Analytics is disabled during editing mode.

A: The "Set" method acts as an Add/Update. Depending on whether the visitor is returning, or new, this could reduce code blocks needed.

Tracker.Visitor.Tags.Set("YourTagName", "YourTagValue" );

By default, sitecore has a list of visitor tags, it uses for it's reports. (Email, First Name, Second Name, Company, Organization, Full Name, StateProvince). I found this out by looking at query used to build the visit reports "/sitecore/system/Settings/Analytics/Reports SQL Queries/Visits Visitor Tags". It reduced the amount of tags I thought I had to create.
Mark also has an awesome answer here where he explains how to add custom visitor tags you create to the Visit Reports. If I had the rep I would up vote you Mark. It was a big help.


text:
Q: Sed : removing lines where pattern result also appears elsewhere Let's suppose I have this sample
 foo/bar/123-465.txt
 foo/bar/456-781.txt
 foo/bar/102-445.txt
 foo/bar/123-721.txt

I want to remove every line where the regex /[0-9]*- result also appears on another line. In other terms : I want to remove every line where the file prefix is present more than once in my file.
Therefore only keeping :
 foo/bar/456-781.txt
 foo/bar/102-445.txt

I bet sed can do this, but how ?

A: Ok I misunderstood your problem, here's how to do it:
grep -vf <(grep -o '/[0-9]*-' file | sort | uniq -d) file

In action:
 cat file
 foo/bar/123-465.txt
 foo/bar/456-781.txt
 foo/bar/102-445.txt
 foo/bar/123-721.txt

grep -vf <(grep -o '/[0-9]*-' file | sort | uniq -d) file
 foo/bar/456-781.txt
 foo/bar/102-445.txt

A: You can use the following awk script:
example.awk:
{
  # Get value of interest (before the -)
  prefix=substr($3,0,match($3,/\-/)-1)

  # Increment counter for this value (starting at 0)
  counter[prefix]++

  # Buffer the current line
  buffer[prefix]=$0
}

# At the end print every line which's value of interest appeared just once
END {
  for(index in counter)
    if(counter[index]==1)
      print buffer[index]
}

Execute it like this:
awk -F\ -f example.awk input.file

A: awk '
 match($0, "[0-9]*-") {
    id=substr($0, RSTART, RLENGTH)
    if (store[id])
       dup[id] = 1
    store[id] = $0
 }
 END {
    for(id in store) {
      if(! dup[id]) {
        print store[id]
      }
    }
 }
'


text:
Q: Using AVAudioSequencer to send MIDI to third-party AUv3 instruments I'm having trouble controlling third-party AUv3 instruments with MIDI using AVAudioSequencer (iOS 12.1.4, Swift 4.2, Xcode 10.1) and would appreciate your help.
What I'm doing currently:

*

*Get all AUs of type kAudioUnitType_MusicDevice.

*Instantiate one and connect it to the AVAudioEngine.

*Create some notes, and put them on a MusicTrack.

*Hand the track data over to an AVAudioSequencer connected to the engine.

*Set the destinationAudioUnit of the track to my selected Audio Unit.
So far, so good, but...
When I play the sequence using AVAudioSequencer it plays fine the first time, using the selected Audio Unit. On the second time I get either silence, or a sine wave sound (and I wonder who is making that). I'm thinking the Audio Unit should not be going out of scope in between playbacks of the sequence, but I do stop the engine and restart it again for the new round. (But it should even be possible to swap AUs while the engine is running, so I think this is OK.)
Are there some steps that I'm missing? I would love to include code, but it is really hard to condense it down to its essence from a wall of text. But if you want to ask for specifics, I can answer. Or if you can point me to a working example that shows how to reliably send MIDI to AUv3 using AVAudioSequencer, that would be great.
Is AVAudioSequencer even supposed to work with other Audio Units than Apple's? Or should I start looking for other ways to send MIDI over to AUv3?
I should add that I can consistently send MIDI to the AUv3 using the InstrumentPlayer method from Apple's AUv3Host sample, but that involves a concurrent thread, and results in all sorts of UI sync and timing problems.
EDIT: I added an example project to GitHub:
https://github.com/jerekapyaho/so54753738
It seems that it's now working in iPadOS 13.7, but I don't think I'm doing anything that different than earlier, except this loads a MIDI file from the bundle, instead of generating it from data on the fly.
If someone still has iOS 12, it would be interesting to know if it's broken there, but working on iOS 13.x (x = ?)

A: In case you are using AVAudioUnitSampler as an audio unit instrument, the sine tone happens when you stop and start the audio engine without reloading the preset. Whenever you start the engine you need to load any instruments back into the sampler (e.g. a SoundFont), otherwise you may hear the sine. This is an issue with the Apple AUSampler, not with 3rd party instruments.
Btw you can test it under iOS 12 using the simulator.


text:
Q: How to find string that occurs between 3rd and 4th instances of a character What I think I'm needing is an expression to exclude anything outside of the 3rd and 4th instances of a character, backlashes in this case. Does that sound right?
The problem I'm trying to solve is how to get the ShareName from a given UNC path in PowerShell.
Find: "Share01" in example source string:
\\FQDN\Share01\Directories\...\...\...\...
PowerShell's Split-Path is proving to be a bit limitied in this regard, and RegEx is ...hard!

A: Hm I'm really late to this party, but I will suggest an alternative: Use the [Uri] type:
$unc = '\\FQDN\Share01\Directories\...\...\...\...'
$upath = [Uri]$unc

Testing if the path really is a UNC path:
$upath.IsUnc

Getting the Share
$upath.Segments[1]            # Returns Share01/
$upath.Segments[1].Trim('/')  # Trims the trailing /

Or a one liner with no escaping or trimming:
[System.IO.Path]::GetPathRoot($unc).Split('\')[-1]

A: In simple scenarios I'd use an approach similar to the one suggested by @Avshalom, but with the String.Split() method instead of the -split operator to avoid regular expressions.
$unc = '\\FQDN\Share01\Directories\...\...\...\...'

$sharename = $unc.Split('\')[3]

If you want to be on the safe side you should canonicalize the path separators first, since PowerShell accepts both / and \ as separators in a path:
$sharename = $unc.Replace('/', '\').Split('\')[3]

If you want to play it really safe there probably isn't a way around regular expressions, though, because there are a number of things to take care of:

*

*Ensure the path is actually a UNC path (i.e. starts with a double slash/backslash and has at least a server and share component).

*Handle both \ and /.

*Handle consecutive path separators (.//some\\\folder/\path is a valid pathspec in PowerShell).

To handle all of this you could do the following:
$unc = '\\FQDN\Share01\Directories\...\...\...\...'
$re  = '^[\\/]{2}[^\\/]+[\\/]+([^\\/]+)'

if ($unc -match $re) {
  $sharename = $matches[1]
} else {
  "Not a valid UNC path: $unc"
}

Regular expression breakdown:

*

*^[\\/]{2} matches two consecutive slashes or backslashes at the beginning of a string.

*[^\\/]+ matches a sequence of one or more characters that are neither slash nor backslash (i.e. a path component).

*[\\/]+ matches consecutive path separators.

*(...) group a submatch (in this case the share name) so that it can be back-referenced, e.g. via the automatic variable $matches.

A: Another option:
('\\FQDN\Share01\Directories\...\...\...\...' -split '\\' | ? {$_} )[1]

A: Modifiy this code for foud your search:
 $value="\\FQDN\Share01\Directories\...\...\...\..."
 $valuetosearch="Share01"
 $listresult=$value -split "\\"
 $counter = 0
 $listresult | select @{Name="Value";Expression={$_}}, @{Name="Rang";Expression={$global:counter; $global:counter++}} | where { $_.Rang -eq 3 -and $_.Value -eq $valuetosearch}


text:
Q: How to Make a Macro to Apply 3-Color Scale with Relative Cell Referencing In column C I have a starting balance, in column D I have the remaining balance. I can apply a 3-color scale to that cell and make the color gradually change from green to yellow to red. The problem I am facing is I need to apply these same rules to 200+ other cells, each with their own unique starting balance in column C. This prevents me from just copying the rule because Excel tells me I can not use relative cell references with these rules. To try and fix this so I do not need to click through the conditional formatting wizard 200+ times, I'm trying to make a macro that applies these rules to each cell in column D. so far this is what I have.
What I am running into is that the 3-Color Scale rule is being applied to each cell, but the formula used to determine the color thresholds is not being inserted. it leaves me with this

My background in VBA is about of week of google, so forgive me if its over complicated. I used the macro recorder then changed all of the .select and .selection stuff to reference the objects directly to learn how the conditional formatting rules are initially applied.
    Dim wsT As Worksheet

    LastRow = Cells(Rows.Count, "A").End(xlUp).Row

    Set wsT = ThisWorkbook.Worksheets("Tracking")

    For X = 5 To LastRow

    wsT.Range("D" & X).FormatConditions.AddColorScale ColorScaleType:=3
    wsT.Range("D" & X).FormatConditions(wsT.Range("D" & X).FormatConditions.Count).SetFirstPriority
    wsT.Range("D" & X).FormatConditions(1).ColorScaleCriteria(1).Type = _
        xlConditionValueFormula
    wsT.Range("D" & X).FormatConditions(1).ColorScaleCriteria(1).Value = _
        wsT.Range("C" & X) * 0.1

    With wsT.Range("D" & X).FormatConditions(1).ColorScaleCriteria(1).FormatColor
        .Color = 7039480
        .TintAndShade = 0
    End With

    wsT.Range("D" & X).FormatConditions(1).ColorScaleCriteria(2).Type = _
        xlConditionValueFormula
    wsT.Range("D" & X).FormatConditions(1).ColorScaleCriteria(2).Value = _
        wsT.Range("C" & X) * 0.65

    With wsT.Range("D" & X).FormatConditions(1).ColorScaleCriteria(2).FormatColor
        .Color = 8711167
        .TintAndShade = 0
    End With

    wsT.Range("D" & X).FormatConditions(1).ColorScaleCriteria(3).Type = _
        xlConditionValueFormula
    wsT.Range("D" & X).FormatConditions(1).ColorScaleCriteria(3).Value = _
        wsT.Range("C" & X) * 0.85

    With wsT.Range("D" & X).FormatConditions(1).ColorScaleCriteria(3).FormatColor
        .Color = 8109667
        .TintAndShade = 0
    End With

    Next X

End Sub

A: My previous answer was incorrect.  Your problem is that formulas need to be strings that start with =, like "=0.1*$C$1".
I wrote the following:
Sub Test()
Dim ws As Worksheet, rg As Range, cs As ColorScale
Set ws = ActiveSheet
For Each rg In ws.Range("D1", ws.Cells(ws.Rows.Count, "D").End(xlUp).Address)
   Set cs = rg.FormatConditions.AddColorScale(ColorScaleType:=3)
   cs.ColorScaleCriteria(1).Type = xlConditionValueFormula
   cs.ColorScaleCriteria(1).Value = "=0.1*$C$" & CStr(rg.Row)
   cs.ColorScaleCriteria(1).FormatColor.Color = 7039480
   cs.ColorScaleCriteria(1).FormatColor.TintAndShade = 0
   cs.ColorScaleCriteria(2).Type = xlConditionValueFormula
   cs.ColorScaleCriteria(2).Value = "=0.65*$C$" & CStr(rg.Row)
   cs.ColorScaleCriteria(2).FormatColor.Color = 8711167
   cs.ColorScaleCriteria(2).FormatColor.TintAndShade = 0
   cs.ColorScaleCriteria(3).Type = xlConditionValueFormula
   cs.ColorScaleCriteria(3).Value = "=0.85*$C$" & CStr(rg.Row)
   cs.ColorScaleCriteria(3).FormatColor.Color = 8109667
   cs.ColorScaleCriteria(3).FormatColor.TintAndShade = 0
Next rg
End Sub

Obviously, your worksheet should be set to ThisWorkbook.Worksheets("Tracking") and your beginning range should be "D5".


text:
Q: Using Popen in Python to execute bat script with variable I have a python script that is calling a bat script called testrunner.bat which in turns executes a TestSuite in SOAPUI.  I actually have gotten the external call to work just fine with the following command:
Popen("testrunner.bat -s\"CCT000 - Deploy Software Release\" -R\"TestSuite Report\" -E\"Default environment\" -Ppath.packages.sq=Y:\\NIGHTLY C:\\CI\\HEDeployment\\CI-XXX-DeploySwRelease")

However, I need to be able to have the software "level" to be dynamic and need to pass the variable level into the command in place of "NIGHTLY" so I can specify if it's nightly software, or stable, etc.  I have seen that I should break all the arguments up separately, but I am having a hard time.

A: subprocess.Popen() can take a list of arguments as well as a string. So, this should work for you:
release_type = "NIGHTLY"
Popen(['testrunner.bat',
       '-s"CCT000 - Deploy Software Release"',
       '-R"TestSuite Report"',
       '-E"Default environment"',
       '-Ppath.packages.sq=Y:' + release_type,
       'C:CIHEDeploymentCI-XXX-DeploySwRelease'])

As mentioned in the docs, shlex.split can be very useful for splitting your original command string into pieces. However, at least in my case, I had to re-add the double quotes.
Also, recall that single-quoted strings can contain double quotes, and vice versa, so you don't need to escape the quotes here.


text:
Q: Is there any benefit to completing the pipe levels in Mario Run? I recently unlocked the black pipe level by getting all of the black coins in the game, and it's really hard! Will I earn anything for completing it? It seems like you don't get any reward for completing the first two pipe levels.

A: I beat it and you get nothing.

A: I beat them. They're just for fun (although there is a little message at the very end).


text:
Q: Run time error '3706': Provider cannot be found -Visual Basic I am trying to connect Visual Basic to MS Access using ADODB. But as I execute my code, it prompts: "Provider cannot be found.It may not be installed properly." But when I check on my directory I've got my "msjetoledb40.dll" installed.
Here is my code:
Dim conn As ADODB.Connection, rec As ADODB.Recordset

    Sub sample()

    Set conn = New ADODB.Connection

    conn.Open ("Provider=Microsoft.Jet.OLEDB 4.0;Data Source=C:\sample.mdb;Persist Security Info=false;")
End Sub

A: This would be better:
Sub sample()

  Dim conn As ADODB.Connection, rec As ADODB.Recordset
  Set conn = New ADODB.Connection
  conn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\sample.mdb;"
  conn.Open
End Sub

You missed a point.
Microsoft.Jet.OLEDB 4.0 => Microsoft.Jet.OLEDB.4.0
Ref: http://www.connectionstrings.com/.

A: Confirming the version of your MS Office on which the script is running. If you have installed MS Office 2013 or later, you should revise the connection string from:
Provider=Microsoft.Jet.OLEDB 4.0;Data Source=C:\sample.mdb;Persist Security Info=false;

to:
Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\sample.mdb;Persist Security Info=false;

At least, this sovled my problem.

A: My solution:
Error 3706
cs = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & sPath & ";Persist Security Info=False;"

Just Change 12.0  for 15.0
cs = "Provider=Microsoft.ACE.OLEDB.15.0;Data Source=" & sPath & ";Persist Security Info=False;"

and works, always you must to try change the version of the controller!.


text:
Q: Encoder.htmlEncoder in JS On a website, I retrieve a string the user entered.
DataItem.getProperty('-----some name ----')

The problem is that some users put a <script></script> in there.
How can I escape/html-encode this string nicely ?

A: How about;
function HTMLEncode(buff) {
    var e = document.createElement("div");
    e.appendChild(document.createTextNode(buff));
    return e.innerHTML;
}

 In:  AAA <script>BBB</script> CCC <DDD>
 Out: AAA <script>BBB</script> CCC <DDD>


text:
Q: Opamp Astable Multivibrator - initial delay I'm trying to build a low frequency oscillator (think about 0.01Hz - 5Hz) using a TL072 as an astable multivibrator. Here's the circuit in LTspice:

And here's the simulated output:

Where does the 2.8s initial delay come from? It appeared once I raised R to 1M to decrease the frequency to suit my range. Also, where would one put a potentiometer for frequency adjustment? I also suspected using an electrolytic capacitor in this configuration would damage it as it's repetitively getting a negative voltage, so I limited C1 to 100n.

A: Model 1 mV of offset voltage and this won't happen. The simulated op-amp is starting up in a precariously balanced-on-a-point condition that is totally unrealistic.
To adjust the frequency, change R to a pot (better with a resistor in series). You can use a film capacitor. Ceramic caps are another possibility, but suffer from voltage coefficient (this circuit does not produce linear sawtooth anyway).
Note that period, not frequency, is linear in R as well.
For shaping to sine waves it might be better to use an op-amp + comparator oscillator, which will give you nice linear triangle waves, and can be adapted into a VCO which is linear frequency for input voltage by switching the integrator to +/- gain with comparator state.


text:
Q: Package-lock.json file in angular 5 creating the problem Always package-lock dependency libraries creating problem. When we are trying to do npm install there is no issues but when we try merge the code to master branch build failed. One of the dependency library failing. when we see it jfrog that library critical due lower version and expecting higher version to upgrade. We have modify directly in package-lock file and check in the code that issue resolved but other library coming. what is the best way to identify and resolve the problem?

A: Try using npm ci instead of npm install when you build for deployment.  As I understand it, this command will use the package-lock.json file.
Use npm install and commit changes to the package-lock.json file when your intent is to update the dependencies for deployment.
This is recommended in the docs and could help you to control the package-lock.json file and get consistent builds.


text:
Q: NSMutableArray arrayWithCapacity issue I am deeply sorry as if this is a stupid question. if it is please leave a comment and I will remove it but here is my code below:
NumberedArray = [NSMutableArray arrayWithCapacity:50];
NSUInteger randomNumber = arc4random() % [NumberedArray count];
for (int i = 0; i<randomNumber; i++) {
    // Run some code
}

}
Now I get an error of: Thread 1: EXC_ARITHMETIC (code=EXC_I386_DIV, subcode=0X0)
So my best Guess is that the machine is getting confused because I am telling it that this array has capacity of 50 and now pick one of its slots randomly and perform some code is long as the loop is less than this randomly picked number.
but what I really want to do is to have the computer run a code based on randomly picked time interval.
This is a game where this code performs a enemy moving from left to right based on randomly picked time interval. Is this even a right approach? and if not what should I try instead? Thanks.

A: Capacity 50 doesn't mean your array contains 50 elements. Its count is 0. So you perform division by zero and that's why it crashes. Forget about using arrayWithCapacity: or initWithCapacity: because it doesn't mean anything practically helpful.
UPDATE:
If you need random number in a range of 50 then why not use just:
NSUInteger randomNumber = arc4random() % 50;

and initialise your array like this:
numberedArray = [NSMutableArray array];


text:
Q: Codeigniter redirect add dynamic 3rd URI segment I'd like to get this to redirect to welcome/stats/3 asuming site_id is 3
function add_keyword()
{
    $data = array(
        'keyword' => $this->input->post('keywords'),
        'depth' => $this->input->post('depth'),
        'site_id' => $this->input->post('site_id')
    );

    $site_id = $this->input->post('site_id');

    $this->site_model->add_keyword($data);
    redirect('welcome/stats/', $site_id);
}

A: You have to concatenate $site_id, not pass it as a second parameter:
redirect('welcome/stats/' . $site_id);


text:
Q: Getting SQL Procedure ResultSet Information For SQL Server 2012, any idea how to get the results from a SQL stored procedure without running it?
Closest I found find is from sp_depends which has a selected but it gives me results even when its in the where statement.
Hoping to find a way to find what columns are selected, but not in where statement.
Let me rephrase a little bit: I don't need the data, just what columns it returns, so I can create my result classes via a T4.

A: Whatever you're trying to do in a SP might be doable in a function instead. You can do many of the same things in a custom function that you can in simple stored procedures, but functions aren't "run" like a stored procedure (i.e. exec sp_blah)
I can create a function like this:
 create function CustomAdd @i int, @ii int
 returns int
 as
 return (@i + @ii)

Then any time I want to use it I would write something like:
select CustomAdd(343,4343)


text:
Q: VCS Trigger in TeamCity not working I'm trying to get a VCS trigger to work in TeamCity with TFS but no matter what I do, I can't get it to trigger on a checkin
I've defined the VCS trigger as +:fodl/FODL.Database.InvestmentDataMart.APTExtract/**
..which I believe should only trigger a build if changes are detected in that directory but none of the pending changes every seem to trigger a build
Here's a screenshot of my build trigger:-

And a screenshot of my build source directory where all files have been checked out to:-

Does anyone know what I'm doing wrong? I can't use checkout rules to target just the FODL.Database.InvestmentDataMart.APTExtract folder as all the solution files all live in the base directory above it (FODL)

A: Try +:**/fodl/FODL.Database.InvestmentDataMart.APTExtract/**. If the disconnect is "where I think the root directory is" versus "where TC thinks the root directory is", the prepended wildcard should fix it.

A: I am not sure if this is obvious or not, but the VCS trigger only let's you control if the build will run and what rules will trigger the build. The VCS trigger does not do anything if TeamCity is not aware of the change in the source control repository. For that you need to either

*

*Define a scheduled trigger that will change for changes in your source repository.

*Or configure TFS to notify TeamCity (through web hooks or other kind of integration) that there is a change.


text:
Q: Robot Framework: is there a better way to test items in a menu? I'm writing a test to verify a web menu has all the required items, so I created a keyword called "Verify Menu" with several items like this:
Verify Menu
  Wait Until Element Is Visible     ${menu}
  Page Should Contain Element       ${home menu item}
  Element Text Should Be            ${home menu item}  Home
  Page Should Contain Element       ${products menu item}
  Element Text Should Be            ${products menu item}  Products
  Page Should Contain Element       ${brands menu item}
  Element Text Should Be            ${brands menu item}  Brands
  Page Should Contain Element       ${find us menu item}
  Element Text Should Be            ${find us menu item}  Find us
  Page Should Contain Element       ${our history menu item}
  Element Text Should Be            ${our history menu item}  Our History
  Page Should Contain Element       ${contact us menu item}
  Element Text Should Be            ${contact us menu item}  Contact Us

I know this is a keyword implementation and not part of a test itself, however, it looks a bit messy to me.
Is there a better way to do this?

A: It seems to me that the Wait Until Element Is Visible is there to determine the page has fully loaded. Then the subsequent combinations of Page Should Contain Element and Element Text Should Be are there to verify the element.
Personally I think the Page Should Contain Element is included in the Element Text Should Be as well. It will fail and provide a similar message.
That said, if you want to keep the duo, but do away with the extra lines of code, then opt for a custom keyword:
Verify Menu
  Wait Until Element Is Visible     ${menu}
  Validate Element            ${home menu item}  Home
  Validate Element            ${products menu item}  Products
  Validate Element            ${brands menu item}  Brands
  Validate Element            ${find us menu item}  Find us
  Validate Element            ${our history menu item}  Our History
  Validate Element            ${contact us menu item}  Contact Us

*** Keywords ***
Validate Element
    [Arguments]    ${identifier}    ${value}
    Page Should Contain Element       ${identifier}
    Element Text Should Be            ${identifier}    ${value}


text:
Q: accessing span in iframe through javascript or jquery I want to access the yellow highlighted span tag value give in the image below:

I tried the following in chrome console but it gives undefined value as follows:

Where am I getting wrong? How do I solve this? How do I get the span value?

A: You need to use:
$('#id_frame').contents().find('#queuedBetTotal').text();

You should also know that if the iframe source is pointing to a different domain, due to security reasons, you will not be able to access the contents of this iframe in javascript.

A: $('iframe').contents().find('#queuedBetTotal').html();
if you don't have id means you can use the tag name.


text:
Q: How do I return a partcular string if column value is null MySQL How do I return a particular string if column value is null MySQL? So basically in the instance below sometimes the values "tableA.Name" is sometimes Null as the user has forgot to fill it.
In this case rather than returning Null, I'd like some sort of if statement to check if the value is null then say "Name not assigned"
My MySQL query:
SELECT `shoes_item`.Product_Name, `run_task`.Name, `shoes_item`.Notes FROM `shoes_item` As test
LEFT OUTER JOIN `run_item`
ON `run_item`.shoes_ID = `shoes_item`.shoes_ID
LEFT OUTER JOIN `run_details`
ON `run_details`.run_Item_ID = `run_item`.run_Item_ID

A: select coalesce(tableA.name, 'Name not assigned') as name

A: Is his what you are looking for?
SELECT IFNULL(`shoes_item`.Product_Name,"name not assigned") as product_name, `run_task`.Name, `shoes_item`.Notes FROM `shoes_item` As test
LEFT OUTER JOIN `run_item`
ON `run_item`.shoes_ID = `shoes_item`.shoes_ID
LEFT OUTER JOIN `run_details`
ON `run_details`.run_Item_ID = `run_item`.run_Item_ID

A: You can use IFNULL function
For example IFNULL(tableA.Name,'Name not assigned')

A: You can easily solve this problem by using the mysql if condition, it will solve both the issue like the column is null or blank.
The query will be.
select if(tableA.Name IS NULL || tableA.Name=' ','Name not assigned',tableA.Name)

as Name from tableA;


text:
Q: How to return status 301 on port 80 without webserver Is there any way to implement HTTP redirect on port 80 if there's no web servers installed?
I want to protect my server from random access and redirect whoever hits port 80 or 443 there to the main websites. Right now it is setup to drop connection attempts on both ports.
I know, I could've created simple app that will listen port 80 and return http header with 301 status, but I'm curious if that's can be done kinda native?

A: You can use netcat as a very simple web server:
yes | xargs -i printf 'HTTP/1.0 301 Moved Permanently\nLocation: http://example.com\n\n' | sudo nc -k -l 80


text:
Q: Clojure - pass component to functions not executed during start or stop In the README of Stuart Sierra's component, there is a function add-user that is given as an example, but not seen anywhere else :
(defn add-user [database username favorite-color]
  (execute-insert (:connection database)
    "INSERT INTO users (username, favorite_color)"
    username favorite-color))

I imagine it could be executed (for instance) on a web server route. I have no trouble imagining that username and favorite-colour would be parameters to that route, and thus readily available when calling add-user.
I guess that having this would make the database component of the web-server (for example) component.
However I am having some trouble figuring where the database component instance parameter of add-user should come from exactly.
I feel that directly accessing the system (ie. doing (:database my-system-ns/system))) to retrieve it would defeat part of the purpose of using components in the first place.
For instance if I am using pedestal, I may have my pedestal component (who has access to the database component) set up this key :
::bootstrap/routes #(deref #'my-routes-ns/routes)

And this would be something like that :
;; in my-routes-ns
(defroutes routes [[[ "/add-user" {:post add-user-handler} ]]])

;; same function again for clarity
(defn add-user [database username favorite-color]
  (execute-insert (:connection database)
    "INSERT INTO users (username, favorite_color)"
    username favorite-color))

;; my route handler
(defn add-user-handler [request]
  ;; How do I get access to the database component from here ?
  (add-user database "user" "red"))

How do I get access to my database component in this example ?

A: In a typical application, you might have a web-server component that depends (see component/using) on your database component, and a collection of public functions associated with the database component that its consumers could call to query the database.
The web-server component will then be responsible for setting up your request handler and starting a listener (like Jetty). This will involve taking the database component and injecting it into your handler, perhaps by partial application (if your handler looks like (defn handler [database request] …), say), so that it can call add-user on the actual database component.
Note that depending on the design of your app, your setup may not match the above exactly – for example,web-server could only use the database component through one or more layers of intermediate components.

A: FYI, the README of component suggest create a closure over one or more component,
(defn app-routes
  "Returns the web handler function as a closure over the
  application component."
  [app-component]
  ;; Instead of static 'defroutes':
  (web-framework/routes
   (GET "/" request (home-page app-component request))
   (POST "/foo" request (foo-page app-component request))
   (not-found "Not Found")))

(defrecord WebServer [http-server app-component]
  component/Lifecycle
  (start [this]
    (assoc this :http-server
           (web-framework/start-http-server
             (app-routes app-component))))
  (stop [this]
    (stop-http-server http-server)
    this))

(defn web-server
  "Returns a new instance of the web server component which
  creates its handler dynamically."
  []
  (component/using (map->WebServer {})
                   [:app-component]))


text:
Q: Multiple setTimeout to hide controls In my page I have:

Dim sb As New StringBuilder
sb.AppendLine("function pageLoad(sender, args) {")
sb.AppendLine("  setTimeout( function() { $(""#ContentPlaceHolder1_tbcTables_ctl00_lblCostCenterImportMessage"").fadeOut(3000); }, 6000 ); ")
sb.AppendLine("  setTimeout( function() { $(""#ContentPlaceHolder1_tbcTables_ctl00_lblCustomerImportMessage"").fadeOut(3000); }, 6000 ); ")
sb.AppendLine("};")

ClientScript.RegisterStartupScript(Me.GetType, "scriptlblTimeOut", sb.ToString, True)

This is working for the first label to fade out, but the second doesn't do that.
How can I put multiple fade outs in the pageload?
rg.
Eric

A: strange, I checked the name of the second label, it was not wrong, then I ran the page again and now it is working....
Don't you just hate it when that happens. :-)


text:
Q: Color to ARGB Convert I have an integer color values like -16447153. And how to convert it ARGB?
In c#, he used color function,
Color.FromArgb(buf[buf_pos])

is there a function in delphi as like above otherwise how can i convert ?
I tried like this:
procedure TJP2RenderPreview.put_region(size : _Ckdu_coords; buf : array of Integer; offX, offY : Integer);
var
  x, y          : Integer;
  width, height : Integer;
  buf_pos       : Integer;
  RowPtr        : PRGBQuad;
begin
  width:= size.__property_get_x;
  height:= size.__property_get_y;
  buf_pos:=0;

  for y := offY to offY + height - 1  do
  begin
    RowPtr:= formMain.imgPreview.Bitmap.ScanLine[y];
    Inc(RowPtr, offX);
    for x := 0 to width - 1  do
    begin
      RowPtr.rgbReserved:= (buf[buf_pos] div $1000000);
      RowPtr.rgbRed:= ((buf[buf_pos] mod $1000000) div $10000);
      RowPtr.rgbGreen:= ((buf[buf_pos] mod $10000) div $100);
      RowPtr.rgbBlue:= (buf[buf_pos] mod $100);
      Inc(RowPtr);
      Inc(buf_pos);
    end;
  end;

  formMain.imgPreview.Refresh;
  formMain.imgPreview.Update;
end;

But this is not true, it seems grey :/

A: You appear to have got your channels mixed up. You are treating the input as RGBA when you say it is ARGB. In any case, your code using div and mod is inefficent. Bitwise shifting is the idiomatic way.
You can do it like this for ARGB input:
procedure ARGBtoColorChannels(ARGB: DWORD; out A, R, G, B: Byte);
begin
  A := Byte(ARGB);
  R := Byte(ARGB shr 8);
  G := Byte(ARGB shr 16);
  B := Byte(ARGB shr 24);
end;

Or if you start with RGBA then it goes like this:
procedure RGBAtoColorChannels(RGBA: DWORD; out A, R, G, B: Byte);
begin
  R := Byte(RGBA);
  G := Byte(RGBA shr 8);
  B := Byte(RGBA shr 16);
  A := Byte(RGBA shr 24);
end;

And these are little endian versions, since Delphi only targets on little endian machines, at the time of writing.
If you are looking for a function to convert ARGB to RGBA then you can make one like so:
function ARGBtoRGBA(ARGB: DWORD): DWORD;
var
  A, R, G, B: Byte;
begin
  ARGBtoColorChannels(ARGB, A, R, G, B);
  Result := R or (G shl 8) or (B shl 16) or (A shl 24);
end;

And for completeness the reverse is:
function RGBAtoARGB(RGBA: DWORD): DWORD;
var
  A, R, G, B: Byte;
begin
  RGBAtoColorChannels(RGBA, A, R, G, B);
  Result := A or (R shl 8) or (G shl 16) or (B shl 24);
end;

In order for you to know what to do, you need to understand what buf is. Is it ARGB or RGBA? Assuming it it ARGB, which seems likely given the content of your question, you are attempting to copy to RowPtr, which also appears to be ARGB. In which case you can blit the color like this:
PInteger(RowPtr)^ := buf[buf_pos];

I would also strongly recommend that you change the type of the buf parameter. An unsigned type is better here, because you may need to perform bitwise operations. What's more you are copying the entire array via the stack which is very inefficient. For large bitmaps you will suffer stack overflow. Instead that parameter should be:
const buf: array of DWORD;

or
const buf: array of Cardinal;

Using const means that a reference to the array is passed, rather than a copy.
You may as well avoid using PRGBQuad and declare RowPtr to be of type PCardinal, say.
Then you can assign like this:
RowPtr^ := buf[buf_pos];

At that point you don't need to do it pixel by pixel. You can copy an entire scanline with Move because this is a simply blit.
for y := offY to offY + height - 1  do
begin
  RowPtr := formMain.imgPreview.Bitmap.ScanLine[y];
  Inc(RowPtr, offX);
  Move(buf[buf_pos], RowPtr^, width*SizeOf(RowPtr^));
  Inc(buf_pos, width);
end;

Calling Refresh and Update seems pointless. I'm not sure you need to call either, but if you do, just call Invalidate instead!