text:
Q: Same Generic commit object getting saved from different instances I am using Javers version 5.1.2, with jdk 11, in my application, where I am committing Generic Object T and saving into mongodb. The Generic commit objects are actually created from generic rest service, where user can pass any Json.
Every thing is going fine on single instance. Whenever any re commit is sent with same request, Javers commit.getChanges().isEmpty() method returns true.
Issues:
1) Whenever same request to sent to different instance, commit.getChanges().isEmpty() method returns false.
2) If I commit one request, and restart the instance and then again commit, commit.getChanges().isEmpty() again returns false. Instead of true.
As a result of above issue, new version is getting created if request goes to different new instance or instance is restarted.
Could you please let me know, how we can handle this issue.
I will extract code from the project and will create a sample running project and share.
Right now, I can share few classes, please see, if these help:

//---------------------Entitiy Class:
import java.util.Map;

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;

@AllArgsConstructor
@NoArgsConstructor
@ToString
public class ClientEntity<T> {

    @Getter
    @Setter
    private String entityId;

    @Getter
    @Setter
    private T commitObj;

    @Getter
    @Setter
    private String authorName;

    @Getter
    @Setter
    private boolean major;

    @Getter
    @Setter
    private Map<String, String> commitProperties;

}

//--------DataIntegrator
@Service
public class DataIntegrator {

    private final Javers javers;

    private IVersionRepository versionDao;

    private IdGenerator idGenerator;

    @Inject
    public DataIntegrator(Javers javers, IVersionRepository versionDao, IdGenerator idGenerator) {
        this.javers = javers;
        this.versionDao = versionDao;
        this.idGenerator = idGenerator;
    }

    public <T> String commit(ClientEntity<T> clientObject) {
        CommitEntity commitEntity = new CommitEntity();
        commitEntity.setEntityId(clientObject.getEntityId());
        commitEntity.setEntityObject(clientObject.getCommitObj());

        Map<String, String> commitProperties = new HashMap<>();
        commitProperties.putAll(clientObject.getCommitProperties());
        commitProperties.put(commit_id_property_key, clientObject.getEntityId());
        commitProperties.putAll(idGenerator.getEntityVersions(clientObject.getEntityId(), clientObject.isMajor()));

        Commit commit = javers.commit(clientObject.getAuthorName(), commitEntity, commitProperties);

        if (commit.getChanges().isEmpty()) {
            return "No Changes Found";
        }
        versionDao.save(
                new VersionHead(clientObject.getEntityId(), Long.parseLong(commitProperties.get(major_version_id_key)),
                        Long.parseLong(commitProperties.get(minor_version_id_key))));

        return commit.getProperties().get(major_version_id_key) + ":"
                + commit.getProperties().get(minor_version_id_key);
    }
}

1) commitObj is a Generic object, in ClientEntity, which holds Json coming from the Rest webService. The JSON can be any valid json. Can have nested structure also.
2) After calling javers.commit method, we are checking if it is existing entity or there is any change using commit.getChanges().isEmpty().

*

*If same second request goes to same instance, it returns true for change, as expected

*If same second request goes to different instance, under load balancer, it takes it as different request and commit.getChanges().isEmpty() returns false. Expected response should be true, as it is same version.

*If after first request, I restart instance, and make a same request, it returns false, instead of true, which means, getChanges method taking the same request as same.


text:
Q: Add Promise return type to method in Angular I have the following method which returns an array of TreeNodes
  basketItemNodes: TreeNode[] = [];

  getBasketItems() {
    this.basketService.getAllBasketItems()
      .subscribe(
        res => {
          this.basketItemNodes = <TreeNode []> res;
        },
        err => {
          console.log(err);
        }
      );
      return this.basketItemNodes;
  }

How can I change the return type to a Promise or Observable?

A: If you want to return Observable, then do not subscribe to it here. Instead you could simply map the response to <TreeNode []> and return.
basketItemNodes: TreeNode[] = [];

getBasketItems() {
    return this.basketService.getAllBasketItems()
      .pipe(map(res => this.basketItemNodes = <TreeNode[]> res));
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Difficulty accessing specific data in axios GET request I'm using the CryptoCompare API (https://www.cryptocompare.com/api/#-api-data-coinlist-) and I'm having difficulty accessing specific coin information on search. Instead, I'm returned the whole list of coins rather than the one I searched. I'm guessing it's a problem within my then statement, but I'm not sure. Here's the code I have so far-- the problem area is in searchImage

class SearchForm extends React.Component{
    constructor(){
        super();
        this.state = {
            currentSearch: "",
            priceResults: [],
            cryImage: [],
        }
        this.handleChange = this.handleChange.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);
        this.cryPrice = this.cryPrice.bind(this);
    }

    cryPrice(param){
        axios.get(`https://min-api.cryptocompare.com/data/pricemulti?fsyms=${param}&tsyms=CAD`)
            .then(res => {
                const cryptos = res.data;
                console.log(cryptos);
                this.setState({
                    priceResults: cryptos
                })
            })
        }

    searchImage(param){
        axios.get(`https://min-api.cryptocompare.com/data/all/coinlist`, {
            params: {
                name: `${param}`,
            }
        }).then(res => {
            const cryImage = res.data;
            console.log(cryImage);
            this.setState({
                cryImage
            })
        })
    }

    handleChange(e){
        const currentSearchValue = e.target.value;
        this.setState({
            currentSearch: currentSearchValue
        })
        console.log(currentSearchValue);
    }

    handleSubmit(e){
        e.preventDefault();
        this.cryPrice(this.state.currentSearch);
        this.searchImage(this.state.currentSearch);
        this.setState({
            currentSearch: ""
        })
    }

A: It says in the docs (from my understanding) that this get request takes no params.

CoinList
Get general info for all the coins available on the website.
URL Parameters
None

So when you send the request you will always get all of the coins. Now what you can do is filter the only one you are interested in through the response. This means that in the body of the function you are using in your .then you can simply read the info about the coin given through param.


text:
Q: Cache being halfway final I have a small question i came up with reading this thread:
Why are static variables considered evil?
In my application i have a really massive amount of lets say configuration variables. E.g. fonts, colors, cached images, ... As most of them never change i considered them being static.  Nevertheless my application is an applet and as the client has been executing the applet once, some of these static information may change, as a given configuration may have been changed. Therefore lets say this kind of data is used to change rarely, but is not considered being final.
In addition as the amount of information i handle that way is huge, i mapped them onto own Enums like that:
public enum Fonts {

    COLOR_CHOOSER, MAP_META_DATA;
    private Font localFont;

    public Font getValue() {
        return localFont;
    }

    private void setValue(Font newFont) {
        localFont = newFont;
    }
}

protected static void initFonts() {
    Fonts.COLOR_CHOOSER.setValue(new Font("Arial", Font.PLAIN, 15));
    Fonts.MAP_META_DATA.setValue(font_race.deriveFont(Font.BOLD, 11));
}

By using enums like that, I was able to identify the value I am looking for pretty easily, while i can maintain all of them at just one place.
Someone may say, since this is static, I could alternatively place them within the objects, they are used in anyway. Nevertheless, I considered the current behavior being more easy to read.
Besides of that the initFonts() method becomes replaced in future by a mapping method, which gets the currently hard coded values from an external source like json or xml. Therefore if i work OO this would mean to forward any of the incoming data to the corresponding objects, which I consider of being NOT easy to read.
To come up with my question:
How would somebody of you map/cache halfway final parameters (I also considered having a hashmap with an enum as key value). E.g for Images, Fonts, Colors, pixel margins, etc. Is the way i am using these enums appropriate or may I consider them being evil, since they are static? If yes - what would be an appropriate way, which keeps being easy to read and easy to maintain?!
I considered my solution of being a possible way to go, but were going to rethink the whole design after reading the above mentioned thread.
Thanks a lot for any advice.
Kind regards.

A: Enums are alright to represent static final data, which is why I don't think it's proper to have such an initFonts() method, modifying the content of the enum values, even if it's using a private method. What you should have is more like:
public enum Fonts {
    COLOR_CHOOSER(new Font("Arial", Font.PLAIN, 15)),
    MAP_META_DATA(new Font("Arial", Font.BOLD, 11)); // No reference to font_race, of course

    private final Font localFont;

    private Fonts(Font font) {
        localFont = font;
    }

    public Font getValue() {
        return localFont;
    }
}

I don't see why you say that your kind of configuration data is not final: it doesn't seem to change while the application is running.
However, if the runtime initialization needs to load values that may change, as opposed to being determined at compilation time, an enum may not be the correct model anymore, if it's unable to initialize its values itself in a simple manner (calling too much stuff from the static initializer of an enum might not be the best think to do). In that case, I'd replace the direct use of enums by an intermediate service, for example holding an immutable Map<Fonts, Font> (which might be an EnumMap<Fonts, Font> wrapped with Collections.unmodifiableMap()) initialized once and for all using the proper method, and instead of calling Fonts.COLOR_CHOOSER.getValue(), you'd call FontService.getFont(Fonts.COLOR_CHOOSER).


text:
Q: Is Moore's law (empirically) the same for both memory capacity and processing speed? Has memory and processing power increased over time around basically in the same rate, or can we say that one or the other has increased more? Has cost decreased in the same rate? And how about the near future?
I am aware this question is not directly related to programming, but I thought it would be better to ask it here for some reasons:

*

*I work as a programmer, not a computer science theorist (so I probably would not find it very helpful the kind of question I would receive from the Theoretical Computer Science site, for instance).

*I prefer answers based upon a programmers real experience.

*And I am worried about real programming-related issues, specially the functional x imperative debate.

About the 3rd item: currently we've being seeing a lot of arguments about how the increase of using functional programming techniques is related to the now common multi-core machines, and how the free lunch is over [pdf].
But it seems to me that the functional paradigm is much more memory consuming (but this is an opinion, not a fact), and I have not seem many arguments about this future increase in memory needs.

A: Not strictly an answer, but ...
Your question implies that you are wondering whether functional programming will become unavoidable due to limitations in moore's law. Perhaps that's besides the point. The main driver behind new technologies in programming is not performance, or we would all be writing assembly. The main driver is complexity. New programming techniques and technologies become popular because they make it easier to build bigger systems.
In other words, if functional programming takes over, it won't be because it offers better performance, it will be because it lets you build bigger apps faster. And that has nothing to do with moore's law.

A: So Moore's Law specifically states that the density of transistors will double about every 18 months. What this translates into effectively is faster processors and more RAM. Let's look at it from a few comparisons.
1996 A top of the line desktop had about a 300 MHz Processor, 32 MBs of RAM and a 2GB hard drive. Computers were just becoming powerful enough that the MPEG audio format (MP3) could be decompressed and played back in real time. And people were concerned about the performance of a Virtual Machine based language such as Java.
2011 My phone has a 1GHz Processor 512 MB RAM, 16GB of storage and can play MP3 and practically every other format.
In 15 years, my phone is more powerful than my computer was, not only is Java used for application development, but so is another interpreted platform (.NET). So yes given time, Moore's law will make any thing that is resource constrained today a viable technology.
Also, I've never heard of functional languages as being more memory intensive than OO.

A: A huge problem today is that memory latency has hardly improved at all. This article estimates that over the last 20 years memory has improved

*

*size - 128x

*Bandwith - 20x

*Latency - 1.3x

Processors combat this with larger and more advanced caching systems and pre-fetching. And as a result it becomes more important to keep memory access predictable and avoid random access.
Most of the benefit of functional programming is related to making it easier to parallelize computation, and this is clearly an increasing concern since processor frequency has stopped scaling.
I'm not aware of any significant difference regarding memory usage of functional programming. I would think that this is much more related to language design and compiler efficiency than programming paradigm. If performance is important, low level access to the hardware is useful, and functional languages typically does not provide this.
It seem to me that functional techniques has become much more popular, in large part due to increased productivity and easier parallelization. Pure functional languages has remained somewhat uncommon.

A: It's important to note that Moore's Law does not talk about processor speeds. It talks about transistor density.
In fact, we hit the wall on clock rates quite a long time ago, and clocks have generally been decreasing since the P4. There have been additional performance gains with stuff like OOO execution and other mechanisms to exploit ILP, but these days the extra density is going towards more cache and more cores, rather than straightforwardly boosting the speed of each core.
Memory, on the other hand, is much more straightforward to implement - a higher transistor density basically means you can pack more memory cells into the same package, without having to do any complex redesign.
Basically, memory scales exceptionally well with increasing transistor density. Processors, not so much.

A: Moore's Law was originally about the number of circuit elements that would fit on a chip.  The comparison to increased processor speed came later.
Faster and smaller elements benefit both the CPU and memory, so one would expect a roughly parallel increase in CPU and memory capability.  Simply as a matter of qualitative impression, it seems to me that they've been increasing more or less together, along with hard disk size.  (My first computer with a hard disk was a Mac SE, with an 8 MHz 68000 processor (16/32 bits), 1M of memory, and a 20M disk drive.  Everything's increased in my current machines by factors between one and ten thousand.)

