text:
Q: Navigation Drawer Using Appcompat v7 - Issues with ?android:attr Tag I am using an actionbar and navigation drawer in my project.  Using appcompat v7 and v4.
I have added the appcompat v7 WITH resources.
The following is my textview for the navigation drawer list taken straight from the android sample app found at Creating a Navigation Drawer
The bottom three lines all cause my application to fail, it builds okay, but I get a force close and I am not sure how to solve the problem.  I don't understand why the attributes are not being found, considering I added the appcompat with its resources. Or are they not valid with the appcompat or something?
MinSDK Version is 10 and at which the code fails. Above API 10 the code works fine.
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@android:id/text1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center_vertical"
    android:paddingLeft="16dp"
    android:paddingRight="16dp"
    android:textColor="#fff"
    android:textAppearance="?android:attr/textAppearanceListItemSmall"
    android:background="?android:attr/activatedBackgroundIndicator"
    android:minHeight="?android:attr/listPreferredItemHeightSmall"/>

A: I had same issue. As i understand older apis haven't predefined textAppearanceListItemSmall, activatedBackgroundIndicator and listPreferredItemHeightSmall. So if you need you can specify your own values or remove this lines and rely on your luck.

A: You can use the values as defined in the compatibility library: It specifies all except the background, which I have chosen listChoiceBackgroundIndicator, although you might play with others as well.
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@android:id/text1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:textAppearance="?attr/textAppearanceListItemSmall"
    android:gravity="center_vertical"
    android:paddingLeft="16dp"
    android:paddingRight="16dp"
    android:textColor="#fff"
    android:background="?attr/listChoiceBackgroundIndicator"
    android:minHeight="?attr/listPreferredItemHeightSmall"/>


text:
Q: What happens when I exhaust a mine/quarry? After I use up all the materials in a mine or quarry, what happens to it? Does it just remain as an unusable chunk of land, or does it slowly recharge or decay, or something else entirely?

A: The buildings used by a mine and quarry can be removed, but the land they used will not be usable again. This is covered in the Help Menu of the game. The relevant sections are below.
Mines

Mines cannot be fully removed. The building can be taken down, but the area that the mine takes up won't ever be available for use for other purposes.

Quarry

Quarries cannot be removed. After the quarry is no longer useful, the building can be taken down, but the hole that has been dug in the quarry won't ever be available for any other use.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Angular 2 set boolean at end of iteration using *ngFor I am loading some data via rest-endport to safe it in an array. In an *ngFor directive i am currently iterating through all that data. So everthing is working.
Is there any possible way in Angular to e.g. set a boolean whenever the iteration of the array is finished (so that i can fire another function on complete)?
-- Edit--
On the ngOnInit lifecycle method i am retreiving the data:
ngOnInit() {
   this.restService.getSomeBooks(5000).subscribe(buch => {
     this.buecher = buch;
     this.fetched = true;
   })
}

After that - in HTML - i am iterating over that data:

some table-heads

        {{buchforTable.author}}
        {{buchforTable.erscheinungsdatum}}
        {{buchforTable.isbn.toString()}}
        {{buchforTable.verlag}}
        {{buchforTable.uuid}}

The *ngFor-iteration should set a boolean variable whenever it is done.

A: As Alex Po already mentioned, trackBy is working. As you can see in the following snippet, with trackBy it is possible to handle events based on the current index of the iteration.

    {{buchforTable.author}}
    {{buchforTable.erscheinungsdatum}}
    {{buchforTable.isbn.toString()}}
    {{buchforTable.verlag}}
    {{buchforTable.uuid}}

To measure the time of the rendering process of all array-objects the trackBy-function would look like this (array contains 5000 objects here -> index 0 to 4999):
 trackByFn(index){
    if(index == 0)
      this.renderStart = performance.now();
    if(index == 4999) {
      var renderStopp = performance.now();
      var timeToRender = renderStopp - this.renderStart;
    }
  }


text:
Q: Theme supports only one menu. I need to add more - but how? My theme is Nisarg. I will give all the coding below.
I have looked everywhere in order to add a navigation menu I'm trying to construct a website that gives lots of information and hence requires many menus.
I have never coded before nor recognise any of the language.
I see extracts from people to add code when I do it - it just crashes my site and says there are errors on various lines.
I can't get any info for a beginner for anywhere- so anyone? please? Just point me to a decent dummy guide (it took me hours to find functions.php and that you can edit)
Code is here:
<?php
/**
 * Nisarg functions and definitions
 *
 * @package Nisarg
 */

if ( ! function_exists( 'nisarg_setup' ) ) :
/**
 * Sets up theme defaults and registers support for various WordPress features.
 *
 * Note that this function is hooked into the after_setup_theme hook, which
 * runs before the init hook. The init hook is too late for some features, such
 * as indicating support for post thumbnails.
 */

/**
 * Nisarg only works in WordPress 4.1 or later.
 */
if ( version_compare( $GLOBALS['wp_version'], '4.2', '<' ) ) {
    require get_template_directory() . '/inc/back-compat.php';
}

function nisarg_setup() {
    /*
     * Make theme available for translation.
     * Translations can be filed in the /languages/ directory.
     * If you're building a theme based on Nisarg, use a find and replace
     * to change 'nisarg' to the name of your theme in all the template files
     */
    load_theme_textdomain( 'nisarg', get_template_directory() . '/languages' );

    // Add default posts and comments RSS feed links to head.
    add_theme_support( 'automatic-feed-links' );

    /*
     * Let WordPress manage the document title.
     * By adding theme support, we declare that this theme does not use a
     * hard-coded <title> tag in the document head, and expect WordPress to
     * provide it for us.
     */
    add_theme_support( 'title-tag' );

    /*
     * Enable support for Post Thumbnails on posts and pages.
     *
     * @link http://codex.wordpress.org/Function_Reference/add_theme_support#Post_Thumbnails
     */
    add_theme_support( 'post-thumbnails' );
    set_post_thumbnail_size( 604, 270);
    add_image_size( 'nisarg-full-width', 1038, 576, true );

    function register_nisarg_menus() {
        // This theme uses wp_nav_menu() in one location.
        register_nav_menus( array(
            'primary' => esc_html__( 'Top Primary Menu', 'nisarg' ),
        ) );
    }

    add_action( 'init', 'register_nisarg_menus' );

    /*
     * Switch default core markup for search form, comment form, and comments
     * to output valid HTML5.
     */
    add_theme_support( 'html5', array(
        'search-form',
        'comment-form',
        'comment-list',
        'gallery',
        'caption',
    ) );

    /*
     * Enable support for Post Formats.
     * See http://codex.wordpress.org/Post_Formats
     */
    add_theme_support( 'post-formats', array(
        'aside',
        'image',
        'video',
        'quote',
        'link',
        'gallery'
    ) );

    // Set up the WordPress core custom background feature.
    add_theme_support( 'custom-background', apply_filters( 'nisarg_custom_background_args', array(
        'default-color' => 'f5f5f5',
        'default-image' => '',
    ) ) );
}
endif; // nisarg_setup
add_action( 'after_setup_theme', 'nisarg_setup' );

/**
 * Sets the content width in pixels, based on the theme's design and stylesheet.
 *
 * Priority 0 to make it available to lower priority callbacks.
 *
 * @global int $content_width
 *
 */
function nisarg_content_width() {
    $GLOBALS['content_width'] = apply_filters( 'nisarg_content_width', 640 );
}
add_action( 'after_setup_theme', 'nisarg_content_width', 0 );

/**
 * Register widget area.
 *
 * @link http://codex.wordpress.org/Function_Reference/register_sidebar
 */
function nisarg_widgets_init() {
    register_sidebar( array(
        'name'          => esc_html__( 'Sidebar', 'nisarg' ),
        'id'            => 'sidebar-1',
        'description'   => '',
        'before_widget' => '',
        'after_widget'  => '',
        'before_title'  => '
',
        'after_title'   => '
',
    ) );
}
add_action( 'widgets_init', 'nisarg_widgets_init' );

/**
 * Enqueue scripts and styles.
 */
function nisarg_scripts() {
    wp_enqueue_style( 'bootstrap', get_template_directory_uri().'/css/bootstrap.css' );

    wp_enqueue_style( 'nisarg-style', get_stylesheet_uri() );

    wp_enqueue_style( 'font-awesome', get_template_directory_uri().'/font-awesome/css/font-awesome.min.css' );

    wp_enqueue_script( 'bootstrap', get_template_directory_uri() . '/js/bootstrap.js',array('jquery'),'',true);

    wp_enqueue_script( 'nisarg-skip-link-focus-fix', get_template_directory_uri() . '/js/skip-link-focus-fix.js', array('jquery'), '20130115', true );

    wp_enqueue_script( 'nisarg-js', get_template_directory_uri() . '/js/nisarg.js',array('jquery'),'',true);

    wp_enqueue_script( 'html5shiv', get_template_directory_uri().'/js/html5shiv.js', array(),'3.7.3',false );
    wp_script_add_data( 'html5shiv', 'conditional', 'lt IE 9' );

    if ( is_singular() && comments_open() && get_option( 'thread_comments' ) ) {
        wp_enqueue_script( 'comment-reply' );
    }
}
add_action( 'wp_enqueue_scripts', 'nisarg_scripts' );

/**
 * Implement the Custom Header feature.
 */
require get_template_directory() . '/inc/custom-header.php';

/**
 * Custom template tags for this theme.
 */
require get_template_directory() . '/inc/template-tags.php';

/**
 * Custom functions that act independently of the theme templates.
 */
require get_template_directory() . '/inc/extras.php';

/**
 * Customizer additions.
 */
require get_template_directory() . '/inc/customizer.php';

/**
 * Load Jetpack compatibility file.
 */
require get_template_directory() . '/inc/jetpack.php';
/**
 * Load custom nav walker
 */
require get_template_directory() . '/inc/navwalker.php';

function nisarg_google_fonts() {
    $query_args = array(

        'family' => 'Lato:400,300italic,700|Source+Sans+Pro:400,400italic'
    );
    wp_register_style( 'nisarggooglefonts', add_query_arg( $query_args, "//fonts.googleapis.com/css" ), array(), null );
    wp_enqueue_style( 'nisarggooglefonts');
}

add_action('wp_enqueue_scripts', 'nisarg_google_fonts');

function nisarg_new_excerpt_more( $more ) {
    return '...
' . __(' Read More', 'nisarg') . ' '. __(' Read More', 'nisarg').'
';
}
add_filter( 'excerpt_more', 'nisarg_new_excerpt_more' );

function custom_excerpt_length( $length ) {
    return 80;
}
add_filter( 'excerpt_length', 'custom_excerpt_length', 999 );

/**
 * Return the post URL.
 *
 * @uses get_url_in_content() to get the URL in the post meta (if it exists) or
 * the first link found in the post content.
 *
 * Falls back to the post permalink if no URL is found in the post.
 *
 *  * @return string The Link format URL.
 */
