text:
Q: Time taken to reflect the custom dimension changes in GA4 I am trying to use Google-analytics-API.
In it, I require to fetch the user id of the respective users.
For that I have created the custom dimension (userId) -> customUser:userId
But the response doesn't contain any value it is empty for it though if I try with any other standard dimension I am getting the values for it.
Is there any time period after which the changes will be reflected for custom dimensions?
Requests
{
  :property=>"properties/property_id",
  :dimensions=>[{:name=>"customUser:userId", :dimension_expression=>nil}],
  :metrics=>[{:name=>"activeUsers", :expression=>"", :invisible=>false}],
  :date_ranges=>[{:start_date=>"yesterday", :end_date=>"today", :name=>"date"}],
  :dimension_filter=>nil,
  :metric_filter=>nil,
  :currency_code=>"",
  :cohort_spec=>nil,
  :keep_empty_rows=>false,
  :return_property_quota=>false
}

A: Yes, it takes 48 hours to GA4 to be updated with the new custom information and You will see a value of (not set) for a custom dimension in the first 48 hours.
Please have a look at the documentation Create custom dimensions


text:
Q: How to detect C-style multidimensional arrays in templates specialization? I have the following code:
enum type_kind{unkown=-1,carray, multi_carray};

template<class T>
struct detect_carray{
   constexpr static int kind=unkown;
};
template<class T, std::size_t N>
struct detect_carray<T[N]>{
   constexpr static int kind=carray;
};

Now, I want to add another specialization for detecting multidimensional arrays in C-style, that is, T[a][b]....
What is the syntax to achieve this? Can I use Variadic templates?
I expect the following behavior:
int main()
{
std::cout<<detect_carray<std::vector<int>>::kind;//-1
std::cout<<detect_carray<int[3]>::kind;//0
std::cout<<detect_carray<double[3][5]>::kind;//1
std::cout<<detect_carray<std::complex<double>[3][5][8][16]>::kind;//1
//Correct out: -1011
}

A: There's already a trait called std::rank in the standard library so the solution is quite simple:
template <class T>
struct detect_carray {
  enum type_kind { unknown = -1, carray, multi_carray };

  static constexpr int kind = [] {
    switch (std::rank_v<T>) {
      case 0: return unknown;
      case 1: return carray;
      default: return multi_carray;
    }
  }();
};

A: Just add a specialization for multidimensional arrays:
template<class T, std::size_t N1, std::size_t N2>
struct detect_carray<T[N1][N2]>{
   constexpr static int kind=multi_carray;
};

then
std::cout<<detect_carray<std::vector<int>>::kind;//-1
std::cout<<detect_carray<int[3]>::kind;//0
std::cout<<detect_carray<double[3][5]>::kind;//1
std::cout<<detect_carray<std::complex<double>[3][5][8][16]>::kind;//1

LIVE
BTW: For double[3][5], T will be double (and N1 will be 3 and N2 will be 5). For std::complex<double>[3][5][8][16], T will be std::complex<double> [8][16] (and N1 will be 3 and N2 will be 5).

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I delete files on Ubuntu? Can anyone give me a simple answer as to how I can delete files on Ubuntu? I have tried seeing if there was a delete option when selecting a file, but it doesn't show.

A: Open Nautilus, the default file manager for Ubuntu (I assume that you are using that since you are fairly new to AskUbuntu)
By default "Move To Trash" option provided in nautilus (by right clicking on file) as follows:

Go to the menus at the top and click Edit->Preferences
In the window that appears, choose the Behavior tab, then click the button to include a Delete Command as shown in the image below.
Following that you should be able to delete a file directly from the  File Manager:

Now you can see "Delete" option (after right-clicking) as follows:

However you can delete files/directories by Delete and Shift+Delete.
In case you don't have write permission for a file or directory Move to Trash or Delete will not work and will be greyed out. This usually is the case for all files outside of your home directory /home/<username>.
Only if you are in desperate need to delete such files from the graphical file manager it is possible to run nautilus as root by sudo -i nautilus but this is not recommended. With a wrong command or accidental mouse move you risk to damage your whole system to a state where it can not even boot.

Please make yourself familiar with the Ubuntu concept of sudo, the Debian File System Hierarchy, and most importantly permissions before you do anything as root with Nautilus.

A: Assuming that the file is inside your home folder or an external disk, you can delete file by:

*

*right clicking the file and selecting "delete"

*selecting the file and pressing the delete key on your keyboard

*clicking and dragging the file to your trash, which is in the launcher (left pane of Ubuntu) and in the list of locations on the left of your file browser

*in the terminal, performing rm /path/to/file

If the file is not yours (belongs to another user or to the system), you can use sudo nautilus, replacing nautilus with rm /path/to/file or another file browser. Be warned, deleting system files may make your copy of Ubuntu, other operating systems on your computer, or even your computer itself unusable!

A: press ctrl + alt + T this opens the terminal then run this command
sudo nautilus

then simply locate your file and now after finding your file you can modify or create it if you have any permission to modify or delete them

A: Assuming you are using the Files file manager, the Move to Trash option when you right click a file is a delete option in practice, but you have the option to restore files in the trash can would you change your mind.
If you really want to delete files irrevocably, the answer provided by Charles Green shows you how.

A: choose the file and press the "delete" button. If you want to delete directly bypassing the trash then press "shift+delete".


text:
Q: How to enable/disable buildkit in docker? I got this command from the documentation, but i really have no idea how can I use it or where should I start to move, I'm new to docker, and concepts are still hard to me to digest:
$ DOCKER_BUILDKIT=1 docker build .

How can I use this command to enable/disable buildkit in docker engine??
I want to disable it, because as i knew it is enabled by default and i suspect it as i can't build anything by docker since i get always this error
failed to solve with frontend dockerfile.v0: failed to read dockerfile: open /var/lib/docker/tmp/buildkit-mount847288160/Dockerfile: no such file or directory

A: You must adjust the Docker Engine's daemon settings, stored in the daemon.json, and restart the engine. As @Zeitounator suggests, you should be able to temporarily disable the buildkit with DOCKER_BUILDKIT=0 docker build .. Docker CLI will parse that environment variable and should honor it as that checking is done here in the docker/cli source code.
To adjust the Docker daemon's buildkit settings, you can follow the instructions below.
From these docs. Partially on the command line, you can do that this way in Powershell:

*

*Open the file, on the command line the easiest way to do this is:

notepad "$env:USERPROFILE\.docker\daemon.json"

*Change the value of "buildkit" to false so it looks like this:

{
  "registry-mirrors": [],
  "insecure-registries": [],
  "debug": true,
  "experimental": false,
  "features": {
    "buildkit": false
  }
}

*Restart the Docker service:

Restart-Service *docker*

Alternatively, on Docker Desktop for Windows app:
Open the Dashboard > Settings:
Select Docker Engine and edit the json "features" field to read false if it's not already:

A: For me restarting docker engine and system didnt work.
But after I reset the factory settings it started working again.
Go to Docker desktop troubleshoot options and reset to factory defaults.

A: On Windows 10 x64 and Docker Desktop:
# Start DOS cmd prompt
set DOCKER_BUILDKIT=0
docker ...

No need to edit any files, restart service, etc. It just works as Docker checks the this environment variable when it runs.
Case study
Docker gave an error on the command line when I was logged into a remote PC using MobaXTerm on the command line. This fixed it.

A: *

*Open your Docker desktop application

*Find settings

*Find Docker Engine

*You can find below json
{
"builder": {
"gc": {
"defaultKeepStorage": "20GB",
"enabled": true
}
},
"experimental": false,
"features": {
"buildkit": false
}
}

*Default value of "buildkit":true -> change to false

*Restart the engine