A: As others have stated Moore's law was really about transitor density. Since smaller geometries mean faster switching and data travel times, we saw speed improve along with density and the two were conflated. Several years ago a total power dissapation barrier was reached, faster clockrates are more power hungry, and without exotic cooling mechanisms we couldn't continue to advance them. But transistor budgets have gone on exponentially increasing, that means greater parallelism both within a core, and by replication of more cores has been pursued instead. Also caches become bigger with time, and this helps reduce the CPUspeed to memory speed mismatch penalty somewhat.
Functional programming, or any other technique which trades off programmer complexity for (somewhat) reduced resource usage efficiency is a consequence of the advances in HW capability. The sweetspot in the tradeoff between source code complexity and raw performance changes when machine capabilty increases. Also the capability to afford/contemplate more complex computations, leads to demand for more complex applications, which has an impact on the sweetspot of the tradeoff as well. If we only had kilohertz clocks and small memories, we would probably consider assembly to be the  highest level language we would want to consider.


text:
Q: discrete mathematics question $2-2\times 7+2\times 7^2− \cdots +2(-7)^n = \frac{1-(-7)^{n+1}}{4}$ This question is from the book Discrete Mathematics and its Applications by Kenneth Rosen page 329. Again for question 8 I face the same probelm I know the solution but I do not understand it.
Question 8) Prove that:  $2 − 2\times 7 + 2\times 7^2 − \cdots + 2(−7)^n = \frac{1−(−7)^{n+1}}{4}$ whenever $n$ is a nonnegative integer.

The answer:

The problem is I don't understand it especially the last part I marked in red can someone explain it to me please?

A: We have:
\begin{align}
[2-2*7+2*7^2-...+2*(-7)^{k}]+2*(-7)^{k+1} &=\frac{1-(-7)^{k+1}+8(-7)^{k+1}}{4}\\
&=\frac{1+8(-7)^{k+1}-1(-7)^{k+1}}{4}
\end{align}
Can you take it from here?


text:
Q: Woocommerce how to redirect a custom end point on my-account page It's the continue of my previous question
Woocommerce how to exclude the child pages (endpoints) of myaccount from the template redirect hook?
The login-register form has to be shown only like popup, so I've made redirect, to avoid default my-account page for not logged users.
I use that code to make redirect from my-account page itself, and to exclude 'lost-password' from that rule, to make possible for non-logged users to renew their passwords.
add_action( 'template_redirect', 'wish_custom_redirect' );

function wish_custom_redirect() {
  global $wp;

  if (
        !is_user_logged_in()
        &&
        ('my-account' == $wp->request)
        &&
        ('lost-password' != $wp->request)
     )
  {
    wp_redirect( home_url() );
    exit;
  }
}
add_action('wp_logout','auto_redirect_after_logout');

function auto_redirect_after_logout(){

  wp_redirect( home_url() );
  exit();
}

But it doesn't work with custom endpoint tabs in myaccount. If user log out, they can return to previous page and see that standard login form page, which has to be hidden.
How I created this endpoints. One for example, others are made by the same way.
/**
 * 1. Register new endpoint slug to use for My Account page
 */

/**
 * @important-note  Resave Permalinks or it will give 404 error
 */
function ts_custom_add_my_returns_endpoint() {
    add_rewrite_endpoint( 'my_returns', EP_ROOT | EP_PAGES );
}

add_action( 'init', 'ts_custom_add_my_returns_endpoint' );

/**
 * 2. Add new query var
 */

function ts_custom_my_returns_query_vars( $vars ) {
    $vars[] = 'my_returns';
    return $vars;
}

add_filter( 'woocommerce_get_query_vars', 'ts_custom_my_returns_query_vars', 0 );

/**
 * 3. Insert the new endpoint into the My Account menu
 */

function ts_custom_add_my_returns_link_my_account( $items ) {
    $items['my_returns'] = 'My returns';
    return $items;
}

add_filter( 'woocommerce_account_menu_items', 'ts_custom_add_my_returns_link_my_account' );

/**
 * 4. Add content to the new endpoint
 */

function ts_custom_my_returns_content() {?>

<?php echo get_theme_mod('my_returns_tab_heading') ?>

<?php
$orders = wc_get_orders( array(
  'numberposts' => -1,
   'orderby' => 'date',
   'order' => 'DESC',
   'customer_id' => get_current_user_id(),
   'status' => array('refunded','cancelled'),
) );

//* Loop through each WC_Order object
foreach( $orders as $order ){?>

        <?php
        $order_data = $order->get_data(); // The Order data
        $order_id = $order_data['id'];
        $order_currency = $order_data['currency'];
        $order_status = $order_data['status'];
         ?>

#<?php echo  $order_id;?>

                <?php
                foreach ($order->get_items() as $key => $lineItem) {
                $product_id = $lineItem['product_id'];
                $product = wc_get_product( $product_id );

                $item_meta_data = $lineItem->get_meta_data();
                $colormeta = $lineItem->get_meta( 'pa_color', true );
                $sizemeta = $lineItem->get_meta( 'pa_size', true ); ?>

                                <?php echo $product->get_image(['322', '304']);?>

                                <?php echo $lineItem['name'] ?>

                                <?php echo $lineItem['total'] . $order_currency?>

<?php esc_html_e( 'Quantity', 'woocommerce' )?>: <?php echo $lineItem['qty']?>

                <?php }  ?>

                    <button class="order-total"><?php echo get_theme_mod('orders_total_button');?></button>

  <?php esc_html_e( 'Price', 'woocommerce' )?>: <?php echo $order->get_total() . '  ' . $order_currency; ?>

  <?php esc_html_e( 'Quantity', 'woocommerce' )?>: <?php echo  $order->get_item_count(); ?>

 <?php esc_html_e( 'Status', 'woocommerce' )?>: <?php

                   if( 'cancelled'== $order->get_status() ) {
                     echo _x( 'Cancelled', 'Order status', 'woocommerce' );
                  }
                  if( 'refunded'== $order->get_status() ) {
                     echo _x( 'Refunded', 'Order status', 'woocommerce' );
                    }

                   ?>

 <?php esc_html_e( 'Order Date', 'woocommerce' )?> <?php
                    if( $date_created = $order->get_date_created() ){
                        // Display the localized formatted date
                         $formated_date_created = $date_created->date_i18n('d.m.Y ');
                         echo  $formated_date_created;
                    }

                   ?>

 <?php echo get_theme_mod('delivery_date_text')?>:
                   <?php
                        // The orders date
                         $date_created = $order->get_date_created();
                         $date_created =  $date_created->date('d.m.Y');
                        // The order date + 5 days
                        $delivery_date = date_i18n( 'd.m.Y', strtotime( $date_created . ' +21 days' ));
                        echo $delivery_date;
                    ?>

<?php  }?>

 <?php
}
add_action( 'woocommerce_account_my_returns_endpoint', 'ts_custom_my_returns_content' );

I tried to include them in query, but it didn't help. I tried with and without slash.
add_action( 'template_redirect', 'wish_custom_redirect' );

function wish_custom_redirect() {
  global $wp;

  if (
        !is_user_logged_in()
        &&
        ('my-account' == $wp->request)
         &&
        ('my-account/my_returns' == $wp->request)
         or
         &&
        ('my_returns' == $wp->request)
       /*with and without slash in the end and in the beginning*/
        &&
        ('lost-password' != $wp->request)
     )
  {
    wp_redirect( home_url() );
    exit;
  }
}

Yes, I saved them in settings > permalinks > save changes after creating, cause without that they showed 404. I just clicked 'save changes' in settings > permalinks > save changes.
How to include them in that redirect and to save 'lost-password' excluded?

A: You've got those redirect rules mixed up! Try the following snippet:
add_action('template_redirect', 'wish_custom_redirect_extended');

function wish_custom_redirect_extended()
{
    global $wp, $wp_query;

    if (
        !is_user_logged_in()
        &&
        ('my-account' == $wp->request)
        ||
        ('my-account/my_returns' == $wp->request)
        &&
        ('lost-password' != $wp->request)
    ) {
        wp_safe_redirect(site_url());
        exit;
    }
}


text:
Q: PDF programatically set font without being forced to set font size According to the PDF syntax given by Adobe here it seems that there is no possibility to set the actual font, without setting at the same time also the font size.
I am in the situation that the font size is already specified and set before together with a different font. I just want to keep the size just alter the font.
Exemplarily looks like this
/F1 12 Tf

where F1 "reprents" the font, the font size being 12.
Did I miss something, or is there a nice workaround for it?
Please note, that I have no access to the current font size and don't want to alter it.

A: Generally it requires a PDF editor to do font replacement, often with mixed results, as there is no simple means to substitute one font tag for another here I crafted a PDF to show how just simply swapping /F1 /F2 /F3 and /F4 may corrupt the output.
So line 1 and 2 are different styles of Arial font and lines 3 and 4 are Consolas so we can see as I cycle the font tags I might be able to replace one style by another but here only once in each font family and clearly line length will be changed.

So IF you know you want to swap style later it is essential to use proportional / fixed pitch static fonts.

