text:
Q: How to edit a datevalue with a textfield Since ExtJs is missing a datetime field, I figured the easiest way to edit a datetime value in a grid was to use a textfield. I didn't find a simple example that validates the field and updates the record transparently for the user.
This is the column in my grid, where I want to add my editor
Ext.define('Fiddle.grid.DateEdit', {
    columns: [{
        text: 'Datetime value',
        dataIndex: 'mydatetime',
        xtype:'datecolumn',
        format: 'Y-m-d H:i:s'
    }]
})

A: This is a minimalistic approach, that handles validation and date to string conversion transparently for the user:
Ext.define('Fiddle.grid.DateEdit', {
    columns: [{
        text: 'Datetime value',
        dataIndex: 'mydatetime',
        xtype:'datecolumn',
        format: 'Y-m-d H:i:s',
        editor: {
            xtype:'textfield',
            errorMessage: 'Invalid date format',
            format: 'Y-m-d H:i:s',
            validator: function(val){return val.match(/\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}/) ? true : this.errorMessage},
            valueToRaw: function(val){return Ext.Date.format(val, this.format)},
            rawToValue: function(val){return Ext.Date.parse(val, this.format)}
        }
    }]
})


text:
Q: Awesome package from Careers 2.0 So, I got home yesterday, and found a mysterious package waiting for me.  I opened it up to be greeted by a very fancy Careers 2.0 box, with the phrase "go forth and be awesome" on it.
Inside this box was an Stackoverflow branded portfolio exclusive Stack Overflow padfolio.  It came with a copy of my Careers 2.0 résumé, a copy of the Joel Test, and a very cool Stackoverflow pen.
I was just wanted to say thanks for this!  It's awesome!  Also, who else got one?
Here are some pictures: plus.google.com/photos/... (excuse the quaility, don't you just love cell phone cameras :-P)

A: Since this post seems to be about thanking SE and generally feeling superior, here ya go:
Physics swag for top users
A tshirt with a mexican hat on it! A retractable sharpie! A Serious Writing™ pen!
Oh, and a sticker so that your forehead can also feel superior!

Seriously though, this stuff is the norm on many online collaboration sites.
I already have a Google Mapmaker and a Wikipedia Ambassador tshirt. Whenever I wear these, people ask me what mapmaker is/how I got the tshirt. And I get to rant about the relevant online community :) Been able to get a few people interested as well!
So, it's good for the site. A careers-branded portfolio is even better, since it specifically targets viable users/customers of careers (these are the guys who see your portfolio, right?). Pretty awesome idea.
And of course, we get bragging rights! Win-win{*}!!
*Except for the unlucky souls who don't get  any swag

A: Thank you Stack Overflow Careers Team, very cool, I am truly grateful!
@Rocket, correction though, you say:

Inside this box was a Stackoverflow branded portfolio.

when the included letter states:

"Since you're going to be going on interviews, we wanted to make sure
  that you're well equipped so we're sending you one of our exclusive
  Stack Overflow padfolios!"

Now, an "exclusive Stack Overflow padfolio" is something to brag about ;-)
Also, I'm embarressed to say I was not aware of The Joel Test: 12 Steps to Better Code and feel I should read some books.
Here are some of the same pics:
https://plus.google.com/photos/102643749903002577693/albums/5742441911288281457
Thanks again, for the gift and encouragement. And thank you for such amazing services!

redpajama_set_name: RedPajamaStackExchange


text:
Q: cocoalibspotify SPPlaylistContainer Vs SPPlaylist - can i load the container only to get the flattenplaylists? I wrote a program that fetch the userplaylist,
the problem is with the loading time which is very high (around 20sec)
is there another approach about loading those playlist(userplaylists) ?
i used SPASYNCLOAD to load the container then another SPASYNCLOAD to load the user flatten playlists.
the second SPASYNCLOAD is taking too much time.
any ideas?

A: Playlists will take a long time to load, especially on the first login when there's no cache. Loading all of the playlists at once actually isn't recommended, because if the user has a lot of playlists you need to be careful about memory usage.
The approach you're doing is the correct way to load all the playlists, though. It taking time is expected.


text:
Q: SharePoint 2013 and Office Web Apps I am trying to get SharePoint 2013 Foundation to work with Office Web Apps, but it does not seem to be working.
I followed this guide to get it setup.  I have it setup behind a reverse proxy (ISS ARR).
When I attempt to create a document in SharePoint, the default dialog comes up:

How do I go about debugging this?  I'm not really sure where to start -
Update
This is the process that I followed:
Topology
The setup involved two servers.
Server I (Office Web Apps)

*

*IP: 192.168.1.13

*Name: OfficeServer

*Local: office.domain.local

*Public: office.domain.com

Server II (SharePoint)

*

*IP: 192.168.1.6

*Name: ShareServer

*Local: portal.domain.local

*Public: portal.domain.com

There is an IIS ARR with a wildcard SSL certificate that sits between both of these servers and the internet.  This is used for SSL offloading.
OWA Setup

*

*Prepare OWA Server:
Add-WindowsFeature Web-Server,Web-Mgmt-Tools,Web-Mgmt-Console,Web-WebServer,Web-Common-Http,Web-Default-Doc,Web-Static-Content,Web-Performance,Web-Stat-Compression,Web-Dyn-Compression,Web-Security,Web-Filtering,Web-Windows-Auth,Web-App-Dev,Web-Net-Ext45,Web-Asp-Net45,Web-ISAPI-Ext,Web-ISAPI-Filter,Web-Includes,InkandHandwritingServices

*Install Office Web Apps

*Deploy Farm:
Import-Module OfficeWebApps
 New-OfficeWebAppsFarm –InternalURL "http://office.domain.local" -ExternalURL "https://office.domain.com" -EditingEnabled:$true -SSLOffloaded
SharePoint Setup

*

*Create Binding
New-SPWOPIBinding -ServerName office.domain.com
 Set-SPWOPIZone –zone "external-https"
 $config = (Get-SPSecurityTokenServiceConfig)
 $config.AllowOAuthOverHttp = $false
 $config.Update()


text:
Q: Magento product list by tags shows titles in wrong language I have a Magento store setup in 2 languages (EN and RU) and I haven't modified any backend code for the page where it displays a list of products by tagId.
For tags in russian, the whole page displays in russian, except the titles of the products in the list, which, for some reason, are still displayed in English. The products in question have translations for both languages.
I've tried setting storeId in core /Mage/Tag/Model/Tag.php and /Mage/Tag/Model/Block/Product/List.php, but with no luck and the default code sets the store Id in /Mage/Tag/Model/Block/Product/Result.php like this:
protected function _getProductCollection()
{
    if(is_null($this->_productCollection)) {
        $tagModel = Mage::getModel('tag/tag');
        $this->_productCollection = $tagModel->getEntityCollection()
            ->addAttributeToSelect(Mage::getSingleton('catalog/config')->getProductAttributes())
            ->addTagFilter($this->getTag()->getId())
            ->addStoreFilter(Mage::app()->getStore()->getId())
            ->addMinimalPrice()
            ->addUrlRewrite()
            ->setActiveFilter();
        Mage::getSingleton('catalog/product_status')->addSaleableFilterToCollection($this->_productCollection);
        Mage::getSingleton('catalog/product_visibility')->addVisibleInSiteFilterToCollection(
            $this->_productCollection
        );
    }

    return $this->_productCollection;
}

I've searched for this issue everywhere, but can't find any similar case anywhere.
Any help would be greatly appreciated

A: I fixed it by debugging my /app/design/frontend/package/theme/template/catalog/product/list.phtml. I realized that if I get product name just after "foreach" collection it was OK but then some lines after it wasn't.
Problem was with a custom function that loaded media_gallery attribute:
$product->load('media_gallery')

I solved changing it into:
$product = Mage::getModel('catalog/product')->load($product->getId());

I hope it helps you or at least you could debug your list.phtml and get where the product loses its attributes.


text:
Q: how to handle ValueError:Julian Day must be positive I read netcdf file i got error 'ValueError: Julian Day must be positive' .please suggest:
dtime,beta_row,ht_data=[],[],[]
f =Dataset(path)
dtime.extend(netCDF4.num2date(f.variables['time'][:],f.variables['time'].units))


text:
Q: How do i get the value for the key of an object in a firestore database iOS Swift let db = Firestore.firestore()
let query = db.collection("users").whereField("email", isEqualTo: email).value(forKey: "email")

This is my code. I want to retrieve from a firestore database an object. Then i want to retrieve the value for a key. The issue is that it crashes with the following code.
Any fix or something like that?

A: Your code is not reading anything from Firestore yet:
let query = db.collection("users").whereField("email", isEqualTo: email).value(forKey: "email")

This merely defines a query that (when executed) will find documents in the users collection. In fact, I think you'll want to leave it at:
let query = db.collection("users").whereField("email", isEqualTo: email)

Now you need to get data once, or listen for realtime updates. The first one is simplest:
query.getDocuments() { (querySnapshot, err) in
    if let err = err {
        print("Error getting documents: \(err)")
    } else {
        for document in querySnapshot!.documents {
            print("\(document.documentID) => \(document.data())")
        }
    }
}

The document.data() in here is a dictionary, so you can get the value of any field from that through the dictionary, or with document.get("field").


text:
Q: How to Connect VM over VPN on Google Cloud Platform I created a VPN Connection with FortiGate and "Established" a connection in Google Cloud, but when I try to ping a VM that's on the Compute Engine the request times out.
The subnet creation mode for the VM is Legacy VPC network and was automatically generated when migration the VM with CloudEndure.
How can I access the VM on the VPN?