text:
Q: What do you call it when you have two subnets and find the a common SUPERsubnet that can be used to access both of them?4 I have a Networking test in about 6 hours and I lost my notes on the subject matter and can't recall what the acronym was! Here's the problem case:
Given the address 150.20.0.0/27 find the following subnets and appropriate 'subsubnets' (what's that called as well).
The graphic then goes on to show a diagram of many routers all connected and some routers have a switch connected with a number like 6000h meaning 6000 hosts. My task is to find the SUBsubnet that is needed to accomodate the ammount of hosts without wasting any IP addresses.
The thing I remember is that SUBsubnets have a different subnet mask '/28, /30' than the base father mask.
There is also the matter of connectivity, I have to make sure the entire network can ping whereever. They gave a class on the subject, but again, I can't remember the acronym. I think it was CDLRP or something like that. We're using Cisco's Packet Tracer, so any commands related to this would be great. Basically it's like this:

I hope all of this is making sense to you guys. Any help would be appreciated and some links to tutorials so I can brush up on them before the test.

A: CIDR ?  http://en.wikipedia.org/wiki/CIDR

A: It's called CIDR and actually it means that you don't have classes in your network.
Which can be translated as ... you can use any submask you want.

A: Route summarization != CIDR. In fact a classful network is a summarization of its subnets.


text:
Q: Remote Desktop Zooming Using Remote Desktop from a device with a hi-res screen (say, a Surface Pro) is decidedly tricky - as everything displays 1:1 scale and so looks tiny.
If the machine you are remoting into runs Server 2008 R2 or later, you can change the dpi zooming setting (see here).
But for older hosts, that doesn't work.
Using normal Remote Desktop, you can connect with a lower resolution, say 1280x768, and turn on smart-sizing. However smart-sizing can scale down (to display a huge desktop in a small area) but does not seem to scale up (to display a small desktop in a big area).
Using the Windows 8 Remote Desktop App, you can zoom - but you cannot set the default resolution of the host.
What I want is a lower resolution in the host, scaled up to fit my screen.
So both of those are close to what I want, but dont quite work. So question is:
Does the Remote Desktop App allow screen resolution to be set somehow?
Is there some other Remote Desktop client that can handle zooming better?

A: I eventually found a solution to this via this blog post by Falafel Softare.
Basically:

*

*Download Microsoft's souped-up RDP client called Remote Desktop Connection Manager 2.2

*When you add a new server, go to the 'Remote Desktop Settings' tab of the Properties and select 'Same as client area'

I've written this up in a bit more detail with screenshots on my blog.
Edit: Remote Desktop Connection Manager 2.2 has been replaced by version 2.7. People in comments say 2.7 will work on Win8.1 with some settings changed, however on Windows 10 doesnt look like it solves the problem. Unfortunately MS have not left v2.2 anywhere for us.

A: In Windows 8.1 and the corresponding Windows Server 2012 R2, there is a new feature (though not mentioned in the docs http://technet.microsoft.com/en-us/library/dn283323.aspx ): there is an integration with the window manager (DWM) of Windows such that the remote machine (server) will try to match the client's DPI, thus making things look natural size (bigger).
It looks a bit weird on my Surface 2 with some older programs that are not designed with scaling up in mind (basically, DWM just zooms the window, resulting in pixelated apps), but it works.

A: Microsoft released an app which on iOS and Android is known as RD Client, and on windows App store as Microsoft Remote Desktop.
This app will natively try to connect with a lower resolution to make the experience more viable. But what it also does is allowing you to set the desktop resolution itself, and by pinching the screen, you can then zoom in, so you only see a portion of the screen if you need to read, or pinch out if you want to see the whole desktop.
I have a 2560x1440 27" monitor that I use to connect to my RD server, and my mobile phone with 5.6" has the same resolution. I can connect to the same desktop, but unlike with my desktop, from my phone, its just not readable. But the pinch and zoom makes it perfect to work with, a solution you seem to be after too.
I do not have a Surface pro, so it may be that the setting is located differently than on my Android, but I'll tell you where I found it on my android so you can look for it on your device.
It can either be specified for a specific pc/server, or globally for all connections.
Go to the menu of the app itself and you'll find Display Resolution. Press + Custom and add your own resolution, set it to 100% scaling. There is a "Match this device" option, but that will induce scaling, and we don't want that.
Once added, select that resolution, and connect. Now you should have what you want, and you can zoom in by pinching.


text:
Q: How to get product collection by Widget's Encoded Conditions in Magento 2.3.5 I have a widget with conditions_encoded (including Multiple Category Ids, Multiple SKUs) in one section of the admin panel.
The requirement is to show the product list with custom pagination, custom mode, sorting, filter option by Widget's encoded condition(s) Multiple Category Ids, Multiple SKU in custom page.
I can't understand how to render the encoded conditions array of Multiple Category Ids and Multiple SKU that are given as the condition(s) in the widget and how to show the product collection with related pagination, mode, and also filter option in the left panel like category product list page.
The conditions_encoded screenshot has been attached here. It will be helpful if it has been given a proper solution or clue.
Thank You.

A: There is a widget for arbitrary product lists (as mentioned by @Nits). If you insert the widget on any CMS page or block and turn off the WYSIWYG editor ("Hide editor" button), you can see how the parameters look like.
For example, I created the widget with the condition "category = 4", showing five products:
{{widget type="Magento\CatalogWidget\Block\Product\ProductsList" title="My products" products_count="5" template="product/widget/content/grid.phtml" conditions_encoded="a:2:[i:1;a:4:[s:4:`type`;s:50:`Magento|CatalogWidget|Model|Rule|Condition|Combine`;s:10:`aggregator`;s:3:`all`;s:5:`value`;s:1:`1`;s:9:`new_child`;s:0:``;]s:4:`1--1`;a:4:[s:4:`type`;s:50:`Magento|CatalogWidget|Model|Rule|Condition|Product`;s:9:`attribute`;s:12:`category_ids`;s:8:`operator`;s:2:`==`;s:5:`value`;s:1:`4`;]]"}}

From that you can see that the class is Magento\CatalogWidget\Block\Product\ProductsList and you can create it programmatically as follows:
$productsBlock = $this->getLayout()->createBlock(\Magento\CatalogWidget\Block\Product\ProductsList::class);
$productsBlock->setTitle("My products");
$productsBlock->setProductsCount(5);
$productsBlock->setTemplate("product/widget/content/grid.phtml");
$productsBlock->setConditionsEncoded("a:2:[i:1;a:4:[s:4:`type`;s:50:`Magento|CatalogWidget|Model|Rule|Condition|Combine`;s:10:`aggregator`;s:3:`all`;s:5:`value`;s:1:`1`;s:9:`new_child`;s:0:``;]s:4:`1--1`;a:4:[s:4:`type`;s:50:`Magento|CatalogWidget|Model|Rule|Condition|Product`;s:9:`attribute`;s:12:`category_ids`;s:8:`operator`;s:2:`==`;s:5:`value`;s:1:`4`;]]");

But "conditions_encoded" is a serialized array (with some characters replaced for WYSIWYG compatibility). This serialized array is difficult to construct manually, but luckily you can also use "conditions" with the unserialized value instead in PHP code. So you can replace the last line from above with:
$productsBlock->setConditions(
    [
        1 => [
            'type' => \Magento\CatalogWidget\Model\Rule\Condition\Combine::class,
            'aggregator' => 'all',
            'value' => '1',
            'new_child' => '',
        ],
        '1-1' => [
            'type' => \Magento\CatalogWidget\Model\Rule\Condition\Product::class,
            'attribute' => 'category_ids',
            'operator' => '==',
            'value' => '4',
        ]
    ]
);

Then output:

echo $productsBlock->toHtml();


text:
Q: how to configure PHPMY ADMIN with Docker I need to configure PHPMyAdmin in the docker-compose.yml file ?
How I did this, Can anyone help me out from this?
Thanks in advance.

A: Here is a part of my past project which used mysql and phpadmin.
Don't forget to replace variables which your own settings.
version: '3.5'

services:
    db:
        image: mysql:latest
        container_name: db
        ports:
          - "3306:3306"
        networks:
          internal:
            ipv4_address: 172.2.0.2
        restart: always
        environment:
            MYSQL_ROOT_PASSWORD: ${DB_ROOT_PASSWORD}
            MYSQL_DATABASE: wordpress
            MYSQL_USER: ${DB_USER}
            MYSQL_PASSWORD: ${DB_PASSWORD}

    phpmyadmin:
        depends_on:
          - db
        image: phpmyadmin/phpmyadmin:latest
        container_name: phpmyadmin
        ports:
          - "8001:80"
        networks:
          internal:
            ipv4_address: 172.2.0.3
        restart: always
        environment:
          - PMA_HOST=db
          - PMA_USER=${DB_USER}
          - PMA_PASSWORD=${DB_PASSWORD}
          - PMA_PORT=3306
        volumes:
          - phpmyadmin:/sessions

networks:
  internal:
    driver: bridge
    ipam:
      driver: default
      config:
        - subnet: 172.2.0.0/16

volumes:
    phpmyadmin:
        name: phpmyadmin_data


text:
Q: cannot get and data from an event into html via jquery I am a beginner with leaflet and javascript, jquery.
I have an index.html page where I am displaying a map, and then I want that when the user moves the mouse over the map, the coordinates pointed by the mouse gets printed under the map.
In order to do so, I have a div element under the map, having id "coordinate", and I want to replace it with jquery with the information coming from the event "mousemove", fired when the mouse moves over the map.
Here below is my code.
Everything works well, and console.log(...) correctly prints the mousemove event and the two coordinates number into my console, except for the fact that the html text to be relaced is hardcoded as  into the div as

Lat: ${e.latlng.lat} Long: ${e.latlng.lng}

and the information from the event is not substituted.

It's like it cannot interpret ${...} as a variable.
What is wrong?
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>leaflet geoproject</title>

     <link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.3/dist/leaflet.css"
     integrity="sha256-kLaT2GOSpHechhsozzB+flnD+zUyjE2LlfWPgU04xyI="
     crossorigin=""/>

    <button onclick=fullScreenview()>View in full screen</button>

void

A: For template literals you need to use backticks instead of single quotes
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals
i.E
`Lat: ${e.latlng.lat} Long: ${e.latlng.lng}`

instead of
'Lat: ${e.latlng.lat} Long: ${e.latlng.lng}'


text:
Q: Set all None and NaN values to 0 in a datframe - 'NoneType' object has no attribute 'isnull' # Check for None and NaN values in the dataframe and clean if needed
print("Any NaN values in the dataframe? True or False",  end='\n')
display(dfManual_With_NaN.isnull().values.any())
print("",  end='\n')

Output: True

print("Total Number of NaN values in the dataframe",  end='\n')
display(dfManual_With_NaN.isnull().sum().sum())
print("",  end='\n')

Output: 1

print("Display the total number of rows with a NaN",  end='\n')
df_NaN_Rows = dfManual_With_NaN[dfManual_With_NaN.isnull().T.any().T]
display(df_NaN_Rows.head(100))
print("",  end='\n')

Output:

# Update None and NaN to zero
dfManual_Booked = dfManual_With_NaN.fillna(value='NaN', inplace=True) # Replace None values with NaN
dfManual_Booked = dfManual_Booked.fillna(0)              # Replace NaN with 0.

Errors here: 'NoneType' object has no attribute 'isnull'

So I update None values to NaN then look to set all NaN to 0. Any guidance as to why this is failing?

A: When using inplace=True, you are performing the operation on the same dataframe instead of returning a new one (also the function call would return None when inplace=True).
Also NaN and None are treated the same for the fillna call, so just do dfManual_Booked = dfManual_Booked.fillna(0) would suffice. (Or just dfManual_Booked.fillna(0, inplace=True))


text: Q: No functor to subcategory? As far as I'm aware, you can always craft a function from one set to another unless the target is the empty set. To me this is easy to understand because the empty set is...empty, so of course you can't draw a map on it. But I'm a bit less clear on the same thing with categories. Say you have a category with objects A and B, and morphisms $f: A \to B$ and $g: B \to A$. There would be no functor from this category to a wide subcategory with only $f$ and not $g$ because you would a) lose composition and b) be mapping the hom-set of morphisms from B to A to the empty set. But to me this is just a bit weird that you don't have a functor from a category to a  subcategory of it since it feels like there is an obvious logical relationship from the category to the subcategory in question. It feels like there should be a functor. Am I making a mistake somewhere, or is this something I just have to get used to?


text:
Q: first child element of particular type I have some section with three children (one
 and two
)

Half

    left half

    right half

Then I am adding some styles to these blocks
section > h1 { ... }
section > div { ... }

I want to specify additional styles for the first
 element in the section.
I can't write use just section > :first-child because first child in section is
.
So how I should write?

A: That's what :nth-of-type is for:
section > div:nth-of-type(1) {
    /* CSS properties go here... */
}

A: You're looking for :first-of-type

A: Using only section > div:nth-of-type(1) { will select first div element where parent element is section, and hence I feel will be a loose selector, make it stricter by using
section.half > div:nth-of-type(1) { /* This will select 1st div element inside
                                     * section having class .half
                                     */
    /* Styles goes here */
}

Demo
You can also use first-of-type Demo
section.half > div:first-of-type {
    /* Styles goes here */
}

A: Working jsFiddle Demo
No doubt, Joseph Silber answer is great. But if you don't want to use CSS3, here is the trick:
section > div { background: red; }
section > div + div { background: transparent; }

First, you select all div elements and set your properties to it. Then, you select second div and later and
reset those properties for it.


text:
Q: Angular 2 Break Into a new row Im looking to build a grid of items that breaks every 3rd and splits into a new row of another 3 cols.. I cant seems to figure out a way to do this intuitively with Ionic 2/Angular 2.
In PHP I would solve this problem using something like the following
    <?php

    echo '
';
    $i = 0

    while()....

    if($i % 3 === 0){
        echo '

';
    }

    endwhile;

    echo '
';

unfortunately angular 2 wont allow me to do an ngIf to close a div. Has anyone got any neat tricks for solving this ?

A: Well this is the fastest way to do this on ionic 2.
Template:
<ion-grid>
  <ion-row *ngFor="let row of grid">
      <ion-col width-33 *ngFor="let image of row">
          <ion-img [src]="image.url">
       </ion-col>
  </ion-row>
</ion-grid>

Component:
  grid: Array;

  loadGallery() {
     let rowsCount = Math.ceil(this.images.length / 3);
     grid = Array(rowsCount);

     for(let i = 0; i < rowsCount; i++) {
        grid[i] = this.getImages(i, 3);
     }
  }

  getImages(fromIndex:number, amount: number): Array {
    if ((fromIndex + amount) >= this.images.length)
       return this.image.slice(fromIndex, this.images.length - 1);
    return this.image.slice(fromIndex, amount);
  }

Just run the loadGallery() function when you fill the this.images (this is just a fancy name for the array where you will put the images).
I hope it helps.
Source: http://blog.ionic.io/layout-the-cool-way-using-the-ionic-2-grid-component


text:
Q: How can I put complex pointer data as property into qt plugin xml file I have implemented a widget in Qt like below:
class MyWidget : public QWidget
{
    Q_OBJECT
    Q_PROPERTY( bool BooVal READ getBoolVal WRITE setBoolVal)
    Q_PROPERTY( MyPointer* PointerData READ getPointer WRITE setPointer);

    ...
}

I want to use it in QtDesinger. Therefore I implemented QDesignerCustomWidgetInterface interface like below:
class MyPlugin : public QObject, public QDesignerCustomWidgetInterface
{

    ...
}

QWidget *MyPlugin::createWidget( QWidget *parent )
{
    return new MyWidget(parent);
}

But in QtDesigner property window I can't set complex data like Q_PROPERTY(MyPointer* PointerData ...). Some Qt widget like QTreeWidget can set complex pointer data in QtDesigner through custom interface. e.g. in QTreeWidget when I set parent node and it's children, sth like below appears in .ui file
<widget class="QTreeWidget" name="treeWidget">
  <item>
    <property name="text">
       <string>1</string>
    </property>
    <item>
       <property name="text">
           <string>1-1</string>
       </property>
    </item>
  </item>
</widget>

In fact I want to create a plugin like QTreeWidget and set complex data like QTreeWidgetItem* through QtDesinger.

A: Do you want to save a subclass of QTreeWidget in UI xml form?
you can use
void QAbstractFormBuilder::save(QIODevice * device, QWidget * widget)

function of void QAbstractFormBuilder class or QFormBuilder class.


text:
Q: Using Git to track Ruby on rails Other than the database and log files are there any other files that should not be in the repository for security reasons?
The project will mostly be worked on by myself however the code is to be stored on a shared repository which will  be available to a few other users should they want to pull from it. The project is reasonably simple, so i am not too worried about security in my actual code - this is more to protect any test data etc and to build up 'good practice' in this type of project.

A: A typical .gitignore file in a "ruby on rails" context could look something like:
config/database.yml
db/*.sqlite3
log/*.log
log/*.pid
tmp/**/*"

But, as pointed out by the article "rorgitignore : .gitignore files specific for Ruby on Rails", you can also use .gitignore to add empty directories.

Because git tracks contents, not files, it doesn't save any empty
  directories, since there is no content to track.
This means that when you clone your project from a git repository, it is
  missing the log, tmp, lib and other directories.
This small script fixes that, so git adds even empty directories

for DIR in `find . -type d | sed -re 's/\.\///g' | grep -v '^\.git'`; do
    [ `ls -a $DIR | wc -l` -le 2 ] && \
    echo Creating and git-adding $DIR/.gitignore && \
    touch $DIR/.gitignore && \
    git add -f $DIR/.gitignore
done

this just outputs the commands to add an empty .gitignore file to all empty directories in a git project and git add -f'em to the repo.

If you are still focused only on the main .gitignore file, here is a more complete one, from iCoreTech Research Labs
config/database.yml
*~
*.cache
*.log
*.pid
tmp/**/*
.DS\_Store
db/cstore/**
doc/api
doc/app
doc/plugins
coverage/*
db/*.sqlite3
*.tmproj
Capfile


text:
Q: how to download multiple images for my website? So i was trying this for a single image.
import urllib.request
urllib.request.urlretrieve("link.com","name1.jpg")

and found out that the link of the images is constant and only one digit is variable.
The first link : https://image.slidesharecdn.com/marketinginternationalsept2013-150330215818-conversion-gate01/95/marketing-international-1-638.jpg?cb=1427770871
The last link : https://image.slidesharecdn.com/marketinginternationalsept2013-150330215818-conversion-gate01/95/marketing-international-92-638.jpg?cb=1427770871

Where only 1 to 92 number is variable.

I'm stuck in making a list incremented through that number in the link, and a list for the image name.To automate this process instead of downloading one by one like i did.
Any help please, thanks.

A: Just loop through the image numbers and get each one individually.
import urllib.request

for i in range(92):
    import urllib
    f = open(f'{i+1}.jpg','wb')
    f.write(urllib.request.urlopen(f'https://image.slidesharecdn.com/marketinginternationalsept2013-150330215818-conversion-gate01/95/marketing-international-1{i+1}-638.jpg').read())
    f.close()

A: Your solution Didn't work for several problems.
So i went for this solution:
for i in list(range(1,92)):
    link_1 = "image.slidesharecdn.com/…" name = str(i)+".jpg"
    print(link_1, name)
urllib.request.urlretrieve(link_1, name)

And it worked! thanks for help –


text:
Q: Adding widget instance into my theme via xml So I have a few custom widgets instances that I'd like to include into some theme .xml files. However I'd like these to be added via XML rather than as Layout Updates under
New Widget Instance.
I know I can add a widget via XML by also setting all the widget options within the XML, however i'd like to give the client some ability to configure these in the backend themselves.
At the moment the only way I can think of to add a static block and then have a widget added withint the content of that, but this seems a rather unelagant solution compared with just adding a widget instace directly.
Looking for something like below but for a widget rather than a static block
<block type="cms/block" name="cms_footer_links" before="footer_links">
                <action method="setBlockId"><block_id>footer_links</block_id</action>
</block>

A: Here an example of adding New Products widgets via catalog.xml (or any other file) layout:
<block
  type="catalog/product_widget_new" name="custom_widget_name"
  template="catalog/product/widget/new/column/new_default_list.phtml">
    <!-- populate widget by options -->
    <action method="setData"><name>products_count</name><value>3</value></action>
    <action method="setData"><name>cache_lifetime</name><value>3600</value></action>
</block>

A: Looks like what I was asking for isn't possible (by default atleast) so I either need to choose to add the widget (and add the values) via XML, or just use a backend widget instance.


text:
Q: Domain analysis in surveys When using the survey procs in SAS on imputed dated, is it best to include the
imputation variable on the table or domain statement, or should it be
included on the by statement?  I found one paper
(http://support.sas.com/resources/papers/proceedings10/265-2010.pdf) that
included it on the domain statement which seems kind of strange to me
since imputations are not really subsets of the data in the same way
something like a grouping based on age or sex or race is.  Can someone
explain?  Thx.


text:
Q: How to clear application cache programatically in Marshmallow I want to clear my application cache programatically in Android Marshmallow 6.0. I tried the following code, but it's not working in Marshmallow.I read on stack overflow that below code is deprecated from API level 19. I add  CLEAR_APP_CACHE permission in my Manifests.xml
 public  void trimCache(Context context) {
        try {
            File dir = context.getCacheDir();
            if (dir != null && dir.isDirectory()) {
                deleteDir(dir);
            }
        } catch (Exception e) {
            // TODO: handle exception
        }
    }

 public  boolean deleteDir(File dir) {
        if (dir != null && dir.isDirectory()) {
            String[] children = dir.list();
            for (int i = 0; i < children.length; i++) {
                boolean success = deleteDir(new File(dir, children[i]));
                if (!success) {
                    return false;
                }
            }
        }

        // The directory is now empty so delete it
        return dir.delete();
    }

A: Add the following permission in your manifest:
<uses-permission android:name="android.permission.CLEAR_APP_CACHE" />

You should check for the external cache directory also.
public  void trimCache(Context context) {
        try {
            File dir = context.getCacheDir();
            if (dir != null && dir.isDirectory()) {
                deleteDir(dir);
            }
            File exDir = context.getExternalCacheDir();
            if (exDir != null && exDir.isDirectory()) {
                deleteDir(exDir);
            }
        } catch (Exception e) {
            // TODO: handle exception
        }
    }


text:
Q: How to detect when the Windows start menu / start screen opens? How to setup an event-handler or callback for the Windows start menu (or Windows 8 start screen) opening?
Or, at least, how to check if the start menu is currently open?
I prefer a solution for this problem in C#, but a solution in C++ is also greatly appreciated.

A: Apparently the start screen visibility callback/event thing doesn't work for a desktop app (see the out-#ifed code below), but simple polling works nicely.
#include <algorithm>        // std::swap
#include <functional>       // std::function
#include <iostream>
#include <stdlib.h>         // EXIT_FAILURE, EXIT_SUCCESS
#include <stdexcept>        // std::runtime_error, std::exception
#include <system_error>     // std::system_error
#include <string>           // std::string
using namespace std;

#include <conio.h>          // _kbhit

#undef UNICODE
#define UNICODE
#include <windows.h>
#include <shobjidl.h>       // IAppVisibilityEvents

auto fail( string const& message, int code = 0 )
    -> bool
{ throw system_error( code, system_category(), message ); }

class On_block_exit
{
private:
    function<void()>    f_;
public:
    ~On_block_exit() { f_(); }
    On_block_exit( function<void()> f ): f_( f ) {}
};

enum Success { success };

auto operator>>( HRESULT const hr, Success const )
    -> bool
{ ::SetLastError( hr );  return SUCCEEDED( hr ); }

template< class Interface >
class Com_ptr
{
private:
    Interface*  p_;
public:
    Interface* pointer() const { return p_; }
    Interface* operator->() const { return p_; }

    void** as_out_arg()
    {
        *this = Com_ptr();
        return reinterpret_cast<void**>( &p_ );
    }

    friend
    void swap( Com_ptr& a, Com_ptr& b ) throw()
    { swap( a.p_, b.p_ ); }

    void operator=( Com_ptr rhs ) { swap( *this, rhs ); }

    ~Com_ptr() { if( p_ ) { p_->Release(); } }

    Com_ptr( Interface* const p = nullptr ): p_( p ) {}

    Com_ptr( Com_ptr const& other )
        : p_( other.p_ )
    { if( p_ ) { p_->AddRef(); } }
};

auto is_startscreen_shown( Com_ptr<IAppVisibility> p_app_visibility )
    -> bool
{
    BOOL    result;
    p_app_visibility->IsLauncherVisible( &result )
        >> success
        || fail( "IAppVisibility::IsLauncherVisible", ::GetLastError() );
    return !!result;
}

template< class Base >
struct With_dummy_iunknown_
    : Base
{
    ULONG __stdcall AddRef() override { return 0; }

    ULONG __stdcall Release() override { return 0; }

    HRESULT __stdcall QueryInterface( REFIID riid, void **ppvObject ) override
    {
        if( riid == IID_IUnknown )
        {
            *ppvObject = this;
            return S_OK;
        }
        return E_NOINTERFACE;
    }
};

void cpp_main()
{
    ::CoInitialize( nullptr )
        >> success
        || fail( "CoInitialize", ::GetLastError() );

    Com_ptr<IAppVisibility> p_app_visibility;

    ::CoCreateInstance(
        CLSID_AppVisibility, nullptr, CLSCTX_ALL, IID_IAppVisibility, p_app_visibility.as_out_arg()
        ) >> success
        || fail( "CoCreateInstance CLSID_AppVisibility IID_IAppVisibility", ::GetLastError() );

    cout << "Press the 'Any' key to quit." << endl;
    bool was_shown = false; bool first_iteration = true; int n = 0;
    for( ;; )
    {
        if( _kbhit() ) { break; }

        bool const is_shown = is_startscreen_shown( p_app_visibility );
        if( first_iteration || is_shown != was_shown )
        {
            cout << n << ": ";
            if( is_shown )
            {
                cout << "Currently showing the start screen" << endl;
            }
            else
            {
                cout << "Currently showing normal desktop or app." << endl;
            }
            ++n;
        }
        first_iteration = false;
        was_shown = is_shown;
        Sleep( 50 );
    }

#if 0
    struct Events: IAppVisibilityEvents
    {
        HRESULT __stdcall AppVisibilityOnMonitorChanged(
            HMONITOR                monitor_handle,
            MONITOR_APP_VISIBILITY  previous_mode,
            MONITOR_APP_VISIBILITY  current_mode
            ) override
        { return S_OK; }

        HRESULT __stdcall LauncherVisibilityChange(
            BOOL is_now_visible
            ) override
        {
            cout
                << (!!is_now_visible? "Showing the start screen" : "Hiding start screen, showing desktop/app")
                << endl;
            return S_OK;
        }
    };

    With_dummy_iunknown_<Events> events;
    DWORD cookie = 1;
    p_app_visibility->Advise( &events, &cookie )
        >> success
        || fail( "IAppVisibility::Advise", ::GetLastError() );
    On_block_exit unadvise( [=](){ p_app_visibility->Unadvise( cookie ); } );

    ::MessageBox( 0, L"Press OK to quit.", L"Watching...", MB_SETFOREGROUND );
#endif
}

auto main()
    -> int
{
    try
    {
        cpp_main();
        return EXIT_SUCCESS;
    }
    catch( system_error const& x )
    {
        cerr << "!" << x.what() << " (code " << x.code().value() << ")" << endl;
    }
    catch( exception const& x )
    {
        cerr << "!" << x.what() << endl;
    }
    return EXIT_FAILURE;
}


text:
Q: Is it appropriate to run the Error Correction Model on data which are not I(1)? I have intraday data (frequency = 1 min.) for 6 stocks and 1950 observations per each time series.
I checked stationarity for the level data and first difference and it appears that:

*

*5 stocks's level data are non-stationary and 1 is stationary,

*all 6 stocks's first differences are stationary,
meaning that that 1 stock is not I(1) and that 5 stocks are I(1).

My question is: Is it appropriate to run Engle-Granger methodology, ending with Error Correction Model, on the data pair which includes 1 time series which is I(1) and the other one which is not I(1)?

A: Running a VECM requires testing of cointegration as a prerequisite. Only if the series are cointegrated , can we proceed with a VECM.  Also prior to running cointegration, the mandatory stationarity testing requires that the variables are non stationary at level and stationary on first difference ( Integrated of the same order).

A: The short answer is "no." It's actually OK to use ECMs if ALL variables are stationary. And it's obviously OK if they are ALL I(1).
The real requirement is that the equation is "balanced" which means that all the variables are at the SAME order of integration (whatever that order happens to be). If one is stationary and the other is I(1) that's bad, and will potentially lead to spurious results.
Of course in reality you may not have enough power to actually determine the order of integration of variables...and they may actually be "fractionally integrated" which causes other issues.
See this paper  (which is part of a longer back and forth about the proper use of ECMs) for more details
https://www.cambridge.org/core/journals/political-analysis/article/abs/treating-time-with-all-due-seriousness/6819BB223EB54EF830FCE7065FBFF965


text:
Q: Using Android to connect to mysql database I'm going to attempt to write to an app that needs to access a remote database running on a server. I know you can use jdbc when writing java applications, but can this be done in android too? Or is there a better way. Any direction would be appreciated.

A: I'd recommend implementing services on the server that would behave differently based on input parameters (e.g. userId) rather than try to connect directly through devices. Also, for performance reasons, I'd recommend the response format of json over xml.


text:
Q: Fast communication between Service and Activity I have modified the Android Bluetooth Chat code so that bytes received from the BluetoothChatService will be sent directly to the BluetoothChat Activity.
The sending rate of the other Bluetooth device is 125Khz, each packet is 20bytes.
So there will be around 125*20 bytes per second which has to be received by the Service and then sent to the Activity.
However, I found out that there will be packet loss in the data received by the Activity. I have verified that the data received in the Service is indeed correct.
This is the part of code which sends a 20 byte object to the Activity.
mHandler.obtainMessage(BluetoothChat.MESSAGE_READ, 20, -1, buffer)
                        .sendToTarget();

This is the handler that gets message back from The BluetoothChatService
private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
           case MESSAGE_READ:
                byte[] readBuf = (byte[]) msg.obj;
    ...}
}

Any idea how to solve this problem? Thanks.

A:
This is the part of code which sends a 20 byte object to the Activity.

It is sending a reference to your buffer. If you reuse that buffer when reading in more Bluetooth data, your old data may be overwritten before the activity has had a chance to use the data.


text:
Q: Assets compile failed with out of memory I try to compile assets on the production server, but when I run rake task with compile - process goes too long and I get error with memory out.There is trace
RAILS_ENV=production rake assets:precompile --trace
** Invoke assets:precompile (first_time)
** Invoke assets:environment (first_time)
** Execute assets:environment
** Invoke environment (first_time)
** Execute environment
** Invoke bower:before_precompile (first_time)
** Execute bower:before_precompile
** Execute assets:precompile
rake aborted!
ExecJS::RuntimeError: FATAL ERROR: Evacuation Allocation failed - process out of memory
(execjs):1
/home/ubuntu/staging/releases/21/vendor/bundle/ruby/2.2.0/gems/execjs-2.6.0/lib/execjs/external_runtime.rb:219:in `exec_runtime'
/home/ubuntu/staging/releases/21/vendor/bundle/ruby/2.2.0/gems/execjs-2.6.0/lib/execjs/external_runtime.rb:39:in `exec'
/home/ubuntu/staging/releases/21/vendor/bundle/ruby/2.2.0/gems/execjs-2.6.0/lib/execjs/external_runtime.rb:21:in `eval'
/home/ubuntu/staging/releases/21/vendor/bundle/ruby/2.2.0/gems/execjs-2.6.0/lib/execjs/external_runtime.rb:46:in `call'
/home/ubuntu/staging/releases/21/vendor/bundle/ruby/2.2.0/gems/uglifier-2.7.1/lib/uglifier.rb:212:in `run_uglifyjs'
/home/ubuntu/staging/releases/21/vendor/bundle/ruby/2.2.0/gems/uglifier-2.7.1/lib/uglifier.rb:179:in `compile'
/home/ubuntu/staging/releases/21/vendor/bundle/ruby/2.2.0/gems/sprockets-3.3.2/lib/sprockets/uglifier_compressor.rb:52:in `call'
/home/ubuntu/staging/releases/21/vendor/bundle/ruby/2.2.0/gems/sprockets-3.3.2/lib/sprockets/uglifier_compressor.rb:28:in `call'
/home/ubuntu/staging/releases/21/vendor/bundle/ruby/2.2.0/gems/sprockets-3.3.2/lib/sprockets/processor_utils.rb:75:in `call_processor'
/home/ubuntu/staging/releases/21/vendor/bundle/ruby/2.2.0/gems/sprockets-3.3.2/lib/sprockets/processor_utils.rb:57:in `block in call_processors'

I also try run this with config.assets.compile = false but I get same error, how I can fix it?
sorry for my bad English


text:
Q: Slow performance cropping large JPEG2000 images with ImageMagick/Jasper I have a 4000x3000, 3.7MB JPEG2000 file that I'm trying to process into cropped tiles. I do this with a command like:
convert 486.jp2 -crop 256x256+0+0 -format jpg 486_crop.jpg

This command takes 5 seconds to run on a current-model Mac Pro. ImageMagick is using the Jasper library, which I've read is very slow. I just want to make sure I'm not botching the command somehow before I abandon ImageMagick in this application.

A: ImageMagick has poor perf (pretty good results though). You can consider GraphicsMagick instead. A few interesting benchmarks (there is one for the crop option): GraphicsMagick 1.3.8 vs ImageMagick 6.5.8-10 Benchmark Report

A: On a year old Mac mini (2.53 C2D):
$ ls -hn test.jp2
-rw-r--r--  1 501  20    10M Aug 12 23:40 test.jp2

$ time convert test.jp2 -crop 256x256 -format jpg test/%d.jpg

real    0m3.971s
user    0m3.383s
sys     0m0.535s

On a current-model quad-core Mac Pro it should run no slower.
I am using a stock version of ImageMagick from ports:
$ convert -version
Version: ImageMagick 6.6.3-0 2010-08-31 Q16 http://www.imagemagick.org
Copyright: Copyright (C) 1999-2010 ImageMagick Studio LLC
Features: OpenMP OpenCL

Also it is same slow when tiling PNG or plain JPEG. Seems to me that JPEG2000 isn't the issue here.


text:
Q: Cython with Python3.5: convert list of string to char** I am trying to pass a list of string to a C++ function that takes a char** as argument using Cython.
I tried other solutions I can't remember but I mainly tried the two following options:

*

*Using a convertion function extracted from here, which is basically the same answer than here, but it raises an error, on the g++ compilation which is
cy_wrapper.cpp: In function 'char** _pyx_f_10cy_wrapper_to_cstring_array(PyObject*)':
cy_wrapper.cpp:1223:44: error 'PyString_AsString' was not declared in this scope
    __pyx_t_5 = PyString_AsString(__pyx_t_4); if (unlikely(__pyx_t_5 == ((char *)NULL))

*Using the encoding method of python strings, as suggested in here but the answer is not satisfying since it raises the error:
cy_wrapper.pyx:14:35: Storing unsafe C derivative of temporary Python reference

I looked in the library files at ~/.local/lib/python3.5/site-packages/Cython/Includes/cpython and I found the file string.pxd which contains the function PyString_AsString I need.
Why is it not found? If there is no possibility to use it, is there a workaround?
I am working on Ubuntu 16.04.4 LTS (tegra kernel) on a arm64 arch.
My cy_wrapper.pyx is exactly like this:
from cpython.string cimport PyString_AsString
from libc.stdlib cimport malloc

cdef extern:
    cdef cppclass imageNet:
        imageNet* Create(int argc, char** argv)

cdef char** to_cstring_array(list_str):
    cdef char** ret = <char **>malloc(len(list_str) * sizeof(char *))
    for i in range(len(list_str)):
        ret[i] = PyString_AsString(list_str[i])
    return ret

cdef class PyImageNet:
    cdef imageNet* c_net
    def Create(self, argc, kwargs):
        cdef char** c_argv = to_cstring_array(kwargs)
        return PyImageNetFactory(self.c_net.Create(argc, c_argv))

cdef object PyImageNetFactory(imageNet* ptr):
    cdef PyImageNet py_obj = PyImageNet()
    py_obj.c_net = ptr
    return py_obj

My setup.py:
from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext

setup(
      cmdclass = {"build_ext": build_ext},
      ext_modules = [
          Extension("cy_wrapper",
                    sources=["cy_wrapper.pyx"],
                    libraries=["shared_inference"],
                    language="c++",
                    extra_compile_args=["-O3", "-Wall"],
                    extra_link_args=["-L../build/"]
                    )
          ]
)

Ofc libshared_inference.so is located in ../build/ and defines the class imageNet.

A: For those interested, here is how I converted my list of string into a char** (I forgot to mention in my question that my method was static, but it does not really matter regarding my solution), hope this will help someone.
# cy_wrapper.pyx
from libc.stdlib cimport malloc, free

cdef extern:
    cdef cppclass imageNet:
        @staticmethod
        imageNet* Create(int argc, char** argv)

cdef class PyImageNet:
    cdef imageNet* c_net
    @staticmethod
    def Create(args):
        # Declare char**
        cdef char** c_argv
        # Allocate memory
        c_argv = <char**>malloc(len(args) * sizeof(char*))
        # Check if allocation went fine
        if c_argv is NULL:
            raise MemoryError()
        # Convert str to char* and store it into our char**
        for i in range(len(args)):
            args[i] = args[i].encode()
            c_argv[i] = args[i]
        # Grabbing return value
        cdef imageNet* c_tmp_net = imageNet.Create(len(args), c_argv)
        # Let him go
        free(c_argv)
        # Return python-compatible value
        return PyImageNetFactory(c_tmp_net)

cdef object PyImageNetFactory(imageNet* ptr):
    cdef PyImageNet py_obj = PyImageNet()
    py_obj.c_net = ptr
    return py_obj

Test code:
# test.py
import cy_wrapper
args = ["str1", "str2"]
net = cy_wrapper.PyImageNet.Create(args)


text:
Q: skypeforlinux white screen on 14.04 Yesterday my skypeforlinux program started showing only a white screen after login. I see the chat window for a fraction of a second and then it goes white. The top menus still show (and appear functional, I can press 'quit') but no dialogs, chats, etc appear.
I have tried restarting and tried clearing the config/skypeforlinux directory. No change. I don't have sudo access to the machine so can't reinstall the software.
If I start Skype via the command line then I get the following messages just as the white screen appears:
ALSA lib pcm.c:2239:(snd_pcm_open_noupdate) Unknown PCM mic_call
ALSA lib pcm.c:2239:(snd_pcm_open_noupdate) Unknown PCM call
ALSA lib pcm.c:2239:(snd_pcm_open_noupdate) Unknown PCM mic_call
ALSA lib pcm.c:2239:(snd_pcm_open_noupdate) Unknown PCM call
ALSA lib pcm.c:2239:(snd_pcm_open_noupdate) Unknown PCM mic_call
ALSA lib pcm.c:2239:(snd_pcm_open_noupdate) Unknown PCM call
X Error of failed request:  BadRequest (invalid request code or no such operation)
  Major opcode of failed request:  140 (RANDR)
  Minor opcode of failed request:  42 ()
  Serial number of failed request:  10
  Current serial number in output stream:  10

Any ideas what's happening here? It was working fine until yesterday.

A: I am having the same problem on Ubuntu 14.04.5.
As I just posted on the Microsoft forum, a workaround for me is the usage of version 8.10.0.4. You can download it here.
I deleted the ~/.config/skypeforlinux folder and installed it via terminal:
sudo dpkg -i /skypeforlinux_8.10.0.4_amd64.deb
Hopefully this works for you, too. :)

A: @dermaze's solution worked for me too but version 8.10.0.4 is not available any more and the URL is now broken. I was able to download the Debian package with a previous version of Skype at this URL.

A: Picking the latest version from here (after uninstalling Skype) helped. Awesome!
https://www.ubuntuupdates.org/?type=ppas&vals=159

A: worked for me, by changing to latest version of skype from
https://www.ubuntuupdates.org/?type=ppas&vals=159
1. downloaded "skypeforlinux_8.19.76.8_amd64.deb".
2. install via dpkg command


text:
Q: Why my navigation buttons in jqGrid are shown like this? Can I change its design? (Image present in question)
Can I change the design of my jqGrid button? my loadonce:false, but in that case I can't use my pager because it gets disabled.


text:
Q: How to create crawelable Ajax using jquery? I am going to create a crawelable ajax by jquery, How to do it? before I had a website that used jquery Ajax for searching my website but nothing indexed.
this is the new way tha I use:
page 1

And then show result by ajax and don't allow the link to go:
javascript
    $("body").on("click","#linkA",function(e){
    e.preventDefault();
    var href=$(this).attr('href');

   $.ajax({
    type:"POST",
    url:"ajax/return.php",
    data:({page:href}),
    success:function(data){
        $("body").html(data);
    }

   })
});

my questions:
1- Is the way that I am using true?
2- Is this way crawelable?

A: I think the way that you are using is true, and it's a good way, but google has an article about Making AJAX Applications Crawlable

A: As long as the links you provide in the "href" attribute are also rendered correctly by the server if the browser accesses them directly, you're on the safe site. You should also use HTML5 History API and Pushstate in order to reflect the url of the page currently shown, so visitors can use their browser history buttons, send links to pages and favorize them in their browser.
Google and the other search engines normaly won't execute your javascript and try directly to access the links you provide.
If your site got heavy scripts to load or static parts like header, footer, menu it's a great way to improve your loading / rendering speed by hijacking the links and loading only the needed content via javascript.


text: Q: Confusion over Trees in Set Theory Let $T$ be a normal Suslin tree, so among other things for each $x \in T$, there is some $y > x$ at each higher level less than $\omega_1$, and every branch in $T$ is at most countable. My question is, how can both of these be true? Can we not construct a branch of length $\omega_1$ by induction starting at a root and choosing an element in the level above?


text:
Q: insert a row after a group and fill with next row values I would like to insert a new row after each group (grp) and fill some of the new columns with the next row values and some with previous row values
I'm trying to use:
x<-rbind(setDT(DF), DF[,.SD[.N], grp][, color := shift(color,1L, type = "lag")][, Lat:= shift(Lat,1L, type = "lead")])[order(id)]

on a DF:
a <- c(1,2,3,4,5,6,7,8,9,10)
b <- c(10,20,30,40,50,60,70,80,90,100)
c <- c("a","a","b","b","b","a","a","b","c","c")
d <- c(11,23,67,89,90,100,101,123,200,290)
df <- data.frame(color=a, Lat=b, grp=c, id=d)

I'm probably using the shift() incorrect and I cant seem to make it work.
thanks
expected results to be:
   color Lat grp  id
1      1  10   a  11
2      2  20   a  23
new row with color from previous row, Lat from next row, grp from previous and if from next
3      3  30   b  67
4      4  40   b  89
5      5  50   b  90
new row as before
6      6  60   a 100
7      7  70   a 101
new row as before
8      8  80   b 123
new row as before
9      9  90   c 200
10    10 100   c 290

A: We create two lead columns i.e. next row values of 'Lat', and 'id' before we do the group by rleid of 'grp'.  Here, the rleid is checking whether the adjacent elements of 'grp' are the same or not.  If it is different, it assigns a new id to that element
library(data.table)
setDT(df)[, c("LatN", "idN") := shift(.SD, type = 'lead'), .SDcols = c('Lat', 'id')]

Get the last observation of the selected columns by the rleid of 'grp'
tmp <- df[, .(color = color[.N], Lat = LatN[.N], id = idN[.N], grp = grp[.N]),
       .(grp1 = rleid(grp))][, grp1 := NULL]

rbind with the original dataset columns, order by the 'color' and remove any NA rows
na.omit(rbind(df[,.(color, Lat, id, grp)], tmp)[order(color)])
#     color Lat  id grp
# 1:     1  10  11   a
# 2:     2  20  23   a
# 3:     2  30  67   a
# 4:     3  30  67   b
# 5:     4  40  89   b
# 6:     5  50  90   b
# 7:     5  60 100   b
# 8:     6  60 100   a
# 9:     7  70 101   a
#10:     7  80 123   a
#11:     8  80 123   b
#12:     8  90 200   b
#13:     9  90 200   c
#14:    10 100 290   c


text:
Q: Jquery DataTables to exclude rows with a certain class I have an HTML table in which I have applied the DataTables function to. I use the first  row of the table with the class 'template' applied as my template row. Then pick this formatting up and populate all the rows in the table using a JSON feed. The problem is that the pagination provided by DataTables includes this hidden template row so always makes my first page display 1 less row than all the others.
Is there a way to exclude any rows (of which there will only be one) with the class 'template' applied to the tr?

<link href="/bower_components/datatables-plugins/integration/bootstrap/3/dataTables.bootstrap.css" rel="stylesheet">

<link href="/bower_components/datatables-responsive/css/dataTables.responsive.css" rel="stylesheet">

                Name
                Helpful?
                Created
                Live?
                Actions

                #NAME#
                 #UP_VOTE#  #DOWN_VOTE#
                #CREATED#

                #ACTIONS#

$(document).ready(function() {

    delay( function() {
        $('#problem_table').DataTable({
            responsive: true,
            pageLength: 20,
            aLengthMenu: [[20, 40, 60, -1], [20, 40, 60, "All"]],
            aoColumnDefs : [{ "bSortable" : false, "aTargets" : [ "no-sort"     ] }]
        });
    }, 200 );

});

A: You can use the good old custum row filter for this :
$.fn.dataTableExt.afnFiltering.push(
    function( oSettings, aData, iDataIndex ) {
        var row = oSettings.aoData[iDataIndex].nTr;
        return $(row).hasClass('template') ? false : true;
    }
);

Even though it is pre-1.10.x hungarian notation, it still works with DataTable() instances.
demo -> http://jsfiddle.net/zaxkrc49/


text:
Q: How to Write to a file and then read the file in Python I have written the following code:
supported = open("Mails/mymails.txt",'w')
with open("emails.txt","r") as handle:
    for line in handle:
        if line.strip():
            list = line.split(":")
            email = list[0]
            domain = email.split("@")
            if domain[1] in blacklist:
                blacklisted = blacklisted+1
            if domain[1] in dictionary and domain[1] not in blacklist:
                valid=valid+1
                supported.write(domain[1])

    print(valid,blacklisted)
with open("Mails/mymails.txt",'r') as handle1:

    for line1 in handle1:
        print(line1)

I used append mode and it worked fine, but when i use multiple files, i have to manually delete supported.txt file to make sure the new file lines are not appended to old file lines
Any help is appreciated

A: I closed the file and it worked fine
like : supported.close() at the end of first with statement


text:
Q: What does the "Function Call" activity mean in the Chrome profiler? Is this code that the browser is running that isn't code that I wrote?

A: This Chrome Doc says Function Call is "A top-level JavaScript function call was made (only appears when browser enters JavaScript engine)." But I'm still not sure exactly what that means.


text:
Q: Generalize Theorem 4.13. in Brezis's Functional Analysis Let $(X, \mathcal A, \mu)$ be a $\sigma$-finite measure space and $(E, |\cdot|)$ a Banach space. Fix $p \in [1, \infty)$. Let $L_p := L_p (X, \mu, E)$ and $\|\cdot\|_{L_p}$ be its norm. Here we use the Bochner integral. I'm trying to generalize Theorem 4.13. in Brezis's Functional Analysis, i.e.,

Theorem: If the $\sigma$-algebra $\mathcal A$ is countably generated and $E$ separable, then $L_p$ is separable.

Could you have a check on my below attampt?

Proof: Let $\mathcal F$ be the collection of all measurable sets with finite measure. We define a pseudometric metric $d_\mu$ on $\mathcal F$ by $d_{\mu}(A, B) := \mu(A \triangle B)$. Then $d_\mu$ becomes a metric when $\mathcal F$ is considered modulo the equivalence relation $\sim$ defined by
$$
A \sim B \iff \mu(A \triangle B) = 0 \quad \forall A,B \in \mathcal F.
$$
Then we have

*

*Lemma 1 If the $\sigma$-algebra $\mathcal A$ is countably generated, then $d_\mu$ is separable.

Also,

*

*Lemma 2: The space $\mathcal S := \mathcal S(X, \mu, E)$ of simple functions is dense in $\big (L_p, \|\cdot\|_{L_p} \big)$ for all $p \in [1, \infty)$. [Prop 4.8 in Amann's Analysis III]

By Lemma 2, it suffices to prove that $\mathcal S$ is separable. Let $D$ be a countable dense subset of $E$. By the finite form of a function in $\mathcal S$ and the triangle inequality, it suffices to prove that $\mathcal I := \{e 1_{A} : e\in D, A \in \mathcal F\}$ is separable. Fix some $e \in D$ such that $|e|=1$. Again, it suffices to prove that $\{e 1_{A} : A \in \mathcal F\}$ is separable. Consider the map
$$
T:\mathcal F \to L_1, A \mapsto e1_A.
$$
It follows from $1_{A \triangle B} = |1_A-1_B|$ that $T$ is an isometric embedding. By Lemma 1,  $d_\mu$ is separable. So $T(\mathcal F)$ is also separable. This completes the proof.


text:
Q: BIRT Console is not displaying anything I am attempting to display to my console using BIRT, however I am having no success.
I am using eclipsec.exe, and trying to display a simple count on console.
for(var i=1; i<11; i++)
{
    Packages.java.lang.System.out.println ("Count is: " + i);
}

However the console does not display anything.

A: I know this is not a direct answer, but as an alternative, you could use java.util.logging like this:
When starting eclipse, add the argument
  -vmargs -Djava.util.logging.config.file=\path\to\logging.properties
The logging.properties file could look like this:
handlers= java.util.logging.FileHandler
.level= INFO
java.util.logging.FileHandler.pattern = /path/to/birt-designer.log
java.util.logging.FileHandler.limit = 5000000
java.util.logging.FileHandler.count = 1
java.util.logging.FileHandler.formatter = java.util.logging.SimpleFormatter
java.util.logging.FileHandler.level = ALL

Then in the initialize script of the report, add something like this:
importPackage(Packages.java.util.logging);
var log = {
    _log: Logger.getLogger("birt.js"),
    debug: function(s) { this._log.fine(s); },
    info: function(s) { this._log.info(s); },
    warn: function(s) { this._log.warning(s); },
    warning: function(s) { this._log.warning(s); },
    error: function(args) {
        this._log.severe("" + args);
    }
};
log._log.setLevel(Level.ALL);

Now you can log like this:
log.debug("Whatever");
log.info("Blah Blah");
log.warn("Something looks insane");
log.error("Something went completely wrong");

A: It seems that it's impossible to output log in Eclipse console, but this is, in my opinion, the easiest workaround - to log into a file:
importPackage(Packages.java.io);
out = new PrintWriter(new FileWriter("d:/LOG.txt", true));
out.println("Test Event");
out.close();

You just have to put these 4 line in your script and you'll get logs in the file.


text:
Q: What if IEnumerable returns just one string I'm doing a simple Linq query on an XML file
IEnumerable<string> value = from item in myFile.Descendants("ProductName")
                            select (string)item;

Normally (If I have more than one row) I can iterate using a foreach loop :
foreach (string str in value)
{
    Console.WriteLine(str);
}

But what if I'm sure that I have just one item, And my method signature is :
public string getValue()
{
    return ?;
}

What should I return (If I want to remove the foreach loop) ?

A: If you are sure that there is always exactly one string, you can return value.Single().
Some more options:

*

*First()

*FirstOrDefault()

*SingleOrDefault()
It depends if you want to raise an exception if there are more than one element (use Single or SingleOrDefault), or no element at all (use First or Single).
If you always except exactly one element, I would stick with Single(), since it will throw an exception if there are zero or more than one element.

A: There are Single / SingleOrDefault and First / FirstOrDefault methods that can resolve an enumerable of elements down to one.
The Single method expects only one element and will exception if the result contains zero or more than one elements. Use SingleOrDefault to cope with zero as well as one.
The "First" pair can both handle more than one, but First again throws if there are no elements.
All of these methods come with an overload that allows you to specify conditions, negating the need to use a .Where call.
In your case:
string value = (from item in myFile.Descendants("ProductName")
                select (string)item)
               .SingleOrDefault();

When choosing between Single or First, use Single if you expect one element, use SingleOrDefault if you expect zero or one elements, and use First / FirstOrDefault (along with some sort of OrderBy) if you don't care how many elements are returned.
Also note, these methods use deferred execution, so once First is satisfied it stops iterating.

A: If you want to return only one item, then use FirstOrDefault():
public string getValue()
{
    IEnumerable<string> value = from item in myFile.Descendants("ProductName")
                        select (string)item;
    return value.FirstOrDefault();
}

A: If you are sure that you have only one and must be only one you should use Single .
This actually will throw an exception if you have more than one.


text:
Q: react button for refresh(re-call) API I have an API that gives me a random location each time I recall the API, and I want the button to just re-call the API.
I tried to use an arrow function and a normal function but I get a different error; my general idea is to wrap the fetching method with a function and then call this function twice, the first call before I render the component and the second call on this button.
These are my attempts:
(Note: my buggy function is handleOnClick)
 state = {
   isLoading: true,
   shop: null,
   error: null
 };

 componentDidMount() {
   // fix CORB and CORS issues by using proxy
   var proxyUrl = 'https://cors-anywhere.herokuapp.com/',
     targetUrl ='https://wainnakel.com/api/v1/GenerateFS.php?uid=26.2716025,50.2017993&g%20et_param=value';

     function handleOnClick() {
       fetch(proxyUrl + targetUrl)
     .then(res => res.json())
     .then(shop => {
       console.table(shop); // create table in console
       this.setState({
         shop ,
         isLoading:false,
       });
     })
     .catch(e => {
       console.log(e);
     });
   }

   handleOnClick();
 }

   showLocation = () => {
   var location = `${this.state.shop.lat}%2C%20${this.state.shop.lon}`;
  var gmapurl =`https://maps.google.com/maps?q=${location}&t=&z=17&ie=UTF8&iwloc=&output=embed`;
  return gmapurl;
};

 render() {

   const { isLoading, shop, error } = this.state; //no need to write this.state every time

   let gmapurl ;  //create variable that we will store the new location from the API

   return (

     <React.Fragment>
          <Navigation />

     {/* // Display a message if we faced an error */}
     {error ?
{error.message}
 : null}
     {!isLoading ? ( //   check data if it ready
     //and take lat and lon from api ,and place it in  embedded google map url
    gmapurl =`https://maps.google.com/maps?q=${this.state.shop.lat}%2C%20${this.state.shop.lon}&t=&z=17&ie=UTF8&iwloc=&output=embed`,

       shop ? (

 {this.state.shop.name}

        {/* MAP */}

map veiw

           <button className="btn" onClick={() =>  {handleOnClick}}>

أقتراح آخر</button>

 ) : ( '')
):(      // show loading icon if there is a delay in data

 )
     }

     </React.Fragment>
   );
 }
}