IF you plan ahead it is possible to embed fonts for swapping style but generally not family, OR you could as many do set a generic font and rely on the system replacing those with local default fonts.
Otherwise you need to read the text in one font and rewrite that text block in a different font bearing in mind the need to reflow the line lengths or adjust sizes to suit, hence many a font is found with non uniform units.
For fairly simple font substitution I would normally resort to X-change editor or FlexiPDF editor


text:
Q: How to make xargs handle spaces and special characters? I have a file that contains a list of names. i.e.:
Long Name One (001)
Long Name Two (201)
Long Name Three (123)
...

with spaces and some special characters. I wanted to make directories out of these names, i.e.:
cat file | xargs -l1 mkdir

It makes individual directories separated by spaces, i.e. Long, Name, One, Two, Three, instead of  Long Name One (001), Long Name Two (201), Long Name Three (123).
How can I do that?

A: If your xargs implementation support -0 option:
tr '\n' '\0' <file | xargs -0 -l1 mkdir

POSIXly:
while IFS= read -r file; do
  mkdir -p -- "$file"
done <file

(Note that using while loop to process text considered bad practice in shell script)

A: xargs expects a very special input format where arguments are delimited by blanks or newlines (sometimes other forms of vertical whitespace, sometimes dependant on the current locale), and where single quote, double quotes and backslash can be used to escape them (but in a different way from shell quotes).
-l1 is not to pass one line of input as one single argument to mkdir, but to call one mkdir invocation for each single line of input but with words on that line still separated out as different arguments to mkdir.
The GNU implementation of xargs added a -0 option decades ago to accept NUL-delimited input. That's the most obvious way to separate words that are going to end up being arguments to a command because the NUL character happens to be the only character that cannot occur in a command argument or file name (your chosen list format which puts one file per line can't represent all possible file names as it doesn't allow a newline in a file name).
That -0 has been copied by several other xargs implementations but not all.
With those you can do:
<file tr '\n' '\0' | xargs -0 mkdir -p --

That will call mkdir as few times as possible with as many arguments as possible.
But note that if file is empty, mkdir will still be run and you'll get a syntax error by mkdir because of the missing argument. GNU xargs added a -r option for that which has been copied by a few other implementations.
GNU xargs also added (later) a -d option to be able to specify arbitrary delimiters, but I don't think any other implementation copied it. With GNU xargs, the best way is with:
xargs -rd '\n' -a file mkdir -p --

By passing the file with -a (also a GNU extension) instead of stdin, that means mkdir's stdin is preserved.
POSIXly, you'd need to post-process the input to put it in the format expected by xargs. You could do it for instance with:
<file sed 's/"/"\\""/g; s/^/"/; s/$/"/' | xargs mkdir -p --

Where we enclose each line inside double quotes and escape each " as "\"" before feeding to xargs.
But beware of possible limitations:

*

*the error when the file is empty already mentioned above

*it may fail with some implementations (including of sed) if the content of file is not valid text in the current locale. If file contains file names encoding in more than one different charset, or a charset different from the the locale's one, you can fix the locale to C which should help.

*some xargs implementations have ridiculously low limits on the maximum length of an argument (can be as low as 255 bytes).

To work around the syntax error upon empty input error, you can write:
<file sed 's/"/"\\""/g; s/^/"/; s/$/"/' |
  xargs sh -c '[ "$#" -eq 0 ] || exec mkdir -p -- "$@"' sh

A: Make the names null terminated and split there:
cat file | tr '\n' '\0' | xargs -l1 -0 mkdir

tr will replace the newline that cat output with \0, and the -0 flags in xargs is telling it to split arguments on the \0.

A: Use -d '\n' with your xargs command:
cat file | xargs -d '\n' -l1 mkdir

From manpage:
-d delim
              Input  items  are  terminated  by the specified character.  Quotes and backslash are not special; every
              character in the input is taken literally.  Disables the end-of-file string, which is treated like  any
              other  argument.   This can be used when the input consists of simply newline-separated items, although
              it is almost always better to design your program to use --null where this is possible.  The  specified
              delimiter  may be a single character, a C-style character escape such as \n, or an octal or hexadecimal
              escape code.  Octal and hexadecimal escape codes are understood as for the printf command.    Multibyte
              characters are not supported.

Example output:
$ ls
file

$ cat file
Long Name One (001)
Long Name Two (201)
Long Name Three (123)

$ cat file | xargs -d '\n' -l1 mkdir

$ ls -1
file
Long Name One (001)
Long Name Three (123)
Long Name Two (201)

A: You can do this POSIXLY with the -I option:
xargs -I % mkdir % < file

http://pubs.opengroup.org/onlinepubs/9699919799/utilities/xargs.html


text: Q: Is there a way to make my cloud bucket content public to only my subscriber of my website? I have a website and I have stored certain files in google cloud bucket. I want the condition wherein the subscribers of my website have only access to the bucket (by clicking the url, which I will link in my website). Current problem is whenever anyone clicks the link in my website, it is directing to google.storeapis. So the user may feel that I have connected my website to another site.


text:
Q: Create new git repos from exist git cloned project I have some repos cloned from http://drupal.org/project/
For work behind firewall, I want to import these cloned project to my local git server. How can I do that?

A: Each cloned repository can be used as a server.
If I correctly understand your needs, you just have to push to your own server from the checkout.
You can be interrested in some of the git push command like --all
So a command like git push --all <url of your repository>


text:
Q: HIVE: CREATE TABLE AS SELECT command cannot specify the list of columns for the target table How can I make this work?
  hive> desc temp;
  OK
  a                     int
  b                     int
  Time taken: 0.077 seconds, Fetched: 2 row(s)

I want to create t2 HIVE table with column names c and d but getting below error.
  hive> create table t2(c int,d int) as select a,b from temp;
  FAILED: SemanticException [Error 10065]: CREATE TABLE AS SELECT command         cannot specify the list of columns for the target table

A: You need not to mention table schema again as you are specifying to take the schema from another table. So your table creation statement should be like
create table t2 as select a,b from temp;

A: I know this is old, but by definition, but in case anyone else has the same question, the answer is pretty straightforward.
By definition, CREATE TABLE AS SELECT is used to persist a resultset as a table. This means that if you want the new table to have different column names, you need to use a different resultset to create it. An easy way you do that is with column aliases:
create table t2 as select a as c, b as d from temp;

I know you said you didn't want to do this (although there was a small typo - your query would fail because it would try to name both columns c), but hopefully this explains why you should approach it this way: you need to build a dataset whose metadata matches the table you want to create.


text:
Q: Shibboleth 3 IDP or SP setup with IP address I have successful setup Shibboleth IDP and SP with separate sub domains after digging on internet.
Example.
       IDP : http://idp.url.com/
   SP  : http://sp.url.com/

Now,My Question is:
Is it possible to setup these IDP and SP with static IP? (Not a single example available on Web)
For Example:
IDP : http://192.168.100.240/
   SP  : http://192.168.100.133/

I have tried enough but not getting How to do this. If is it possible, what kind of changes requires for it.

A: At last Resolved IP based configuration,
While installing IDP use 192.168.100.240 instead idp.url.com entity name. (you can use any thing for organization scope/name(like jubinpatel.com even using IP) )
Only Take care about all certificates. here I made mistake, create new certificates if requires and config new/changed Password in property files.
Also if you going to change https ports, take care of same port related metadata file changes and tomcat/jetty server configuration.


text:
Q: using jquery to addclass when an anchor is clicked having trouble with this.  Any help would be appreciated.
I'm trying to add the "slide" class to the left-menu div by using the Id "lm"
doesn't seem to be working for me.

$(document).ready(function() {});

$("#toggle", ).click(function() {
  $("#lm").addClass("slide");
});
  .left-menu {
  height: 55%;
  width: 45%;
  position: absolute;
  top: 0;
  left: 0;
  padding: 0;
  list-style: none;
  border-right: 2px solid #fff;
  background-color: #000;
  z-index: 1000;
}

.slide {
  -webkit-transform: translate(-20, 0);
  -moz-transform: translate(-20em, 0);
  -o-transform: translate(-20em, 0);
  -ms-transform: translate(-20em, 0);
  transform: translate(-51em, 0);
  -webkit-transition: 10s;
  -moz-transition: 10s;
  -o-transition: 10s;
  transition: 10s;

    [sv]

    Home

A: Your syntax is wrong, put the click FUNCTION in the $(document).ready(), and also there is a comma(,) exist in your script at this line $("#toggle",).click(). Remove it.
Try this :
$(document).ready(function(){
    $("#toggle").click(function(){
       $("#lm").addClass("slide");
    });
});

A: Try this .Your jquery code has syntax error & Not with proper format
Change as like this ,
Why ?

*

*You should add the click function inside the  $(document).ready(function() {//click function}) not with outside , And its not closing properly })

*Also css slide class not closing properly }

*$("#toggle,") its a invalid selector .so remove the , in $("#toggle,")

Note Don't forget to add jquery library link

Working Example

$(document).ready(function() {
$("#toggle").click(function() {
$("#lm").addClass("slide");
});
})
.left-menu {
  height: 55%;
  width: 45%;
  position: absolute;
  top: 100px;
  left: 0;
  padding: 0;
  list-style: none;
  border-right: 2px solid #fff;
  background-color: #000;
  z-index: 1000;
}

.slide {
  -webkit-transform: translate(-20, 0);
  -moz-transform: translate(-20em, 0);
  -o-transform: translate(-20em, 0);
  -ms-transform: translate(-20em, 0);
  transform: translate(-51em, 0);
  -webkit-transition: 10s;
  -moz-transition: 10s;
  -o-transition: 10s;
  transition: 10s;
  }

    [sv]sxx

    Home

A: Just remove that comma and check the below code.

$(document).ready(function() {
  $("#toggle").click(function() {
    $("#lm").addClass("slide");
  });
})
.left-menu {
  height: 55%;
  width: 45%;
  position: absolute;
  top: 100px;
  left: 0;
  padding: 0;
  list-style: none;
  border-right: 2px solid #fff;
  background-color: #000;
  z-index: 1000;
}

.slide {
  -webkit-transform: translate(-20, 0);
  -moz-transform: translate(-20em, 0);
  -o-transform: translate(-20em, 0);
  -ms-transform: translate(-20em, 0);
  transform: translate(-51em, 0);
  -webkit-transition: 10s;
  -moz-transition: 10s;
  -o-transition: 10s;
  transition: 10s;
  }

    [sv]sxx

    Home

A: Add click event inside document.ready() function.
And remove ',' after #toggle.
$(document).ready(function(){
$("#toggle").click(function(){
   $("#lm").addClass("slide");
});

});

A: This is because you are using jquery click function which is going to be deprecated soon, please use
$("#toggle").on('click', function(){
   $("#lm").addClass("slide");
});


text:
Q: cryptdb mysql proxy not working I installed cryptDB  and it is running from the shell and give outputs.The data is stored as encrypted in the db.But when i use mysql proxy to run it,the data is plane that is no encryption is performed.Please help me how the data is encrypted and stored using mysql proxy.I need to know how the key is entered to encrypt data

A: It might be helpful if you describe in detail what you did and what you saw. Anyway, I have been working with CryptDB to do some tests. I used mysqlproxy, which is the second method to test/run CryptDB stated in the README file. I don't think we can see encrypted data when using the proxy, because when we select from database, the result has already been decrypted. Therefore what we see is plain text.
I guess when you say 'running from shell' you might mean running the cdb_test, the first approached mentioned in README. Yes I think in this way, we can see the encrypted data.
When you create tables and insert data, you might want to go back to where the mysqlproxy is running to check whether it shows you the encrypted data.


text:
Q: How to call variable for calculate? Java Jframe int tmp = Integer.parseInt(jtmp.getText());
int tmp2 = Integer.parseInt(jCalc.getText());
String tmp3 = jSymbol.getText()); //The symbol is *
jCalc.setText("");
jCalcKalkulator.setText(String.valueOf(tmp + tmp3 + tmp2));

I want make tmp * tmp2 but with call variable from a textfield. Thanks.

A: You can't do that this way. But you can do
int operand1 = Integer.parseInt(jtmp.getText());
int operand2 = Integer.parseInt(jCalc.getText());
String operator = jSymbol.getText());