function nisarg_get_link_url() {
    $nisarg_content = get_the_content();
    $nisarg_has_url = get_url_in_content( $nisarg_content );

    return ( $nisarg_has_url ) ? $nisarg_has_url : apply_filters( 'the_permalink', get_permalink() );
}

A: You need to add a new menu here:
function register_nisarg_menus() {
        // This theme uses wp_nav_menu() in one location.
        register_nav_menus( array(
            'primary' => esc_html__( 'Top Primary Menu', 'nisarg' ),
            'my_new_menu' => esc_html__( 'My New Menu', 'nisarg' ) //this is the new line
        ) );
    }

and you use it like this in your HTML code to output the menu, using the ID:
<?php
    wp_nav_menu(array(
       'theme_location' => 'my_new_menu'
    ));
?>

you can read more about the menus here.


text:
Q: How do you delete user profiles in powershell? I am writing a powershell script to delete user profiles and I understand the method I am using is not the best. I was wondering what would be a better way to do it? I am still very much new to powershell but I am willing to learn
The code I already have:
$ErrorActionPreference= 'silentlycontinue'
$Users = Get-WmiObject -Class Win32_UserProfile
$IgnoreList = "helpdesk", "administrator", "Default"

:OuterLoop
foreach ($User in $Users) {
    foreach ($name in $IgnoreList) {
        if ($User.localpath -like "*\$name") {
            continue OuterLoop
        }
    }

    $User.Delete()
}

A: WHy script this when the enterprise approach is GPO.

How to Delete Old User Profiles Using GPO and PowerShell?

No reason to do this from scratch, leverage what others have provided...
Use PowerShell to remove local profiles
How to delete user profiles older than a specified number of days in Windows
...as well as the modules from the MS powershellgallery.com, as you look at whatever approach you decide use.
Find-Module -Name '*user*profile*' | Format-Table -AutoSize

<#
# Results

Version Name                               Repository Description
------- ----                               ---------- -----------
1.0     UserProfile                        PSGallery  This module manages user profiles on local and remote computers
0.1.1   Microsoft.Graph.Users.ProfilePhoto PSGallery  Microsoft Graph PowerShell Cmdlets
1.0.6   Get-UserProfile                    PSGallery  The Get-UserProfile module list or remove User Profiles from local
#>

Find-Module -Name '*userprofile*' | Format-List -Force

Update
Yet, you specifically said...

'I understand the method I am using is not the best. I was wondering
  what would be a better way to do it?

... and what we all have suggested, using GPO is the best way, the normal industry-accepted enterprise way to do this. Don't script, unless you have no other choice. Windows AD will do this for you.
Don't reinvent the wheel unless you know it's really a better wheel. In learning, of course, there is study, trial, and error, but learn and use from sources that have already done this. There are tons of examples all over the web for this use case. Just search for it. No reason to do this from scratch.

'powershell remove user profiles'