and this the error I got

  Line 82:  Expected an assignment or function call and instead saw an expression no-unused-expressions

  Line 82:  'handleOnClick' is not defined  no-undef

A: Your handleOnClick is a local function, that can only be called from inside componentDidMount. To be able to call it from anywhere inside the class, use a method. Maybe the name should be a bit more descriptive of the task that it actually does, e.g. loadShop:
 loadShop() {
   this.setState({ isLoading: true });

  fetch(proxyUrl + targetUrl)
    .then(res => res.json())
    .then(shop => {
      console.table(shop);
      this.setState({
         shop ,
         isLoading:false,
      });
     });
 }

Then you can call it from anywhere inside the class as this.loadShop(), e.g.
 <button onClick={() => this.loadShop()} >


text:
Q: how to use piwik with smartGWT hey all i am trying to use Piwik in smartGWT to make some statistics
the method i use is :
public static native void  PiwikReport(String email)/*-{
    window.alert("hello1");
    var pkBaseURL ="https://hpsmartplanner.com/piwik/piwik.js";
    var piwikTracker = Piwik.getTracker(pkBaseURL + "piwik.php", 1);
    piwikTracker.setCustomVariable(1,  "User Name",email , "page");
    piwikTracker.setCustomVariable(2,  "Type",  "Channel Partner" , "page");
    piwikTracker.setCustomVariable(3,  "Event",  "Signin" , "page");
    piwikTracker.trackPageView();
    window.alert("hello");
}-*/;