String result = "";
if (operator.equals("*")) {
    result = String.valueOf(operand1 * operand2);
}
// todo other operators

jCalcKalkulator.setText(result);

Note how the code is much more readable when you choose good variables names, rather than tmp1, tmp2 and tmp3. You should also rename jtmp to operand1TextField, jCalc to operand2TextField, and jSymbol to operatorTextField.


text:
Q: ASP.Net MVC 5 -Attempt by security transparent method 'WebMatrix.WebData.SimpleMembershipProvider.ValidateUser to access security method failed I am using Simplemembership in my asp.net web api project. When i try to validate the user using the below code, i get the error(Error 1)
 if (!Membership.ValidateUser(username, password))
       {
         throw new ValidationException("Username or pwassword is incorrect.");
       }

Error 1:

Attempt by security transparent method
  'WebMatrix.WebData.SimpleMembershipProvider.
  ValidateUser(System.String, System.String)' to access security
  critical method
  'System.Web.WebPages.StringExtensions.IsEmpty(System.String)' failed.

Earlier i got a similar error(Error 2) which i resolved by installing these packages:
Install-Package Microsoft.AspNet.WebHelpers

Install-Package Microsoft.AspNet.WebPages.Data

Error 2:

Attempt by security transparent method
  'WebMatrix.WebData.PreApplicationStartCode.OnConnectionOpened(
  System.Object, WebMatrix.Data.ConnectionEventArgs)' to access security
  critical method 'System.Web.WebPages.
  HttpContextExtensions.RegisterForDispose(System.Web.HttpContextBase,
  System.IDisposable)' failed.

I did clean the solution and tried, still getting the same error,
Do i need to install any more packages or does even the simplemembership work in web api?

A: The current fix for me was by upgrading to .Net 4.5.3. I figured this out of frustration. This issue doesnt just affect MVC 5 but core Webmatrix projects as well after upgrading to webpages 3.2.3. I think it is a framework issue that will be fixed with the new Microsoft Identity. The current fix for me is below:
Note: Please use the property pages wizard in visual studio to change your target framework to .Net Framework 4.5.3. It will update your web.config
<compilation debug="true" targetFramework="4.5.3">
  <assemblies>
    <add assembly="System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/>
  </assemblies>
</compilation>

Step 1: Install-Package Microsoft.AspNet.WebHelpers
Step 2: Install-Package Microsoft.AspNet.WebPages.Data
Step 3: [Optional] Install-Package Owin
Step 4: Change targetFramework to .Net 4.5.3 via Property pages dialog box


text:
Q: How to correctly input dask Dataframe as parameter to a function? When i am passing a Dask Dataframe as parameter he is converting to pandas Dataframe.
print(type(sellout_df))
simulate_sku_predictions(sellout_df.loc[(sellout_df['sku'] == sku) & (sellout_df['store_id'] == store)].compute(), store, sku)

Prints => <class 'dask.dataframe.core.DataFrame'>
Entering on defined function
def simulate_sku_predictions(sellout_sku_df, store, sku):
    print(type(sellout_sku_df))

Prints => <class 'pandas.core.frame.DataFrame'>
I can't use compute and dask functions.
I'm new to dask but i don't think  it's appropriate converting in the middle of the code if "i don't have to".

A: dask.DataFrame.compute() returns a Pandas DataFrame. Thus, the code is not passing a Dask DataFrame to simulate_sku_predictions. The argument,
sellout_df.loc[(sellout_df['sku'] == sku) & (sellout_df['store_id'] == store)].compute()

is evaluated to a Pandas DataFrame before it is passed as an argument to simulate_sku_predictions.
If you remove the call to compute(), then sellout_df.loc[...] will be a Dask DataFrame, and you could pass that to simulate_sku_predictions.


text:
Q: I am able to start the app in background in Android 10 but not in Android 12 (android-beacon-library) Expected behavior
The app should be waked up and run in background periodically in Android 12 same as Android 10.
Actual behavior
The app wakes up and run periodically in Android 10 but not in Android 12.
Steps to reproduce this behavior
Step 1: open the app
Step 2: kill the app
Step 3: observer logs in the logcat
Mobile device model and OS version
Both are Samsung phone, one is OS Android 10 , the other one is OS Android 12
Android Beacon Library version
v2.19.4
My code are below:
class HewApplication: Application(), RangeNotifier {
  private var beaconManager: BeaconManager? = null
  private val hewRegion = Region("hewRegion", null, null, null)

override fun onCreate() {
  super.onCreate()
  println("ttt HewApplication onCreate...")
  beaconManager = BeaconManager.getInstanceForApplication(applicationContext)
  beaconManager?.addRangeNotifier(this)
  beaconManager?.startRangingBeacons(hewRegion)
}

override fun didRangeBeaconsInRegion(beacons: MutableCollection?, region: Region?) {
  println("ttt didRangeBeaconsInRegion: beacons: $beacons")
}

}

About the permission for Android 12:
android.permission.ACCESS_FINE_LOCATION: true
android.permission.BLUETOOTH_CONNECT: true
android.permission.ACCESS_BACKGROUND_LOCATION: true
android.permission.BLUETOOTH_SCAN: true


text:
Q: Flutter http package get failed (69) When trying to import http package I can see the red underlining as it is error.
In terminal I tried running "flutter clean" and then adding "http: ^0.12.0" to pubspeck.yaml and running "flutter packages get" but it shows:
"Could not resolve URL "https://pub.dartlang.org".
pub get failed (69)"
Packages like "flutter/material.dart" are correctly imported. Don't know what to do.
Could this be issue with http not being back-compatible with flutter 1.0?