A: Sounds like your firewall rules might be the culprit. (Did you also check your routes to ensure there's a route to the other side of the VPN tunnel?)


text:
Q: Android ListView item: stableIds and yet getting incorrect position Unfortunately I really think I have to explain my situation a little bit extensively.
I am writing an android app regarding the ancient Latin language: my goals are showing to users the entire conjugation of latin verbs, and giving them the right verbal analysis when they search for a specific inflected form.
This is my manifest.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.android_application.app_name"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="8" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".ConjActivity"
            android:label="@string/app_name"
            android:parentActivityName=".MainActivity" >
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value="com.android_application.app_name.MainActivity"/>
        </activity>
    </application>

</manifest>

Just know that in order to achieve the first goal I automatically create ALL the forms of every verb as strings, and every conjugation is showed as a simple ListView with only one TextView string as item: one item = one inflected verbal form.
Now, I need to customize my items, modifying some times their textStyle, some times their alignment, etc. In order to do so, I created my custom ListAdapter this way:
private static class ConjAdapter extends ArrayAdapter<String> {

    private ArrayList<Long> ids;
    private HashMap<String, Long> mIdMap;

    public ConjAdapter(Context context, int textViewResourceId, List<String> objects) {
        super(context, textViewResourceId, objects);
        ids = new ArrayList<Long>();
        mIdMap = new HashMap<String, Long>();
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View v = super.getView(position, convertView, parent);
        ViewHolder holder;

        if(convertView==null){
            convertView = LayoutInflater.from(context).inflate(R.layout.simple_list_item_1, parent, false);
            holder = new ViewHolder();
            holder.txt = (TextView) convertView.findViewById(R.id.text1);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        long id = getItemId(position);

        if(sel_vb!=null){
            if(ids.contains(id)){ v.setBackgroundColor(context.getResources().getColor(R.color.row_bckgr_RED));
        } else {
                v.setBackgroundColor(Color.TRANSPARENT);
            }
        }

        for(Map.Entry<String, Long> map : mIdMap.entrySet()){
            if(id==map.getValue()){
                holder.txt.setText(map.getKey());
                break;
            }
        }

        String item = (String) holder.txt.getText();
        if(item.equals(context.getResources().getString(R.string.ind))||
                item.equals(context.getResources().getString(R.string.subj))||
                item.equals(context.getResources().getString(R.string.imp))||
                item.equals(context.getResources().getString(R.string.inf))||
                item.equals(context.getResources().getString(R.string.pt))||
                item.equals(context.getResources().getString(R.string.ger))||
                item.equals(context.getResources().getString(R.string.gerv))||
                item.equals(context.getResources().getString(R.string.sup))){
            holder.txt.setGravity(Gravity.CENTER);
            holder.txt.setTextSize(20f);
            holder.txt.setTypeface(null, Typeface.BOLD);
        } else if(item.equals(context.getResources().getString(R.string.pres))||
                item.equals(context.getResources().getString(R.string.impf))||
                item.equals(context.getResources().getString(R.string.fut))||
                item.equals(context.getResources().getString(R.string.pf))||
                item.equals(context.getResources().getString(R.string.ppf))||
                item.equals(context.getResources().getString(R.string.futant))){
            holder.txt.setTypeface(null, Typeface.ITALIC);
            holder.txt.setTextSize(19f);
        } else {
            holder.txt.setPadding(10, 0, 0, 0);
        }

        return convertView;
    }

    @Override
    public long getItemId(int position) {
        String item = getItem(position);
        return mIdMap.get(item);
    }

    @Override
    public boolean hasStableIds() {
        return true;
    }

    static class ViewHolder {
        TextView txt;
    }

}

The problem is that after the 19th item something goes wrong in the sense that I receive no error messages nor the app crashes, but my custom code doesn't work anymore and items, that should have some features, have on the contrary other ones.
And this situation worsens when I scroll my list up and down.
After what I read, I really think that this problem regards the recycling goal of the convertview variable called by the getView() of my custom adapter.
And here is my question: why does it happen even with stable ids (that I store in mIdMap along with the associated item strings) and how can I detach my item from the incorrect position variable?
Update
Here is the code with which I populate mIdMap and ids:
HashMap<String, Long> tempMap = conjadapt.mIdMap;
for(int i=0, j=0; i<displ_conj.size(); i++, j++){
    tempMap.put(displ_conj.get(i), (long) j);
}
if(sel_vb!=null){
    for(Map.Entry<String, Long> map : tempMap.entrySet()){
        if(map.getKey().equals(sel_vb))
            conjadapt.ids.add(map.getValue());
    }
}

where displ_conj is the ArrayList in which I store my data. mIdMap stores a long variables because the getItemId() has to return a long and with that I need to do some stuff somewhere else.

A: You are right this is a recylcing problem and it has nothing to do with stable Ids. As pointed out by samgak, you should not be invoking the super call:
View v = super.getView(position, convertView, parent);

That will create a whole new View which you are then modifying the background color. However, since that View is never returned, it gets tossed to the wind when the method call completes. So basically, your getView method is doing some extra work that's never used.  You should be solely dealing with convertView. Though, this is not causing the recycling problem you are seeing.
It also looks like you are attempting to show a red background for the sel_vb.  I'm assuming that means selected verb? Know there is a built in mechanism to do this. ListViews support a method called setItemChecked(position, boolean). Basically you can highlight any position using that method call.  Note you'll need to enable a choice mode first. You can change the default blue highlight via styles or by creating your own layout instead of using the Android provided one.
Unfortunately there's not much documentation that really explains how enabling stable Ids affect the ListView. It's only ever used when enabling a choice mode. It helps ensure the correct item is highlighted/checked during things like screen configurations or mutations to the adapter while something is highlighted/checked. Otherwise, stable ids has nothing to do with View generation.
Its hard to say exactly what's causing the funky recycling behavior but it's definitely something related to how you populate the text via the Id mapping.  Specifically this guy:
    for(Map.Entry<String, Long> map : mIdMap.entrySet()){
        if(id==map.getValue()){
            holder.txt.setText(map.getKey());
            break;
        }
    }

My suggestion would be to completely remove all the Id logic from the getView method.  Instead populate the text by doing:
holder.txt.setText(getItem(position));

One more performance consideration.  I suggest looking into implement different view types. For your case, you could have 3 different view types based on this logic:
   String item = (String) holder.txt.getText();

    //First type
    if(item.equals(context.getResources().getString(R.string.ind))||
            item.equals(context.getResources().getString(R.string.subj))||
            item.equals(context.getResources().getString(R.string.imp))||
            item.equals(context.getResources().getString(R.string.inf))||
            item.equals(context.getResources().getString(R.string.pt))||
            item.equals(context.getResources().getString(R.string.ger))||
            item.equals(context.getResources().getString(R.string.gerv))||
            item.equals(context.getResources().getString(R.string.sup))){

    //Second type
    } else if(item.equals(context.getResources().getString(R.string.pres))||
            item.equals(context.getResources().getString(R.string.impf))||
            item.equals(context.getResources().getString(R.string.fut))||
            item.equals(context.getResources().getString(R.string.pf))||
            item.equals(context.getResources().getString(R.string.ppf))||
            item.equals(context.getResources().getString(R.string.futant))){

    } else {
       //Third type
    }

Then you can create three custom layouts to inflate instead of relying on the built in simple_list_item_1 layout. This improves the View recycling and gets rid of the inflate and later modify logic.

A: Solution
Thanks to @JaySoyer and his great tips about performance issues I actually managed to solve my problem, and I thought useful share the code after my corrections.
From what I learned, the problem was that I tried too much to define features programmatically and I left too less to the xml part.
The Solution really had to do with viewTypes. Overriding getViewTypeCount() and getItemViewType() and inflating one layout for every viewType was the key to my problem.
In my case I needed 4 viewTypes (due to the presence of different dividers, different textStyles, etc.), and now my adapter looks like this:
private static class ConjAdapter extends ArrayAdapter<String> {

    private ArrayList<Long> ids;
    private HashMap<String, Long> mIdMap;
    private ViewHolder holder;

    private final int
            IND_MODE_TYPE = 0,
            ELSE_MODE_TYPE = 1,
            TENSE_TYPE = 2,
            FORM_TYPE = 3;

    public ConjAdapter(Context context, int textViewResourceId, List<String> objects) {
        super(context, textViewResourceId, objects);
        ids = new ArrayList<Long>();
        mIdMap = new HashMap<String, Long>();
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        if(convertView==null){
            if(getItemViewType(position)==IND_MODE_TYPE){
                convertView = LayoutInflater.from(context).inflate(R.layout.item_mode_ind, parent, false);
                holder = new ViewHolder();
                holder.txt = (TextView) convertView.findViewById(R.id.text1);
                convertView.setTag(holder);
            }else if(getItemViewType(position)==ELSE_MODE_TYPE){
                convertView = LayoutInflater.from(context).inflate(R.layout.item_mode_else, parent, false);
                holder = new ViewHolder();
                holder.txt = (TextView) convertView.findViewById(R.id.text1);
                holder.divider1 = (View) convertView.findViewById(R.id.conj_divider1);
                convertView.setTag(holder);
            } else if(getItemViewType(position)==TENSE_TYPE){
                convertView = LayoutInflater.from(context).inflate(R.layout.item_tense, parent, false);
                holder = new ViewHolder();
                holder.divider2 = (View) convertView.findViewById(R.id.conj_divider2);
                holder.txt = (TextView) convertView.findViewById(R.id.text1);
                convertView.setTag(holder);
            } else {
                convertView = LayoutInflater.from(context).inflate(R.layout.item_form, parent, false);
                holder = new ViewHolder();
                holder.txt = (TextView) convertView.findViewById(R.id.text1);
                convertView.setTag(holder);
            }
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        long id = getItemId(position);

        if(sel_vb!=null){
            if(ids.contains(id)){
                convertView.setBackgroundColor(context.getResources().getColor(R.color.row_bckgr_RED));
            } else {
                convertView.setBackgroundColor(Color.TRANSPARENT);
            }
        }

        holder.txt.setText(getItem(position));

        return convertView;
    }

    @Override
    public long getItemId(int position) {

        String item = getItem(position);
        return mIdMap.get(item);
    }

    @Override
    public boolean hasStableIds() {
        return true;
    }

    @Override
    public int getItemViewType(int position) {
        String item = getItem(position);

        if(item.equals(context.getResources().getString(R.string.ind))){
            return IND_MODE_TYPE;
        } else if(item.equals(context.getResources().getString(R.string.subj))||
                item.equals(context.getResources().getString(R.string.imp))||
                item.equals(context.getResources().getString(R.string.inf))||
                item.equals(context.getResources().getString(R.string.pt))||
                item.equals(context.getResources().getString(R.string.ger))||
                item.equals(context.getResources().getString(R.string.gerv))||
                item.equals(context.getResources().getString(R.string.sup))){
            return ELSE_MODE_TYPE;
        } else if(item.equals(context.getResources().getString(R.string.pres))||
                item.equals(context.getResources().getString(R.string.impf))||
                item.equals(context.getResources().getString(R.string.fut))||
                item.equals(context.getResources().getString(R.string.pf))||
                item.equals(context.getResources().getString(R.string.ppf))||
                item.equals(context.getResources().getString(R.string.futant))){
            return TENSE_TYPE;
        } else {
            return FORM_TYPE;
        }
    }

    @Override
    public int getViewTypeCount() {
        return 4;
    }

    static class ViewHolder {
        TextView txt;
        View divider1, divider2;
    }

}

As you can see, I only had to create as many layouts as the number of viewTypes (managing correctly all the needed settings via xml) and to inflate the right one after a simple check on the actual viewType, and that's it.
Hope that was useful!


text:
Q: Map field values in Dataset using Spark SQL in JAVA In my dataset before I write to elasticsearch I need to map certain values of a column and replace them such as

*

*"REJECT" to "PENDING",

*"UNKNOWN" to "FAILED" etc..

  Dataset<Row> finalData = data.select(
                data.col("cus_ref").as("key"),
                functions.struct(
                        data.col("username").as("user_id"),
                        data.col("channelId").as("channel"),
                        data.col("country_code").as("country"),
                        data.col("status").as("latest_status"),
                        data.col("acc_number").as("account"),
                        data.col("amt").as("amount"),
                        data.col("currency"),
                        data.col("processing_date"),
                        data.col("sub_date").as("received_time"),
                        data.col("product_code").as("product"),
                        data.col("name")).as("summary"));

For data.col("status") how do I map the values and replace them on the fly?

A: You can use 'when-otherwise' clauses:
val updateDF = finalData.withColumn("latest_status",
     when(col("latest_status") === "REJECT", "PENDING")
    .when(col("latest_status") === "UNKNOWN", "FAILED")
    .otherwise("foobar"))

Hope it helps


text:
Q: ember store.find promise not being fulfilled in time I'm using an ArrayController with an ItemController but I'm having problems with getting my store.find promise fulfilled before the hotelName and hotelAddress properties in my ItemController are used.  Any idea on how I can unsure the store find is fulfilled before returning?   I know the store.find works.  I'm able to see the results but the timing is off.  Thank you.
export default Ember.ArrayController.extend({
    itemController: ...,
});

export default Ember.ObjectController.extend({
    init: function() {
        this._super();
    },
    hotelName: function() {
        var self = this;
        self.store.find('hotel', this.get('hotelId')).then(function(hotel) {
            self.set('hotelName', hotel.get('name'));
        });
    }.property('hotelId'),

    hotelAddress: function() {
        var self = this;
        self.store.find('hotel', this.get('hotelId')).then(function(hotel) {
            self.set('hotelAddress', hotel.get('street'));
        });
    }.property('hotelId')
});


text:
Q: How to insert a div tag in more than one location at the same time? I have a div tag with class name insert. I want to move this tag to several locations onclick. Here is my code:

<!DOCTYPE html>

This is a test page

How are you?

How are you?

How are you?

How are you?

Insert me in each small-container div class!

Basically, when I click on anything within the div class main-container, I want to place the div class insert before each of the small-container classes. At present, the insert class only gets placed before the last instance of the small-container class. It doesn't get placed in the first three instances of the small-container class.


text:
Q: How to add Debian Universe in etc/apt/sources.list? In /etc/apt/sources.list
I added universe to
deb http://http.debian.net/debian wheezy main contrib non-free universe
When I did aptitude update the log complained about:
W: Failed to fetch http://http.debian.net/debian/dists/wheezy/Release:
Unable to find expected entry 'universe/binary-i386/Packages' in Release file (Wrong sources.list entry or malformed file)

Should I care about the error?
Have I added Debian Universe correctly?

A: There's not Universe, universe, nor another permutation in Debian. This is a Ubuntu and derivatives only component. The only components you will find in debian are main, contrib and non-free. Only those.


text:
Q: dplyr : Error in mutate_impl(.data, dots) : argument 'times' incorrect I have a tibble as :
# A tibble: 2 × 2
  read_seq unique_id
     <chr>     <dbl>
1 AATTGGCC         1
2   GGGTTT         2

I want to create a new variable containing a string of the same size as read_seq. I did  that but have an error:
> r %>% mutate(y=paste(rep("H",width(read_seq)),sep=""))
Error in mutate_impl(.data, dots) : argument 'times' incorrect

When I only try to catch read_seq width it works :
> r %>% mutate(y=width(read_seq))
# A tibble: 2 × 3
  read_seq unique_id     y
     <chr>     <dbl> <int>
1 AATTGGCC         1     8
2   GGGTTT         2     6

Here's the dput() of the example for reproducibility :
r <- structure(list(read_seq = c("AATTGGCC", "GGGTTT"), unique_id = c(1,
2)), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA,
-2L), .Names = c("read_seq", "unique_id"))

A: The error comes from rep, the times parameter needs to be either 1 or the same length as x, which is not the case here:
rep("H", c(1,2))
Error in rep("H", c(1, 2)) : invalid 'times' argument

You can use strrep instead, which recycles x and times as necessary:
r %>% mutate(y = strrep("H",nchar(read_seq)))

# A tibble: 2 x 3
#  read_seq unique_id        y
#     <chr>     <dbl>    <chr>
#1 AATTGGCC         1 HHHHHHHH
#2   GGGTTT         2   HHHHHH

Or if you need some random strings of equal sizes, use stringi::stri_rand_strings:
r %>% mutate(y = stri_rand_strings(length(read_seq), nchar(read_seq)))

# A tibble: 2 x 3
#  read_seq unique_id        y
#     <chr>     <dbl>    <chr>
#1 AATTGGCC         1 H0flAbNS
#2   GGGTTT         2   QrQOLj


text:
Q:  not working when initial-scale is changed By default, in the index.html file:
<meta name="viewport" content="width=device-width, initial-scale=1" />

I changed it to:
<meta name="viewport" content="width=device-width, initial-scale=2" />

Nothing happened.
What did I do wrong?

A: meta viewport is only supported by mobile browsers.
To achieve the same effect on a desktop browser, you can use the zoom property.

body{
  zoom: 200%;
}
Hello World!


text:
Q: getting error while running hive jobs with oozie in Status: Failed
Vertex failed, vertexName=Map 1, vertexId=vertex_1470692453676_0866_1_00, diagnostics=[Task failed, taskId=task_1470692453676_0866_1_00_000000, diagnostics=[TaskAttempt 0 failed, info=[Error: Failure while running task:java.lang.IllegalArgumentException: tez.runtime.io.sort.mb 2048 should be larger than 0 and should be less than the available task memory (MB):2048
        at com.google.common.base.Preconditions.checkArgument(Preconditions.java:92)
        at org.apache.tez.runtime.library.common.sort.impl.ExternalSorter.getInitialMemoryRequirement(ExternalSorter.java:327)
        at org.apache.tez.runtime.library.output.OrderedPartitionedKVOutput.initialize(OrderedPartitionedKVOutput.java:93)
        at org.apache.tez.runtime.LogicalIOProcessorRuntimeTask$InitializeOutputCallable._callInternal(LogicalIOProcessorRuntimeTask.java:505)
        at org.apache.tez.runtime.LogicalIOProcessorRuntimeTask$InitializeOutputCallable.callInternal(LogicalIOProcessorRuntimeTask.java:487)
        at org.apache.tez.runtime.LogicalIOProcessorRuntimeTask$InitializeOutputCallable.callInternal(LogicalIOProcessorRuntimeTask.java:472)
        at org.apache.tez.common.CallableWithNdc.call(CallableWithNdc.java:36)
        at java.util.concurrent.FutureTask.run(FutureTask.java:266)
        at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
        at java.util.concurrent.FutureTask.run(FutureTask.java:266)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
        at java.lang.Thread.run(Thread.java:745)
], TaskAttempt 1 failed, info=[Error: Failure while running task:java.lang.IllegalArgumentException: tez.runtime.io.sort.mb 2048 should be larger than 0 and should be less than the available task memory (MB):2048
        at com.google.common.base.Preconditions.checkArgument(Preconditions.java:92)
        at org.apache.tez.runtime.library.common.sort.impl.ExternalSorter.getInitialMemoryRequirement(ExternalSorter.java:327)
        at org.apache.tez.runtime.library.output.OrderedPartitionedKVOutput.initialize(OrderedPartitionedKVOutput.java:93)
        at org.apache.tez.runtime.LogicalIOProcessorRuntimeTask$InitializeOutputCallable._callInternal(LogicalIOProcessorRuntimeTask.java:505)
        at org.apache.tez.runtime.LogicalIOProcessorRuntimeTask$InitializeOutputCallable.callInternal(LogicalIOProcessorRuntimeTask.java:487)
        at org.apache.tez.runtime.LogicalIOProcessorRuntimeTask$InitializeOutputCallable.callInternal(LogicalIOProcessorRuntimeTask.java:472)
        at org.apache.tez.common.CallableWithNdc.call(CallableWithNdc.java:36)
        at java.util.concurrent.FutureTask.run(FutureTask.java:266)
        at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
        at java.util.concurrent.FutureTask.run(FutureTask.java:266)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
        at java.lang.Thread.run(Thread.java:745)
], TaskAttempt 2 failed, info=[Error: Failure while running task:java.lang.IllegalArgumentException: tez.runtime.io.sort.mb 2048 should be larger than 0 and should be less than the available task memory (MB):2048

A: Try resetting the sort buffer size to its default value
 tez.runtime.io.sort.mb=512
in your hive-site.xml and retry


text:
Q: Overriding Magento Controller functions I am overriding the AccountController in a Magento Extension.
In my controller i have the present
require_once 'Mage/Customer/controllers/AccountController.php';

My question is I am overriding the createPostAction() function inside my controller like so;
public function createPostAction() {

//Do stuff

}

so do i have to include the original createPostAction() function code found in the Magento AccountController.php inside my createPostAction() function or can i just add my additional code inside my createPostAction() function and the override will take in both functions the action is fired?

A: copy the complete function createPostAction() code from the core to the controller where you are overriding and make the changes in this function.
overriding means createPostAction will be called from your overriden controller not core if you overridden.
Note:- for more information on how to override createPostAction from accountcontroller.php refer http://magento-online-tutorials.blogspot.in/2015/10/how-to-override-createpost-action-in.html


text:
Q: How to use named parameters in c++ In python we can pass arguments to called function using argument name like in the following code , how can we do the same thing  C++ ,
I needed this because ,if we have too many parameter it easy to mess up the location of the argument passed in called function and calling function
def calendar(year,month,day):
    return "f{day}:{month}:{year}"
print(calendar(day=4,year=2021,month=9) #here arguments are passed in order of day,year and month

Output
 "4:9:2021"
irrespective of passing parameters not in order as passed while defining function by using named arguments
string calendar(int year,int month,int day)
{
    return year,month,day;
}

int main ()
{
cout<<calendar(" ? ");// How can we pass arguments like that of python in c++
}

A: Neither C nor C++ supports named parameters.
The closest you can come to this is to define a struct with all of the parameters:
struct cal_params {
    int year;
    int month;
    int day;
};

Define the function to take an instance of that struct:
char *calendar(struct cal_params params)
{
    ...
}

Then call the function with a compound literal using designated initializers:
char *str = calendar((struct cal_params){ .year=2021, .month=9, .day=4});

A: In C++20, a designated initializer was added, but the initialization must be in order according to the order of declaration.
struct date_t {
  int year, month, day;
};

std::string make_calendar(date_t date) {
  return std::format("{0}:{1}:{2}", date.year, date.month, date.day);
}

Then, you can call it like:
make_calendar({.year = 2001, .month = 9, .day = 4})

A: C++ does not have this feature. As shown in this answer you can emulate it by naming members of a struct. Alternatively you can name the individual types of the arguments:
#include <string>
#include <iostream>

struct Year { int value; };
struct Month { int value; };
struct Day { int value; };

std::string calendar(Year y,Month m,Day d)
{
    return std::to_string(y.value) + "-" + std::to_string(m.value) + "-" + std::to_string(d.value);
}

int main ()
{
    std::cout<<calendar(Year{2001},Month{31},Day{42});
}


text:
Q: Pass listbox items from page1 to page2 using sessioon Can anyone show an example how listbox and session work.
E.g to pass listbox items from page1 to page2.
thx!
            if (!Page.IsPostBack)
            {
                lstFarger.Items.Add(blo);
                lstFarger.Items.Add(gron);
                lstFarger.Items.Add(brun);
                lstFarger.Items.Add(gul);
            }
        }

        protected void btnLaggTill_Click(object sender, EventArgs e)
        {
            if (!lstLagdaFarger.Items.Contains(lstFarger.SelectedItem) && lstLagdaFarger.Items.Count<3)
            {
                lstLagdaFarger.Items.Add(lstFarger.SelectedItem.Text);

            }
            else
            {
                lblFelMeddelande.Visible = true;
            }
            if (lstLagdaFarger.Items.Count == 3)
            {

                Response.Redirect("WebForm2.aspx");
            }

A: Why do you need to pass ListItems, you can save the datasource in session. However, is it really necessary to use the Session, why can't you select the data again? You gain not much but a Session needs server memory and also could contain outdated data.
Having said that, if you really want to use the session to store the listitems...
In your button click handler:
if (lstLagdaFarger.Items.Count == 3)
{
    Session["LagdaFargerItems"] = lstLagdaFarger.Items;
    Response.Redirect("WebForm2.aspx");
}

in page 2:
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack && Session["LagdaFargerItems"] != null)
    {
        ListItemCollection lic = (ListItemCollection)Session["LagdaFargerItems"];
        foreach(ListItem li in lic)
            lstLagdaFarger.Items.Add(li); // your other ListBox on page2
    }
}


text:
Q: Append of lists in Python A strange append of list in python.
Here I defined a class
class test:
    group = []
    def __init__(self,name):
    self.name = str(name)

Then I write those
test0 = test(0)
test1 = test(1)
test_list = [test0, test1]

I want to save test1.name into test0.group
test_list[0].group.append(test_list[1].name)

I print test0.group , it's ['1'] , everything is OK.
But while I want to save test0.name into test1.group
test_list[1].group.append(test_list[0].name)

Then I print test1.group , it's ['1','0']. I don't know why it isn't ['0']?
By the way, here I print test0.group , it's also the ['1','0'].

A: That is because the group variable is a variable shared by all instances of the class test and therefore test0 and test1 share the same group. When you do the first append i.e. '1' it is fine but when you do the second append you are appending to the same list and therefore it becomes ['1', '0']. In fact, if you print test0.group as the last line of your code, you will see that it also is ['1', '0'] because they are the same variable. I am not sure what you are trying to achieve but if you want separate groups then you should make them self.group instead and move them into the __init__ method. If you can rephrase your question, I can maybe help you with what you are actually trying to achieve.

A: I believe the issue is in the class definition:
class test:
    group = []
    def __init__(self,name):
    self.name = str(name)

At this point, the __init__ method does nothing and self.name = str(name) never gets called. You need to indent self.name = str(name) in order for it to be in __init__'s body. Try this:
class test:
    group = []
    def __init__(self,name):
        self.name = str(name)

A: This is basically the same problem discussed in here.
Surprisingly? when you define class, Python interpreter execute class field. And then if you create a new instance of the class, class field is not executed. So class field is executed once only when you define class. Like:
class someClass:
    someVar = 0        #<---This class field is executed once
    def __init__(self):
        pass

OK. Now you defined class. Next you create new instance of the class. Like:
instance1 = someClass()
instance2 = someClass()

This will create new memory and copy data from someClass.
Now instance1 and instance2 do not share memory space. They have own independent memory space. So instance1.someVar and instance2.someVar has different memory space. But 0 in instance1.someVar and 0 in instance2.someVar are completely same object(0 is on same memory space). You can ensure it doing like:
print id(instance1.someVar)==id(instance2.someVar)

So you can find 0 is completely same object.
This is not the only case when someClass.someVar = 0. Same thing will happen when you use [] replacement of 0.

Back to your code. You can simply occur your problem doing like this:
class test:
    group = []
    def __init__(self,name):
        self.name = str(name)

test0 = test(0)
test1 = test(1)

test0.group.append(100)

print test0.group
print test1.group
#[100]
#[100]
#will be printed

This is because test0.group and test1.group point same object. Like:
+-----------+
|test0.group|------+
+-----------+      |
                   v
               +-------+
               |  []   |
               +-------+
                   ^
+-----------+      |
|test1.group|------+
+-----------+

When you executed test0.group.append(100), it becomes like:
+-----------+
|test0.group|------+
+-----------+      |
                   v
               +-------+
               | [100] |
               +-------+
                   ^
+-----------+      |
|test1.group|------+
+-----------+

Also you can set another object. Like:
test1.group = "123"

Then test1.group becomes like:
+-----------+
|test0.group|------+
+-----------+      |
                   v
               +-------+
               | [100] |
               +-------+

+-----------+       +-----+
|test1.group|------>|"123"|
+-----------+       +-----+

Sorry for my bad English. I hope it helps. :)


text:
Q: How to return all string elements from an array? Hey im a beginner javascripter and need to know the proper way of doing this. I need this function to return to me all the strings of the array and nothing more, by only using the method .filter
So it should output ['Mike', '23', 'elephant']
const array = [10, 'Mike', '23', NaN, 'elephant']

function stringsOnly(array) {
    const filteredStrings = array.filter((item) => {
        return item.stringsOnly
    })
    return filteredStrings
}
stringsOnly()

A: You could get the type of the variable and reuurn the filtered array.
By calling the function, you need to hand over the array as well.

function stringsOnly(array) {
    return array.filter(item => typeof item === 'string');
}

const array = [10, 'Mike', '23', NaN, 'elephant'];

console.log(stringsOnly(array));


text:
Q: Maschke's theorem for $G$-graded algebras I am reading the paper Algebras graded by a group of Knus. Immediately I run into problems, which I will now detail:
Let $G$ be a group and $K$ a field. A $G$-graded algebra $A$  is a finite-dimensional $K$-algebra $A$ with unit together with a direct sum decomposition as $A$-module $A=\bigoplus_{g\in G}A_g$ such that $A_gA_h\subset A_{gh}$. A subspace $I$ of $A$ is graded if it is the direct sum of the intersections $I\cap A_g$. An $G$-graded algebra $A$ is called simple if there are no proper graded two-sided ideals.
Then Knus proves the following analogue of Maschke's theorem:

Let $A$ be a simple graded algebra. If the characteristic of $K$ does not divide $\dim_K(A)$, then $A$ is semisimple.

I will now write down the proof as in the paper:

Proof: Let $x=\sum_{g\in G}x_g\in \text{Rad}(A)\setminus \left\{0\right\}$. Since $A$ is simple graded, we may assume that $x_0=1$. Hence $\text{Trace}(x)=\dim_K(A)$ is not zero and $x$ is not nilpotent. Therefore the radical must be zero.

I do not understand this proof. I get that we need to show that $\text{Rad}(A)=\left\{0\right\}$. We know that the radical is nilpotent so if we find a non-zero element in $\text{Rad}(A)$ which is not nilpotent we get a contradiction, that much is clear to me.
I do not understand why we may assume $x_0\neq 0$. I do not understand what $\text{Trace}(x)$ is, is it the trace of the multiplication by $x$? I suspect we use the condition on the characteristic of $K$ in the equality $\text{Trace}(x)=\dim_K(A)$, but I don't understand this equality and I do not see how this implies that $x$ is not nilpotent.
Any help would be much appreciated.

A: First, note that since $x\neq 0$, $x_g\neq 0$ for some $g\in G$. Now, as $x_g$ is a homogeneous element, $Ax_g A$ is a 2-sided graded ideal. Since $A$ is simple, $1\in Ax_gA$. That is, there exists $a,a'\in A$ such that $a x_g a'=1$. Now, $axa'=y\in Rad(A)$ is nonzero and satisfies $y_1=1$. Without loss of generality, we may assume that $x=y$, in which case $x_1=1$.
As you say, we understand the trace of $x$ to be the trace of the operator $y\mapsto xy$. Note that $x=1+\sum_{g\neq 1}x_g$, so
$$Tr(x)=Tr(1)+\sum_{g\neq 1}Tr(x_g).$$
However, for $g\neq 1$, $x_gA_h\subset A_{gh}\neq A_h$, so $Tr(x_g)=0$. It finally remains to note that $Tr(1)=\dim_K(A)$.


text:
Q: What file system does ceph use for its OSDs everyone.
According to Sage A. Weil's paper, Ceph was using EBOFS as the file system for its OSDs. However, I looked into the source code of Ceph and could hardly find any code of EBOFS. Is Ceph still using EBOFS or has opted to use other types of file system for a single OSB?
Thank you:-)

A: The EBOFS was deprecated many years ago.
then the default fs for osd filestore backend is btrfs for years,
bc the btrfs is not stable that time,
ceph community change it to xfs as deafult fs until now.
The filestore layer was aimed to HDD
Now community developed a new objectstore layer named bluestore,
which is designed for high speed storage disk like SSD


text:
Q: Can't run Linux "awk" command in script from PHP I have the shell script "test.sh":
  #!/system/bin/sh

  PID=$(ps | grep logcat | grep root |grep -v grep | awk '{print $2}')
  echo "Using awk: $PID"

  PID=$(ps | grep logcat | grep root |grep -v grep | cut -d " " -f 7 )
  echo "Using cut: $PID"

When I run the script from PHP:
exec("su -c sh /path/to/my/script/test.sh");

I got this output:
Using awk:
Using cut: 6512

So "cut" command is work but "awk" command doesn't when I run the script from PHP, but when I run it from terminal:
# sh test.sh

I can get both awk and cut work fine! This how look like the output of "ps":
USER      PID   PPID  VSIZE  RSS   WCHAN       PC         NAME
root      6512  5115  3044   1108  poll_sched b6e4bb0c S logcat

Do I missed something?

A: You should learn how to debug first
You said

So "cut" command is work but "awk" command doesn't when I run the
  script from PHP, but when I run it from terminal:

I wonder how ?
actually throws error like below, in CLI
$ php -r 'exec("su -c sh /path/to/my/script/test.sh");'
su: user /path/to/my/script/test.sh does not exist

You first need below syntax while debugging code
// basic :  stdin (0) stdout (1) stderr (2)

exec('your_command 2>&1', $output, $return_status);

// to see the response from your command
// su: user /path/to/my/script/test.sh does not exist
print_r($output);

Remember :

*

*su gives you root permissions but it does not change the PATH variable and current working directory.

*The operating system assumes that, in the absence of a username, the
  user wants to change to a root session, and thus the user is prompted
  for the root password

[akshay@localhost Desktop]$ su
Password:
[root@localhost Desktop]# pwd
/home/akshay/Desktop
[root@localhost Desktop]# exit
exit

[akshay@localhost Desktop]$ su -
Password:
[root@localhost ~]# pwd
/root

Solution:
You should allow executing your script without password prompt ( don't use su use sudo )
To allow apache user to execute your script and some commands you may make entry like below in /etc/sudoers
# which awk => give you awk path
# same use in your script also, or else set path variable
www-data ALL=NOPASSWD: /path/to/my/script/test.sh, /bin/cut, /usr/bin/awk

So it becomes :
// assuming your script is executable
exec("sudo /path/to/my/script/test.sh 2>&1", $output);
print_r($output);


text:
Q: How to scrape text from an html page using C#? I have a web page that when navigated to only returns a simple text value, like the number 100. I need to grab that value from the page, so I can use it in my application. The application is a simple Windows Forms app, with a web browser control on it.
I have tried numerous things, but it's not grabbing the text, as if it doesn't exist. Yet if I right click and view source, it's there.
This can't be that difficult...It's just some text.
Just to clarify the document contains NO html, only a number. When using WebClient or WebRequest, it doesn't return the value.
    private void RegisterWindow_Load(object sender, EventArgs e)
    {
        webBrowser1.Navigate("MYURL");
        webBrowser1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(webBrowser1_DocumentCompleted);

    }

    void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
    {
        // Check and see if we have navigated to the final page.
        string registeredUrl = "MYURL";
        string currentPage = webBrowser1.Url.ToString();
        string response = string.Empty;

        if (webBrowser1.Url.ToString() == registeredUrl)
        {
            // Now parse the authkey from the url
            response = GetWebRequest(currentPage);
            MessageBox.Show(response);
        }
    }

    /// <summary>
    /// Send a Web Request and get a Web Response back.
    /// This respons can be a valid URL, simple text response, or
    /// HTML response.
    /// </summary>
    /// <param name="url"></param>
    /// <returns></returns>
    public string GetWebRequest(string url)
    {
        var client = new WebClient();
        var content = client.DownloadString(url);

        return content;
    }

A: You should be able to do something as straightforward as:
var client = new WebClient();
var content = client.DownloadString("<YOUR URL>");
var number = Int32.Parse(content);

MSDN documentation for DownloadString(string).

A: If the document contains only number without any HTML, this should work:
public string GetWebRequest()
{
    return webBrowser1.Document.Body.InnerText;
}

A: I wrote a blog post on Web scraping in .NET several years ago. You could try the techniques there. Hopefully they're not obsolete.
For example:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

request.UserAgent = _UserAgent;
request.CookieContainer = cookies;  // optional

using (WebResponse response = request.GetResponse())
{
  using (Stream responseStream = response.GetResponseStream())
  {
    using (StreamReader reader = new StreamReader(responseStream))
    {
      html = reader.ReadToEnd();
    }
  }
}

Remember that your browser is sending a User-Agent header, may be sending cookies, may be going through a configured proxy server, etc. Particularly for secured or intranet sites, a simple WebClient call may be insufficient. You may need to do some checking with Fiddler as @SLaks suggested.

A: You can load the page HTML/TXT content to a string then use a string function to extract the number.


text:
Q: How to find probability from a sequence of numbers, which is being divided into two equal parts? There is a sequence of numbers $1,2,\ldots,4N$, which is being divided into two equal parts. I need to find probability, that in every part there will be equal count of even and odd numbers.

A: Assume these are labelled parts, left box, right box. The number of ways to choose the occupants of the left box is $\binom{4N}{2N}$. These are all equally likely.
Now we count the favourables, the ways in which the left box has equal numbers of evens and odds. There are $\binom{2N}{N}$ ways to choose the evens, and for each way there are $\binom{2N}{N}$ ways to choose the odds, for a total of $\binom{2N}{N}^2$.
For the probability, divide.


text:
Q: Unit testing on browser (Typescript + Webpack) I want to add unit test to this project. It's a basic webpack + typescript project that will be used by another web application. Unit test should run on browser.
I tried mocha but just import 'mocha' throws compile error.
(I have test file in project_folder/test/test.ts which is the entry for webpack.)
WARNING in ./node_modules/mocha/lib/mocha.js 219:20-37
Critical dependency: the request of a dependency is an expression
 @ ./node_modules/mocha/browser-entry.js
 @ ./test/test.ts

WARNING in ./node_modules/mocha/lib/mocha.js 227:24-70
Critical dependency: the request of a dependency is an expression
 @ ./node_modules/mocha/browser-entry.js
 @ ./test/test.ts

WARNING in ./node_modules/mocha/lib/mocha.js 277:24-35
Critical dependency: the request of a dependency is an expression
 @ ./node_modules/mocha/browser-entry.js
 @ ./test/test.ts

WARNING in ./node_modules/mocha/lib/mocha.js 327:35-48
Critical dependency: the request of a dependency is an expression
 @ ./node_modules/mocha/browser-entry.js
 @ ./test/test.ts

WARNING in ./node_modules/mocha/lib/mocha.js 342:23-44
Critical dependency: the request of a dependency is an expression
 @ ./node_modules/mocha/browser-entry.js
 @ ./test/test.ts

ERROR in ./node_modules/mocha/lib/browser/growl.js
Module not found: Error: Can't resolve '../../package' in 'C:\Users\s1n7ax\Documents\GitHub\open-unicode-converter\node_modules\mocha\lib\browser'
 @ ./node_modules/mocha/lib/browser/growl.js 127:13-37
 @ ./node_modules/mocha/lib/mocha.js
 @ ./node_modules/mocha/browser-entry.js
 @ ./test/test.ts

ERROR in ./node_modules/mkdirp/index.js
Module not found: Error: Can't resolve 'fs' in 'C:\Users\s1n7ax\Documents\GitHub\open-unicode-converter\node_modules\mkdirp'
 @ ./node_modules/mkdirp/index.js 2:9-22
 @ ./node_modules/mocha/lib/reporters/xunit.js
 @ ./node_modules/mocha/lib/reporters/index.js
 @ ./node_modules/mocha/lib/mocha.js
 @ ./node_modules/mocha/browser-entry.js
 @ ./test/test.ts
npm ERR! code ELIFECYCLE
npm ERR! errno 2
npm ERR! open-unicode-converter@1.0.0 build: `webpack`
npm ERR! Exit status 2
npm ERR!
npm ERR! Failed at the open-unicode-converter@1.0.0 build script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\s1n7ax\AppData\Roaming\npm-cache\_logs\2019-03-02T20_59_10_221Z-debug.log

If test is written without import statement, there are no compile errors, but at runtime it throws an error because method describe is not defined.
It's important the test to be a typescript file, because typescript classes has to be imported. Is there a library that can be used with typescript + webpack and runs on browser?
test/test.ts
import 'mocha'
describe('sample', () => {
    it('should return something', () => {
    })
});

webpack.config.js
const path = require('path');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const webpack = require('webpack');

let distPath = path.resolve(__dirname, 'dist');
let srcPath = path.resolve(__dirname, 'src');
let testPath = path.resolve(__dirname, 'test');

module.exports = {
    mode: 'development',
    devtool: 'inline-source-map',
    entry: "./test/index.test.ts",
    module: {
        rules: [
            {
                test: /\.tsx?$/,
                use: 'ts-loader',
                exclude: /node_modules/
            }
        ]
    },
    plugins: [
        // this copy index.html from test/index.html to dist
        new CopyWebpackPlugin([
            {from: path.resolve(__dirname, 'test'), to: distPath, ignore: ['*.ts', '*.tsx', '*.js']}
        ]),
    ],
    resolve: {
        extensions: ['.tsx', '.ts', '.js']
    },
    output: {
        filename: '[name].js',
        path: distPath
    },
    devServer: {
        contentBase: path.join(__dirname, 'dist'),
        compress: true,
        port: 9000
    }
};

package.json
"scripts": {
    "build": "webpack",
    "watch": "webpack --watch",
    "test:browser": "npm run build && start http://localhost:9000 && webpack-dev-server"
}

A: Found it.
To the top of webpack.config.js, add
const nodeExternals = require('webpack-node-externals');

and add to the config:
externals: [nodeExternals()]

As a side note, in package.json I have a.o.
"mocha": "6.2.1",
"webpack": "4.41.0",
"webpack-node-externals": "1.7.2",


text:
Q: How to exclude folders and directory path from find command I've got the following command
find /tmp/sjohal/archivetest > list

However I need the output to show the filenames in the folder without the directory path.
What is the best way to do this?
My current output looks as follows:
/tmp/sjohal/archivetest
/tmp/sjohal/archivetest/test2
/tmp/sjohal/archivetest/test1
/tmp/sjohal/archivetest/test3
/tmp/sjohal/archivetest/list.txt

I only require the output to show the files:
test2
test1
test3

A: For all the files in the directory (without subdirectories)
find /tmp/sjohal/archivetest -maxdepth 1 ! -name 'list.txt' -type f -printf "%f\n"

A: Try using ls command:
ls /tmp/sjohal/archivetest > list.txt


text:
Q: Snowflake load data from S3(COPY) vs load from EXTERNAL table What is difference in performance for below two cases, which one is cost optimised in case of execution as well as storage.

*

*Create external table with files in S3, and load("INSERT INTO.... SELECT..." ) to Snowflake target from external table.

*Load data to temporary table from S3 and then load("INSERT INTO.... SELECT..." ) to Snowflake target from temporary table.

A: OK - if you want to use the power of the Snowflake platform as much as possible (pushdown optimisation) then you need to get your data into Snowflake as efficiently as possible first and then run your SQL queries against it ((join, filter, aggregator, etc). Use COPY to move your S3/Azure/Google files into Snowflake tables and then run INSERT... SELECT against these.
There is no reason to create EXTERNAL tables and, if you do, it will perform much worse than the approach I have proposed.
External Tables - short explanation
For the sake of simplicity, let's assume that your Snowflake instance is running on AWS and you also have some files in an S3 bucket.
All your Snowflake data is being stored in S3 by Snowflake but in a heavily compressed and optimised format. Snowflake holds metadata about where and what your data is that allows it to present your data as tables/columns.
An External table is basically exactly the same thing: Snowflake holds metadata about the files in your S3 bucket that allows it to present the data as tables/columns. The differences are that:

*

*The external data is not being compressed/optimised and therefore it takes up more storage and is slower to query

*Effectively, the query engine for your external table is the S3 environment (unless/until Snowflake has read the data into memory/cache where it can then process it as though it was Snowflake data)

*There is probably some element of network latency - depending on where your Snowflake account and S3 buckets are located in the global AWS infrastructure

Hope this helps?

A: This is an old question but I wanted to add a different point of view where external tables make some sense. If it didn't make sense for some users, Snowflake wouldn't have spent precious resources creating it in the first place, right?
I'm currently working on ingesting a constant stream of data similar to IoT devices but more focused in purpose. Blob storage is the main point of storage for this data and it will constantly grow. However, not all data is useful. We have a separate data ingestion pipeline that tells us what devices and what duration has useful data.
At this point, there are two solutions we could use (eliminating just copying everything as the useless data is truly useless and quite large). We could create dynamic COPY INTO scripts that only copy in the useful data in batch. There's some complexity here due to the variable nature of "useful data". We'd still need to join this data but it's in Snowflake now.
What we did instead was set up the blob storage as external tables and directly join it to the tables that defines useful data, and save that into an incremental table(dbt). The blob storage is partitioned for this query. The only downside here is that you need to refresh the external table's metadata to include new files(don't want to auto-refresh as the data is streaming and will require a warehouse be up constantly), and there's some performance hit from hitting the external table although it doesn't really matter since it's done in batch anyways.
I would like to look longer term at cost comparison but for now it's not worth looking into because it costs so little.


text:
Q: JMeter scheduler doesn't stop after duration elapsed I want to set Duration for test working. In my Thread Group I set

*

*Number of Threads = 1

*Ramp-up period = 0

*checked 'Forever'

*checked 'Scheduler'

*Duration = 10

*Startup delay = 0

So if test needs more than 10 seconds to be finished, elapsed time is quit right - 10 second. BUT if it needs, for example, 5 seconds, it stops after 5 seconds, not after 10 as I expect.
How to make script to work until Duration time elapsed?
UPD.
Screenshot of Thread Group settings
Logs for last running:
2017/04/11 19:53:33 INFO  - jmeter.engine.StandardJMeterEngine: Running the test!
2017/04/11 19:53:33 INFO  - jmeter.samplers.SampleEvent: List of sample_variables: []
2017/04/11 19:53:33 INFO  - jmeter.gui.util.JMeterMenuBar: setRunning(true,*local*)
2017/04/11 19:53:33 INFO  - jmeter.engine.StandardJMeterEngine: Starting ThreadGroup: 1 : Thread Group
2017/04/11 19:53:33 INFO  - jmeter.engine.StandardJMeterEngine: Starting 1 threads for group Thread Group.
2017/04/11 19:53:33 INFO  - jmeter.engine.StandardJMeterEngine: Thread will continue on error
2017/04/11 19:53:33 INFO  - jmeter.threads.ThreadGroup: Starting thread group number 1 threads 1 ramp-up 0 perThread 0.0 delayedStart=false
2017/04/11 19:53:33 INFO  - jmeter.threads.ThreadGroup: Started thread group number 1
2017/04/11 19:53:33 INFO  - jmeter.engine.StandardJMeterEngine: All thread groups have been started
2017/04/11 19:53:33 INFO  - jmeter.threads.JMeterThread: Thread started: Thread Group 1-1
2017/04/11 19:53:33 INFO  - jmeter.services.FileServer: Stored: data.txt
2017/04/11 19:53:40 INFO  - jmeter.threads.JMeterThread: Stop Thread seen for thread Thread Group 1-1, reason:org.apache.jorphan.util.JMeterStopThreadException: End of file:data.txt detected for CSV DataSet:CSV get parameter for request configured with stopThread:true, recycle:false
2017/04/11 19:53:40 INFO  - jmeter.threads.JMeterThread: Thread finished: Thread Group 1-1
2017/04/11 19:53:40 INFO  - jmeter.engine.StandardJMeterEngine: Notifying test listeners of end of test
2017/04/11 19:53:40 INFO  - jmeter.services.FileServer: Close: data.txt
2017/04/11 19:53:40 INFO  - jmeter.gui.util.JMeterMenuBar: setRunning(false,*local*)

A: Given you set Loop Count as "Forever" your test should run for 10 seconds (or even more if JMeter will need to gracefully shutdown a lot of samplers) so my expectation is that either error occurs or you are using some form of test end logic like If Controller of Test Action sampler which trigger premature stop.
When JMeter behaves in a unexpected manner remember always to check jmeter.log file - normally it contains enough troubleshooting information. If you are not able to figure out the reason yourself - post the log file here.
As an alternative you could try Ultimate Thread Group which provides more advanced way of defining the load pattern and it comes with the anticipated load chart.
The Ultimate Thread Group (as well as any other plugin) can be installed using JMeter Plugins Manager


text:
Q: What is the equivalent function in AmiBroker AFL for "ta.change" in TradingView Pine-Script? I need to know the function from AmiBroker AFL which serves the same purpose as "ta.change" from TradingView Pine Script. "ta.change" Compares the current source value to its value length bars ago and returns the difference between the values when they are numerical. When a 'bool' source is used, returns true when the current source is different from the previous source.
Regards.

A: In AFL you can use Ref function to calculate change:
length = 5;
change = source - Ref( source, -length );


text:
Q: Powershell script on VM cannot create files or folders I am currently using a VM to run powershell scripts that  run Xunit.runner.console and send the output to a .html file . I have run into an issue that on the VM when i run the scripts it will cannot create the file or folder. when i do this on my local machine there is no issue the file is created with the xunit output. I have tried to see if its a permissions issue but cannot find any that would stop me from creating the file. I have use the -Force but this does not allow Xunit to write to the file.
Any help is much appreciated
This is the Powershell script that runs:
#$FolderCreate =New-Item -ItemType Directory -Force -Path C:\Users\Administrator\Desktop\resultsfolder
#$FileCreate=New-Item "C:\Users\Administrator\Desktop\New folder\Results $(get-date -f dd-MM-yyyy).html" -ItemType file
$Location=Set-Location -Path "C:\Tests\Powershell Test Scripts"

$Runner= .\XunitRunnerLocation.ps1  "C:\Tests\TrueFalse Test\bin\Debug\TrueFalse Tests.dll" -html "C:\Users\Administrator\Desktop\New folder\Results $(get-date -f dd-MM-yyyy).html"

The Below Error i think is related to my test to AssertFalse Which will cause the test to fail
xunit.console.exe :     TrueFalse_Tests.True_False_Tests.Assert_Fail [FAIL]
At C:\Tests\Powershell Test Scripts\XunitRunnerLocation.ps1:5 char:1
+ & $runner $testAssembly
+ ~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (    TrueFalse_T...ert_Fail [FAIL]:String) [], RemoteException
    + FullyQualifiedErrorId : NativeCommandError


text:
Q: Load a Javascript in another Javascript in Play-scala Framework How can we load another javascript in js file in Playframe work
This is my conf file
# Routes
# This file defines all application routes (Higher priority routes first)
# ~~~~

# Home page
GET     /                           controllers.Application.index
POST    /upload                     controllers.Application.uploadFile

# Map static resources from the /public folder to the /assets URL path
GET     /assets/*file               controllers.Assets.versioned(path="/public", file: Asset)

I tried a to load js file:
(function(window){

  var RECORDER_WORKER_PATH  = '/javascripts/recordWorker.js")';
  var ENCODER_WORKER_PATH   = '/javascripts/mp3Worker.js")';

but i ended up with this in the webconsole:
Error:ScriptFile not found at 'javascripts/recordWorker.js
Error:ScriptFile not found at 'javascripts/mp3Worker.js

A: Static assets are served under /assets/* per your definition in the routes file.
You should therefore prepend /assets/ to your URIs.
(function(window){

    var RECORDER_WORKER_PATH  = '/assets/javascripts/recordWorker.js")';
    var ENCODER_WORKER_PATH   = '/assets/javascripts/mp3Worker.js")';

See Play Asset controller docs for more details.


text:
Q: Highlight all occurrences of a selected object with ReSharper I was used to use RockScroll (or MetalScroll), but when I started to use ReSharper my RockScroll start to show some bugs. Well, this is scope to another discussion https://stackoverflow.com/questions/1089493/is-rockscroll-compatible-with-resharper.
But my problem is related, because now without MetalScroll I can't highlight all occurrences, what I consider very useful in many situations.
Someone have another plugin for VS2010 or for ReSharper that do the same or better?

A: I think you are looking for "Highlight usages in file" This can be access via Shift+Alt+F11 or Ctrl+Shift+F7 depending if you are using VS key bindings or InteliJ bindings. Use either Ctrl+Alt+Up/Down or Ctrl+Alt+PageUp/PageDown to go to next and previous highlights.
You can also use the Ctrl+Alt+G combo to bring up a menu of what to jump to. This can be used to move the cursor to the next occurrence.

A: You should try Productivity Power Tools for Visual Studio 2010. There are other versions, at least one for Visual Studio 2013 and another one for Visual Studio 2015.
It plays nicely with ReSharper and has this selected text matches highlighting both in the editor and the scrollbars among many other features.

A: Try the visual studio extension RockMargin which highlight the occurrences on double click (like most IDEs). Works fine with VS 2015 and ReSharper.


text:
Q: Visual Studio Profiler vs. Release Mode - what is the difference? I am using WinForms, Visual Studio 2013, .Net 4.5
When running my application through the Visual Studio Profiler, it works exactly the way it should and when running it through either Debug or Release mode, I face horrible freezing and repainting issues.
What is the difference between running your application in the Visual Studio Profiler vs. running in through the Release Mode?
Thank you in advance

A: Finally found the answer here:
Why does my program run way faster when I enable profiling?

When you run your application within Visual Studio, the debugger is attached to it. When you run it using the profiler, the debugger is not attached.
If you press F5 to run your program, even with the Release build, the debugger is still attached.

Since I was running my application through Visual Studio, I was seeing some really strange behavior such as slow repainting, freezing, etc. - I spent days chasing the usual suspects, double buffering, not invoking calls from background threads, missing locks, etc. and it turns out I was chasing a bug that wasn't there on a first place. Hope this saves someone hours or headache.


text:
Q: What does this expression, 1>0, evalute to (on 64 bit) in C? To test "What does this expression, 1>0, evalutes to (on 64 bit) in C?" question, I wrote this program.
int main()
{
    printf("char=%d", 1>0 );
    return 0;
}

*

*It prints "1". Is it right way to find the expression, 1>0?

*And does operating system bit (64bit) matter? Why did the problem state (on 64 bit)???

A: In C, a > b is an expression of int type that is either equal to 0 or 1. That is not a function of the operating system: of course though the exact nature of an int is dependent on your platform.
So 1 > 0 is an int with value 1.
So your code is equivalent to printf("char=%d", 1);

A: According to C11 Standard, Section 6.5.8: Relational operators -

6. Each of the operators < (less than), > (greater than), <= (less than or equal to), and >= (greater than or equal to) shall yield 1 if the specified relation is true and 0 if it is false, The result has type int.

The Footnote (which is very important to understand) says,

The expression a<b<c is not interpreted as in ordinary mathematics. As the syntax indicates, it means (a<b)<c; in other words, 'if a is less than b, compare 1 to c; otherwise, compare 0 to c'.

So,
printf("char=%d", 1>0 );

is evaluated as
printf("char=%d", 1 );

The same way if,
int num = 0xAA;
int mun = 0x55;

printf("char=%d", 0xAA>0x55 );

The result will be
1

Update: The whole confusion about 32-bit vs 64-bit system is irrelevant for this particular issue you are facing. You don't need to consider that as of now.

A: In C, true is represented by 1(one) or any nonzero value and false is represented by 0(zero). As 1>0 is true you get a 1 which represents true. All relational operators work the same way. It works the same on 16 bit,32 bit and 64 bit machine.


text:
Q: Matlab loop through images in a folder an transform each picture with Imreadto an array I want to loop through a list of images in Matlab by unsing a loop. I want to get one Image at a time and turn it into a Matrix by using the imread function. Then I want to save each Matrix in a variable that is alphabetical and declared automatically in a separate loop.
myFolder = '/user/Matlab/projectfile/pictures';
filePattern = fullfile(myFolder, '*.bmp');
theFiles = dir(filePattern);
for k = 1 : length(theFiles)
    baseFileName = theFiles(k).name;
    fullFileName = fullfile(theFiles(k).folder, baseFileName);
    imageArray = imread(fullFileName)

My problem is that I don't get the return. If I save my imageArray it only creates a Matrix of one image. But I need the program to save each Matrix within a unique Variable such as A,B,C,D... and so on. It should not matter how many pictures there are.
If anyone has a tipp for me I would be glad, thx :)

A: I think you can use structure and dynamic call.
Here an example :
A=struct();
for k = 1 : 5
    fieldName=char(strcat('Field_',string(k)));
    A.(fieldName)=k; % Be sure to use parenthesis
end

The A variable is then :
A =

  struct with fields:

    Field_1: 1
    Field_2: 2
    Field_3: 3
    Field_4: 4
    Field_5: 5

So with that, you can store variables as wish.
Hope it helps, tell me if I misunderstood.


text:
Q: SED: Replacing String After Single Quote I have a file named file.txt that contains the following:
CREATE LARGE TABLESPACE LONGSPCE1 IN DATABASE PARTITION GROUP IBMDEFAULTGROUP PAGESIZE 4096 MANAGED BY DATABASE
     USING (FILE '/db2data1/TGT_INST/TGT_DB/LONGSPCE1.c1' 1588368,
            FILE '/db2data2/TGT_INST/TGT_DB/LONGSPCE1.c2' 1588368,
            FILE '/db2data3/TGT_INST/TGT_DB/LONGSPCE1.c3' 1588368,
            FILE '/db2data4/TGT_INST/TGT_DB/LONGSPCE1.c4' 1588368)

I am trying to change the numerics after  the c[0-9]' to a value of 100.
I have tried the following with no luck.
cat file.txt |sed 's/(c1'' )\([0-9]*\)/$1 100/g'

A: You can use:
sed "s/\(c[0-9]\+'\) [0-9]\+/\1 100/" file.txt

USING (FILE '/db2data1/TGT_INST/TGT_DB/LONGSPCE1.c1' 100,
       FILE '/db2data2/TGT_INST/TGT_DB/LONGSPCE1.c2' 100,
       FILE '/db2data3/TGT_INST/TGT_DB/LONGSPCE1.c3' 100,
       FILE '/db2data4/TGT_INST/TGT_DB/LONGSPCE1.c4' 100)


text:
Q: while/foreach/for get 3 results at a time? I am trying to get 3 results out of a mysql database at a time (so it would display 3 at a time)
So it would be something like
$sql = mysql_query("SELECT * FROM table");
while ($row = mysql_fetch_array($sql)) {
    print $row['username'];
    print $row['username2'];
    print $row['username3'];
}

but $row['username']; and $row['username2']; $row['username3']; would just be the first second and third results out of the mysql table.
and then it would repeat and $row['username']; and $row['username2']; and $row['username3']; would be the 4th, 5th and 6th and so on.
Any idea of how I could do this?

A: To show just the three results, you can do like this:
$sql = mysql_query("SELECT * FROM table");

$count = 0;
while ($row = mysql_fetch_array($sql)) {
    $count++;
    if ($count === 3) break;
    print $row['username'];
}

Or if you want, you can specify the LIMIT clause in your query to fetch just three records:
$sql = mysql_query("SELECT * FROM table LIMIT 3");

while ($row = mysql_fetch_array($sql)) {
    print $row['username'];
}

With LIMIT clause, you can also specify the start index and number of rows to be returned like this:
$sql = mysql_query("SELECT * FROM table LIMIT 4, 3");

The above query will return 3 rows starting from 4th row.

A: You can use limit clauses,
select * from table limit 1, 3

then for the next 3,
select * from table limit 4, 3

(you might want to look up the syntax, I may have the order backwards)

A: $sql = mysql_query("SELECT * FROM table");

$count = 0;
while ($row = mysql_fetch_array($sql)) {
    $count++;
    if ($count % 3 == 0) print "
" /* or any other way you want to break up the data */
    print $row['username'];
}

A: I think your logic is flawed, Steven.
Why do you need to access three records during one single iteration of a loop?  This sounds like an illogical problem.  My bet is that you're looking at a problem the wrong way.  Can you provide a context for this problem?

A: While it does sound like your approach is somewhat illogical, I suppose you could store the results in an array, putting in three usernames at a time, and then outputting the data from the array instead. Like so:
$q = mysql_query("SELECT * FROM table");
$usernames = array();
while($d = mysql_fetch_assoc($q)) {
   $usernames[] = $d['username'];
   if(count($usernames) = 3) {
      sprintf('user 1: %s, user 2: %s, user 3: %s
', $usernames[0], $usernames[1], $usernames[3]);
      $usernames = array();
   }
}

The above is assuming that I understood your question correctly. I still don't quite know why you want to use this approach, though - you might be better off rethinking the logic behind this.

A: You could do this:
function mysql_fetch_n_rows($rs, $n)
{
  $rows = array();
  while ($n-- && ($row = mysql_fetch_array($rs)))
  {
    $rows[] = $row;
  }

  return $rows;
}

$rs = mysql_query("SELECT * FROM table");

while ($rows = mysql_fetch_n_rows($rs, 3))
{
    print $rows[0]['username'];
    print $rows[1]['username'];
    print $rows[2]['username'];
}

(Disclaimer: obviously you'd need to verify that you actually got 3 rows back. You might only get one or two.)
But I doubt you really need the above code. Generally it's much easier to do a ($i % 3) as some of the other answers suggest. I definitely do not post this answer because I think it's the best general solution, but only as an example of creating a general purpose function instead of trying to hard code this type of solution within the while loop.

A: my 5 cents for use with templates
I am fond on using templates
<?
$data = dbgetall("SELECT username FROM table");
$data = array_chunk($data,3);
?>

<? foreach ($data as $chunk): ?>

<? foreach ($chunk as $row): ?>
  <?=$row['username']?>
<? endforeach ?>

<? endforeach ?>


text:
Q: Bash: Flip strings to the other side of the delimiter Basically, I have a file formatted like
ABC:123

And I would like to flip the strings around the delimiter, so it would look like this
123:ABC

I would prefer to do this with bash/linux tools.
Thanks for any help!

A: That's reasonably easy with internal bash commands, assuming two fields, as per the following transcript:
pax:~$ x='abc:123'
pax:~$ echo "${x#*:}:${x%:*}"
123:abc

The first substitution ${x#*:} removes everything from the start up to the colon. The second, ${x%:*}, removes everything from the colon to the end.
Then you just re-join them with the colon in-between.
It doesn't matter for your particular data but % and # use the shortest possible pattern. The %% and ## variants will give you the longest possible pattern (greedy).

As an aside, this is ideal if you doing it for one string at a time since you don't need to kick up an external process to do the work for you. But, if you're processing an entire file, there are better ways to do it, such as with awk:
pax:~$ printf "abc:123\ndef:456\nghi:789\n" | awk -F: '{print $2 FS $1}'
123:abc
456:def
789:ghi

A: #!/bin/sh -x

var1=$(echo -e 'ABC:123' | cut -d':' -f1)
var2=$(echo -e 'ABC:123' | cut -d':' -f2)
echo -e "${var2}":"${var1}"

I use cut to split the string into two parts, and store both of those parts as variables.
From there, it's possible to use echo to re-arrange the variables as you see fit.

A: Using sed.
sed -E 's/(.*):(.*)/\2:\1/' file.txt

Using paste and cut with process substitution.
paste -d: <(cut -d : -f2 file.txt) <(cut -d : -f1 file.txt)

A slower/slowest shell solution on large set of data/files.
while IFS=: read -r left rigth; do printf '%s:%s\n' "$rigth" "$left"; done < file.txt


text:
Q: with javascript onclick add classname to a div I want to achieve with javascript something like when i clink on any of thumbnail (btn-1, btn-2 and btn-3) the specific class should be add to box div dynamically.
my code: JSFiddle

document.getElementById('btn-1').onclick = function() {
  document.getElementById('box').className = 'bg-1';
}
#box {
  background-color: darkgray;
  width: 200px;
  height: 200px;
}

.thumbnail {
  width: 30px;
  height: 30px;
  border: 1px solid;
  margin: 5px;
  position: relative;
  float: left;
}

#btn-1 {
  background-color: red;
}

#btn-2 {
  background-color: green;
}

#btn-3 {
  background-color: blue;
}

.bg-1 {
  background-color: red;
}

.bg-2 {
  background-color: blue;
}

.bg-3 {
   background-color: blue;
}

A: You javascript is working, but your CSS isn't.
You need to add !important as follows to .bg-1, .bg-2 and .bg-3
.bg-1 {
  background-color: red !important;
}

Otherwise the id styling is taking preference over the class styling
You can see the classname is being added if you right click on the grey div and choose inspect element in Chrome.

A: You want to use jquery .addClass() function:
$('.myButton').addClass('myNewClass');

The function would probably look something like this:
$(function () {
     $('.thumbnail').click(function() {
         $('#box').addClass($(this).attr('id'));
     });
})

A: You can get all the thumbnails as an array, and then iterate through the array and dynamically add an event listener to each, which will add the desired className to box when clicked:
var thumbnails = document.getElementsByClassName('thumbnail');

Array.from(thumbnails).forEach(function(thumbnail) {
    var id = thumbnail.id;
    thumbnail.addEventListener('click', function() {
        document.getElementById('box').className = id.replace('btn', 'bg')
    });
});

A: Instead of bothering with classes, use simply a data- attribute like: data-bg="#f00"

$('[data-bg]').css('background', function () {
  $(this).on('click', () => $('#box').css('background', this.dataset.bg));
  return this.dataset.bg;
});
#box {
  background: darkgray;
  width: 120px; height: 120px;
}