and in HTML file
   <!-- Piwik -->
    <script type="text/javascript" >
      var _paq = _paq || [];
      _paq.push(["trackPageView"]);
      _paq.push(["enableLinkTracking"]);

      (function() {
        var u=(("https:" == document.location.protocol) ? "https" : "http") + "://hpsmartplanner.com/piwik/";
        _paq.push(["setTrackerUrl", u+"piwik.php"]);
        _paq.push(["setSiteId", "1"]);
        var d=document, g=d.createElement("script"), s=d.getElementsByTagName("script")[0]; g.type="text/javascript";
        g.defer=true; g.async=true; g.src=u+"piwik.js"; s.parentNode.insertBefore(g,s);
      })();
    </script>
    <!-- End Piwik Code -->

it prints hello1 "the first alert" but it didn't  print the second one
can any one please provide any help ?
thanx.


text:
Q: Can a Templated User Control be used for data entry? I've found code examples that demonstrate templated user controls. They work fine for displaying data, but I can't get them to work for entering data. I have a TextBox in my template, and can change the value in it, but I can't get that changed value in my code. I attempt to get the user control's values in a button click handler, but I always get just the initial value. Also, when I click the button, the templated user control's value(s) are reset. Is data entry supposed to work with templated user controls?
My code is similar to the MSDN topic "How to: Create Templated ASP.NET User Controls".
Default.aspx ===============================
<%@ Page Language="C#" %>
<%@ Register TagPrefix="uc" tagname="TemplateTest" Src="TemplatedUC.ascx" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <title>Templated User Control Test</title>