A: So the problem was I was behind proxy and added enviromental variables (https_proxy) as strings in quotation marks, where they should be added without " ". More here (https://www.dartlang.org/tools/pub/troubleshoot).

A: On Linux/macOS:
$ export https_proxy=hostname:port

On Windows Command Prompt:
$ set https_proxy=hostname:port

On Windows PowerShell:
$ $Env:https_proxy="hostname:port"

If the proxy requires credentials, you can set them as follows.
On Linux/macOS:
$ export https_proxy=username:password@hostname:port

On Windows Command Prompt:
$ set https_proxy=username:password@hostname:port

On Windows PowerShell:
$ $Env:https_proxy="username:password@hostname:port"

For more information refer this link

A: This usually happens when you are behind proxy.
To see what proxy it is using use following commands on Mac -> Terminal
echo $ALL_PROXY or echo $https_proxy

Set appropriate proxy using -
export https_proxy="https://<username>:<password>@<proxy>:<port>"

There will be a strange problem here though, if your password contains "@" then you can either try to replace it with special character %40 or worst case change your password to something with _.

A: Connect to V_P_N(Cisco) and check again.


text:
Q: Avoid XML Escape Double Quote I'm currently trying to serialize a class into XML to be posted to php web service.
Whenever I did the normal serialization using XMLSerializer, XML declaration is always appear in the first line of the XML document (similar as to <?xml ....?>). I tested the XML and unable to get it working because the endpoint does not accept XML declaration and I can't do anything about it.
I'm unfamiliar with XML Serialization in C# to be honest.
Therefore, I used XMLWriter to do this as below :-
private string SerializeClassToString(GetRiskReport value)
{
    var emptyNS = new XmlSerializerNamespaces(new[] { XmlQualifiedName.Empty });
    var ser = new XmlSerializer(value.GetType());
    var settings = new XmlWriterSettings();
    settings.OmitXmlDeclaration = true;

    using (var stream = new StringWriter())
    {
        using (var writer = XmlWriter.Create(stream, settings))
        {
            ser.Serialize(writer, value, emptyNS);
            return stream.ToString();
        }
    }
}

Result for the Namespace is
<GetRiskReport FCRA=\"false\" ReturnResultsOnly=\"false\" Monitoring=\"false\">

... and I'm able to omit the XML Declaration, however I'm being introduced with 2 new problem.
I got \r\n for new line and I have escaped double quote such as ReturnResultsOnly=\"false\" Monitoring=\"false\" which is also unable processed by the endpoint.
I would like to ask is that does anyone can give me an idea on how to change the XmlWriterSetting to omit XML Declaration, avoid \r\n and also avoid escaped double quotes \"
Thanks for your advice in advance.
Simon

A: Try with following settings
settings.NewLineHandling = NewLineHandling.None;
settings.CheckCharacters = false;

A: private void SerializeClassToString(GetRiskReport value)
{
    var emptyNS = new XmlSerializerNamespaces(new[]{XmlQualifiedName.Empty});
    var ser = new XmlSerializer(value.GetType());
    var settings = new XmlWriterSettings();
    settings.OmitXmlDeclaration = true;

string path = 'your_file_path_here'
if (File.Exists(path)) File.Delete(path);
FileStream stream = File.Create(path);
using (var writer = XmlWriter.Create(stream, settings))
    {
        ser.Serialize(writer, value, emptyNS);
        return;
    }
}

There was no way to avoid ms bug or thier intensional specification about xmlserializing.It's easier and faster to use filestream object.


text:
Q: Build applications for iPhone using Linux or Windows? I would like to build an application (in Java preferably) running on the iOS of Apple's iPhone.
The thing is, that I don't have an Apple computer. I mainly use Linux, and Windows when I have to.
Is it possible to build applications for iPhone using the Linux platform?
What type of software is best to learn the ropes of? Suggestions?

A: PhoneGap uses html, Titanium uses javascript. Both run on iOS (after jumping through the proper hoops).
I believe you can use the xcodebuild option from commandline to work with native Objective C iOS projects in Linux if I'm not mistaken. If not, you can virtualize a Mac environment to run xcode in full.
Typically, it's best to learn the ropes of the native platform for best results. Most other options will require sacrificing functionality or ease of implementation.
As a last resort, you may be able to install OS X on your PC if you have compatible components. Check out "Hackintosh" for more info on this route.


text:
Q: How can I return a data object when throwing a RestException? function put($id, $name)
{
   try
   {
       product::put($id, $name);
   }
   catch(\util\BadNameException $e)
   {
       throw new RestException(400, "Please supply a better name.");
   }
}

When returning the error message I also want to include the result of (array)product::getNamingConvention() in the error. How can I do that?
I could just return a custom array with the error message and data, but I don't know how to set the status code to 400 in that case?
I'm using Restler 3.

A: Responder class is responsible for giving a structure to error response and success response
You can extend the Responder class as shown below to add data property
use \Luracast\Restler\Responder;
use \Luracast\Restler\Defaults;

class MyResponder extends Responder
{
    public static $data = null;

    public function formatError($statusCode, $message)
    {
        $r = array(
            'error' => array(
                'code' => $statusCode,
                'message' => $message
            )
        );
        if (isset(self::$data)) {
            $r['data'] = self::$data;
        }
        return $r;
    }
}

Defaults::$responderClass = 'MyResponder';

And then set the data from your class as shown below
function put($id, $name)
{
   try
   {
       product::put($id, $name);
   }
   catch(\util\BadNameException $e)
   {
       MyResponder::$data = product::getNamingConvention();
       throw new RestException(400, "Please supply a better name.");
   }
}


text:
Q: DNS management for WHMCS / cPanel? I currently have WHMCS (www.whmcs.com) that I use for the billing system for my hosting company. It integrates with cPanel and WHM. I want to be able to allow clients to:

*

*Change MX Records

*Change DNS info (CNAME, A Record etc)

1 can be done in cPanel. But 2 not. So my questions are:

*

*Is there a program/application available that will give clients access to this? I.e. So they can change their DNS info?

*How do other companies do it?

A: There is already a WHMCS addon to do this.
cPanel DNS manager for WHMCS

A: CPanel offers an API which can be used to provide customers with the DNS Editing abilities, you either need to create your own backend to allow this, or use a client management system which supports it. CPanel also provide a 'CPanel DNS Only' suite to create redundant nameservers, unfortunately at this time it appears WHMCS does not support this.
If this is something you absolutely need, you will need to consider outsourcing the script request or consider changing your CMS to something such as Hostbill (hostbillapp.com).
http://docs.cpanel.net/twiki/bin/view/AllDocumentation/WHMDocs/ConfigureCluster
http://www.cpanel.net/products/cpanelwhm/related-server-software.html


text:
Q: How to show array of images in my blade view? I want to show array of images in my blade view. I have a table which has some fields like name, address, images. where images are more than one how I can show multiple images in my blade-view.

                        {{-- {{dd($business->image)}} --}}
                        {{-- @json($business->image) --}}

for each loop etc doesn't work for me like this,I can even fetch/show single image on my view
@foreach($business['image'] as $image)
  <image src="{{ $business['Name']}}" />
@endforeach

and my controller from where I save data to DB. there is no image model I am storing images directly to a business model
  // Business insertion from user side
    public function store(Request $request)
    {
        if ($request->hasFile('pictures')) {
            foreach ($request->file('pictures') as $picture) {
                $pictures[] = $fileName = time() . $picture->getclientOriginalName();
                Storage::put('public/' . $fileName, file_get_contents($picture));
            }
            Business::create([
                'image' => implode(',', $pictures),
                'name' => $request->name,
                'price' => $request->input('price'),
                'description' => $request->input('description'),
                'user_id' => $request->input('user'),
                'category_id' => $request->input('category'),
                'subCategory_id' => $request->input('subCategory'),
                'province_id' => $request->input('province'),
                'city_id' => $request->input('city'),
            ]);
        }
        return redirect('sell-business-form')->with('success', 'Your business is under review, Please wait for confirmation');

 public function businessDetail($id)
    {
        $business = Business::findOrFail($id);
        return view('front-end.business-detail', compact('business'));
    }

please help me out


text:
Q: Angular compile complete event I've a html template that's been compiled and added to my dom via an append function. However it is not possible to change the style of the template objects because I have to wait till they are completely rendered in the dom. How is this possible?
My method call looks like that at the moment:
angular.element(document.getElementById('htmlContent')).append(app.compile(template)(app.rootScope));


text:
Q: Why does a H.264 encode of a H.265 video increase the file size? So recently I had to use ffmpeg to make a video go from H.265 to H.264 to make it more web compliant.
The file size went from 4.32 MB to 10.32 MB.
In my head we have a video that is done in H.265. H.264 is of course worse and there has already been a run of H.265, so it will barely be able to do something. This is where I imagine it would go from 4.32 MB -> 4.12 MB. However it does not, it rather doubles in size.
Analogy: Let's say you have a professional painter (H.265) that does a painting. Then his older brother (H.264) who is not as good paints over with a little bit of their details. The artwork will now look worse, but at the same time it will cost less.
Have I completely misunderstood how codecs work? Can you "revert" back to a former codec, then resulting in a bigger file size?

A: In general H.265 is more efficient than H.264.
Efficiency means:

*

*With H.265 you will get better quality at the same file size or

*the same quality with a smaller file

This is true if you start with an uncompressed or high quality file and use a high quality H.264 and compare it to high quality H.265 compressor.
If you start with a compressed H.264 file and transcode to H.265 - all bets are off.
If you add a generation (decompress and recompress) quality goes down.
If you have a very good H.264 compressor aka 'x264' and compare it to a bad H.265 compressor - H.264 can outperform H.265.
Keep in mind compressors are not standardized - pretty much the only rule for a compressor - it needs to decompress correctly.
Each vendor (or open source project) adds a secrete (or open) sauce.
You can control the quality with a vast set of parameter - including the bitrate.
So if you specify a higher bitrate (or the default is higher) then your H.265 may get bigger than H.265 - so try to specify a lower bitrate and compare the quality.


text:
Q: Adding two numbers that were declared as char type in java how it is posible? If the single quotes are removed in the declaration it is showing 11
class Sample
{
    public static void main(String ar[])
    {
         char v1='5';
         char v2='6';
         System.out.println(v1 + v2);
    }
}

Output:
        107

A: In Java, a char is a 16-bit, unsigned integral type. When used in arithmetic operations, they are "promoted" to int operands with the same value.
The Unicode character '5' has a value of 53, and '6' has a value of 54. Add them together, and you have 107.

A: You can get the numeric equivalent of a char using Character.getNumericValue(char):
class Sample
{
  public static void main(String ar[])
  {
    char v1='5';
    char v2='6';
    int i1 = Character.getNumericValue(v1);
    int i2 = Character.getNumericValue(v2);
    System.out.println(i1 + i2);
  }
}

The function maps chars like '5' to numbers like 5.
Fun fact: it also works with other numbering systems like '๕', the Thai number 5.


text:
Q: pick up specific rows from duplicates on a dataframe with only selected columns This is a slight variation of the question that was answered previously in SO.
(Unique on a dataframe with only selected columns)
The only difference from that question and mine is that I have to mention which specific rows from the duplicates should be retained. My rows are names I am thinking something such as to give a substring to delete the rows which have that substring but I am unable to put it into codes. For eg: if duplicate rows are exm123 and tre123, I want to retain the ones with tre substring)
If you guys think without any substring there are more easy ways to do the same in R, I am more than happy to learn the alternative. Thanks.
  dat:
  Index Name      id1   id2
  1 exm-9980        1   202183358
  2 exm-53487       1   203186865
  3 exm-tre10248    1   85537661
  4 exm-7747       10   102827758
  5 exm-29639      10   18289634
  6 exm-76467      10   27436462
  7 exm-tre7540    10   18289634
  8 exm-4560589    10   74890584
  9 vg-194357      11   102589148
  10 exm-0867390   11   61110815
  11 exm-IN3127     1   85537661
  12 exm-tre2315   11   18632984
  13 exm-12411      6   30332555
  14 exm-128711    11   18632984

nm1 <- c('id1', 'id2')
indx <- duplicated(dat[,nm1])|duplicated(dat[,nm1],fromLast=TRUE)
df22=dat[!indx|(indx & grepl("^tre", dat$Name)),]
which(indx==T)

indx: 3,5,7,12.14,11,13

when I cross check using values from id1 and id2 from the main data for index 13
      f1=dat[dat$id1==6& dat$id2==30332555,]
f1 is a matrix of 1 row. if it is a duplicate it should be a matrix of rows 2 or more.
I am unable to load the full data as it is more than 100k rows. But I hope this will help in showing the problem in a clear way.

A: Using the example dataset:
 nm1 <- c('id1', 'id2')
 indx <- duplicated(dat[,nm1])|duplicated(dat[,nm1], fromLast=TRUE)

dat[!indx|(indx & grepl("^tre", dat$Name)),]
 #   Index      Name id1    id2
 #1     1 exm-49980   1   2021
 #2     2  exm-3487   1  20318
 #3     3  exm-0248   1   8553
 #4     4 exm-17747  10 102827
 #5     5 exm-29639  10  18289
 #7     7  tre-2987  10  27436
 #8     8  vg-18999  18 279990

data
 dat <- structure(list(Index = 1:8, Name = c("exm-49980", "exm-3487",
 "exm-0248", "exm-17747", "exm-29639", "exm-6467", "tre-2987",
 "vg-18999"), id1 = c(1L, 1L, 1L, 10L, 10L, 10L, 10L, 18L), id2 = c(2021L,
 20318L, 8553L, 102827L, 18289L, 27436L, 27436L, 279990L)), .Names = c("Index",
 "Name", "id1", "id2"), class = "data.frame", row.names = c(NA,
-8L))

Update
 nm1 <- c('id1', 'id2')
 indx <- duplicated(dat[,nm1])|duplicated(dat[,nm1], fromLast=TRUE)

 dat1 <- dat[!indx|(indx&grepl("-tre", dat$Name)),] #check the `grepl`.  The pattern is changed as per the new example.  Here, the `Name` no longer starts with `tre`.
 dat1
 #    Index         Name id1       id2
 #1      1     exm-9980   1 202183358
 #2      2    exm-53487   1 203186865
 #3      3 exm-tre10248   1  85537661
 #4      4     exm-7747  10 102827758
 #6      6    exm-76467  10  27436462
 #7      7  exm-tre7540  10  18289634
 #8      8  exm-4560589  10  74890584
 #9      9    vg-194357  11 102589148
 #10    10  exm-0867390  11  61110815
 #12    12  exm-tre2315  11  18632984
 #13    13    exm-12411   6  30332555

data
 dat <- structure(list(Index = 1:14, Name = c("exm-9980", "exm-53487",
 "exm-tre10248", "exm-7747", "exm-29639", "exm-76467", "exm-tre7540",
 "exm-4560589", "vg-194357", "exm-0867390", "exm-IN3127", "exm-tre2315",
 "exm-12411", "exm-128711"), id1 = c(1L, 1L, 1L, 10L, 10L, 10L,
 10L, 10L, 11L, 11L, 1L, 11L, 6L, 11L), id2 = c(202183358L, 203186865L,
 85537661L, 102827758L, 18289634L, 27436462L, 18289634L, 74890584L,
 102589148L, 61110815L, 85537661L, 18632984L, 30332555L, 18632984L
 )), .Names = c("Index", "Name", "id1", "id2"), class = "data.frame", row.names = c(NA,
 -14L))


text:
Q: how to determine the transparent color index of ICO image with PIL? Specifically, this is from an .ico file, so there is no "transparent" "info" attribute like you would get in a gif.   The below example illustrates converting Yahoo!'s favicon to a png using the correct transparency index of "0", which I guessed.  how to detect that the ico is in fact transparent and that the transparency index is 0 ?
import urllib2
import Image
import StringIO

resp = urllib2.urlopen("http://www.yahoo.com/favicon.ico")
image = Image.open(StringIO.StringIO(resp.read()))

f = file("test.png", "w")

# I guessed that the transparent index is 0.  how to
# determine it correctly ?
image.save(f, "PNG", quality=95, transparency=0)

A: looks like someone recognized that PIL doesn't really read ICO correctly (I can see the same thing after reconciling its source code with some research on the ICO format - there is an AND bitmap which determines transparency)
 and came up with this extension:
http://www.djangosnippets.org/snippets/1287/
since this is useful for non-django applications, I've reposted here with a few tweaks to its exception throws:
import operator
import struct

from PIL import BmpImagePlugin, PngImagePlugin, Image

def load_icon(file, index=None):
    '''
    Load Windows ICO image.

    See http://en.wikipedia.org/w/index.php?oldid=264332061 for file format
    description.
    '''
    if isinstance(file, basestring):
        file = open(file, 'rb')

    try:
        header = struct.unpack('<3H', file.read(6))
    except:
        raise IOError('Not an ICO file')

    # Check magic
    if header[:2] != (0, 1):
        raise IOError('Not an ICO file')

    # Collect icon directories
    directories = []
    for i in xrange(header[2]):
        directory = list(struct.unpack('<4B2H2I', file.read(16)))
        for j in xrange(3):
            if not directory[j]:
                directory[j] = 256

        directories.append(directory)

    if index is None:
        # Select best icon
        directory = max(directories, key=operator.itemgetter(slice(0, 3)))
    else:
        directory = directories[index]

    # Seek to the bitmap data
    file.seek(directory[7])

    prefix = file.read(16)
    file.seek(-16, 1)

    if PngImagePlugin._accept(prefix):
        # Windows Vista icon with PNG inside
        image = PngImagePlugin.PngImageFile(file)
    else:
        # Load XOR bitmap
        image = BmpImagePlugin.DibImageFile(file)
        if image.mode == 'RGBA':
            # Windows XP 32-bit color depth icon without AND bitmap
            pass
        else:
            # Patch up the bitmap height
            image.size = image.size[0], image.size[1] >> 1
            d, e, o, a = image.tile[0]
            image.tile[0] = d, (0, 0) + image.size, o, a

            # Calculate AND bitmap dimensions. See
            # http://en.wikipedia.org/w/index.php?oldid=264236948#Pixel_storage
            # for description
            offset = o + a[1] * image.size[1]
            stride = ((image.size[0] + 31) >> 5) << 2
            size = stride * image.size[1]

            # Load AND bitmap
            file.seek(offset)
            string = file.read(size)
            mask = Image.fromstring('1', image.size, string, 'raw',
                                    ('1;I', stride, -1))

            image = image.convert('RGBA')
            image.putalpha(mask)

    return image


text:
Q: r - Replace NAs with values according to two index vectors I have a spatial points data frame with characteristics of houses sold spanning through several years.
I appended to it neighborhood attributes using "over" in {sp}. For each year of my housing data there is a neighborhood´s data set joined.
The problem: neighborhood data for different years don't always contain the same variables. Therefore, when joined to the housing data, I obtain NAs in these non-shared variables for houses sold in some particular years.
Ideal solution: for each row in my data, replace NAs with same column data (V1) from the same neighborhood (nb) but closest year available (y).
      [,y]  [,nb] [,V1]
 [1,] 1993 30000 2752
 [2,] 1993 30000 2752
 [3,] 1994 30000 NA
 [4,] 1994 50000 2554
 [5,] 1995 30000 NA
 [6,] 1996 30000 2650
 [7,] 1996 50000 NA

Ideally, replace NAs such that [3,V1] = 2752; [5,V1] = 2650, and [7,V1] = 2554. The data frame contains over 250k obs so looping through the whole thing is rather cumbersome.

A: You can use the function below for your purpose.
get_rid_of_NAs <- function(urmatrix) {
  myvector <- vector()
  counter <- 0
  myvector_1 <- vector()

  for(i in 1:nrow(urmatrix)){
   out <- urmatrix[i,2]
   out_1 <- urmatrix[i,1]
   myvector_1 <- c(myvector_1,out_1)
   myvector <- c(myvector,out)

   if(urmatrix[i,3]!=NA){
   next
   }
   orders <- order(myvector[myvector==out],decreasing=TRUE)
   index <- which.min(myvector_1[orders])
   urmatrix[i,3] <- urmatrix[index,3]
   }
 return(urmatrix)
}

Now use the function to compute.
           get_rid_of_NAs(ENTERYOURMATRIXHERE.)

R can easily handle such a loop, but i would suggest the for loop in this case.
Seriously there are many people here saying "there aer 10min data r cant handle etc etc." R is not excel, R is created to handle the data


text:
Q: What should we focus while reading RFC document I'm actually reading RFC documents on SMTP, URL's in the view of contributing to some programming library.
I just feel, things are not to the point and the adjectives are even referenced to their respective pages describing specifically. Being this specific for a policy making probably required but how a developer should get the exact point of what that entire paper is making quickly? Actually once I start reading one RFC, being newbie, within 5mins I see myself lost reading another RFC being referenced.
Any tips from guys who got experience is appreciated!

A: The counter-question to that is what are you trying to get out of reading RFCs?  What level of understanding do you need to obtain?
RFCs are meant to be verbose enough that the reader can implement behaviour that conforms to the spec.  The RFC is the spec.  Reading the spec is always going to be very detailed and low level.
You would be better off searching for guides to the functionality that you need to understand and getting a grasp of the basics before diving into the RFC, in the same way that you might read the documentation for a program to understand what it's meant to do before you start reading the source code to figure out how it does it.


text:
Q: What does the two first coordinates in "rect" argument for matplotlib axes? According to https://matplotlib.org/api/axes_api.html and https://matplotlib.org/api/axes_api.html the input to the axes is rect=[left,bottom,width,hight] but it does not seem like left/bottom does anything.
The following plots below (seems) identical.
plt.axes([0.5,10000,1,1])
plt.plot(range(100),np.sin(range(100)))
plt.show()

plt.axes([0,10000,1,1])
plt.plot(range(100),np.sin(range(100)))
plt.show()

plt.axes([0,0,1,1])
plt.plot(range(100),np.sin(range(100)))
plt.show()

EDIT:
Using VSCode as IDE and matplotlib version 3.1.2


text:
Q: What is the correct way to use wow.js in Rails 6 with webpacker? I am trying to use wow.js with my Ruby on Rails 6.1.3.2 project. I have installed wowjs with Yarn and I see it in my node_modules folder.
I have imported wowjs into my application app/javascript/packs/application.js
import WOW from 'wowjs';
require("wowjs/css/libs/animate.css")

I have a script.js file located at this path: app/javascript/script.js and initiates WOW
    wow = new WOW({
        animateClass: 'animated',
        offset: 100
    });
    wow.init();

script.js is imported into app/javascript/packs/application.rb after wowjs is imported like this:
import WOW from 'wowjs';
require("wowjs/css/libs/animate.css")
import "scripts.js"

I keep getting the following error in the console:
scripts.js:514 Uncaught ReferenceError: WOW is not defined
at Object.<anonymous> (scripts.js:514)
at Object../app/javascript/scripts.js (scripts.js:897)
at __webpack_require__ (bootstrap:63)
at Module../app/javascript/packs/application.js (application.js:1)
at __webpack_require__ (bootstrap:63)
at bootstrap:198
at bootstrap:198

I have other modules that I have installed in a similar manner that are not throwing errors. I'd like to understand what the "rails way" of doing this is. Thanks in advance for your assistance.

A: Install jquery, wowjs by yarn, add this line to app/javascript/packs/application.js:
window.WOW = require('wowjs').WOW;

Embed wow css to project by add to app/assets/stylesheets/application.scss this line:
 @import "wowjs/css/libs/animate";

And finish by create this view example app/views/pages/home.html.erb:
Welcome to project railstrace !

ABC

DEF

Note: If set new WOW({live: false}).init() will remove this warning: MutationObserver is not supported by your browser.
Enjoy!

A: The answer to this question was ultimately the following:
Move the import statements from application.js to scripts.js where the modules were being used:
import "splitting/dist/splitting.css";
import "splitting/dist/splitting-cells.css";
import Splitting from "splitting";

I was missing the declaration of 'wow' as a 'var'. So I added 'var' to the script.js like this:
var wow = new WOW({
    animateClass: 'animated',
    offset: 100
});
wow.init();

The key lesson for me was that the import statements needed to be at the top of the script that was consuming the modules. I had assumed that just by virtue of them being imported into application.js that was enough to make them available to all scripts. Perhaps that was a newbie lesson. Many thanks to @rossta for some important guidance. I'm looking forward to his soon coming The Webpacker Course.


text:
Q: Stacking multiclass classification accuracy is lower than same model for binary classification problem? I have developed a stacked classification model which consists of Random forest, CNN, and logistic regression as a meta-model. Its accuracy is 99% for binary classification problem and its accuracy on multiclass classification is very low.
Epoch 1/50
11527/11527 - 172s - loss: 0.4597 - accuracy: 0.0560
Epoch 2/50
11527/11527 - 153s - loss: 0.2507 - accuracy: 0.0486
Epoch 3/50
11527/11527 - 125s - loss: 0.1830 - accuracy: 0.0442
Epoch 4/50
11527/11527 - 118s - loss: 0.1447 - accuracy: 0.0442
Epoch 5/50
11527/11527 - 96s - loss: 0.1220 - accuracy: 0.0440

I am using Keras APIs kerasClassifer and stackingClassifier and also used softmax activation for output in the CNN model.
What is the problem with model?


text:
Q: How should I compare elements at every position in two lists using numpy? Suppose there are two lists with the same dimension, let's say [0,1,2,2] and [0,1,2,2]. How should I compare two elements at every position and return a matrix which, in this case, is [[1,0,0,0],[0,1,0,0],[0,0,1,1],[0,0,1,1]]?
i.e. f(x,y)=1 if x=y else 0, and x,y are come from the above two lists respectively.
Already tried the for-loop block with python, which is rather slow when dealing with large lists.
Is there any efficient way of handling this problem with numpy instead of using codes below:
for i in list_1:
   for j in list_2:
      1 if i==j else 0

A: You can use np.equal to compare the elements and use np.where to convert it into 1 or 0.:
import numpy as np

a = np.array([0,1,2,2])
b = np.array([0,1,2,2])

z = np.where(np.equal(a, b[:,np.newaxis]), 1, 0)

Output:
array([[1, 0, 0, 0],
       [0, 1, 0, 0],
       [0, 0, 1, 1],
       [0, 0, 1, 1]])

Or as @Onyambu suggested, you can do
z = (a==b[:,None]).astype(int)

A: Try the below code, I hope this would help.
print([1 if i==j else 0 for i,j in zip([0,1,2,2],[0,1,0,2])])

Ouput :
[1, 1, 0, 1]


text:
Q: Swift iOS - How can I analyze a given MP3 file to determine what time the beats are at? I want to make an app that will find what timestamps the beats are at, as well as the "long notes", and generally I want to know everything about the track and store it in an array of "properties" which would look like this, let's say (for the beats):
beatsTimeStamps = [1, 4, 7, 10, 12] (all integers are in seconds). i.e. These would be the times at which a beat occurs in a 15 second track, let's say.
Another example would be a dictionary that stores info about long chords, such as:
longChordsTimeIntervals: [1: 4, 7:10, 15:20], which follows the format [beginningTimeStampOfChord1: endingTimeStampOfChord1, beginningTimeStampOfChord2: endingTimeStampOfChord2, etc....].
It would also be preferable to know what notes the chord consists of, but that's probably way harder.
How can I go about analyzing an audio track to get this sort of information ? None of the 3rd-party iOS Audio frameworks out there seem to do this easily.

A: There are tons of research papers on state-of-the-art in the areas of Audio Tempo Estimation and Audio Beat Tracking on the MIREX music-ir web site.
http://www.music-ir.org/mirex/wiki/MIREX_HOME
http://www.music-ir.org/mirex/wiki/2015:Audio_Tempo_Estimation
http://www.music-ir.org/mirex/wiki/2015:Audio_Beat_Tracking
It's not something to be simply found in the standard iOS Audio Frameworks.  iOS devices likely have more than enough compute power, but creating the algorithm and the code will not be trivial.
There's also stuff on the MIREX site on polyphonic pitch estimation, but that is much harder than beat tracking.


text:
Q: Assuming that the ball bounces indefinitely, find the total distance that the ball travels. A ball has the property that each time it falls a distance onto a hard, level surface it rebounds to a height $rh$ where $0< r <1$. Suppose that the ball is dropped from an initial height of $H$ meters. Assuming that the ball bounces indefinitely, find the total distance that the ball travels.
Write your answer both with sigma notation and as a closed formula
This is the work I've done to reach sigma notation and the closed formula:
$a_{1}=H$
$a_{2}=2Hr$
$a_{3}=2Hr^{2}$
$a_{4}=2Hr^{3}$
$a_{n}=2Hr^{n-1}$
$s_{n}=H+2Hr+2Hr^{2}+...+2Hr^{n-1}$
Is the sigma notation:
$H+\sum_{n=2}^{\infty}2Hr^{n-1}=2Hr+2Hr^{2}+2Hr^{3}+...+2Hr^{n-1}$
geometric series: $\frac{a_{1}}{1-r}$
$a = 2Hr$
$r = r$
$H + 2Hr$
$H + \frac{2Hr}{1-r}$
$\frac{H(1-r)+2Hr)}{1-r}$
$\frac{H-rH+2Hr}{1-r}$
$H\frac{1-r+2r}{1-r}$
Closed form:
$Distance = H(\frac{1+r}{1-r})$
Does this all look correct?