[data-bg] {
  width: 30px; height: 30px;
  margin: 5px;
  float: left;
}


text:
Q: make: *** [modules] Error 2 when trying to install rtl8723de driver I was trying to install a wifi driver in my Ubuntu 18.04.
kernel 14.5 and hp laptop.
I ran these commands:
sudo apt-get install build-essential dkms
wget -d -c -O 'rtl8723de.zip' https://github.com/smlinux/rtl8723de/archive/4.11-up.zip
unzip rtl8723de.zip
cd rtl8723de
make

After make I get this output in terminal:
make ARCH=x86_64 CROSS_COMPILE= -C /lib/modules/4.15.0-22-generic/build M=/home/praveen/rtl8723de  modules
make[1]: Entering directory '/usr/src/linux-headers-4.15.0-22-generic'
Makefile:976: "Cannot use CONFIG_STACK_VALIDATION=y, please install libelf-dev, libelf-devel or elfutils-libelf-devel"
  CC [M]  /home/praveen/rtl8723de/core/rtw_cmd.o
In file included from /home/praveen/rtl8723de/include/osdep_service.h:42:0,
                 from /home/praveen/rtl8723de/include/drv_types.h:32,
                 from /home/praveen/rtl8723de/core/rtw_cmd.c:22:
/home/praveen/rtl8723de/include/osdep_service_linux.h: In function '_init_timer':
/home/praveen/rtl8723de/include/osdep_service_linux.h:287:8: error: '_timer {aka struct timer_list}' has no member named 'data'
  ptimer->data = (unsigned long)cntx;
        ^~