Which are showing what you are already doing... Example(s) - pre-built scripts for this use case via the Ms powershellgallery.com.
Use PowerShell delete a user profile (step-by-step guide)
Get-CimInstance -ComputerName SRV1,SRV2,SRV3 -Class Win32_UserProfile |
Where-Object { $_.LocalPath.split('\')[-1] -eq 'UserA' } |
Remove-CimInstance

Remove-UserProfile - Remove Local User Profiles and Clean C:\Users Directory

This script contains a function (Remove-UserProfile) which is used to
  remove user profiles, and additional contents of the C:\Users
  directory (if specified) on a local computer.
Download: Remove-UserProfile.ps1
Delete Unused user Profiles on local machine (PowerShell)
Script Delete user profiles over multiple servers v2

ANd using the modules that you see from the above commands, is not something to do later in life. Those are in / available from MS and in PowerShell directly for a reason. Everything you are using in PowerShell is coming from modules hosted on your machine and the ones you download and install from MS and other resources.
Again, use the built-in enterprise tools in Windows or other chosen OS as designed, and if they don't provide what you need, then look to other options, like scripting to an object-level that the enterprise tool is not exposing in its GUI.

A: I do a similar thing.  With a lot of profiles, I've found I've had to wait for the cpu to calm down because of the appxsvc service spawning threads without limit.  I used to delete per-user firewall rules, but that doesn't seem necessary anymore.
$excludedprofilelist = 'C:\Users\admin1','C:\users\admin2'

$myprofiles = $profiles | where { !$_.Special -and
  $excludedprofilelist -notcontains $_.LocalPath }

$sleepseconds = 1
$numcores = 4

foreach ($profile in $myprofiles) {
  $msg = "deleting profile " + $profile.LocalPath
  $profile | remove-wmiobject
  $msg = $msg + " $?"
  echo $msg   # the result

  # recycle bin
  if (test-path c:\`$recycle.bin\$($profile.sid)) {
    rm -r c:\`$recycle.bin\$($profile.sid) -force
  }

  # wait for appx cleanup, what if profile delete error?
  #while ( (get-appxpackage -user $profile.sid).count ) {
  #  sleep 1
  #}
  do {
    # make sure it's running
    $id = Get-WmiObject -Class Win32_Service -Filter "Name = 'appxsvc'" |
      Select-Object -ExpandProperty ProcessId

    # $proc = get-process -id $id
    # access is denied
    # 4proc.priorityclass = 'belownormal'

    $cpu1 = (get-process -Id $id).cpu
    sleep $sleepseconds
    $cpu2 = (get-process -Id $id).cpu
    $cpu = [int](($cpu2 - $cpu1)/($numcores*$sleepseconds) * 100)
  } while ($cpu)
}


text:
Q: не могу записать mp3 файл на sdcard         protected String doInBackground(String... f_url) {
        int count;
        try {
            String root = Environment.getExternalStorageDirectory().toString();

            System.out.println("Downloading");
            URL url = new URL(f_url[0]);

            URLConnection conection = url.openConnection();
            conection.connect();

            int lenghtOfFile = conection.getContentLength();

            InputStream input = new BufferedInputStream(url.openStream(), 8192);

            OutputStream output = new FileOutputStream(root+"/"+list.get(con_position)+".mp3");
            byte data[] = new byte[1024];

            long total = 0;
            while ((count = input.read(data)) != -1) {
                total += count;

                output.write(data, 0, count);

            }
            output.flush();
            output.close();
            input.close();

        } catch (Exception e) {
            Log.e("Error: ", e.getMessage());
        }

        return null;
    }

    @Override
    protected void onPostExecute(String file_url) {
        System.out.println("Downloaded");

        pDialog.dismiss();
    }

}

с манифестом все в порядке, в doInBackground передаю URL строку ресурса. Вроде трафик идет но не долго, следовательно никаких файлов нет, помогите пожалуйста


text:
Q: WooCommerce Subscriptions - Only Allow user one active subscription I am in the process of building a membership / subscription based site for a client of mine and we are using Woocommerce Subscriptions and Woocommerce Memberships plugin.
Now the problem is the my client is building a few promo pages which basically allows the user to purchase an upgrade. This is fine but my client only wants one unique subscription by customer (with its associated membership).
So the agreed solution is that, on a purchase of any new subscription product, all other subscriptions should be cancelled. All associated membership deleted/cancelled and only the latest subscription should remain active with its accompanying membership.
So I have tried to build this solution but it is just not working, so any advise/direction would be most welcome.
What I have tried:
function wp56908_new_order_housekeeping ($order_id)
{
    $args = array(
        'subscriptions_per_page' => -1,
        'customer_id'            => get_current_user_id(),
    );

    $subscriptions = wcs_get_subscriptions($args);

    foreach ($subscriptions as $subscription) {
        $s_order_id = method_exists( $subscription, 'get_parent_id' ) ? $subscription->get_parent_id() : $subscription->order->id;
        if ($s_order_id != $order_id) {
            $cancel_note = 'Customer purchased new subscription in order #' . $order_id;
            $subscription->update_status( 'cancelled', $cancel_note );
        }
    }
}
add_action( 'woocommerce_thankyou', 'wp56908_new_order_housekeeping',  10, 1  );

A: This is the support email I got from WooCommerce regarding the issue with the function wcs_get_subscriptions().

Thanks for contacting support and report us this issue!
I've tried it in a local install and I confirm that this seems to be a
  bug! I've already reported it to our development team and a patch
  should be included in next updates. By now, if you're in a real hurry
  and want to get it working, you could search for this code (in
  wcs-functions.php line 483):
// We need to restrict subscriptions to those which contain a certain
  product/variation if ( ( 0 != $args['product_id'] && is_numeric(
  $args['product_id'] ) ) || ( 0 != $args['variation_id'] && is_numeric(
  $args['variation_id'] ) ) ) { $query_args['post__in'] =
  wcs_get_subscriptions_for_product( array( $args['product_id'],
  $args['variation_id'] ) ); }
And replace it with something like:
// We need to restrict subscriptions to those which contain a certain
  product/variation if ( ( 0 != $args['product_id'] && is_numeric(
  $args['product_id'] ) ) || ( 0 != $args['variation_id'] && is_numeric(
  $args['variation_id'] ) ) ) { $prod_args = array( $args['product_id'],
  $args['variation_id'] ); $prod_args = array_filter($prod_args,
  function($prod_args) { return ($prod_args !== 0);  });
  $query_args['post__in'] = wcs_get_subscriptions_for_product(
  $prod_args ); }
Please take in mind that this is not the ideal solution because you'll
  be modifying our plugin's code directly and these changes can be lost
  after updating, but if you feel comfortable with code and want to take
  the risk as a temporary workaround until we add the proper patch in
  our plugin, you can do it. ;)
Let me know if you need any help with this!
Thanks, Bernat

A: There's a new setting in the WC Subscriptions plugin which lets you limit to one active subscription. You can find more information here: https://woocommerce.com/document/subscriptions/store-manager-guide/#:~:text=Limit%20subscriptions,the%20subscription%20from%20the%20dropdown.
The end user will get the message:
"You have a subscription to this product. Choosing a new subscription will replace your existing subscription."


text:
Q: What is the "spectrum of $L^1(G)$"? If $G$ is a locally compact abelian group, what does "the spectrum of $L^1(G)$ mean?" This comes from Folland's A Course in Abstract Harmonic Analysis. As I understand it, $L^1(G)$ is the integrable functions (wrt Haar measure) on G. I always think of spectrum as the set of eigenvalues of an operator (or I guess the set of prime ideals if we're taking the spectrum of a ring). Can someone clarify for me the situation? Folland tells us on page 88 that the spectrum of $L^1(G)$ can be identified with the P-dual of $G$. What is going on?

A: $L^1(G)$ is a commutative Banach algebra. As such, it has a spectrum: as a set, this is the set of its closed maximal ideals. It is also a topological space in a certain canonical way.


text:
Q: Why is diamond transparent while graphite is not? Diamond and graphite are both made of the same atom, carbon. Diamond has a tetrahedron structure while graphite has a flat hexagonal structure. Why is diamond transparent while graphite is not (at least not with more than a couple of layers)?

A: The answer lies in the band structure of the two materials. The band structure describes how the electrons in a solid are bound, and what other energy states are available to them.
Very simply, the band gap for transparent diamonds is very wide (see this link):

Normally, diamond is not a conductor: all the electrons live in the "valence band", and you need a photon with at least 5.4 eV of energy to push an electron into the conduction band. In the process, that photon would be absorbed. A photon with less energy cannot give its energy to an electron, because that electron "has nowhere to go". And since visible light has energies of between 1.65 and 3.1 eV, only UV photons have enough energy to be absorbed by pure diamond.
That same link also describes how impurities give rise to color in diamond: for example, nitrogen atoms produce an "intermediate" energy level, and this gives rise to more energetic electrons that could jump the gap to the conduction band and absorb light.
By contrast, graphite is a conductor. As a conductor, it has electrons in the conduction band already. You know this, because even a tiny voltage will give rise to a current - this tells us that the electrons didn't need to be "lifted" into the conduction band first. And since electrons will absorb any amount of energy easily, the material absorbs all wavelengths of light: which makes it black.

A: Diamonds are unstable compared to coal (or more exactly, graphite) so high
 temperature and pressure are required for diamonds to form from graphite.
 The reason that coal (graphite) is black and diamonds are clear has to do
 with how the carbon atoms are connected together in the two different forms
 of carbon. In diamond each carbon atom is bonded to its neighbors like the
 points of a pyramid. In graphite (coal) the atoms are connected to one
 another is flat planes. The flat planes can absorb light of all wavelengths
 (colors) while the pyramids found in diamonds cannot absorb any visible
 light and as a result are transparent. The reason for the difference is that
 the electrons in the large flat sheets of graphite can all "jiggle" at many
 frequencies, but the tightly bound and constrained electrons in diamond are
 not free to "jiggle" and thus cannot absorb light.
 Heat and pressure change coal into diamond, but it is the change in crystal
 structure that results in the color change. Graphite is composed of flat
 sheets of carbon similar to shale and basically keeps going in all direction
 until the end of the sheet. Diamond is a 7-carbon crystal, which is
 3-dimentional and therefore gives the crystal light refracting properites.
 Color is a result of light absorbtion or light reflextion. Black means
 that all possible colors are being absorbed and white means that all colors
 are reflected. In the case of diamond, it is clear because light passes
 through it.


text:
Q: How to Apply Lagrange multiplier well This problem was originally:

*

*Sphere $S$: $x^2+y^2+z^2=50$

*Point $P(0,5,5)$

*Circle $C$ is an intersection of a plane that passes $P$, and sphere
  $S$.

*The radius of the circle $C$ is $1$.

  Find the maximum of area of the projection of $C$ on the $xy$ plane.

I want to apply lagrange multiplier on this problem. So I converted to:

Constraints: $$a^2+b^2+c^2=1$$ $$b+c=\frac 75$$
Problem: Find the minimum of $$c$$.

Where the vector $(a,b,c)$ is the normal of the plane that passes $P$.
Solution using Cauchy- Schwarz Inequality:
$$0 a+b=\frac 75 -c$$
$$a^2+b^2=1-c^2$$
$$(0^2+1^2)(a^2+b^2) \ge(0 a+b)^2$$
$$\therefore (1-c^2) \ge (\frac 75-c)^2$$
$$\therefore \frac 34 \le c \le \frac 45$$
How can I use lagrange multiplier method on this problem effectively? Thanks.

A: You've already got everything you need. You can either proceed with two multipliers: $$L(a,b,c;\lambda,\mu) = c - \lambda(a^2+b^2+c^2-1) - \mu\left(b+c-\frac75\right)$$ or incorporate the linear constraint right away: $$L(a,c;\lambda) = c-\lambda\left(a^2+\frac1{25}(7-5c)^2+c^2-1\right).$$ I'd do the latter since it immediately eliminates two variables from the calculations and gets you to a set of equations that you'd have arrived at anyway. After differentiating, besides the constraint equation we have $$-2\lambda a = 0 \\ \left(\frac{14}5-4c\right)\lambda+1 = 0.$$ From this we quickly find that $\lambda\ne0$, so $a=0$, which leaves a quadratic equation in $c$.


text:
Q: Display overlay on fancy box without title I use fancy box to display images, and I use title to add element on image to display when user hover image.
But when I display thumbs and hover them tooltip with title appear.
Is it possible to use something else to display element on image hover and not to be title or maybe hide this title somehow.


text:
Q: Setting connection timezone with Spring and DBCP and MySQL My Enviroment

*

*Java 5

*Spring 2.5.5

*DBCP DataSource (org.apache.commons.dbcp.BasicDataSource)

*MySQL

Similar posts

*

*Setting session timezone with spring jdbc oracle
Links

*

*http://www.mysqlfaqs.net/mysql-faqs/General-Questions/How-to-manage-Time-Zone-in-MySQL
My Problem

*

*I need to set on my connection the timezone, aiming to prevent the conversions when dealing with TIMESTAMP columns.

My Idea/research

*

*DBCP Connection Pool did not mention anything around timezone. LINK

*What I investigate and thought that was oK is described on THIS post, exemplifying is:
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
    destroy-method="close">
    <property name="URL" value="${database.url}" />
    <property name="user" value="${database.username}" />
    <property name="password" value="${database.passwd}" />
    <property name="connectionCachingEnabled" value="true"/>
    <property name="sessionTimeZone" value="GMT-3"/>
</bean>

Asking for help area :)

*

*But this is not working!!

*What I want here is a simple way, preferentially using Spring to configure the timezone on jdbc connection.

Thanks in advance for any help/tips/advice/knowledge share

SOLUTION:
My Solution was based on tips collected on this post! Thanks for all!
(...)
@Override
public Connection getConnection() {
    Connection conn = null;
    Statement statement = null;
    try {
        conn = super.getConnection();
        statement = conn.createStatement();
        statement.execute("SET time_zone = \'" + timezone+"\'");
    } catch (SQLException e) {
        LOG.fatal("Error while SET time_zone", e);
    } finally {
        try {
            statement.close();
        } catch (SQLException e) {
            LOG.warn("Error while closing statement", e);
        }
    }
    if(LOG.isDebugEnabled())
        LOG.debug("SET time_zone("+timezone+") for connection, succeed!");
    return conn;
}
(...)

and on my Spring configuration file:
<bean id="dataSource" class="com.my.package.dbcp.TimezoneEnabledDataSource" destroy-method="close">
    (...)
    <property name="timezone" value="${database.timezone}" />
    (...)
</bean>

I hope this post can help someone in the future. Any question ping me!

A: You should be able to put the same SQL statements in the initConnectionSqls property of the DBCP configuration element. Just add this to the DBCP configuration element
<property name="initConnectionSqls" value="SET time_zone = '${database.timezone}'"/>

Depending on your version of DBCP, you may have to use connectionInitSqls as the property name. This information is straight from DBCP configuration documentation.

A: If the data source doesn't have such a property, you can extend it and add that property:
public TimezoneEnabledDataSource extends BasicDataSource {
    private String timezone;
    //getter and setter for it

    @Override
    public Connection getConnection() {
        Connection c = super.getConnection();
        // execute a query: SET time_zone = '-8:00'
        return c;
    }
}

See here http://www.electrictoolbox.com/mysql-set-timezone-per-connection/ for the query details.
MySQL documentation writes:

Per-connection time zones. Each client that connects has its own time zone setting, given by the session time_zone variable. Initially, the session variable takes its value from the global time_zone variable, but the client can change its own time zone with this statement:
mysql> SET time_zone = timezone;

You can also check if c3p0 doesn't have something built-in.

A: One of the possible solutions:
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
    destroy-method="close">
    <property name="URL" value="${database.url}?serverTimezone=America/Los_Angeles" />
    <property name="user" value="${database.username}" />
    <property name="password" value="${database.passwd}" />
    <property name="connectionCachingEnabled" value="true"/>
    <property name="sessionTimeZone" value="GMT-3"/>
</bean>

A: There is no "sessionTimeZone" member in the BasicDataSource. Use C3P0 which is a "better" connection pool than DBCP, or even better, if you are in a Java EE web server, use it to initialize a JNDI datasource ;)


text:
Q: how to insert new row in pandas data frame at desired index I have a data frame which has missing dates
print data

Date  Longitude  Latitude  Elevation  Max Temperature  \
4/11/1979  83.75  24.197701       238     44.769           20.007
4/12/1979  83.75  24.197701       238     41.967           18.027
4/13/1979  83.75  24.197701       238     43.053           20.549
4/15/1979  83.75  24.197701       238     40.826           20.189

How do I insert 4/14/1979 at the 4th row
print data
Date  Longitude  Latitude  Elevation  Max Temperature  \
4/11/1979  83.75  24.197701       238     44.769           20.007
4/12/1979  83.75  24.197701       238     41.967           18.027
4/13/1979  83.75  24.197701       238     43.053           20.549
4/14/1979  0.0    0.0             0       0.0              0.0
4/15/1979  83.75  24.197701       238     40.826           20.189

A: First convert column Date to_datetime, then set_index for resampling.
You can use resample by D (days) and then need fill NaN to 0, one posible solution is replace({np.nan:0}):
df['Date'] = pd.to_datetime(df.Date)
df.set_index('Date', inplace=True)

df = df.resample('D').replace({np.nan:0}).reset_index()
print (df)
        Date  Longitude   Latitude  Elevation     Max  Temperature
0 1979-04-11      83.75  24.197701      238.0  44.769       20.007
1 1979-04-12      83.75  24.197701      238.0  41.967       18.027
2 1979-04-13      83.75  24.197701      238.0  43.053       20.549
3 1979-04-14       0.00   0.000000        0.0   0.000        0.000
4 1979-04-15      83.75  24.197701      238.0  40.826       20.189


text:
Q: convert java object using jaxb to xml and vice versa (marshal and unmarshal) I am suppose to have a method called save() which should marshal the list of computer parts in the right panel to an XML file. In reverse, another method called load() that should unmarshal the saved XML file back into an object.
So basically, the "Save" event will call save() method and save the list of parts in the right panel to an XML file. The "Load" event should clear the right panel, and call load() method.
When load() is called, it should display the unmarshalled data in the right panel. I got "Exit" to work.
I'm having hard time figuring out the "Load" and "Save" parts though.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class PCParts implements ActionListener{

    JList destinationList, sourceList;
    JButton buttonin, buttonout;

    DefaultListModel source, destination;

    public JPanel createContentPane (){

        JPanel totalGUI = new JPanel();

        source = new DefaultListModel();
        destination = new DefaultListModel();

        String shoppingItems[] = {"Case", "Motherboard", "CPU", "RAM", "GPU",
        "HDD", "PSU"};

        for(int i = 0; i < shoppingItems.length; i++)
        {
            source.addElement(shoppingItems[i]);
        }

        destinationList = new JList(source);
        destinationList.setVisibleRowCount(10);
        destinationList.setFixedCellHeight(20);
        destinationList.setFixedCellWidth(140);
        destinationList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);

        JScrollPane list1 = new JScrollPane(destinationList);

        sourceList = new JList(destination);
        sourceList.setVisibleRowCount(10);
        sourceList.setFixedCellHeight(20);
        sourceList.setFixedCellWidth(140);
        sourceList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);

        JScrollPane list2 = new JScrollPane(sourceList);

        JPanel buttonPanel = new JPanel();

        buttonin = new JButton(">>");
        buttonin.setHorizontalAlignment(SwingConstants.RIGHT);
        buttonin.addActionListener(this);
        buttonPanel.add(buttonin);

        JPanel bottomPanel = new JPanel();
        bottomPanel.setLayout(new BoxLayout(bottomPanel, BoxLayout.LINE_AXIS));

        bottomPanel.add(Box.createRigidArea(new Dimension(10,0)));
        bottomPanel.add(list1);
        bottomPanel.add(Box.createRigidArea(new Dimension(5,0)));
        bottomPanel.add(buttonPanel);

                buttonout = new JButton("<<");
                buttonout.addActionListener(this);
                buttonPanel.add(buttonout);
        bottomPanel.add(Box.createRigidArea(new Dimension(5,0)));
        bottomPanel.add(list2);
        bottomPanel.add(Box.createRigidArea(new Dimension(10,0)));

        totalGUI.add(bottomPanel);
        totalGUI.setOpaque(true);
        return totalGUI;
    }

    private JPanel createSquareJPanel(Color color, int size) {
        JPanel tempPanel = new JPanel();
        tempPanel.setBackground(color);
        tempPanel.setMinimumSize(new Dimension(size, size));
        tempPanel.setMaximumSize(new Dimension(size, size));
        tempPanel.setPreferredSize(new Dimension(size, size));
        return tempPanel;
    }

    public void actionPerformed(ActionEvent e)
    {
        int i = 0;

        if(e.getSource() == buttonin)
        {
            int[] fromindex = destinationList.getSelectedIndices();
            Object[] from = destinationList.getSelectedValues();

            for(i = 0; i < from.length; i++)
            {
                destination.addElement(from[i]);
            }

            for(i = (fromindex.length-1); i >=0; i--)
            {
                source.remove(fromindex[i]);
            }
        }

        else if(e.getSource() == buttonout)
        {
            Object[] to = sourceList.getSelectedValues();
            int[] toindex = sourceList.getSelectedIndices();

            for(i = 0; i < to.length; i++)
            {
                source.addElement(to[i]);
            }

            for(i = (toindex.length-1); i >=0; i--)
            {
                destination.remove(toindex[i]);
            }
        }
    }

    private static void createAndShowGUI() {

        JFrame.setDefaultLookAndFeelDecorated(true);
        JFrame frame = new JFrame("PC Parts Builder");
        JMenu file = new JMenu ("File");
        file.setMnemonic (KeyEvent.VK_F);

        PCParts demo = new PCParts();
        frame.setContentPane(demo.createContentPane());

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);

        JMenuBar menuBar = new JMenuBar();
        frame.setJMenuBar(menuBar);

        JMenu mnFile = new JMenu("File");
        menuBar.add(mnFile);

        JMenuItem item;
        file.add(item = new JMenuItem("Load"));
        item.setMnemonic (KeyEvent.VK_O);
        item.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                doOpenCommand();
            }

            private void doOpenCommand() {
                // TODO Auto-generated method stub

            }

        });

        mnFile.add(item);

        JMenuItem mntmSave = new JMenuItem("Save");
        mntmSave.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                doSaveCommand();

            }

            private void doSaveCommand() {

            }
        });
        mnFile.add(mntmSave);

        JMenuItem mntmNewMenuItem = new JMenuItem("Exit");
        mntmNewMenuItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                System.exit(0);
            }
        });
        mnFile.add(mntmNewMenuItem);
    }

    public static void main(String[] args) {

        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }
}

A: Just create a class Parts to hold a List<String>. Then you can just marshal/unmarshal to an instance of that class.
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Parts {

    @XmlElement(name = "part")
    private List<String> part;

    public List<String> getPart() { return part; }
    public void setPart(List<String> part) { this.part = part; }
}

As for the marshalling (save), you would create a Marshaller by creating a JAXBContext using the Parts class. The just call marshal on the marshaller.
See some of the overloaded marshal methods (notice File)
private void doSaveCommand() throws Exception {
    ArrayList<String> save = new ArrayList<>();
    for (int i = 0; i < destination.size(); i++) {
        save.add((String)destination.getElementAt(i));
    }
    Parts parts = new Parts();
    parts.setPart(save);
    JAXBContext context = JAXBContext.newInstance(Parts.class);
    Marshaller marshaller = context.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    marshaller.marshal(parts, System.out);
}

Note you have a little design problem. The DefaultListModels that need to be accessed, can't be because the listener code is in a static context, and models are not static. I just made the models static to get it to work, but you'll want to redesign your code a bit. Here is the result (to standard output - you will to marshal to file).
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<parts>
    <part>Case</part>
    <part>Motherboard</part>
    <part>CPU</part>
</parts>

I'll let you work on the unmarshalling on your own. This should get you started.
Some Resource

*

*Marshaller API doc has some examples

*Unmarshaller API doc has some examples

*JAXContext API doc has some explanation about the context

*General JAXB tutorial


text:
Q: error Invalid type "boolean | undefined" of template literal expression @typescript-eslint/restrict-template-expressions When using eslint's "restrict template expressions", how do you log a boolean variable?  Also, if I wanted to disable the restriction for a line, how to do it?
const flag:boolean = true;

console.log("flag=" + flag);
console.log(`flag=${flag}`);

both generate this error:
error  Invalid type "boolean | undefined" of template literal expression  @typescript-eslint/restrict-template-expressions

A: In your .eslintrc:
module.exports = {
  "rules": {
    "@typescript-eslint/restrict-template-expressions": "error"
  }
};

Ref: https://typescript-eslint.io/rules/restrict-template-expressions/
You can suppress the error for a line like this:
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
console.log(`flag=${flag}`);

Just a little suggestion, if you are using typescript, maybe you should use const or let instead of var


text:
Q: How can I run the emberjs tests on a webserver like nginx/apache? I cloned the git repo and placed in the document root of my nginx install. But when I run http://localhost/ember.js/tests/index.html?package=ember-runtime, get the following error:
Uncaught The module 'handlebars' could not be found, http://localhost/ember.js/tests/minispade.js:39
Source:
    at Object.<anonymous> (http://localhost/ember.js/tests/qunit/qunit.js:832:4)

Is there anyway to run the tests without having the whole ruby infrastructure installed?

A: Handlebars isn't Ruby, it is a javascript library.  I'm not sure why you think that you need Ruby from the output you've posted here.
...
Looking at the docs, it looks like the tests need the rake-pipeline gem.  So yes, you'll need Ruby installed.  I'd recommend using RVM if you are on a Mac or Linux.


text:
Q: C style guide tips for a <80 char line I can't find many recommendations/style guides for
C that mention how to split up lines in C so you
have less then 80 characters per line.
About the only thing I can find is PEP 7,
the style guide for the main Python implmentation
(CPython).
Does a link exist to a comprehensive C style guide
which includes recommendations for wrapping?
Or failing that, at least some good personal advive
on the matter?
P.S.: What do you do with really_long_variable_names_that_go_on_forever
(besides shortening)? Do you put them on the left edge or let it spill?

A: Here is Linus'original article about (linux) kernel coding style. The document probably evolved since, it is part of the source distribution.

A: You can have a look at the GNU Coding Standards which covers much more than coding style, but are pretty interesting nonetheless.

A: The 80 characters per line "rule" is obsolete.
http://richarddingwall.name/2008/05/31/is-the-80-character-line-limit-still-relevant/
http://en.wikipedia.org/wiki/Characters_per_line
http://news.ycombinator.com/item?id=180949
We don't use punched cards much anymore. We have huge displays with great resolutions that will only get larger as time goes on (obviously hand-helds, tablets, and netbooks are big part of modern computing, but I think most of us are coding on desktops and laptops, and even laptops have big displays these days).
Here are the rules that I feel we should consider:

One line of code does one thing.
One line of code is written as one line of code.

In other words, make each line as simple as possible and do not split a logical line into several physical lines. The first part of the rule helps to ensure reasonable brevity so that conforming to the second part is not burdensome.
Some people believe that certain languages encourage complex "one-liners." Perl is an example of a language that is considered by some to be a "write once, read never" language, but you know what? If you don't write obfuscated Perl, if instead you do one thing per line, Perl code can be just as manageable as anything else... ok, maybe not APL ;)
Besides complex one-liners, another drawback that I see with conforming to some artificial character limit is the shortening of identifiers to conform to the rule. Descriptive identifiers that are devoid of abbreviations and acronyms are often clearer than shortened alternatives. Clear identifiers move us that much closer to literate programming.
Perhaps the best "modern" argument that I've heard for keeping the 80, or some other value, character limit is "side-by-side" comparison of code. Side-by-side comparison is useful for comparing different versions of the same source file, as in source code version control system merge operations. Personally, I've noticed that if I abide by the rules I've suggested, the majority of my lines of code are sufficiently short to view them in their entirety when two source files (or even three, for three-way merges) are viewed side-by-side on a modern display. Sure, some of them overrun the viewport. In such cases, I just scroll a little bit if I need to see more. Also, modern comparison tools can easily tell you which lines are different, so you know which lines you should be looking at. If your tooling tells you that there's no reason to scroll, then there's no reason to scroll.

A: I think the old recommendation of 80 chars per line comes from a time when monitors were 80x25, nowadays 128 or more should be fine.


text:
Q: Visual studio code isn't show tips about library's properties and methods I saw that VS can help you with some objects properties or methods when you only write dot after object name VS will show you their properties and methods, but when I try to get help with PIXI.js library, it isn't shown me that. Can it be configurable? Thanks.
Myself created object
PIXI.js


text:
Q: How to Create Sub Menu by Finding "_" Underscore in
* Links using JavaScripts or jQuery I want Convert this HTML code into

Home

Sub Menu

_Sub Menu  Item

_Sub Menu Item

DMCA

this HTML code using Javascript or jQuery, i am working on blogger templates for create a menu system

Home

Sub Menu

Sub Menu  Item

Sub Menu Item

DMCA

A: You can create new HTML(with nested Sub Menus) using an array of objects instead of parsing and finding '_' underscore in your current HTML for sub-menu. Please, find the running code as below:
JSFiddle
menu.html

menu.js
const arr = [{
  name: 'Home',
}, {
  name: 'Sub Menu',
  menus: ['_Sub Menu  Item', '_Sub Menu Item']
}, {
  name: 'DMCA',
}];

const getSub = (item) => {
  let li = '';
  item.menus.forEach(x => {
    li += '
' + x + '
'
  });
  return '
' + li + '
';
}
let li = '';

arr.forEach(item => {
  if (item.menus) {
    const getUL = getSub(item);
    li += '
' + item.name + '' + getUL + '
';
  } else {
    li += '
' + item.name + '
';
  }
});
$('#major').append(li);


text:
Q: Missing Operating System when rebooting from USB Trying to get my 15.10 to 16.04, but want to do a clean install as some of the PPA stuff messed up the OS.. Now I'm trying to do this for over 2 hrs now, following about 15 different solutions so far and not one worked out....and yes, i know it's  duplicate thread, but when I tried to ask on already open ones (like this one, what's the exact image of my issue: Missing Operating System Error When Rebooting from USB Drive) but I couldnt as this lovely site only lets you comment after getting points....
Anyway, first tried to use the USB I was when installed the 15.10 initially. The USB was a mess permission, but managed to clear it up and created the stick with Startup Disk Creator. Upon rebooting and choosing it I got the "Missing Operation System" error, then tried with unetbootin, same outcome. I ended up deciding that it was in fact the USB key being faulty as suggested at many of these workarounds to other people, so I tried unetbootin on HDD, but on boot, I just got back to 15.10...
Then tried it with an other 2 USBs with the exact same outcome... I'm getting really annoyed as I have no idea what the heck is going on as I'm through 20 solutions not one actually saving anything.....
Any ideas much appreciated!

A: I've had all kinds of problems with GUI based USB createors, and it sounds like this might be your issue as well.  You should be VERY careful with this command, but you could use "dd" from the terminal.  The "dd" command can destroy your instillation if you chose the wrong "of" aka "output file" path.  I've tossed in a step-by-step guide but feel free to Google "dd create bootable USB"

*

*Open the "Disks" program ("Windows key" and type "disks")

*Select your USB drive (should have a USB icon)

*In the upper right hand side, click the button with three dashes

*Select the first option "Format Disk..."

*Leave defaults ("Quick" and "MBR/DOS") and click "Format"

*Note the location of the "Device" towards the bottom of the window (in my example, it's "/dev/sdc")

*Open Terminal ("Windows" key" and type "terminal")

*Change directory to where your .iso is (mine is located in my Downloads directory, so I type "cd ~/Downloads")

*Run the "ls" command to check the name of your .iso (in my example, it's "ubuntu-16_04.iso")

*Run "sudo dd if=(your_iso) of=(USB_location)" (in my example, it's "sudo dd if=ubuntu-16_04.iso of=/dev/sdc")

*Wait a bit for dd to finish.  Depending on how big the .iso is, this could take up to 15 minutes, and no progress is shown (aka, just chill until Terminal gives you control again, indicated by a blinking cursor after (username)@(yourMachine))

*Reboot your machine and interrupt boot to select the USB drive (try key-jamming "ESC", "DEL", or "ENTER") and boot your USB

Edited to provide a better walk-through


text:
Q: Different Ways to Load selected files in R In a directory with 100 files (001.csv, 002.csv, ..., 100.csv), I want to load a range of selected files, e.g., file 30 to 50 (030.csv, 031.csv, ..., 050.csv).
One way is:
allFiles = list.files(directory)
csvFiles <- file.path(directory, allFiles[30:50])
dataFrames <- lapply(csvFiles, read.csv)

This method seemed to work. But I still have question:
class(allFiles)
[1] "character"

allFiles is a character of length 100. How to know the file names will be sorted in ascending order, so that 030.csv is in 30th, 050.csv is in 50th position, not any others?
Any other methods to read a selected range of files in R?

A: One way to do it is just to use sort: allFiles <- sort(allFiles).
But in general, I would recommend listing the files explicitly. You can do this as follows:
useFiles <- paste0(sprintf("%03d",30:50),".csv")
csvFiles <- file.path(directory, useFiles)

This way if someone adds another file to the directory later, your code is robust.


text:
Q: Having Trouble With get_category_by_slug In a Custom Function Here's my custom function to list child categories by the parent slug.
function ribbon_list_cats($parent_cat_slug)
{
    $parent_category = get_category_by_slug($parent_cat_slug);
    if ($parent_category->count != 0) {
        echo "
";
        echo wp_list_categories('title_li=&child_of='.$parent_category->term_id.'&hide_empty=0&show_option_none=&echo=0');
        echo "
";
    }
}

I'm having trouble getting it to return and output. It doesn't throw an error. I'm using it multiple times so I created this but when I do it like so:
$parent_category = get_category_by_slug('lifestyle');
if ($parent_category->count != 0) {
    echo "
";
    echo wp_list_categories('title_li=&child_of='.$parent_category->term_id.'&hide_empty=0&show_option_none=&echo=0');
    echo "
";
}

right in the template it works fine. But that's a lot of code to repeat over and over again.
Hope that makes sense. Thanks!

A: function ribbon_list_cats( $parent_cat_slug, $echo = true )
{
    $parent_category = get_category_by_slug( $parent_cat_slug );
    if ( $parent_category->count > 0 )
    {
        $output  = '
';
        $output .= wp_list_categories('title_li=&child_of='.$parent_category->term_id.'&hide_empty=0&show_option_none=&echo=0');
        $output .= '
';
    }
    // Debug: uncomment the following line
    // echo '
'; var_dump( $output ); echo '
';

    if ( $echo === false )
        return $output;

    return print $output;
}

// Call it like this:
ribbon_list_cats( 'uncategorized' );


text:
Q: Extracting Data From SAP Into Excel .currentcellrow I am trying to pull data from SAP into Excel from a list inside SAP. Normally when I click a field, I get a string of code with either .setfocus or something similar that I can change to a .text and set the line equal to a variable.
When I click a field in this list I get something like this
session.findById("wnd[0]/usr/cntlCUSTOM/shellcont/shell").currentCellRow = 2

What I need it to be able to make this variable to loop through, and in every iteration assign the SAP Cell value to a variable.
Does anyone know what I can do to accomplish this?

A: Okay I have no memory of asking this question in the past, but I apparently did. Here is the link to the answer from before.
Extracting .currentCellRow fields from SAP to Excel
Admins: Feel free to remove this post since it is a duplicate. Sorry for the inconvenience!


text:
Q: childNodes is 0 but I have children I have the following HTML. Using JS, I have a HTMLcollection of slot. And then I am trying to remove the child
 for a given slot. But the JS console is throwing an error that there is no child. Is it because I have a HTMLCollection?

const slots = document.getElementsByClassName('slot');

for (let i = 0; i < slots.length; i++) {
  slots[i].addEventListener('dragover', () => {
    const dragging = document.querySelector('.card-dragging');
    slots[i].appendChild(dragging);
    slots[i].removeChild(slots[i].lastChild);
  })
};

A: Your code can benefit from Delegation
You cannot remove the child in the middle of dragging, I expect you want to hide and move it back outside when you drop?
I could not find the .card-dragging so I guessed

const slots = document.querySelector('.slots');
slots.addEventListener('dragover', (e) => {
  const tgt = e.target.closest('div.slot');
  if (!tgt) return;
  const dragging = document.querySelector('.card-dragging');
  tgt.appendChild(dragging);
})
img {
  height: 50px;
}

.slot { border: 1px solid black; }

Drop?


text:
Q: Intellij create Artifacts (JAR) together with Project build Is there a quick option to Build the Artifacts (Like JAR) with the Project Builds?
Instead of use BUILD->BUILD ARTIFACTS->BUILD
Thank you all

A: Go Project Settings => Artifacts => Chose an artifact => Check to "Include in project build" box (image bellow).
Click "Apply" and the artifact will build together with your project build.


text:
Q: Delphi - Make a Delphi program that Self-extract a MIDI file I'm writing a program in Delphi 7, and I think in put a music to run in Background. So, I composed a song in .MIDI called Song.MID, now I want to put my Delphi program to self-extract(SFX) this song and execute, in the end of the program delete it. It's like write it in Hex, I think. How can I do it?

A: Create a new text file, and write: MIDI RCDATA 1.mid, save text file as MID.rc
Then create a new text file, and write: brcc32 mid.rc, save it as "brcc.bat"
run the brcc.bat, to convert *.rc file to *.res
Move MediaPlayer to your form (the media player is on the "System"tab).
Now copy this code to Your project:
unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, MPlayer;

type
  TForm1 = class(TForm)
    mplayer: TMediaPlayer;
    procedure FormCreate(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}
{$R mid.res}

procedure TForm1.FormCreate(Sender: TObject);
var
  stream:tresourcestream;
  tmp:string;
begin
  try
    stream:=tresourcestream.Create(hinstance,'MIDI',RT_RCDATA);
    try
      setlength(tmp,300);
      setlength(tmp,GetTempPath(300,pchar(tmp)));
      tmp:=tmp+inttostr(hinstance)+'.mid';
      stream.SaveToFile(tmp);
    finally
      stream.free;
    end;
    mplayer.FileName:=tmp;
    mplayer.Open;
    mplayer.Play;
  except
  end;
end;

end.

this is the easiest example. So, keygens use a special sound format - *.XM, the file is read into memory from a resource and played using libraries like FMOD (read more in internet)


text:
Q: How to get rid of "var1" and rename "var2" as "Variable? I'm currently making RShiny project which displaying the summary of choosen variable. However, I can't get rid of this "var1" and can't rename "var2". How I supposed to do? I'm new at this field. TIA.
This is my code:
# Define UI
ui <- fluidPage(theme = shinytheme("cerulean"),
                navbarPage(
                  # theme = "cerulean",  # <--- To use a theme, uncomment this
                  "My first app",
                  tabPanel("Navbar 1",
                           sidebarPanel(
                             selectInput(inputId="option",
                                         label="",
                                         c("CHILDREN","FHEAD","FEMALE","ELDERLY","FAMILYSIZE","NOELECTRIC","LOWEDU","GROWTH","POVERTY","ILLITERATE",
                                           "NOTRAINING","DPRONE","RENTED","TAPWATER","NOSEWER","POPULATION"),
                                         selected="CHILDREN"),

                           ), # sidebarPanel
                           mainPanel(
                             tableOutput("table")
                           ) # mainPanel

                  ), # Navbar 1, tabPanel
                  tabPanel("Navbar 2", "This panel is intentionally left blank"),
                  tabPanel("Navbar 3", "This panel is intentionally left blank")

                ) # navbarPage
) # fluidPage

# Define server function
server <- function(input, output) {

  sum <- reactive({
    data <- data %>%
      select(input$option) %>%
      summary() %>%
      as.data.frame() %>%
      tidyr::separate(Freq, c("Stat", "Value"), sep=":") %>%
      tidyr::pivot_wider(names_from =Stat, values_from = Value)
  })

  output$table <-renderTable(sum())
} # server

# Create Shiny object
shinyApp(ui = ui, server = server)

A: Your problem doesn't really have anything to do with Shiny, but in the data manipulation you are doing inside your server code.
We can replicate your problem without creating a Shiny app by setting up like this:
library(tidyverse)

data  <- iris
input <- list(option = "Species")

Now when we run your code we have an unwanted column called Var1, and we have the Var2 column that you want renamed:
data <- data %>%
  select(input$option) %>%
  summary() %>%
  as.data.frame() %>%
  tidyr::separate(Freq, c("Stat", "Value"), sep=":") %>%
  tidyr::pivot_wider(names_from =Stat, values_from = Value)

data
#> # A tibble: 1 x 5
#>   Var1  Var2            `setosa    ` versicolor `virginica `
#>   <fct> <fct>           <chr>        <chr>      <chr>
#> 1 ""    "      Species" "50  "       "50  "     "50  "

We can improve this with a few tweaks. Firstly, we can just select out the Var1 column. Secondly, we can rename the Var2 column. Thirdly, we trim the unwanted whitespace from the entries in our table, and finally, we remove the whitespace from our variable names:
data  <- iris

data <- data %>%
  select(input$option) %>%
  summary() %>%
  as.data.frame() %>%
  select(-Var1) %>%
  rename(Variable = Var2) %>%
  mutate(across(everything(), trimws)) %>%
  tidyr::separate(Freq, c("Stat", "Value"), sep=":") %>%
  tidyr::pivot_wider(names_from =Stat, values_from = Value) %>%
  setNames(trimws(names(.)))

data
#> # A tibble: 1 x 4
#>   Variable setosa versicolor virginica
#>   <chr>    <chr>  <chr>      <chr>
#> 1 Species  50     50         50

Created on 2022-06-21 by the reprex package (v2.0.1)


text:
Q: In ATOM, when I run line 2 of a Python code separately from line 1, I'd like ATOM to remember the object created in the line 1. How? Imagine you want to run a Python code on ATOM in two separate parts, first the first line, then the second line. Eg:
x=5

print(x)

ATOM by default does not keep in memory the objects created in the first line, so if I run the above second line separately from the first it will not know what is x. How can I change that? In Jupyter I can build a code sequentially, is there no way to do that in ATOM? (I want to use it for BERT use, where the first part of the code takes 30min to run)


text:
Q: addClass dont works on conditional I come to you with my next problem xd
This is my js:
$(document).ready(function(e) {

let imagesContainer = $(".slider__imageContainer");
let index = 0;

for(let item of imagesContainer) {
    if(item == imagesContainer[0]) {
        item.addClass("d-block");
    }
    else {
        imagesContainer.addClass("d-none")
    }
}
})

Why dont work the "addClass("d-block") function - but my "else" works fine.
and this is my HTML

A: this is not the element you are thinking, it refers to the HTMLDocument object. You can try
$(item).addClass("d-block");

A: You need to use item instead of this. Also your code could be optimised further from:
 for (let item of imagesContainer) {
    if (item == imagesContainer[0]) {
      item.addClass("d-block");
    } else {
      imagesContainer.addClass("d-none")
    }
  }

to:
  imagesContainer.addClass("d-none");
  imagesContainer[0].addClass("d-block");


text:
Q: jQuery autosuggest example I need to implement an "autosuggest" feature on our site but it needs to re-query the on every keystroke after a certain number of keys (like every character after 2 it would need to query again).  So the result isn't a limiting search.  For example, the autocomplete plugins I've seen work like the following:
[looking for a county]
1. customer types 'CA' and the first result would return 'Canada', 'Cambodia', and 'Camaroon'
2. customer continues to type and hits 'M' the new results would query within the only the existing 3 results (producing results of just 'Cambodia' and 'Camaroon')
I need a solution that would be the equivalent of querying my datasource on each keystroke.  I already have the ajax call that will return my results based on the "typed" params.  For example (in the above example), it would need to make an ajax call passing 'ca' first and if the customer kept typing passing 'can' on the 3 character and so forth.
Thanks.

A: The jQuery UI autocomplete plugin will do what you want.
See this demo http://jqueryui.com/demos/autocomplete/#remote-jsonp
the code for the demo:
$("#city").autocomplete({
            source: function(request, response) {
                $.ajax({
                    url: "http://ws.geonames.org/searchJSON",
                    dataType: "jsonp",
                    data: {
                        featureClass: "P",
                        style: "full",
                        maxRows: 12,
                        name_startsWith: request.term
                    },
                    success: function(data) {
                        response($.map(data.geonames, function(item) {
                            return {
                                label: item.name + (item.adminName1 ? ", " + item.adminName1 : "") + ", " + item.countryName,
                                value: item.name
                            }
                        }))
                    }
                })
            },
            minLength: 2,
            select: function(event, ui) {
                log(ui.item ? ("Selected: " + ui.item.label) : "Nothing selected, input was " + this.value);
            },
            open: function() {
                $(this).removeClass("ui-corner-all").addClass("ui-corner-top");
            },
            close: function() {
                $(this).removeClass("ui-corner-top").addClass("ui-corner-all");

}
        });

You can use the download builder to get just the autocomplete example.  As a bonus autocomplete is themeable and you can pick a themeroller ready theme or edit one and create your own.

A: jqueryui's autocomplete sends the full string each time, so you can do what you'd like to with it. You can also edit the events to save the last searching string and send that along with the new request, if that helped.


text:
Q: Catching Firebase Auth errors with ngrx effects I am working on angular5/firebase/ngrx project and I am having a problem catching errors during signup.
If I submit the signup form using an email I know is already in the system, I get the following error in my console:
POST https://www.googleapis.com/identitytoolkit/v3/relyingparty/signupNewUser?key=AIzaSyB_MH0xkLudBoy2QwVn6jfaFTUjJUylYHs 400 ()
and my effects catches the following error "mail address is already in use by another account." and dispatches signupErrorAction()
But if i immediately resubmit the form, the request does not go anywhere. the call never gets to my effects file or my auth service.  I have to get refresh the page to get any calls to work again.
As far as I can narrow it down is the 400 POST error is causing a problem.  I will post some code and I could use any suggestions anyone might have.  Let me know if you need more info
my-auth-service
public registerWithEmail(payload: any): Promise<any> {
    console.log('signup called');
    return this.afAuth.auth.createUserWithEmailAndPassword(payload.email,
      payload.password);
}

my-effects
/**
* Register with email and passowrd.
*/
@Effect()
public register: Observable<Action> = this.actions$
    .ofType(actions.ActionTypes.SIGN_UP)
    .map((action: actions.SignUpAction) => action.payload)
    .do(console.log)
    .switchMap(payload => this.authService.registerWithEmail(payload))
    .do(console.log)
    .map(data => new actions.SignUpSuccessAction({ user: data.user }))
    .do(console.log)
    .catch(error => Observable.of(new actions.SignUpErrorAction({ error: error })));

my-signup-method
public register() {

    console.log('register');

    const payload = {
      email: this.email,
      password: this.password,
      displayName: this.name
    }

    // dispatch AuthenticationAction and pass in payload
    this.store.dispatch(new SignUpAction(payload));
}

Update: I tried this and got all kinds of errors
    @Effect()
public register: Observable<Action> = this.actions$
    .ofType(actions.ActionTypes.SIGN_UP)
    .pipe(
    map((action: actions.SignUpAction) => action.payload),
    switchMap(payload => this.authService.registerWithEmail(payload)
        .pipe(
        map(data => new actions.SignUpSuccessAction({ user: data.user })),
        catch(error => Observable.of(new actions.SignUpErrorAction({ error: error })))
        )
    );

The first error I get for: map((action: actions.SignUpAction) => action.payload),
The 'this' context of type 'void' is not assignable to method's 'this' of type 'Observable'.
these are my rxjs imports for the effects file
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/switchMap';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/delay';
import 'rxjs/add/operator/do';
import "rxjs/add/operator/debounceTime";
import 'rxjs/add/observable/fromPromise';
import 'rxjs/add/observable/of';

Thanks
PK

A: You need to do the catchError (or catch) within the switchMap, so that the outer Observable does not get canceled on an error.
@Effect()
public register: Observable<Action> = this.actions$
    .ofType(actions.ActionTypes.SIGN_UP)
    .map((action: actions.SignUpAction) => action.payload)
    .switchMap(payload => this.authService.registerWithEmail(payload)
      .map(data => new actions.SignUpSuccessAction({ user: data.user }))
      .catch(error => Observable.of(new actions.SignUpErrorAction({ error: error }))
    )
);

I have also updated your example to use pipeable operators.
@Effect()
public register: Observable<Action> = this.actions$
    .ofType(actions.ActionTypes.SIGN_UP)
    .pipe(
      map((action: actions.SignUpAction) => action.payload),
      switchMap(payload => this.authService.registerWithEmail(payload)
        .pipe(
          map(data => new actions.SignUpSuccessAction({ user: data.user })),
          catchError(error => Observable.of(new actions.SignUpErrorAction({ error: error })))
        )
      )
    );

For this to work you need to add new imports:
import { map, switchMap, catchError } from 'rxjs/operators';


text:
Q: I'm trying to submit a form with Expess.js but I'm having an error exports.campagne_add_post = function(req, res, next) {

    // Validate fields.
    req.assert('name', 'Please fill the name').isLength({ min: 1 }).trim().withMessage('First name must be specified.')
        .isAlphanumeric().withMessage('First name has non-alphanumeric characters.');
    req.assert('date_debut', 'Invalid date_debut').isISO8601();
    req.assert('date_fin', 'Invalid date_fin').isISO8601();
    req.assert('agence', 'Please fill agence name').isLength({ min: 1 }).trim().withMessage('Agence must be specified.')
        .isAlphanumeric().withMessage('Agence has non-alphanumeric characters.');
    req.assert('annonceur', 'Please fill the annonceur name').isLength({ min: 1 }).trim().withMessage('Annonceur name must be specified.')
        .isAlphanumeric().withMessage('Annonceur name has non-alphanumeric characters.');
    req.assert('groupe_annonceur', 'Please fill groupe annonceur').isLength({ min: 1 }).trim().withMessage('Groupe annonceur must be specified.')
        .isAlphanumeric().withMessage('Groupe annonceur has non-alphanumeric characters.');
    req.assert('produit', 'Please fill product name').isLength({ min: 1 }).trim().withMessage('Poduct name must be specified.')
        .isAlphanumeric().withMessage('Product name has non-alphanumeric characters.');

    var errors = req.validationErrors();
    console.log(errors);
    if (!errors) {

        // Sanitize fields (using wildcard).
        sanitizeBody('*').trim().escape();

        var campagne = new Campagne(
            {
                name: req.body.name,
                date_debut: req.body.date_debut,
                date_fin: req.body.date_fin,
                agence: req.body.agence,
                annonceur: req.body.annonceur,
                groupe_annonceur: req.body.groupe_annonceur,
                produit:   req.body.produit

            }
        );

        Campagne.findOne({ 'name': req.body.name })
            .exec(function (err, found_name) {
                if (err) {
                    var errors_detail = ("Error Insert : %s ", err);
                    req.flash('msg_error', errors_detail);
                    res.render('campagne/add-campagne',
                        {
                            name: req.body.name,
                            date_debut: req.body.date_debut,
                            date_fin: req.body.date_fin,
                            agence: req.body.agence,
                            annonceur: req.body.annonceur,
                            groupe_annonceur: req.body.groupe_annonceur,
                            produit:   req.body.produit,
                        });
                }
                if (found_name) {
                    req.flash('msg_error', 'Campagne with the same name already existe');
                    res.render('campagne/add-campagne',
                        {
                            name: req.body.name,
                            date_debut: req.body.date_debut,
                            date_fin: req.body.date_fin,
                            agence: req.body.agence,
                            annonceur: req.body.annonceur,
                            groupe_annonceur: req.body.groupe_annonceur,
                            produit:   req.body.produit,
                        });
                }
                else {
                    if(req.body.date_debut > req.body.date_fin){
                        req.flash('msg_error', 'date_debut must be before date_fin');
                        res.render('campagne/add-campagne',
                            {
                                name: req.body.name,
                                date_debut: req.body.date_debut,
                                date_fin: req.body.date_fin,
                                agence: req.body.agence,
                                annonceur: req.body.annonceur,
                                groupe_annonceur: req.body.groupe_annonceur,
                                produit:   req.body.produit
                            });
                    }else {

                            console.log(req.body.name +'\n');
                            console.log(req.body.date_debut +'\n');
                            console.log(req.body.date_fin +'\n');
                            console.log(req.body.agence +'\n');
                            console.log(req.body.annonceur +'\n');
                            console.log(req.body.produit);
                        campagne.save(function (err) {
                            if (err) {
                                var errors_detail = ("Error Insert : %s ", err);
                                req.flash('msg_error', errors_detail);
                                res.render('campagne/add-campage',
                                    {
                                        name: req.body.name,
                                        date_debut: req.body.date_debut,
                                        date_fin: req.body.date_fin,
                                        agence: req.body.agence,
                                        annonceur: req.body.annonceur,
                                        groupe_annonceur: req.body.groupe_annonceur,
                                        produit:   req.body.produit
                                    });
                            }

                            // Genre saved. Redirect to genre detail page.
                            req.flash('msg_info', 'Create campagne success');
                            res.redirect('/campagnes');

                        });
                    }
                }
            });
    } else {
        console.log(errors);
        errors_detail = "Sory there are error" + "
" ;
        for (i in errors)
        {
            error = errors[i];
            errors_detail += '
'+error.msg+'
';
        }
        errors_detail += "
";
        req.flash('msg_error', errors_detail);
        res.render('campagne/add-campagne',
            {
                name: req.body.name,
                date_debut: req.body.date_debut,
                date_fin: req.body.date_fin,
                agence: req.body.agence,
                annonceur: req.body.annonceur,
                groupe_annonceur: req.body.groupe_annonceur,
                produit:   req.body.produit,
            });
    }
};

When I submit my form I have this message :
Error: Can't set headers after they are sent.
    at validateHeader (_http_outgoing.js:494:11)
    at ServerResponse.setHeader (_http_outgoing.js:501:3)
I saw one of the causes of the error is the redirect in my controller.
I also have a  $__save.error in mongoose.
If I can get somme help it will be nice.

A: Because you aren't returning whenever you are calling res.render. This way you are trying to send response multiple times, hence, setting headers after sending first response.
e.g.
Campagne.findOne({ 'name': req.body.name })
   .exec(function (err, found_name) {
      if (err) {
          var errors_detail = ("Error Insert : %s ", err);
          req.flash('msg_error', errors_detail);
          // you should return here, because it can go to following condition
          return res.render('campagne/add-campagne',{
             // some code
          });
      }

      if (found_name) {
          req.flash('msg_error', 'Campagne with the same name already existe');
          return res.render('campagne/add-campagne', {
              // some code
          });
      }

Do it for all conditions.


text:
Q: How should I filter the results of a RavenDB Lucene search? Say I had a User class like this:
public class User
{
  public bool IsActive {get;set;}
  public string[] Tags{get;set;}
  public string Description {get;set;}
}

I would like to use RavenDB to search for the set of users that match following criteria:

*

*IsActive = true

*Tags contains both 'hello' and 'world'

*Description has the following phrase 'abject failure'

I have researched the Lucene Query syntax, I have even got some stuff working, but it all feels dreadfully clunky with lots of combinatorial string-building to create a text-based lucene query string. I hesitate to put my code up here because it is quite smelly.
I think what I want to do it submit a Lucene Search for the Description and Tags and then filter it with a Where clause for the IsActive field, perhaps like this Filter RavenDB Search Results. But I got lost.
I am using the latest official release (960) so all the groovy stuff that comes after this is not available to me yet. For example, this solution is verboten as 960 does not appear to support the .As<T>() extension.
Question
How do I construct the required Index and Query to perform a search that combines:

*

*a single constraint, eg IsActive

*a collection constraint, eg Tags

*a free-text constraint eg Description
to return a strongly typed list of User objects?
Thank you for any code examples or pointers.

A: You query it like this:
var results = (from u in Session.Query<User>("YourUserIndex")
              where u.IsActive && u.Tags.Any(x=>x == "hello") && x.Tags.Any(x=>x=="world")
              select u)
              .Search(x=>x.Description, "abject failure")
              .ToList();

Where YourUserIndex looks like this:
from u in docs.Users
select new { u.IsActive, u.Tags, u.Description };

And you need to mark the Description field as analyzed.


text:
Q: iPhone 4.0 API to invoke the phone lock screen? Is there an API with the latest 4.0 SDK or earlier that allows an app to programatically invoke the iPhone's lock screen (the one that says "Slide to Unlock") ?

A: No, you can't do anything from the app that interferes with the users ability to control the phone. You could lock someone out of their phone with that capability.


text:
Q: in app purchase detail in database: I am using V3 API for in app purchase I am using V3 API for in app purchase. Transaction is fine. I have used webservice to store transaction detail. But its not getting inserted into the DB. So even after the transaction, the user detail remain unchanged which is a big issue now.
Can any one help me????


text:
Q: How to remove a pending invitation to a Github repo? I would like to write a script that uses the GitHub API to remove a pending invitation to a repository. Intended usage would be something like this:
./remove_pending_invite.sh <name_of_repo> <their_github_username>

I know I can create invitations using a sequence of instructions like this:
# Log in to GitHub
gh auth login --with-token <github_token_here>

# Give the user full access
gh api -XPUT repos/<organization_name>/<name_of_repo>/collaborators/<their_github_username> -f permission=maintain

But I don't know how to remove them. My use-case is that I'd like to remove an invitation that's expired (after 7 days) so I can reinvite the user.

A: The GitHub API does not provide a direct way to remove a pending invitation.
However, you can work around this by using the GitHub API to list pending invitations for a repository, and then deleting the relevant invitation from this list.
First, use the GitHub API to list the pending invitations for a repository:
gh api repos/<organization_name>/<name_of_repo>/invitations

The response should return a list of pending invitations, with the invitee's GitHub username included in the response.
You can then use the GitHub API to delete the invitation for a particular user:
gh api -XDELETE repos/<organization_name>/<name_of_repo>/invitations/<their_github_username>

This should delete the pending invitation for the specified user from the repository.


text:
Q: Windows Explorer can no longer make new folders I (actually, a very unfortunate friend of mine)
  can no longer create new folders from the Windows Explorer program.
(It is important to note that mkdir and friends still work.)
I have no idea how this came to be, but my friend denies any system-wide changes around the time it started.
How might I go about adding it back in as it would normally be?
(Note also that other context menu options remain—the 'new folder' one simply is not among them.)

A: He could try going into the Folder Options from the Control Panel and Restoring all folder options to default. There's nothing in there to indicate that the context menu could be modified in any way, but I guess it's worth a go.


text:
Q: The constructor URL(Elements) is undefined i m using  jsoup Application and trying to get url of web pages. i got  urls of web page. i m trying to get only image urls via url parsing
but when sending request to url i got this error
" The constructor URL(Elements) is undefined "
my question is how can i pass urls that i got from jsoup library
here is my code
' public static void main(String[] args) throws IOException {
    Validate.isTrue(args.length == 1, "usage: supply url to fetch");
    String url = args[0];
    print("Fetching %s...", url);
    Document doc = Jsoup.connect(url).get();
    Elements links = doc.select("a[href]");
    Elements media = doc.select("[src]");
    Elements imports = doc.select("link[href]");

'
and using
'Elements imagepath = doc.select("[src]");'

and passing this Lement into url parsing function
URL url = new URL(imagepath);

can anyone help me to figure it out how to get url parsing function works
thanks in advance

A: The reason you get that exception is because you pass Elements to the URL constructor - the Elements is just the specialization of List<Element>. This means you probably have more than one image assigned to imagepath variable. If you would like to construct the URL objects from the scraped images, consider this code sample:
Elements images = document.select("img");
for (Element element : images) {
    System.out.println(element.attr("abs:src"));
}

This should help you making progress with your application. I would love to answer any further question you might have.


text:
Q: RavenDB poor select performance I'm testing RavenDB for my future projects. Database performance is a must requirement for me, that's why I want to be able to tune RavenDB to be at least in SQL Server's performance range, but my tests shows that raven db is approximately 10x-20x slower in select queries than SQL Server, even when RavenDB is indexed and SQL Server doesn't have any indexes.
I populated database with 150k documents. Each document has a collection of child elements. Db size is approx. 1GB and so is index size too. Raven/Esent/CacheSizeMax is set to 2048 and Raven/Esent/MaxVerPages is set to 128.
Here's how the documents looks like:
{
  "Date": "2028-09-29T01:27:13.7981628",
  "Items": [
    {
      {
      "ProductId": "products/673",
      "Quantity": 26,
      "Price": {
        "Amount": 2443.0,
        "Currency": "USD"
      }
    },
    {
      "ProductId": "products/649",
      "Quantity": 10,
      "Price": {
        "Amount": 1642.0,
        "Currency": "USD"
      }
    }
  ],
  "CustomerId": "customers/10"
}

public class Order
{
    public DateTime Date { get; set; }
    public IList<OrderItem> Items { get; set; }
    public string CustomerId { get; set; }
}

public class OrderItem
{
    public string ProductId { get; set; }
    public int Quantity { get; set; }
    public Price Price { get; set; }
}

public class Price
{
    public decimal Amount { get; set; }
    public string Currency { get; set; }
}

Here's the defined index:
from doc in docs.Orders
from docItemsItem in ((IEnumerable<dynamic>)doc.Items).DefaultIfEmpty()
select new { Items_Price_Amount = docItemsItem.Price.Amount, Items_Quantity = docItemsItem.Quantity, Date = doc.Date }

I defined the index using Management studio, not from code BTW (don't know if it has any negative/positive effect on perfromance).
This query takes from 500ms to 1500ms to complete (Note that this is the time that is needed to execute the query, directly shown from ravendb's console. So it doesn't contain http request time and deserialization overhead. Just query execution time).
session.Query<Order>("OrdersIndex").Where(o =>
    o.Items.Any(oi => oi.Price.Amount > 0 && oi.Quantity < 100)).Take(128).ToList();

I'm running the query on quad core i5 cpu running at 4.2 GHz and the db is located on a SSD.
Now when I populated same amount of data on sql server express, with same schema and same amount of associated objects. without index, sql server executes the same query which includes joins in 35ms. With index it takes 0ms :|.
All tests were performed when db servers were warmed up.
Though, I'm still very satisfied with RavenDB's performance, I'm curious if I am missing something or RavenDB is slower than a relational database?
Sorry for my poor english.
Thanks
UPDATE
Ayande, I tried what you suggested, but when I try to define the index you sent me, I get the following error:
public Index_OrdersIndex()
    {
        this.ViewText = @"from doc in docs.Orders
select new { Items_Price_Amount = doc.Items(s=>s.Price.Amount), Items_Quantity = doc.Items(s=>s.Quantity), Date = doc.Date }
";
        this.ForEntityNames.Add("Orders");
        this.AddMapDefinition(docs => from doc in docs
            where doc["@metadata"]["Raven-Entity-Name"] == "Orders"
            select new { Items_Price_Amount = doc.Items(s => s.Price.Amount), Items_Quantity = doc.Items.(s => s.Quantity), Date = doc.Date, __document_id = doc.__document_id });
        this.AddField("Items_Price_Amount");
        this.AddField("Items_Quantity");
        this.AddField("Date");
        this.AddField("__document_id");
        this.AddQueryParameterForMap("Date");
        this.AddQueryParameterForMap("__document_id");
        this.AddQueryParameterForReduce("Date");
        this.AddQueryParameterForReduce("__document_id");
    }
}

error CS1977: Cannot use a lambda expression as an argument to a dynamically dispatched operation without first casting it to a delegate or expression tree type

A: Davita,
The following index generate ~8 million index entries:
from doc in docs.Orders
from docItemsItem in ((IEnumerable<dynamic>)doc.Items).DefaultIfEmpty()
select new { Items_Price_Amount = docItemsItem.Price.Amount, Items_Quantity = docItemsItem.Quantity, Date = doc.Date }

This one generates far less:
from doc in docs.Orders
select new { Items_Price_Amount = doc.Items(s=>s.Price.Amount), Items_Quantity = doc.Items.(s=>s.Quantity), Date = doc.Date }

And can be queried with the same results, but on our tests showed up to be about twice as fast.
The major problem is that you are making several range queries, which are expensive with a large number of potential values, and then you have a large number of actual matches for the query.
Doing an exact match is significantly faster, by the way.
We are still working on ways to try to speed things up.


text:
Q: How to change bootstrap typographic measurement in the appropriate way? Currently Bootstrap 3 used html {font-size: 62.5%;} and then
body {

  font-size: 14px;
  line-height: 1.42857143;

}

and than px everywhere for typography
h1,
.h1 {
  font-size: 36px;
}
h2,
.h2 {
  font-size: 30px;
}
h3,
.h3 {
  font-size: 24px;
}
h4,
.h4 {
  font-size: 18px;
}
h5,
.h5 {
  font-size: 14px;
}
h6,
.h6 {
  font-size: 12px;
}

And in current condition if I want to make default font-size to 16px should I also increase the px size of all heading levels like 36 to 38 for h1 and also change the line-height which is 1.42857143 for 14px font-size
Or I can just change html {font-size: 62.5%;} to something else and no editing required for body, heading and line height

A: Just trying a quick test seems to reveal the answer:
Example with: html {font-size: 62.5%;}
Example with: html {font-size: 100%;}
The two examples look exactly the same because font sizes set in non-relative units, like px, will not be effected by changes to a parent element's font-size.
If you would like to have this kind of functionality try using em, like so:
Example with body{font-size: 62.5%;}
Example with body{font-size: 100%;}
CSS using em units:
body {
    font-size: 62.5%;
}
h1, .h1 {
    font-size: 3.6em; /* equal to 36px */
}
h2, .h2 {
    font-size: 3.0em; /* equal to 30px */
}
h3, .h3 {
    font-size: 2.4em; /* equal to 24px */
}
h4, .h4 {
    font-size: 1.8em; /* equal to 18px */
}
h5, .h5 {
    font-size: 1.4em; /* equal to 14px */
}
h6, .h6 {
    font-size: 1.2em; /* equal to 12px */
}

Credible Source:

The most popular method in working with em values is to set the
  font-size on the body to 62.5%. Because the default browser font-size
  is 16px, this makes it 10px (without hard-setting it to 10px, which
  wouldn't cascade). Using 10 as a multiplier is much easier than using
  16. This way, you need a font size of 18px? Use font-size: 1.8em.
So why both with all this em business when it's just an abstraction of
  using pixel values anyway? Three possible reasons:

*

*They ARE resizable in IE 6

*The relationship to other sizes (elastic width sites)

*Em's cascade like a mo-fo

Excerpt from:
px – em – % – pt – keyword
Published April 16, 2009 by Chris Coyier
I'm guessing this method may be the origin of the html{font-size: 62.5%;} found in your code.

A: You can use the Customizer to do this with ease. You'll need to manually adjust the line height, but the font sizes for h1..6 are generated based on @font-size-base.

A: I think the best way that you can control the typography in Bootstrap responsive design is by using @Media Queries. You have 4 break points in Bootstrap lg, md, sm and xs, so just choose 1 font size for each resolution group.


text:
Q: Can't use class constructor argument in Python I can't get what I'm doing wrong here. I'm defining a class with the following code:
import sqlite3 as lite
import sys
import os.path
class database:
    def __init__(self,dbfname):
       if os.path.isfile(dbfname):
            self.con = lite.connect(dbfname)
       else:
            self.con = self.createDBfile(dbfname)
    #Other methods...

Then, when I try to make an instance of the class
base = database("mydb.db")

I get an error saying that there is no "global" variable named dbfname .
Traceback (most recent call last):
File "testdb.py", line 67, in <module>
base = database("mydb.db")
File "testdb.py", line 13, in __init__
self.con = self.createDBfile(dbfname)
File "testdb.py", line 15, in createDBfile
if os.path.isfile(dbfname):
NameError: global name 'dbfname' is not defined

What would be the correct way to use the argument variable dbfname ?

A: This code looks fine. The error isn't in the code you posted though; it's in testdb.py on line 15 in the createDBfile() method (not in the __init__()).
How do I know this? Well, lets carefully look at the traceback Python gives us:
Traceback (most recent call last):
  File "testdb.py", line 67, in <module>
    base = database("mydb.db")
  File "testdb.py", line 13, in __init__
    self.con = self.createDBfile(dbfname)
  File "testdb.py", line 15, in createDBfile
    if os.path.isfile(dbfname):
NameError: global name 'dbfname' is not defined

Like the first line says, the most recent call is last. So you read a traceback from down to up (and not from up to down).
The very last line is the actual error, but just before that is:
  File "testdb.py", line 15, in createDBfile
    if os.path.isfile(dbfname):

So it says that in the file testdb.py, on line 15, in the method createDBfile() an error occurred. Python also prints out the contents of this line 15.
Above that is the call to the createDBfile() method in your __init__() function, and above that the call to the __init__() function (by creating the class instance).
You didn't post the contents of this createDBfile() method, so I can't tell you where exactly the error is. I suspect you did something wrong with the function arguments (perhaps as simple as a typo?)


text:
Q: Hover an I tag change the font icon inside it and before it I have this code:

I wanted to change it to fa fa-star-o, for example I hovered the 3rd i in rate-instructors, I wanted it and the first 2 to be in fa fa-star-o only in div with class rate-instructors. Is it possible?
My tried code:
 $('i').each(function() {
    $(this).attr('class','fa fa-star-o');
 });

A: You can do something like this:
$(".rate-instructors i,.rate-activities i").hover(function(){
  $(this).add($(this).prevAll("i")).removeClass("fa-star").addClass("fa-star-o");
  $(this).nextAll("i").removeClass("fa-star-o").addClass("fa-star");
})

Demo

$(".rate-instructors i,.rate-activities i").hover(function(){
  $(this).add($(this).prevAll("i")).removeClass("fa-star").addClass("fa-star-o");
  $(this).nextAll("i").removeClass("fa-star-o").addClass("fa-star");
})
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.css" rel="stylesheet"/>


text:
Q: How many projects can we create within a solition in visual studio 2013? Solution Explorer Screenshot
How many projects can we create? Have any limitation?
In Visual Studio, we can create one or more projects under a single solution.
Thanks,
Tofael Ahmed

A: As far as I am aware there are no official limitations other than your system limitations.  However, there are many opinions on what constitutes an 'appropriate' number.
I have worked with solutions with just one project and others with well over 100 projects.
In my personal opinion I think the determining factor is separation of concerns - if  the projects are used as ways of splitting code into more manageable pieces but the code is still interdependent then I think that is a good reason to have multiple projects.
If you have multiple concerns (e.g. Application, Support Libraries, Tests) you might will consider separate solutions to be appropriate.
In the end, the decision is yours and the limits are effectively your system limitations and your opinions.


text:
Q: Make peer failed in Hyperledger fabric I am using go version 1.6 on Ubuntu system. When i tried to create peer i am getting following error.
$ make peer
.build/bin/peer
CGO_CFLAGS=" " GOBIN=/opt/gopath/src/github.com/hyperledger/fabric/.build/bin go install -tags "experimental" -ldflags "-X github.com/hyperledger/fabric/common/metadata.Version=1.2.0 -X github.com/hyperledger/fabric/common/metadata.CommitSHA=9acd9cd -X github.com/hyperledger/fabric/common/metadata.BaseVersion=0.4.8 -X github.com/hyperledger/fabric/common/metadata.BaseDockerLabel=org.hyperledger.fabric -X github.com/hyperledger/fabric/common/metadata.DockerNamespace=hyperledger -X github.com/hyperledger/fabric/common/metadata.BaseDockerNamespace=hyperledger -X github.com/hyperledger/fabric/common/metadata.Experimental=true" github.com/hyperledger/fabric/peer
vendor/github.com/fsouza/go-dockerclient/client_unix.go:10:2: cannot find package "context" in any of:
    /opt/gopath/src/github.com/hyperledger/fabric/vendor/context (vendor tree)
    /usr/lib/go-1.6/src/context (from $GOROOT)
    /opt/gopath/src/context (from $GOPATH)
bccsp/factory/pluginfactory.go:12:2: cannot find package "plugin" in any of:
    /opt/gopath/src/github.com/hyperledger/fabric/vendor/plugin (vendor tree)
    /usr/lib/go-1.6/src/plugin (from $GOROOT)
    /opt/gopath/src/plugin (from $GOPATH)
Makefile:256: recipe for target '.build/bin/peer' failed
make: *** [.build/bin/peer] Error 1

A: Please use golang 1.10 and in general see the prerequisites page.