A: It seems your difficulty arises because you are doing the parts of the problem in the wrong order. Sigma notation is supposed to be the easy part of the problem, the part that you can do as soon as you understand how to write the $n$th term of the sum,
before you figure out what the closed form of the sum is.
If you can write
$$ s_{n}=H+2Hr+2Hr^{2}+...+2Hr^{n-1} $$
then you should be able to write a $\sum$ notation relevant to the question.
(The first term doesn't fit the right pattern for the $\sum$ notation,
but based on your later work I think you know this and you know how to deal with it.)
The equation
$$ar^{n-1} \stackrel?= \frac{a}{1-r}$$
is plainly and clearly false; just try a few different choices of numbers,
for example $a = 1,$ $r = \frac12,$ $n = 4$ and see how wrong it is.
Remember that when you write $ar^{n-1}$ you are saying to just take $r$ to the $n-1$ power, multiply by $a,$ and then stop and that's your answer.
If you wrote the left side of the equation with $\frac{a}{1-r}$ correctly, it would already be in $\sum$ notation.
Forget about everything you wrote after $\frac{a}{1-r}$ and just try to write the summations for these two places. You might have to look up the  $\frac{a}{1-r}$ to remind yourself this time.


text:
Q: How to define a template method for a non-template class? My compiler is not happy with the way I implement my template methods. It gives tons of error messages like "undefined type T" for these implementations.
This is my first method, it is implemented outside of the class block:
class VectorConvertor
{
    public:
        // ...
        template <class T>
        static void ReverseVectorElements(std::vector<T> & Vector);
        // ...
};