/home/praveen/rtl8723de/include/osdep_service_linux.h:288:2: error: implicit declaration of function 'init_timer'; did you mean '_init_timer'? [-Werror=implicit-function-declaration]
  init_timer(ptimer);
  ^~~~~~~~~~
  _init_timer
cc1: some warnings being treated as errors
scripts/Makefile.build:332: recipe for target '/home/praveen/rtl8723de/core/rtw_cmd.o' failed
make[2]: *** [/home/praveen/rtl8723de/core/rtw_cmd.o] Error 1
Makefile:1552: recipe for target '_module_/home/praveen/rtl8723de' failed
make[1]: *** [_module_/home/praveen/rtl8723de] Error 2
make[1]: Leaving directory '/usr/src/linux-headers-4.15.0-22-generic'
Makefile:1884: recipe for target 'modules' failed
make: *** [modules] Error 2

How do I solve this problem?

A: First, remove the inoperable files:
sudo rm -r rtl8723de*

Next, install another prerequisite:
sudo apt update && sudo apt -y install git

Now clone a better file:
git clone https://github.com/lwfinger/rtlwifi_new.git

Now build the driver:
cd rtlwifi_new
make
sudo make install
sudo modprobe rtl8723de

Your wireless should now be working.
EDIT: When Update Manager installs a newer kernel version, also known as linux-image, after the requested reboot, recompile:
cd ~/rtlwifi_new
make clean
git pull
make
sudo make install
sudo modprobe rtl8723de