Testing Templated User Control

<form id="Form2" runat="server">
    <uc:TemplateTest ID="TemplateTest1" runat="server">
      <MessageTemplate>
        Index: <asp:Label runat="server" ID="Label1" Text='<%# Container.Index %>' />

        Message: <asp:TextBox runat="server" ID="Label2" Text='<%# Container.Message %>' />

      </MessageTemplate>
    </uc:TemplateTest>
    <asp:Button ID="ButtonShowContent" runat="server" Text="Show Content" onclick="ButtonShowContent_Click"  />
    <asp:Label ID="ContentLabel" runat="server" Text=" " Width="100%" />
</form>

TemplatedUC.ascx ============================
<%@ Control Language="C#" ClassName="TemplatedUC" %>
<%@ Import Namespace="System.ComponentModel"  %>

<asp:Placeholder runat="server" ID="PlaceHolder1" />

If you run this and change the value for 'Message', then when you click the button, the data will be displayed. Thank you.


text:
Q: Laravel 4.2 Mandrill Not Working I really have no idea what the issue is, but there are no errors in the log... nothing is happening. Here's my configuration:
In app/config/mail.php
return array(

    'driver' => 'mandrill',

    'host' => 'smtp.mandrillapp.com',

    'port' => 587,

    'from' => array('address' => null, 'name' => null),

    'encryption' => 'tls',

    'username' => 'myemail@mydomain.com',

    'password' => 'my_api_key',

    'sendmail' => '/usr/sbin/sendmail -bs',

    'pretend' => false,

);