template <class T>
void VectorConvertor::ReverseVectorElements(std::vector<T> & Vector)
{
    std::vector<T>::size_type size = Vector.size();
    T swap;
    for (std::vector<T>::size_type i=0; i<size/2; i++)
    {
        swap = Vector.at(i);
        Vector.at(i) = Vector.at(size-1-i);
        Vector.at(size-1-i) = swap;
    }
}

Another one is this; this time the method is implemented inside the class:
class ElementaryMath
{
    public:
        // ...
        template <class T> static char sign(T num)
        {
            return (num >= static_cast<T>(0)) ? static_cast<char>(+1) : static_cast<char>(-1);
        }
        // ...
}

Is there anything wrong with my code, or is this just a problem with the compiler itself?
IDE & Compiler: Visual Studio 2010

A: Your code looks OK to me. But there is one thing that got in my mind. Can you please check if the function "sign" is defined before? Simply hover your mouse on it. C runtime library implements some of its functions using the "#define" keyword and because of that you can't define a function with that same name afterwards.

A: You're missing some typenames and semicolons, but otherwise, the code seems OK. IMHO it's time to file a bug if it still doesn't work.
BTW, the swapping code would be better done with std::swap.

A: Your code compiles without error on VS2005 (apart from a missing semicolon at the end of the definition of ElementaryMath) so you may be looking at a compiler bug.
VS2010 SP1 is available in beta here. Might help, but obviously its beta...

A: typename here:
template <class T>
void VectorConvertor::ReverseVectorElements(std::vector<T> & Vector)
{
    typename std::vector<T>::size_type size = Vector.size();
    T swap;
    for (typename std::vector<T>::size_type i=0; i<size/2; i++)
    {
        swap = Vector.at(i);
        Vector.at(i) = Vector.at(size-1-i);
        Vector.at(size-1-i) = swap;
    }
}

A: class VectorConvertor
{
    public:
    // ...
    template <typename T>
    static void ReverseVectorElements(std::vector<T> & Vector);
};

template <typename T>
void VectorConvertor::ReverseVectorElements(std::vector<T> & Vector)
{
    std::vector<T>::size_type size = Vector.size();
    T swap;
    for (std::vector<T>::size_type i=0; i<size/2; i++)
    {
        swap = Vector.at(i);
        Vector.at(i) = Vector.at(size-1-i);
        Vector.at(size-1-i) = swap;
    }
}

int main()
{
    std::vector <int> i(10,0);

    VectorConvertor obj;   // Since your class isn't a template, template parameter
                           // isn't required for a class template instantiation.
                           // However, if your class was a template class, template-
                           // parameter must have been required for a class template
                           // instantiation.

    obj.ReverseVectorElements(i);  // Equal to obj.ReverseVectorElements<int>(i);
                                   // Based on type of i, compiler can instantiate a
                                   // template function by default.
    getchar();
    return 0;
}

Hope this helps !


text:
Q: can I use accessibility service (android) for receiving info from main screen? first of all I want to apologize if I didn't write correctly with the rules in here, I am quiet new.
I need some help.
I am trying to build an app for my project, I am trying to do the basic first.
I need to get some parameters from the user interaction with his phone, I need to make this happen when the user is out of the app (in the main screen).
I was looking for way and found out that accessibility service should work (I hope I am not wrong). I created an app but it doesn't work, nothing happened. I was looking around the internet and couldn't find anything. here is my code:
package com.example.AccessibilityService;

import android.accessibilityservice.AccessibilityService;
import android.accessibilityservice.FingerprintGestureController;

import android.os.Build;

import android.util.Log;
import android.view.accessibility.AccessibilityEvent;
import android.widget.Toast;

import androidx.annotation.RequiresApi;

public class MyAccessibilityService extends AccessibilityService {