A: Visibly, the code you download can't compile because the data structure timer_list on your computer doesn't match what is use in the source. The driver you download didn't seem to fit with your kernel (also the kernel version give us is not correct. uname -r give you to correct kernel version).
I don't have the solution for you, but did you see this page?


text:
Q: nextjs + auth / this site can't provide a secure connection I have problem with secure connection in my project.
Bellow my setup and code:

What is wrong?
p.s
My code base on this tutorial:
https://thetechhulk.com/auth0-and-next-js-authentication-complete-guide

A: I had a similar issue and the problem was my NEXTAUTH_URL was pointing to https://localhost:3000 instead of http://localhost:3000

A: error image - chrome
url error: "localhost:3000/api/auth/callbackerror=MUST+match+the+registered+callback+URL+for+this+application"
Check your Github OAuth Authorization Callback URL
Github Authorization Callback URL
Check Your ".env.local" NEXTAUTH_URL
this solved the problem for me.


text:
Q: Replacing pyqt5 widgets issue I have widget with some labels placed grid-like.
Code:
    def init_drawers(self):
        self.drawers_widget = QWidget(self)

        width, height = self.get_drawers_size() # ex.: 12, 8
        self.drawers_widget.setGeometry(100, 0, width * 32, height * 32)

        for h in range(height):
            for w in range(width):
                drawer_uid = f"{h}_{w}"

                label = QLabel(self.drawers_widget)
                label.setGeometry(w * 32, h * 32, 32, 32)
                label.mousePressEvent = self.get_generic_clicker(drawer_uid)
                self.bindings[drawer_uid] = (h, w) # {}

                self.drawers[drawer_uid] = label # {}

        self.render_all()