In app/config/services.php
return array(

    'mailgun' => array(
        'domain' => '',
        'secret' => '',
    ),

    'mandrill' => array(
        'secret' => 'my_api_key',
    ),

    'stripe' => array(
        'model'  => 'User',
        'secret' => '',
    ),

);

A: Laravel's documentation is a bit sparse ... I needed to include a "from" line in my send function:
$message->from('no-reply@mydomain.com', 'My Domain Sender');


text:
Q: Pass a structure to a C dll from C# and get the structure values assigned? My C code for dll creation is
  typedef struct st_struct{
     unsigned char a;
     unsigned char b;
   } st_struct;

  __declspec(dllexport) void  __stdcall ftn(st_struct *s )
{
     s->a =10;
     s->b =20;

}
My C # code code is as follows
namespace check_ex
{
    [Serializable]
    [StructLayout(LayoutKind.Sequential)]
    public class st_struct
    {
        public byte a;
        public byte b;
    };

[DllImport("exMydll.dll")]
public static extern void ftn(st_struct inputs);

    public Form1()
    {
        InitializeComponent();
        st_struct x = new st_struct();
        ftn(x);
        Console.Write(x.a, x.b);
    }
}


text:
Q: How to move site from Adobe Business Catalyst to Wordpress I have a site that I has been created in Adobe Business Catalyst. I am not a fan of this CMS. I am looking to change it to a WordPress site. Is there any easy way to do this? Is there any kind of conversion software or service? I want to keep all the file names and redirects, etc the same.