    private FingerprintGestureController gestureController;
    private FingerprintGestureController
            .FingerprintGestureCallback fingerprintGestureCallback;
    private boolean mIsGestureDetectionAvailable;
    @RequiresApi(api = Build.VERSION_CODES.O)
    @Override
    public void onAccessibilityEvent(AccessibilityEvent event) {
        if (fingerprintGestureCallback != null
                || !mIsGestureDetectionAvailable) {
            return;
        }

        fingerprintGestureCallback =
                new FingerprintGestureController.FingerprintGestureCallback() {
                    @Override
                    public void onGestureDetected(int gesture) {
                        switch (gesture) {
                            case GESTURE_SWIPE_DOWN:
                                Toast.makeText(MyAccessibilityService.this,"swipe down occurred",Toast.LENGTH_LONG).show();
                                break;
                            case GESTURE_SWIPE_LEFT:
                                Toast.makeText(MyAccessibilityService.this,"swipe left occurred",Toast.LENGTH_LONG).show();
                                break;
                            case GESTURE_SWIPE_RIGHT:
                                Toast.makeText(MyAccessibilityService.this,"swipe right occurred",Toast.LENGTH_LONG).show();
                                break;
                            case GESTURE_SWIPE_UP:
                                Toast.makeText(MyAccessibilityService.this,"swipe up occurred",Toast.LENGTH_LONG).show();
                                break;
                            default:

                                break;
                        }
                    }

                    @Override
                    public void onGestureDetectionAvailabilityChanged(boolean available) {
                        mIsGestureDetectionAvailable = available;
                    }
                };

        if (fingerprintGestureCallback != null) {
            gestureController.registerFingerprintGestureCallback(
                    fingerprintGestureCallback, null);
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    @Override
    public void onCreate() {
        gestureController = getFingerprintGestureController();
        mIsGestureDetectionAvailable =
                gestureController.isGestureDetectionAvailable();
        if(mIsGestureDetectionAvailable == true)
            Toast.makeText(MyAccessibilityService.this,"working",Toast.LENGTH_LONG).show();
        else
         Toast.makeText(MyAccessibilityService.this,"Not working",Toast.LENGTH_LONG).show();
    }

    @Override
    public void onInterrupt() {

    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    @Override
    protected void onServiceConnected() {
       Log.d("MY_APP_TAG", "hi1234124");
    }
}

manifests file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"

    package="com.example.AccessibilityService">
    <uses-permission android:name="android.permission.USE_FINGERPRINT"></uses-permission>
    <application
        android:allowBackup="true"

        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>

    </activity>
        <service
            android:name=".MyAccessibilityService"
            android:enabled="true"
            android:exported="true"
            android:label="My application"
            android:permission="android.permission.BIND_ACCESSIBILITY_SERVICE">
            <intent-filter>
                <action android:name="android.accessibilityservice.AccessibilityService" />
            </intent-filter>

            <meta-data
                android:name="android.accessibility"
                android:resource="@layout/service_config" />
        </service>
    </application>

</manifest>

service XML:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <accessibility-service
        android:accessibilityEventTypes="typeAllMask"
        android:accessibilityFeedbackType="feedbackAllMask"
        android:accessibilityFlags="flagDefault"
        android:canRequestEnhancedWebAccessibility="true"
        android:canRequestTouchExplorationMode="true"
        android:canRetrieveWindowContent="true"
        android:notificationTimeout="100"
        android:packageNames="@null"

        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

what am I doing wrong ?
I really appreciate some help and I am sorry for the long intro, just had to explain what I am trying to do.
Edit:
it doesn't show here in the code but in my code it says that the permission i gave, USE_FINGERPRINT is deprecated.
My event log:
11/14/2020
9:15 PM * daemon not running; starting now at tcp:5037

9:15 PM * daemon started successfully

9:16 PM Gradle sync started

9:16 PM Gradle sync finished in 7 s 808 ms (from cached state)

9:16 PM Android Studio 4.1.1 available
                Update...

9:17 PM Executing tasks: [:app:assembleDebug] in project C:\Users\rami\AndroidStudioProjects\AccessibilityService

9:18 PM Gradle build finished in 1 m 10 s 421 ms

9:19 PM Install successfully finished in 17 s 624 ms.

9:19 PM Emulator: [6172:6468:1114/211932.545:ERROR:block_files.cc(111)] Failing CreateMapBlock

9:19 PM Emulator: [6172:6468:1114/211932.545:ERROR:entry_impl.cc(985)] Failed to save user data

9:19 PM Emulator: [6172:6468:1114/211933.355:ERROR:backend_impl.cc(1065)] Critical error found -8

9:19 PM Emulator: [6172:6468:1114/211933.356:ERROR:entry_impl.cc(1062)] No file for c1030182

9:19 PM Emulator: [6172:6468:1114/211933.386:ERROR:entry_impl.cc(1062)] No file for b102001e

9:19 PM Emulator: [6172:6468:1114/211933.387:ERROR:entry_impl.cc(1062)] No file for b302002c


text:
Q: Not outputting any values My code seems not to be working properly. My goal is for the year and location to match up in the same row, and print out the information associated with that row. My code is posted below as well as the excel sheet for reading the data.

LOAD_GEN_DATAFILE = 'C:\Users\RoszkowskiM\Desktop\Data_2016.csv' # CSV File to Read

with open(LOAD_GEN_DATAFILE) as csvfile:
     reader = csv.DictReader(csvfile)
     mydict={}
     for row in reader:
         Year=row['Year']
         Busnum=row['Busnum']
         Area=row['Area']
         Power=row['Power']
         TLA=row['TLA']
         Location=row['Location']
         Yearlink=row['Yearlink']
         From=row['From']
         To=row['To']
         Max=row['Max']
         Min=row['Min']
year = raw_input("Please Select Year of Study: ")
print("\n")

commands = ["Millwood-Buchanan", "Astoria-East-Corona", "Bronx", "DUNWOODIE-North-Sherman_Creek",
        "Vernon", "Greenwood-StatenIsland","West_49th","East_13th","Staten_Island","East_River",
        "East_View","DUNWOODIE-SOUTH","Corona-Jamaica","Astoria-East-Corona-Jamaica",
        "Astoria-West-Queensbridge-Vernon","Astoria-West-Queensbridge"]
max_columns = 50

for index, commands in enumerate(commands):
    stars_amount = max(max_columns - len(commands), 0)
    row = "# {} {}({})".format(commands, "." * stars_amount, index + 1)
    print(row)

 location=raw_input(" \n The list above show the TLA Pockets as well as the ID numbers assigned to them ()\n\n Please enter the ID #: ")
 print("\n")

if year==Year and location==Location:
   mydict=[Busnum,Area,Power]

print("Here are all the busses at that location for that year and the new LOAD TOTAL: ")
print("\n")

   for Busnum,Area,Power in mydict:
    Power= float(scaled_power)
    Busnum = int(busnum)
    print('Bus #: %d\t' % Busnum ,'Area Station: %s\t'% Area,'New Load Total: %d MW\t' % Power)


text:
Q: moving a commit above a merge In git, i have 2 commit and a branch merge that have been rebased to look like this
7
6_
  5
  4
3_|
2
1

the merge was done with no-ff.
my client doens't want to roll out commits 1 and 2, so im trying to rebase it to look like this
1
2
7
6_
  5
  4
3_|

This is desirable because then i can branch off of commit 7 and that is my production release.
rebase -i XXXX
flattens the whole thing and has a huge number of conflicts.  since im trying to prepare a production rollout, i don't want to have conflicts because the code will have to go back to testing.
when i do this
rebase -i -p XXXXXX
it moves the commits 1 and 2 correctly, but it deletes the merge and the 4 weeks of work associated with it.  how in the world do i do this?

A: Create a patch from the two commits and apply them in reverse mode to head.
Pro:

*

*Simple solution

*pretty safe depending on the size of the changes

Con:

*

*Leaves the commits in the commit history

*Depending on the amount of changes to the code that is in the two commits, (i.e. changes to the code that happens in the rev. 3-7), the reverse apply won't work

Another hack would be to checkout without the last 7 revisions. Then create patches for the revisions 3-7 and apply those. Should give you the same result and a clean commit history.
But in both cases, I'm wary because you got a lot of conflicts during the rebase.


text:
Q: How can i filter Many2one in Odoo v8 i have a Many2one field with 'ir.model' it gives me a list of different model used in my odoo, on changing the value of this field i want to filter my Many2one with 'ir.model.fields' to list the fields of the chosen model
thanks

A: You can simply put domain in field declaration of ir_model_field_id. e.g.
domain = "[('ir_model_id','=',ir_model_id)]"

A: suppose you want all fields name which used in selected model.
then in ir.model.fields object there is one reference of ir.model,
so simple:
take another many2one of ir.model.fields,
and give domain in this field like:
[('model_id.id','=',your_selected_model_field_name.id)]


text:
Q: Convert UNIX timestamp into Data - iOS I have an iOS application which parses a JSON feed for data. In this data are some UNIX timestamps which I am storing in a NSString. What I want to do is to convert these timestamps into dates (month and day). But I am trying to do this without doing any division myself, because from what I have read online, you should always use Apple's API's to do the conversion for an accurate result.
However my code is not working and I get this error:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFNumber length]: unrecognized selector sent to instance

Here is my code:
NSString *time_string = [timestamps objectAtIndex:indexPath.row];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy-MM-dd"];
NSDate *date = [formatter dateFromString:time_string];

cell.dateOfPub.text = [NSString stringWithFormat:@"%@", date];

I don't understand what I am doing wrong. Any help would be greatly appreciated.
Thanks, Dan

A: double unixTimeStamp = [time_string doubleValue];
NSTimeInterval _interval=unixTimeStamp;
NSDate *date = [NSDate dateWithTimeIntervalSince1970:_interval];
NSDateFormatter *_formatter=[[NSDateFormatter alloc]init];
[_formatter setLocale:[NSLocale currentLocale]];
[_formatter setDateFormat:@"dd.MM.yyyy"];
NSString *_date=[_formatter stringFromDate:date];


text:
Q: Bootstrap for AngularJS scripts not working I am using angularFire and ui bootstrap. All of my styling is fine but none of the javascript details are working. I am using a very thick template (tons of plugins and files) so I have tried ordering the position of the script tags in the index.html to no avail. ex: datepicker, range, modal are all not working but I am not getting any errors in the console. This is driving me crazy! here is some code... hopefully it helps.
Index.html bower script calls just before the ending body tag:

angular.module calls:
angular.module('vagaApp', [
'ngAnimate',
'ui.bootstrap',
'angularPayments',
'ngCookies',
'ngResource',
'ngRoute',
'ngSanitize',
'ngTouch',
'firebase',
'firebase.utils',
'simpleLogin',
'mm.foundation',
'angularSpinner'
]);

example of code not working:

Popup

          <input type="text" class="form-control" datepicker-popup="{{format}}" ng-model="dt" is-open="opened" min-date="minDate" max-date="'2015-06-22'" datepicker-options="dateOptions" date-disabled="disabled(date, mode)" ng-required="true" close-text="Close" />

            <button type="button" class="btn btn-default" ng-click="open($event)"></button>

        Format: <select class="form-control" ng-model="format" ng-options="f for f in formats"><option></option></select>

A: "be sure to include only one file in your project."
from: https://github.com/angular-ui/bootstrap/wiki/FAQ
Could this be your problem?
Try removing 'ui-bootstrap.min.js'
More about the difference between *tpls.min.js and *min.js here:
What is the difference between ui-bootstrap-tpls.min.js and ui-bootstrap.min.js?


text:
Q: Remove Duplicate Data from XML while using redefine in BizTalk I have a schema which is formed by redefining 2 schemas

Now I have called this schema to another using redefine to add elements to Extn. But the elements from previous schema is repeating with the added element.

The Elynx Address is the added element. So how to remove the extra data or add element without repeating. The code to redefine used is :
xs:redefine schemaLocation="InheritSchema.Redefine">
    <xs:complexType name="commAddress">
      <xs:complexContent mixed="false">
        <xs:extension base="commAddress">
          <xs:sequence>
            <xs:element name="ElynxAddress" type="ElynxAddress" maxOccurs="1"/>
          </xs:sequence>
        </xs:extension>
      </xs:complexContent>
    </xs:complexType>
  </xs:redefine>

The complex type ElynxAddress is given as :
<xs:complexType name="ElynxAddress">
    <xs:sequence>
      <xs:element name="Street" type="xs:string" />
      <xs:element name="State" type="xs:string" />
      <xs:element name="County" type="xs:string" />
      <xs:element name="Zip" type="xs:int" />
    </xs:sequence>
  </xs:complexType>

A: Thanks for helping. The particular schema when imported in another schema, does not shows the repeated element. So the issue is solved. :D


text:
Q: Squid Proxy - Authentication if someone invokes a block via SquidGuard? I'm configuring a Linux proxy with Squid and SquidGuard to filter Internet traffic.
I know how to authenticate users against Active Directory (using the basic auth helper) in Squid, and then how to filter access for users using SquidGuard.
In my currently running config, the user gets prompted for his username/password every time he closes and opens the browser.
The question: how can I ask for username/password if the user calls up a "bad" url? (URL on Blacklist of SquidGuard)
My goal is to be able to ask for username/password only if someones calls up a URL on the Blacklists.
I know SquidGuard is rather restricted in terms of configuration for authentication. But I couldn't find any config examples or help concerning my  aim. Of course I'm open for workarounds or entirely different configurations, the result should be the similar.

A: Usual proxy authentication cannot be used in this case. The goal of proxy authentication is to authenticate request(response); by the time your SquidGuard (SG) blocked a request/response this has already been delivered from the server to your Squid.
What you seem to be requesting is the "bypass blocked URL" functionality - for example, SquidGuards blocks access to a "bad" URL and the "blocked" page gets presented to the user. He will then be able to click on the blocked page and provide bypass password - next request for the "bad" URL will not be blocked by SG.
If this is so then as far as I know it is not possible to do in SG. Try looking at DansGuardian.