render_all just iterates over self.drawers and sets 32x32 pixmaps for them, so in result I get big image with clickable fields that change their pixmap on click.
At first everything works fine, but then I need to change layout to, for example, 9*9.
I tried to delete labels:
if self.drawers:
    for k in self.drawers:
         self.drawers[k].close() # or .deleteLater()
    self.drawers.clear()
    self.bindings.clear()

And call init_drawers again (drawers_widget init was out of that function). Main widget resized, but no labels seen - and also they're not responding to clicks.
While using .destroy() instead - click events print new ids, but pixmaps do not update. Also tried to delete drawers_widget too and create it again - same result.
UPD: I get no errors in console.

A: Well, I still don't get why newly created labels with QWidget parent are not displayed, but for my case I've made workaround using @musicamante suggestion
    def init_drawers(self):
        self.draw_widget = QWidget(self)
        self.draw_grid = QGridLayout(self.draw_widget)
        self.draw_grid.setSpacing(0)
        self.draw_grid.setContentsMargins(0, 0, 0, 0)

        self.setup_drawers()

    def setup_drawers(self):
        # cleanup
        if self.draw_grid.count():
            for i in reversed(range(self.draw_grid.count())):
                self.draw_grid.itemAt(i).widget().setParent(None)

        width, height = self.get_drawers_size()
        self.draw_widget.setGeometry(100, 0, width * 32, height * 32)

        for h in range(height):
            for w in range(width):

                label = QLabel()
                label.setFixedSize(32, 32)
                self.draw_grid.addWidget(label, h, w)

        self.render_all()