A: One of my clients wanted to leave Business Catalyst and merge it with a Wordpress.com blog. The way I got around Adobe's lack of export was as follows;

*

*I used my Linux Server to pull everything off the Adobe Servers using
wget --mirror -p --convert-links -P ./Local/Dir Website-ULR

*

*Tutorial Here, Number 10

All the HTML files came down without any extensions so;

*I copied the directory to my Mac and used Fork Lift to batch rename the files to add .html - though any renaming software will do.

The import tool for Wordpress needs an index file to find all your pages so I needed to make an index.html page with links to every post so;

*I copied them back to the Linux machine and used
tree -H baseHREF ./Local/Dir

*

*depending on OS you may need to download the tree package or similar.

This then generated an onscreen HTML file in the Terminal Window so;

*I copied the HTML code it created and put it into Dreamweaver with the rest of the site, though any software will do, to run a batch clean up of the links.

As Wordpress.com doesn't allow you to install plugins I needed to put it on a my local installation of Wordpress to do the import.

*I then used the Import HTML 2 plugin to get the pages into my local Wordpress installation

As I was moving the files to a Wordpress.com site;

*Export from from my Wordpress and import into their blog.

I hope this helps anyone, in total it took me 12 hours to find all the tools I needed and to work out all the steps I needed. If i needed to do it again it would take up to an hour now I know how to do it.
I had more links in the post but as I'm new to the forum I was only allow 2.
Better people than I might be able tell you a quicker way to do this.

A: The only things that can be "exported" in Business Catalyst are E-commerce products and Web App items - they can be exported as .CSV files. You can then hire a programmer to convert them over to a format that works with Wordpress.
Exporting blogs from the Business Catalyst blog module is tricky - one way to do it is to enable RSS and copy the RSS feed and open it in excel to save it as a .CSV or .TAB file where you may be able to import the blogs or get a programmer to convert it into soomething Wordpress compatible.

A: Thank you for taking time to better explain your platform to me.
In the way of an answer, I recommend the following:

*

*Export your current web site details into a csv file using Screaming Frog.

*Then use the CVS Importer WordPress Plugin

This is working for me. I would still be pleased to hear if others have found a process that they also find suitable.


text:
Q: Mouse-over pop-up in Java For an application I'm building in Java, I'm trying to get my program to display a pop-up message when certain objects are hovered over with the mouse. I know how to use mouseEntered() and mouseExited() for knowing if the objects are being hovered over, but I don't know how to actually display the pop-up message itself.
I was thinking of using a JOptionPane, but have no idea how to close the pop-up without the user having to manually close it. Any input would be greatly appreciated.
Thanks


text:
Q: Cinema Booking System with C# I am building a cinema booking system with C# using Visual Studio. The main code I have designed for the program is shown below, absent the classes I have created to hold film, screen, customer, and showing data.
namespace Glosflix
{
    public partial class NewBooking : Form
    {
        public List<Film> filmList = new List<Film>();
        public List<Showing> showingList = new List<Showing>();
        public NewBooking()
        {
            InitializeComponent();
            filmList.Add(new Film("Ida", 90, "15", "A young novitiate discovers the fate that befell her Jewish parents during the Nazi occupation of Poland."));
            filmList.Add(new Film("Leviathan", 147, "15", "Modern retelling of Job, set in the Barents Sea."));
            filmList.Add(new Film("Grand Budapest Hotel", 100, "15", " A hotel concierge inherits a fortune from an aristocrat, and the wrath of her disappointed heirs."));
            Screen screenA = new Screen(250, "1");
            Screen screenB = new Screen(150, "2");
            Screen screenC = new Screen(120, "3");
            showingList.Add(new Showing(512, screenA, filmList[0], "9:00"));
            showingList.Add(new Showing(612, screenA, filmList[0], "15:00"));
            showingList.Add(new Showing(712, screenB, filmList[1], "10:00"));
            showingList.Add(new Showing(812, screenB, filmList[1], "16:00"));
            showingList.Add(new Showing(912, screenC, filmList[2], "12:00"));
            showingList.Add(new Showing(412, screenC, filmList[2], "21:00"));
            Customer customerA = new Customer(5238, "Thomas Stearns");
            cmbTickets.Items.Add(1);
            cmbTickets.Items.Add(2);
            cmbTickets.Items.Add(3);
            cmbTickets.Items.Add(4);
            cmbTickets.Items.Add(5);
            cmbTickets.Items.Add(6);
            cmbTickets.Items.Add(7);
            cmbTickets.Items.Add(8);
            cmbTickets.Items.Add(9);
            cmbTickets.Items.Add(10);

        }

        private void NewBooking_Load(object sender, EventArgs e)
        {
            foreach (Film i in filmList)
                cmbFilm.Items.Add(i.getTitle());
        }

        private void cmbFilm_SelectedIndexChanged(object sender, EventArgs e)
        {
            cmbShowing.Items.Clear();
            String filmTitle = cmbFilm.SelectedItem.ToString();

            foreach (Showing i in showingList)
            {
                if (filmTitle.Equals(i.getFilm().getTitle()))
                {
                  cmbShowing.Items.Add(i.getTime());

                }
            }

            cmbShowing.Enabled = true;
        }

        private void btnBook_Click(object sender, EventArgs e)
        {
            if (cmbShowing.SelectedIndex == -1)
            {
                MessageBox.Show("Please select a film and showing.");
            }
            else if (cmbTickets.SelectedIndex == -1)
            {
                MessageBox.Show("Please select the number of tickets required.");

            }

        }

    }
}

In the code, to make a booking the user interacts with a combobox holding the titles of all available films. This loads all of the showing times associated with the film in a separate combobox. A final combobox holds the values 1 to 10, in which the user chooses the number of tickets they require for their booking.
I want when the user clicks on the book button on the program's interface, all of the information about the showing is displayed in a listbox, based on the information that the user has entered in the interface's comboboxes. I'd also like the program to calculate the total cost of the booking based on the number of tickets the user has selected, and display this in the combobox.
I assume that the best way to implement this would be to create a booking class with a method contained inside it that would multiply the seat number entered with the cost of a cinema ticket, to produce an overall booking cost. How do I go about this?


text:
Q: Easy way to implement a Root Raised Cosine (RRC) filter using Python & Numpy SciPy/Numpy seems to support many filters, but not the root-raised cosine filter.  Is there a trick to easily create one rather than calculating the transfer function?  An approximation would be fine as well.

A: The commpy package has several filters included with it.  The order of return variables was switched in an earlier version (as of this edit, current version is 0.7.0).  To install, foemphasized textllow instructions here or here.
Here's a use example for 1024 symbols of QAM16:
import numpy as np
from commpy.modulation import QAMModem
from commpy.filters import rrcosfilter
N = 1024  # Number of symbols
os = 8 #over sampling factor
# Create modulation. QAM16 makes 4 bits/symbol
mod1 = QAMModem(16)
# Generate the bit stream for N symbols
sB = np.random.randint(0, 2, N*mod1.num_bits_symbol)
# Generate N complex-integer valued symbols
sQ = mod1.modulate(sB)
sQ_upsampled = np.zeros(os*(len(sQ)-1)+1,dtype = np.complex64)
sQ_upsampled[::os] = sQ
# Create a filter with limited bandwidth. Parameters:
#      N: Filter length in samples
#    0.8: Roll off factor alpha
#      1: Symbol period in time-units
#     24: Sample rate in 1/time-units
sPSF = rrcosfilter(N, alpha=0.8, Ts=1, Fs=over_sample)[1]
# Analog signal has N/2 leading and trailing near-zero samples
qW = np.convolve(sPSF, sQ_upsampled)

Here's some explanation of the parameters. N is the number of baud samples. You need 4 times as many bits (in the case of QAM) as samples. I made the sPSF array return with N elements so we can see the signal with leading and trailing samples. See the Wikipedia Root-raised-cosine filter page for explanation of parameter alpha. Ts is the symbol period in seconds and Fs is the number of filter samples per Ts. I like to pretend Ts=1 to keep things simple (unit symbol rate). Then Fs is the number of complex waveform samples per baud point.
If you use return element 0 from rrcosfilter to get the sample time indexes, you need to insert the correct symbol period and filter sample rate in Ts and Fs for the index values to be correctly scaled.

A: It would be nice to have the root-raised cosine filter standardized in a common package. Here is my implementation in the meantime based on commpy. It vectorized with numpy, and normalized without consideration of the symbol rate.
def raised_root_cosine(upsample, num_positive_lobes, alpha):
    """
    Root raised cosine (RRC) filter (FIR) impulse response.

    upsample: number of samples per symbol

    num_positive_lobes: number of positive overlaping symbols
    length of filter is 2 * num_positive_lobes + 1 samples

    alpha: roll-off factor
    """

    N = upsample * (num_positive_lobes * 2 + 1)
    t = (np.arange(N) - N / 2) / upsample

    # result vector
    h_rrc = np.zeros(t.size, dtype=np.float)

    # index for special cases
    sample_i = np.zeros(t.size, dtype=np.bool)

    # deal with special cases
    subi = t == 0
    sample_i = np.bitwise_or(sample_i, subi)
    h_rrc[subi] = 1.0 - alpha + (4 * alpha / np.pi)

    subi = np.abs(t) == 1 / (4 * alpha)
    sample_i = np.bitwise_or(sample_i, subi)
    h_rrc[subi] = (alpha / np.sqrt(2)) \
                * (((1 + 2 / np.pi) * (np.sin(np.pi / (4 * alpha))))
                + ((1 - 2 / np.pi) * (np.cos(np.pi / (4 * alpha)))))

    # base case
    sample_i = np.bitwise_not(sample_i)
    ti = t[sample_i]
    h_rrc[sample_i] = np.sin(np.pi * ti * (1 - alpha)) \
                    + 4 * alpha * ti * np.cos(np.pi * ti * (1 + alpha))
    h_rrc[sample_i] /= (np.pi * ti * (1 - (4 * alpha * ti) ** 2))

    return h_rrc