Calling setup_drawers later does just what I need.
Cleanup method is from this answer and I'm not sure that this is safe, but if I change it to .deleteLater() then after second reload app crashes with
Process finished with exit code -1073740791 (0xC0000409)
(no traceback or something)


text:
Q: datepicker and maskmoney not work on dynamic table (added by) jquery I'm trying to make a dynamic table, where user may add or remove row using jquery.
In my table, there is a field for an input with datepicker and another with maskmoney.
i'm using
https://cdnjs.com/libraries/bootstrap-material-datetimepicker
For datetimepicker
and https://plugins.jquery.com/maskMoney/ For maskmoney.
My function for datetimepicker is :
$('.datepicker').bootstrapMaterialDatePicker({
    format: 'DD-MM-YYYY',
    clearButton: true,
    weekStart: 1,
    time: false
});

For default row :

        #
        Name
        Date
        Price
        QTY (pcs)

            1

                <input type="text" class="form-control" placeholder="..." name="name-1" id="name-1" />

                <input type="text" class="datepicker form-control" placeholder="..." name="date-1" id="date-1">

                <input type="text" class="form-control" placeholder="..." name="price-1" id="price-1" />

                <input type="text" class="form-control" placeholder="..." name="qty-1" id="qty-1" />

                    add

                <button class="btn bg-blue btn-xs btn-block wave-effects">
                    save SAVE
                </button>

everything work fine on the first load, but, when other row(s) generated with jquery, datepicker and maskmoney not work.
Here's my function to add new row :

anyone know why ? is there any solution for this ?
Thanks in advance.
==========================================================================
I solved this case with simple way.
Just add function to call back moneymask and datetimepicker after data append in table.
here's the code :


text:
Q: XCOPY: Is it possible that the source folder contains the destination folder? I want to copy a folder with xcopy. However, as soon as I place the destination folder in the source folder, nothing is being copied anymore. Is there a workaround for this problem?
The idea is to generate a backup of an entire folder strucutre (source) into one subfolder. When executing xcopy I exclude the subfolder for the backup (destination), where my backups should be stored.
I have already tested my code and it works just fine as long as the destination folder does no lie within the source folder.
The code is written with VBA.
Function CopyFolder(ByVal sourcePath As String, ByVal destinationPath As String, ByVal excludeFile As String)
    Dim wsh As Object
    Set wsh = VBA.CreateObject("WScript.Shell")
    Dim waitOnReturn As Boolean: waitOnReturn = True
    Dim windowStyle As Integer: windowStyle = 1

    ' /e -> copys all subfolders including empty ones; /k -> retains the read-only attribute if existend
    wsh.Run "xcopy " & sourcePath & " " & destinationPath & " /e /k /exclude:" & excludeFile, vbNormalFocus, waitOnReturn
End Function

The code is being executed with no error, but when I check the destination folder, no files haven been copied.

A: this should not be possible since it should end with the error: "unable to execute a cyclic copy" or stuff like that.
if you want you can do something like this (one-liner):
FOR /F "usebackq delims=;" %A IN (`dir %sourcePath% /B /AD ^|FINDSTR /V "%destinationPath%"`) DO @xcopy "%sourcePath%\%A\*.*" "%destinationPath%\" /EK

if the SOURCE is filled with directories that you should copy in the DEST. subdirectory with all their files.
Pay Attention to:
 ... %A IN (**`** .... **`**)   <---- theese are reverse quotes (alt+96)

... /AD **^**|FINDSTR /V        <---- this CAP has to be written explicitly like this (but without asterisks, obvious)

 %sourcePath% and %destinationPath%     <---  This is the batch variable notation. Do your String concatenation magic here, since you're launching from inside a vba

Hope this helps you! :-)
Bye


text:
Q: Filter module CakePHP Probably this is not the smartest question. But I'm quite new to CakePHP and the MVC model. Now, creating a simple website with connection to a database is quite easy. But I need to expand the website with a Filter module, like on http://www.femme.nl/badmode, left sidebar. But how to do that? I can't create a Model for that, cause CakePHP complains "Filter" is not a table in the database. So is it better to create a plugin, or behavior.... I don't get it anymore. I got a script already, but don't know a good way to implement it.
I need the model in multiple views, and thus Controllers, so that's the reason I got stuck.

A: If you want to search all tables in the database, according to your second comment you've made to your questions, then you want a search index. A search index can be build by yourself using your database (guess mysql) and using fulltext search.
A better solution would be to use dedicated search index database solution like Elastic Search or Sphinx for that purpose.
But Mark is still right: You want to use the PRG pattern, which the search plugin implements, to transform the POST of the form in your sidebar into conditions that can be used for the search query.


text:
Q: In bootstrap, how to make one div takes full width when possible In bootstrap, we can place two divs next to each other using the following technique

first div

second div

But, if I hide the first div by javascript or display:none, I would like the second div to take all the 24 spaces.
Is there a way to easily achieve that without changing its class to col-md-24 in javscript when hiding the first div?
Thank you

A: Unfortunately, not.  But as you mentioned already, it's as simple as:
$('.col-md-12').eq(0).addClass('hidden');
$('.col-md-12').eq(1).removeClass('col-md-12').addClass('col-md-24');

Obviously this is just in reference to your example above, as you'd be better of using a real CSS class and not eq's.

A: In bootstrap 3, the full width of any container is 12 and there is no ".col-md-24" class.
If you have two div

first div

second div

You can hide first div and modify the second div's class to col-md-12.


text:
Q: Emacs function collapsing Is there some way to collapse Lisp functions in Emacs? I found these answers:
emacs collapsing functions in class using outline-minor-mode
Is it possible to collapse a function in emacs?
But they use add-hook, which gives me an "undefined function" error. What am I missing?

A: You can try origami-mode.
You can find detailed information about it in the Github page, but in short, just install it and call origami-recursively-toggle-node to fold and unfold a function.
There's no need for adding hooks or what not. You probably have something wrong with your config, possibly a require missing somewhere.

A: I use hs-minor-mode, as recommended in a comment by Rorschach in the question. The hs-minor-mode came with my emacs install and it works well.
To determine the useful commands, I typed Ctrl-h v hs-minor-mode-map and examined the keyboard map when hs-minor-mode is active (I added the comments so that the actual key sequences are easily read):
 (3 keymap ; Ctrl-C
    (64 keymap ; @ (at-sign)
        (5 . hs-toggle-hiding) ; Ctrl-E
        (4 . hs-hide-block) ; Ctrl-D
        (20 . hs-hide-all) ; SPACE
        (1 . hs-show-all) ; Ctrl-A
        (3 . hs-toggle-hiding) ; Ctrl-C
        (12 . hs-hide-level) ; Ctrl-L
        (27 keymap ; ESC
            (19 . hs-show-all) ; Ctrl-S
            (8 . hs-hide-all)) ; Ctrl-H
        (19 . hs-show-block) ; Ctrl-S
        (8 . hs-hide-block)))) ; Ctrl-H

The recommended keystrokes are difficult to type. I decided to assign Alt-H to the following elisp (it's not exactly what I want yet, but I do like to assign one keystroke to do multiple things):
(lambda () (interactive)
    (hs-minor-mode 1)
    (if (hs-find-block-beginning)
            (hs-toggle-hiding)
        (let ((from (point-min))
                (to (point-max)))
            (while (and
                (not (hs-overlay-at from))
                (setq from (next-overlay-change from))
                (not (= to from)))) ; locate first hs-overlay
            (if (= to from) ; hs-overlay-was-not-found
                (hs-hide-all)
                (hs-show-all))))))


text:
Q: ClickOnce Publish Signtool Error First I'd like to say:

*

*My certificate is not expired (it expires in 12/31/2039)

*My certificate has not changed

*I don't want to use a new certificate because it will require me to reinstall my application on all client machines.

Suddenly when I try to publish my WCF/WPF solution I get:

Error 2   An error occurred while signing: Failed to sign bin\Debug\app.publish\setup.exe. SignTool Error: The signer's certificate is not valid for signing.
  SignTool Error: An error occurred while attempting to sign: bin\Debug\app.publish\setup.exe

Has anyone else experience this with a certificate that by all means should be valid? Any suggestions on what might be the problem?

A: As indicated, in the case of Windows 7 KB2661254 (code key length < 1024) is the culprit but if you are running Windows 8 you cannot uninstall the KB and you need to discover the keys with length < 1024 and fix them.
See the KB article
http://support.microsoft.com/kb/2661254
UPDATE: It turns out that it was the root certificate for the self signed cert that was 512 bits, not the actual certificate itself. I regenerated on Windows 8 and all was fine with the new cert.

A: AS Kevin suggested, I uninstalled all the Windows updates I got on the day the problem started (10/12/2012) and I was able to publish just fine. Thanks Kevin. I regret not getting a list of the KB's I removed prior to removing them though. :(