A: commpy doesn't seem to be released yet.  But here is my nugget of knowledge.
beta = 0.20 # roll off factor

Tsample = 1.0 # sampling period, should at least twice the rate of the symbol

oversampling_rate = 8 # oversampling of the bit stream, this gives samples per symbol
# must be at least 2X the bit rate

Tsymbol = oversampling_rate * Tsample # pulse duration should be at least 2 * Ts
span = 50 # number of symbols to span, must be even
n = span*oversampling_rate # length of the filter = samples per symbol * symbol span

# t_step must be from -span/2 to +span/2 symbols.
# each symbol has 'sps' number of samples per second.
t_step = Tsample * np.linspace(-n/2,n/2,n+1) # n+1 to include 0 time

BW = (1 + beta) / Tsymbol
a = np.zeros_like(t_step)

for item in list(enumerate(t_step)):
    i,t = item
    # t is n*Ts
    if (1-(2.0*beta*t/Tsymbol)**2) == 0:
        a[i] = np.pi/4 * np.sinc(t/Tsymbol)
        print 'i = %d' % i
    elif t == 0:
        a[i] = np.cos(beta * np.pi * t / Tsymbol)/ (1-(2.0*beta*t/Tsymbol)**2)
        print 't = 0 captured'
        print 'i = %d' % i

    else:
        numerator = np.sinc( np.pi * t/Tsymbol )*np.cos( np.pi*beta*t/Tsymbol )
        denominator = (1.0 - (2.0*beta*t/Tsymbol)**2)
        a[i] =  numerator / denominator

#a = a/sum(a) # normalize total power

plot_filter = 0
if plot_filter == 1:

    w,h = signal.freqz(a)
    fig = plt.figure()
    plt.subplot(2,1,1)
    plt.title('Digital filter (raised cosine) frequency response')
    ax1 = fig.add_subplot(211)
    plt.plot(w/np.pi, 20*np.log10(abs(h)),'b')
    #plt.plot(w/np.pi, abs(h),'b')
    plt.ylabel('Amplitude (dB)', color = 'b')
    plt.xlabel(r'Normalized Frequency ($\pi$ rad/sample)')

    ax2 = ax1.twinx()
    angles = np.unwrap(np.angle(h))
    plt.plot(w/np.pi, angles, 'g')
    plt.ylabel('Angle (radians)', color = 'g')
    plt.grid()
    plt.axis('tight')
    plt.show()

    plt.subplot(2,1,2)
    plt.stem(a)
    plt.show()

A: I think the correct response is to generate the desire impulse response. For a raised cosine filter the function is
h(n) = (sinc(n/T)*cos(pi * alpha* n /T)) / (1-4*(alpha*n/T)**2)

Select the number of points for your filter and generate the weights.
output = scipy.signal.convolve(signal_in, h)

A: This is basically the same function as in CommPy but much smaller in code:
def rcosfilter(N, beta, Ts, Fs):
    t = (np.arange(N) - N / 2) / Fs
    return np.where(np.abs(2*t) == Ts / beta,
        np.pi / 4 * np.sinc(t/Ts),
        np.sinc(t/Ts) * np.cos(np.pi*beta*t/Ts) / (1 - (2*beta*t/Ts) ** 2))

A: SciPy will support any filter.  Just calculate the impulse response and use any of the appropriate scipy.signal filter/convolve functions.


text:
Q: Browse links recursively using selenium I'd like to know if is it possible to browse all links in a site (including the parent links and sublinks) using python selenium (example: yahoo.com),

*

* fetch all links in the homepage,

* open each one of them

* open all the links in the sublinks to three four levels.

I'm using selenium on python.
Thanks
Ala'a

A: Sure it is possible, but you have to instruct selenium to enter these links one by one as you are working within one browser.
In case, the pages are not having the links rendered by JavaScript in the browser, it would be much more efficient to fetch these pages by direct http request and process it this way. In this case I would recommend using requests. However, even with requests it is up to your code to locate all urls in the page and follow up with fetching those pages.
There might be also other Python packages, which are specialized on this kind of task, but here I cannot serve with real experience.

A: You want "web-scraping" software like Scrapy and possibly Beautifulsoup4 - the first is used to build a program called a "spider" which "crawls" through web pages, extracting structured data from them, and following certain (or all) links in them. BS4 is also for extracting data from web pages, and combined with libraries like requests can be used to build your own spider, though at this point something like Scrapy is probably more relevant to what you need.
There are numerous tutorials and examples out there to help you - just start with the google search I linked above.


text:
Q: how to auto redirect on login link click to admin page if user already logged in How to do this ...
i have a login page link above the page /// i want if user already loggedin then anybody click on loginlink then the user will automatically redirect to default.aspx ..
how to do this using vb.net ?

A: If user login then mentioned the session like this:
if(login==true)
{
    sesssion["UID"]=txtUserID.Text.ToString();
}

Then, after user click on the login link then check:
if(session["UID"]!=null)
{
    response.redirect("default.aspx");
}
else
{
    response.redirect("LoginPage.aspx");
}

A: try
Page.User.Identity.IsAuthenticated ==true

A: You have two built-in options when using Membership / Forms Authentication:
1: Use LoginStatus control instead of external link. It will automatically change to Logout when user is logged-in.
Or
2: Use LoginView to display your login and Logout links.


text:
Q: Solve $\sin(x) = 4 \sin(60 ^{\circ} -x)\sin(6 ^{\circ} )\sin(18 ^{\circ} ) $ Solve
$$\sin(x) = 4 \sin(60 ^{\circ} -x)\sin(6 ^{\circ} )\sin(18 ^{\circ} ) $$
under degrees (not radians).
There is a well known identity
$$4 \sin x \sin(60 ^{\circ} −x) \sin(60 ^{\circ} +x) = \sin3x$$
but it doesn't quite help here. I can guess a solution $x = 6^{\circ} $, but I would like a more satisfactory solution other than guessing ...

A: Take five points equally spaced around the circle.  Their centre is at the origin, so
$$\cos0^o+\cos72^o+\cos144^o+\cos216^o+\cos288^o=0\\
\cos36^o-\cos72^o=1/2\\
2\sin54^o\sin18^o=1/2\\
\sin6^o=4\sin54^o\sin6^o\sin18^o$$

A: Apply $\sin(60-x)=\frac{\sqrt3}2\cos x -\frac12\sin x$ and
rearrange the equation to isolate $x$
\begin{align}
\cot x &=\frac{1+2 \sin6\sin18} {2\sqrt3\sin 6\sin 18}
\end{align}
Then, substitute $ \sin 18 =\frac{\sin36}{2\cos18}
= \frac{\sin72}{4\cos18\cos36}
= \frac1{4\cos36}$
to obtain
\begin{align}
\cot x &=\frac{2\cos36+\sin6} {\sqrt3\sin 6}
=\frac{\cos36+(\sin54 +\sin6)} {\sqrt3\sin 6}\\
&=\frac{\cos36+\cos24} {\sqrt3\sin 6}
= \frac{2\cos30\cos6} {\sqrt3\sin 6}= \cot 6
\end{align}
Thus, $x = 6^\circ+ 180^\circ n$.


text:
Q: Do I need to learn about objects, or can I save time and just learn dictionaries? OK to be short =)
I'm noob yes. -.- but I'm convinced i don't need to learn everything.. and that a specific field of knowledge suited to my project may save me time..?
I'm going to build a game that i have designed but not begun constructing.
I'm going to learn everything i need to to get my project finished.
however to save time...
I'm using python
the game needs only to reference locations on a grid with values:
so a green 'pine tree' square = *information *values = tree type / tree's hardness / tree's life ect...
I am perhaps wrong in the assumption there are no objects needed? should i focus all my time on learning how to use the dictionary's function..
what is the most efficient coding for a grid based tile game that simulates change per turn.
So that; a blue square spreads according to sets of rules and according to the adjacent tiles at the end of a turn. And these tiles have values attached...? even just the name of the best feasible technique... i can learn how to do it once i know what i need to learn...

A: Any Python project of any size will become unmanageable without objects.
Is it possible to use modules as your objects instead of classes? Yes, if you really want to. (In Python, a module is what you call a single file.)
However, even if you aren't creating user-defined classes, you still need to learn how to use objects.
Why? Because everything is an object in Python. You need to at least know how to use objects to understand how to use the built in types and functions in Python.
In Python, dictionaries are very important to how things are implemented internally, so your intuition that dictionaries would be an alternative is good.
But dictionaries are objects too, so you'd still have to learn to use objects, without getting the benefit of their ease of use for many things vs. a plain dictionary.
My advice? Do a Python tutorial (or three). The whole thing. Even the parts on networking, or whatever else you don't think you'll be using. You'll learn things about the language that you'll end up using later in ways you'd never anticipate.
Do you need to learn about metaclasses? No. Multiprocessing? No. But you need to learn all of the core language features, and classes and object oriented programming are the core language feature. It's so central to nearly all modern languages that people don't even mention it any more.

A: I disagree that you should learn everything up front.  I think it's just fine to learn parts of the language only as and when you need them.
But in Python you can't really avoid learning something about objects. Everything is an object. A string or an int or any other data type is an object. More relevantly, anything you import is an object. You won't be able to get very far in any project without importing existing features at some point, so you will have to work with an object-oriented interface.
So could you get away without learning how to define your own class of objects? In principle yes.  But to understand the basics is trivial, and then you can learn the rest as you need it.
Class MyObject(object):
    pass

Easy to learn! Now you have a custom type (a class) of object. You can create an actual object by calling m = MyObject(). This class provides almost exactly the same functionality as a dictionary. But you can start with this and then, when you need it, you can add more functionality (inheritance, methods, ...).  If you start with a dictionary when an object is appropriate, you will just paint yourself into a corner.


text:
Q: Trying to space 2 divs between each other at the bottom I am trying to make the following happen:

*

*On image hover, at the bottom it will show comments/reactions on the left and name on the right

I cannot get the 2 divs to space between at the bottom and I do not know why.
https://play.tailwindcss.com/jyBq62Ok90 is the working code

A: You need to set a width, e.g. w-full on the absolute positioned div. Otherwise the div will be as wide as the content and there will be no space between.
See this tailwind play
Hope this helps.

A: As far as I understood , you need to highlight the comment div below as you hover the image with a space between two divs
You can use group-hover utility with a div wrapper. Below code will help you much more

        <ChatAlt2Icon class="h-5 w-5 text-white" />
        12
        <HeartIcon class="ml-2 h-5 w-5 text-white" />
        12

Added: Today