Q:

Android: ListView header and footer Behavior is not displaying properly

This is the view when i'm scrolling it.. it added extra layout that expand some space within my listview item

What listview properties should i assign to fix it?
Here is my List View

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <ListView
        android:id="@+id/listView"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:paddingLeft="10dp"
        android:paddingRight="10dp"
        android:scrollbarStyle="outsideOverlay"
        android:overScrollMode="never"
        android:saveEnabled="false" />
</LinearLayout>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
    <RelativeLayout
        android:id="@+id/relativeHeader"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:background="@android:color/transparent"
        android:cacheColorHint="@android:color/transparent" >

        <LinearLayout
            android:id="@+id/linearNumber"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_alignParentTop="true"
            android:layout_marginBottom="10dp"
            android:paddingBottom="5dp"
            android:paddingTop="5dp" >

            <TextView
                android:id="@+id/textViewNumber"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:gravity="center_vertical|left"
                android:text="Number: "
                android:textStyle="bold"
                android:textColor="#000000" />

            <TextView
                android:id="@+id/textViewNumberValue"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:gravity="center_vertical|left"
                android:text="222-222-222-222"
                android:textColor="#000000" />
        </LinearLayout>
    </RelativeLayout>
</LinearLayout>

My Initialization of ListView

    private void setupListViewAdapter(ListView listView, View headerView, View footerView){
    listView.setDividerHeight(5);
    listView.setFadingEdgeLength(200);
    listView.addHeaderView(headerView, null, false);
    listView.addFooterView(footerView, null, false);
    listView.setFastScrollEnabled(false);
    listView.setAdapter(mDataAdapter);
}

A:

This code made my listview display unwanted view.

  private void initListView(LayoutInflater inflater, ViewGroup container) {
    View headerViewROR = inflater.inflate(R.layout.vp_ror_header, null,false);
    View footerViewROR = inflater.inflate(R.layout.vp_remarks_footer, null,false);

    listView.addHeaderView(headerViewROR, null, false); //--> multiple occurrence need to be removed
    listView.addFooterView(footerViewROR, null, false); //--> multiple occurrence need to be removed
    setupListViewAdapter(listView, headerViewROR,footerViewROR);
}

Initialize adding header and footer twice that causes the listview behavior.. because i also called the listView.addFooterView to my setupListViewAdapter function.

    private void setupListViewAdapter(ListView listView, View headerView, View footerView){
    listView.setDividerHeight(5);
    listView.setFadingEdgeLength(200);
    listView.addHeaderView(headerView, null, false);//--> here is another assignment
    listView.addFooterView(footerView, null, false);//--> here is another assignment
    listView.setScrollingCacheEnabled(false);
    listView.requestFocus(0);
    listView.setAdapter(mDataAdapter);
}


Q:

Quickly append value to a list

PHP has a really quick way to append a value to an array:
$array[] = 'value';

What is the easiest way to do this in python without needing an index number?
 Also, is there an easy way to do this with a list nested inside a dictionary, like this PHP equivalent..
$array['associative'][] = 'value';

A:

my_list.append(value)

or
my_dict[key].append(value)


Q:

ListView, image and SQL question

I have the next code:
    <asp:ListView ID="moreI"
    runat="server"
    DataSourceID="LinqDataSource1" onprerender="moreI_PreRender">

    <ItemTemplate>

            <asp:Image ID="Image1" Width="100px" Height="100px" runat="server" ImageUrl='<%# Eval("ImageUrl") %>' />
 // and so on till the </ItemTemplate> and </asp:ListView>

I have the next method:
    protected void checkTheImage()
{
    foreach (ListViewItem item in moreI.Items)
    {
        ((Image)item.FindControl("Image1")).ImageUrl = "noImage.jpg";
    }
}

And the sql
    protected Boolean ImageCheck()
{
    SqlConnection connection = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\***.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");
    string CommandText2 = "SELECT noImage FROM Machreta WHERE noImage = 1";
    SqlCommand command2 = new SqlCommand(CommandText2, connection);
    connection.Open();
    Boolean check = (Boolean)command2.ExecuteScalar();
    connection.Close();

    //here i stoped without the return.

I have the table Machreta with the column noImage (bit).

where the noImage = true, i want to show the noImage.jpg from the checkTheImage()
where the noImage = false, i want to show the '<%# Eval("ImageUrl") %>'

I have problem with the logic, maybe too many hours of work... what can you suggest me?

A:

I think you need to update the datasource that bind to the listview to contain the boolean variable that specify if to use the ImageUrl or the noimage.jpeg

<asp:ListView ID="moreI"
    runat="server"
    DataSourceID="LinqDataSource1" onprerender="moreI_PreRender">

    <ItemTemplate>

            <asp:Image ID="Image1" Width="100px" Height="100px" runat="server" ImageUrl='<%# checkImage(Eval("ImageUrl"), Eval("noImage")) %>' />
 // and so on till the </ItemTemplate> and </asp:ListView>

  protected string checkTheImage(object ImageUrl, object noImage)
{
    if((bool)noImage)
    {
        return "noImage.jpg";
    }
else
{
return ImageUrl.ToString();
}
}


Q:

Aside and Article overlapping the header

I'm remaking a website for Old Treasures Furniture and Imports in HTML5.
I have an issue with the positioning of the aside and article tags. They seem to like the header so much that they are on top of him.
I have tried to set the position of the two (aside and article) to relative, absolute, fixed. I have tried overflow: hidden; on both as someone suggested in another thread i read. None have positioned them correctly as they should appear:
__________________________
|Header                  |
|------------------------|
|aside|article           |
|     |                  |
|_____|__________________|
|footer                  |
|------------------------|

Only footer is in his correct position.
My index.php:
<!DOCTYPE html>

<link href="01d7r345ur3557y13.css" rel="stylesheet" type="text/css" />

<link rel="shortcut icon" href="http://i.imgur.com/V6a6eGp.png" />
<title>Old Treasures Furniture and Imports</title>

    <?php
        include("aside.php");
    ?>

Welcome to Old Treasures Furniture and Imports,
We are a company dedicated to the manufacture and marketing of solid wood products.
Our services are oriented to decorators, builders, architects and clients like you.

    <?php
        include("footer.php");
    ?>

And my 01d7r345ur3557y13.css:
(I omitted the rest of the CSS, i doubt they have an effect in this.)
body {
margin: 0;
padding: 0;
background: url("http://i.imgur.com/kRh8uzK.png?1") fixed;
}
header {
width: 65%;
height: 250px;
background-image: url("http://i.imgur.com/jxzkFhn.jpg");
background-size: 100% 100%;
margin: 20px auto;
border-top-left-radius: 10px;
border-top-right-radius: 10px;
}
article {
border: 1px #fff solid;
overflow: hidden;
}
footer {
background: url("http://i.imgur.com/x1WvVZp.png");
text-align: center;
color: #FFF;
}
footer p {
font-size: 10px;
}
header, footer, aside, article {
display: block;
}

/*Page Navigation*/
aside {
float: left;
width: 120px;
margin: 0;
}
aside li {
display: block;
}
aside ul {
margin: 0;
padding: 0;
}
.home {
background: url("http://i.imgur.com/ma42CHH.png");
transition: background .25s ease-in-out;
-moz-transition: background .25s ease-in-out;
webkit-transition: background .25s ease-in-out;
width: 119px;
height: 31px;
}
.home:hover {
background: url("http://i.imgur.com/iKLHtvh.png")
}
.products {
background: url("http://i.imgur.com/sqBqNwp.png");
transition: background .25s ease-in-out;
-moz-transition: background .25s ease-in-out;
webkit-transition: background .25s ease-in-out;
width: 119px;
height: 31px;
}
.products:hover {
background: url("http://i.imgur.com/hRGXnqt.png?1");
}
.services {
background: url("");
transition: background .25s ease-in-out;
-moz-transition: background .25s ease-in-out;
webkit-transition: background .25s ease-in-out;
width: 119px;
height: 31px;
}
.services:hover {
background: url("");
}
.contact {
background: url("http://i.imgur.com/etMulj7.png");
transition: background .25s ease-in-out;
-moz-transition: background .25s ease-in-out;
webkit-transition: background .25s ease-in-out;
width: 119px;
height: 31px;
}
.contact:hover {
background: url("http://i.imgur.com/v4ZA6LH.png");
}

As of now, i'm still trying other methods to accomplish this issue. Many thanks!
This is the current website and how the positioning of the elements are supposed to be.
http://www.oldtreasuresfurniture.com/
And this is what I'm currently getting:

A:

1) One issue I can see here is, you have used header tag as a self closing tag.
2) Make sure you have cleared the float at necessary places e.g. - http://www.w3schools.com/cssref/pr_class_clear.asp
3) It would be more helpful to debug, if you share URL of the page where you are facing the issue.


Q:

Disable caps lock on backspace in iPhone

My iPhone (3gs) has this behavior:

I'm typing a text and I put a certain letter in caps
I might decide the letter shouldn't be in caps so I press backspace (a couple of times if I've typed a lot after the capped letter).
when I do this, my iPhone remembers the letter was in caps and already puts on caps (the upward arrow is glowing).

I don't want this (the last bullet). how can I disable it? I've checked the preferences and disabled settings -> general -> keyboard -> Auto-Capitalization and settings -> general -> keyboard -> Enable Caps Lock, yet to no avail.

A:

It happens because you hit caps before typing a letter, so what the iPhone is doing is rather deleting all the code associated with that letter, it deletes the letter leaving the code, so if you backspace again it removes all the code from that space and moves back another space.
If you backspace one step further it removes this formatting.
The settings you have changed do not relate to your issue.
The first is to capitalize proper nouns that grammatically require a capital (which I wish would happen on all applications) the second is to enable the locking of the caps key, which means if you tap it twice in quick succession it will lock in uppercase.


Q:

Chrome Extension Notification Buttons not showing on MacOs/OSX

I'm currently working on a Chrome Extension using the Notification Api. On Chrome in Windows and Linux its working ok, but in MacOs / OSX the notification is being shown without the button. I tried to look any information in Chrome Notification API but they doesn't say anything about buttons not working for MacOS users like for other functionality as imageURL or appIconMaskUrl.
This is the declaration of my notification on the extension:
        type: "basic",
        title: message.participant + " has arrived!",
        message: message.description,
        iconUrl: "icon.jpg",
        buttons: [{title:'Go to Project'}]

A:

AFAIK, from the recent update, the action button icons will not be used and the user will need to hover over the notification and select the "More" button to see the available actions.
From this GitHub post,

To enable actions on the notification (the buttons that allow the user to select an option), open System Preferences > Notifications, select terminal-notifer in the sidebar, and select the "Alerts" alert style.


Q:

How can I add a section to a web.config using PowerShell?

How can I add a section to system.serviceModel in a web.config, if it doesn't already exist?
Before:
<system.serviceModel>
  <serviceHostingEnvironment aspNetCompatibilityEnabled="true" />
</system.serviceModel>

After:
<system.serviceModel>
 <serviceHostingEnvironment aspNetCompatibilityEnabled="true" />
 <bindings>
      <basicHttpBinding>
        <binding name="ValidationServiceSoap" closeTimeout="00:01:00" openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00" allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard" maxBufferSize="65536" maxBufferPoolSize="524288" maxReceivedMessageSize="65536" messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered" useDefaultWebProxy="true">
          <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384" maxBytesPerRead="4096" maxNameTableCharCount="16384" />
          <security mode="Transport">
            <transport clientCredentialType="Ntlm" />
            <message clientCredentialType="UserName" />
          </security>
        </binding>
      </basicHttpBinding>
 <bindings>
</system.serviceModel>

A:

It's not too bad to do this in PowerShell:
$origXml = [xml]@'
<configuration>
<system.serviceModel>
  <serviceHostingEnvironment aspNetCompatibilityEnabled="true" />
</system.serviceModel>
</configuration>
'@

$newXml = @'
 <bindings>
      <basicHttpBinding>
        <binding name="ValidationServiceSoap" closeTimeout="00:01:00" openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00" allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard" maxBufferSize="65536" maxBufferPoolSize="524288" maxReceivedMessageSize="65536" messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered" useDefaultWebProxy="true">
          <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384" maxBytesPerRead="4096" maxNameTableCharCount="16384" />
          <security mode="Transport">
            <transport clientCredentialType="Ntlm" />
            <message clientCredentialType="UserName" />
          </security>
        </binding>
      </basicHttpBinding>
 </bindings>
'@

if (!$origXml.configuration.'system.serviceModel'.bindings)
{
    $tempXmlDoc = new-object System.Xml.XmlDocument
    $tempXmlDoc.LoadXml($newXml)
    $newNode = $origXml.ImportNode($tempXmlDoc.DocumentElement, $true)
    $origXml.configuration.'system.serviceModel'.AppendChild($newNode)
}

Note that this approach only works because the XML you want to inject has a single root element <bindings>.


Q:

nginx is not showing custom error page with uwsgi

I'm trying to add a custom error page for 502 and 504 answers. Currently I have the following nginx configuration for my site (other configuration files are untouched):
server {
    listen       80;
    listen       [::]:80;

    server_name 10.12.112.163;

    add_header X-UA-Compatible "IE=Edge,chrome=1";
    add_header X-Content-Type-Options nosniff;
    add_header X-XSS-Protection "1; mode=block";

    charset utf-8;
    try_files $uri @icons;

    error_page 502 504 /502.html;
    location = /502.html {
       root /home/dmoj/site;
       internal;
    }

    location @icons {
        root /home/dmoj/site/resources/icons;
        error_page 403 404 = @uwsgi;
        log_not_found off;
    }

    location @uwsgi {
        uwsgi_read_timeout 600;
        uwsgi_pass unix:///tmp/dmoj-site.sock;
        include uwsgi_params;
    }
}

When I have uwsgi stopped and take my browser to 10.12.112.163 the default '502 Bad Gateway' message of nginx is showed, however when I go to 10.12.112.163/502.html my page displays perfectly.
I also tested it without the internal directive and it is the same.

A:

Not sure if it's documented somewhere, but I don't think error_page can be chained to another error_page.
In your case, the error_page 404 is very similar to the behaviour of the try_files statement. See this document for details.
So your chained error_page can be replace, like this:
location @icons {
    root /home/dmoj/site/resources/icons;
    try_files $uri @uwsgi;
    log_not_found off;
}


Q:

Is timestampdiff() in MySQL equivalent to datediff() in SQL Server?

I am working on migrating functions from SQL Server 2000 to MySQL.
The following statement executed in SQL Server 2000, gives the output as 109.
SELECT DATEDIFF(wk,'2012-09-01','2014-10-01') AS NoOfWeekends1

The equivalent query of in mysql uses timestampdiff() instead of datediff and gives the output as 108.
SELECT TIMESTAMPDIFF(WEEK, '2012-09-01', '2014-10-01') AS NoOfWeekends1

I need the output to match when executed in MySQL, so it returns 109.

A:

I think this could be caused by one of 2 things:

What is classified as the first day of the week between your SQL Server and MySQL instances.
How weeks are counted between SQL Server and MySQL

Your given date 2012-09-01 falls on a Saturday, which seems to rule out the start day of the week, which is usually Sunday or Monday.
MySQL has a default start day of: 0 (Sunday)
To find out your SQL Server start of the week you can use @@DATEFIRST by running this:
select @@DATEFIRST -- default US English = 7 (Sunday)

You could change your calculation to work on days rather than weeks and dividing by 7 to get a more accurate value, which you can round as you please:
MySQL: SQL Fiddle Demo
SELECT TIMESTAMPDIFF(DAY, '2012-09-01', '2014-10-01')/7 AS NoOfWeekends1

| NOOFWEEKENDS1 |
|---------------|
|      108.5714 |

SQL Server: SQL Fiddle Demo:
SELECT DATEDIFF(d,'2012-09-01','2014-10-01')/7.0 AS NoOfWeekends1

| NOOFWEEKENDS1 |
|---------------|
|    108.571428 |

You could round that up or down depending on if you want to match your previous result or count it as an extra weekend.
SQL Server seems to count the number of Sundays (if that's the start of the week) between 2 dates as shown with this example fiddle where I've changed the date range to be 2 days, a Saturday and a Sunday:
SELECT DATEDIFF(wk,'2012-09-01','2012-09-02') AS NoOfWeekends1

| NOOFWEEKENDS1 |
|---------------|
|             1 |

Where as the same values in MySQL seems to only count a full 7 days as a week as shown in this demo fiddle:
SELECT TIMESTAMPDIFF(WEEK, '2012-09-01', '2012-09-02') AS NoOfWeekends1

| NOOFWEEKENDS1 |
|---------------|
|             0 |

It's only when a full 7 days pass you get the result of 1 as you can see in this demo fiddle:
SELECT TIMESTAMPDIFF(WEEK, '2012-09-01', '2012-09-08') AS NoOfWeekends1

| NOOFWEEKENDS1 |
|---------------|
|             1 |


Q:

How to set up password check on unmounting NTFS partitions?

I have dual boot PC laptop with Windows 7 and Ubuntu 14.04. My PC has two hard drivers:
/dev/sda - that is SSD drive containing Windows C: NTFS partition and Ubuntu / and swap filesystems.
/dev/sdb - that is traditional hard disk drive containing Windows D: NTFS partition
I want to have both of my NTFS partitions mounted automatically and read-only.
Ubuntu 14.04 automatically mounts both NTFS partitions, but read-write, which is not exactly what I want. So I created mount directories under /media and added the following lines to my /etc/fstab:
# Windows C: /dev/sda1
UUID=2EF64975F6493DF9   /media/win_c    ntfs    defaults,umask=222      0  0
# Windows D: /dev/sdb1
UUID=50C40C08C40BEED2   /media/win_d    ntfs    defaults,umask=222      0  0

Now both NTFS partition are mounted automatically and read-only. However, I observed a strange behavior in Nautilus, that I want to correct.
First, the C: partition has different icon than D: partition; moreover, C: partition is attached to Launcher, while D: is not. Why?
Second, I can unmount C: partition by clicking on eject icon, but if I want to unmount D: partition the same way, I am asked of password. I like the password check here, so I want to have the same for C:. Why there is a difference between C: and D: partition behavior? What should I put into my /etc/fstab to have Nautilus ask of password when unmounting C: partition as well?

A:

Well, I have found explanation myself. It turned out that Ubuntu does some voodoo magic around file systems mounted in the /media directory. So in the /etc/fstab file I changed mount points from /media to /mnt as follows:
# Windows C: /dev/sda1
UUID=2EF64975F6493DF9   /mnt/win_c    ntfs    auto,ro      0  0
# Windows D: /dev/sdb1
UUID=50C40C08C40BEED2   /mnt/win_d    ntfs    auto,ro      0  0

Now both NTFS partitions are mounted automatically and read-only on system boot, and both require administrator password to unmount, which is exactly what I wanted to have.
However, there is no any quick access icons for them in the Nautilus, but this is rather unimportant detail than real problem.


Q:

How to make multiple API calls with rate limits per user using RabbitMQ?

In my app I am getting data on behalf of different users via one API which has a rate limit of 1 API call every 2 seconds per user.
Currently I am storing all the calls I need to make in a single message queue. I am using RabbitMQ for this.
There is currently one consumer who is taking one message at a time, doing the call, processing the result and then start with the next message.
The queue is filling up faster than this single consumer can make the API calls (1 call every 2 seconds as I don't know which user comes next and I don't want to hit API limits).
My problem is now that I don't know how to add more consumers which in theory would be possible as the queue holds jobs for different users and the API rate limit is per user so e.g. I could do 2 API calls every 2 seconds if they are from different users.
However I have no information about the messages in the queue. Could be from a single user, could be from many different users.
Only solution I see right now is to create separate queues for each user. But I have many different users (say 1,000) and would rather stay with 1 queue.
If possible I would stick with RabbitMQ as I use this for other similar tasks as well. But if I need to change my stack I would be willing to do so.
App is using the MEAN stack.

A:

You will need to maintain a state somewhere, I had a similar application and what i did was maintain state in Redis, before every call check if user has made request in last 2 seconds eg:
Redis key:
user:<user_id> // value is epoch time-stamp

update Redis once request is made.
refrence:
redis


Q:

play and pause ,video time indicator not displaying my YouTube API in android

I am using the YouTube API. It's working fine but play and pause and the  video time indicator are not displaying.
Below is my code, can any one please help me?
public class PlayYouTube1st extends YouTubeBaseActivity implements
    YouTubePlayer.OnInitializedListener {

private static final int RECOVERY_DIALOG_REQUEST = 1;
String DEVELOPER_KEY = "AIzaSyjksmplqrQPzIDpWjdPeurjklmcJpbg";
// YouTube player view
private YouTubePlayerView youTubeView;
String youLink;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN);

    setContentView(R.layout.youtube_main);
    Intent intent =getIntent();
    youLink=intent.getStringExtra("youtubeLink");
    youTubeView = (YouTubePlayerView) findViewById(R.id.youtube_view);
    Toast.makeText(PlayYouTube1st.this,
            youLink, Toast.LENGTH_LONG).show();

    // Initializing video player with developer key
    youTubeView.initialize(DEVELOPER_KEY, this);

}

@Override
public void onInitializationFailure(YouTubePlayer.Provider provider,
        YouTubeInitializationResult errorReason) {
    if (errorReason.isUserRecoverableError()) {
        errorReason.getErrorDialog(this, RECOVERY_DIALOG_REQUEST).show();
    } else {
        String errorMessage = String.format(
                getString(R.string.error_player), errorReason.toString());
        Toast.makeText(this, errorMessage, Toast.LENGTH_LONG).show();
    }
}

@Override
public void onInitializationSuccess(YouTubePlayer.Provider provider,
        YouTubePlayer player, boolean wasRestored) {
    if (!wasRestored) {

        // loadVideo() will auto play video
        // Use cueVideo() method, if you don't want to play it automatically
        player.loadVideo(youLink);

        // Hiding player controls
        player.setPlayerStyle(PlayerStyle.CHROMELESS);
    }
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == RECOVERY_DIALOG_REQUEST) {
        // Retry initialization if user performed a recovery action
        getYouTubePlayerProvider().initialize(Config.DEVELOPER_KEY, this);
    }
}

private YouTubePlayer.Provider getYouTubePlayerProvider() {
    return (YouTubePlayerView) findViewById(R.id.youtube_view);
}
private YouTubePlayer.PlaybackEventListener playbackEventListener = new YouTubePlayer.PlaybackEventListener() {

    @Override
    public void onBuffering(boolean arg0) {
    }

    @Override
    public void onPaused() {
    }

    @Override
    public void onPlaying() {
    }

    @Override
    public void onSeekTo(int arg0) {
    }

    @Override
    public void onStopped() {
    }

};

private YouTubePlayer.PlayerStateChangeListener playerStateChangeListener = new YouTubePlayer.PlayerStateChangeListener() {

    @Override
    public void onAdStarted() {
    }

    @Override
    public void onError(YouTubePlayer.ErrorReason arg0) {
    }

    @Override
    public void onLoaded(String arg0) {
    }

    @Override
    public void onLoading() {
    }

    @Override
    public void onVideoEnded() {
    }

    @Override
    public void onVideoStarted() {
    }
};

}

A:

change YouTubePlayer style to :
player.setPlayerStyle(PlayerStyle.DEFAULT);

or
player.setPlayerStyle(PlayerStyle.MINIMAL);


Q:

MSBuild task to execute an external MSBuild file

I'm trying to set up a MSBuild file which will invoke another MSBuild file and I'm wondering what's the best way to achieve this.
We're using it in the scenario of where a build server downloads a MSBuild file which then depending on the parameters it'll execute the appropriate 2nd file.
I know I can just use the <Exec Command="msbuild.exe ..." /> task, but that seems to be a bit of a hacky way to do it.
Is there an easier way to use MSBuild to execute another MSBuild file?

A:

You can use the MSBuild task to build a target in another MSBuild project.
You can also put the target in an external .targets file that is imported by both MSBuild projects and use the CallTarget task to build it.
Update: To execute an external command, use the Exec task.

A:

It's not just prettier to use the <MSBuild> task rather than <Exec Command="msbuild.exe .."/>. It means that the single MSBuild process knows about all the projects being built, and there's no collisions; a particular project can't be being built by two threads at once. That's usually vital if you are building with "/m".
There's some other advantages too, such as there being one set of loggers for the whole build.


Q:

Solve boost.thread compilation error with Metrowerks compiler

I'm trying to use boost.thread with metrowerks codewarrior 5.5.3; in the header thread.hpp, I get the error that he's redefining thread::thread_data:
class BOOST_THREAD_DECL thread
{
private:
    ...
    template<typename F>
    struct thread_data:
        detail::thread_data_base
    {
        F f;

        thread_data(F f_):
            f(f_)
        {}
        thread_data(detail::thread_move_t<F> f_):
            f(f_)
        {}

        void run()
        {
            f();
        }
    };
    ...
 };

template<typename F>
struct thread::thread_data<boost::reference_wrapper<F> >:
    detail::thread_data_base
{
    F& f;

    thread_data(boost::reference_wrapper<F> f_):
        f(f_)
    {}

    void run()
    {
        f();
    }
};

I see that, in effect, thread::thread_data seems to be declared twice.
What C++ feature is used there? How can I overcome that compiler deficiency?

A:

The second instance is a partial specialization of the template class, this is valid C++ and should not result in a redefinition error.
I've had problems with such features in a metrowerks compilers in the past too though, more specifically, when using template template parameters with default values, the compiler would never compile it. My workaround was rather easy, don't provide a default value... (1)
If I were you I'd try adding a full specialization for your specific type, and hope the compiler uses some different compile path for those and gets you past this....
(this is just a wild guess, I don't have/use a metrowerks compiler these days)
typedef boost::function< void () > MyThreadFunction; // or whatever you need

template <>
struct thread::thread_data<boost::reference_wrapper< MyThreadFunction > >:
    detail::thread_data_base
{
    ....
};

(1) To be honest, this was many years ago, I don't think any compiler compiled templates fully back then.


Q:

Extract people using numbers mixed with text over different columns

For a sheet/table:
+--------+-------------+------------+----------------+
| Person |    Diag1    |   Diag2    |     Diag3      |
+--------+-------------+------------+----------------+
| A      | 431 - TB    | 652 - PLA  |                |
| B      | 614 - Cough | 884 - Cold | 952 - Headache |
| C      | 747 - BLA   | 949 - POP  |                |
+--------+-------------+------------+----------------+

I have a lookup column:
+------+
| Diag |
+------+
|  431 |
|  650 |
|  949 |
|  555 |
|  484 |
+------+

For each person, if any number in the Diag lookup column lies in any of columns Diag1, Diag2, or Diag 3, that person gets selected from the original table with all associated columns with just the numbers in them.
In this case, sample output:
+--------+-------+-------+-------+
| Person | Diag1 | Diag2 | Diag3 |
+--------+-------+-------+-------+
| A      |   431 |   652 |       |
| C      |   747 |   949 |       |
+--------+-------+-------+-------+

A:

This can be done with formulas, though the formulas aren't the prettiest to look at.  Using your example data, let's say you have a setup like so: Your original table is in columns A:D, your lookup column "Diag" is in column F, and your results are in columns H:K

In cell H2 and copied down is this array formula.  Note that array formulas must be confirmed with CtrlShiftEnter and not just Enter.  You'll know it's been done correctly because in the formula bar you will see it surrounded by curly braces {}.  Do NOT attempt to put in the curly braces manually.
=IFERROR(INDEX(A:A,SMALL(IF(ISNUMBER(FIND($F$2:$F$6,$B$2:$D$4)),ROW($B$2:$D$4)),ROW(H1))),"")

In cell I2 and copied over and down is this regular formula (no array entry necessary):
=IF(H2="","",IF(VLOOKUP($H2,$A:$D,MATCH(I$1,$A$1:$D$1,0),FALSE)="","",--TRIM(LEFT(SUBSTITUTE(VLOOKUP($H2,$A:$D,MATCH(I$1,$A$1:$D$1,0),FALSE),"-",REPT(" ",999)),999))))


Q:

How to get float number in Lua from IUP text entry

I am trying following simple code to get a decimal value from user:
require( "iuplua" )

t1 = iup.text{expand = "YES", padding = "10x10", alignment="ARIGHT", size="40x"}
btn = iup.button {title = "Print:", padding = "10x10", alignment="ACENTER", size="40x"}
qbtn = iup.button{title="Quit", expand = "YES", padding = "10x10", alignment="ACENTER", size="40x"}

function btn:action()
    strval1 = string.match (t1.value, "%d+")
    print (strval1)
    num = tonumber(strval1)
    print (num)
    end

function qbtn:action()
    os.exit()
    end

dlg = iup.dialog {
 iup.vbox{
    iup.hbox{
        iup.label{title="Decimal:", padding = "10x10", alignment="ALEFT", size="40x"},
        t1  },
    iup.hbox{
        btn,
        qbtn }}}

dlg:show()
iup.MainLoop()

However, it prints out only an integer number (part before decimal- even 25.9999 prints as 25).
How can I get float or decimal value entered by user? Thanks for your help.

A:

The problem with the code is that the pattern "%d+" in btn:action only gets the first run of digits.
You can change the pattern to handle decimal points, but it is hard to write a pattern that works in all cases, including optional sign and decimal point and scientific format.
It is best to let tonumber do its work: it will return nil if the string cannot be converted to a number.


Q:

New Google one-tap sign-up from extensions

It looks like calling the googleyolo javascript object doesn't work with chrome extensions, probably because it's using an iframe with redirect under the hood, that extensions do not like.
Am I right in thinking chrome extensions are not supported? If yes, does anyone know if there is a plan to support them?

A:

That’s correct. Currently the API expects the calling page to not run inside an extension. We may change this in the future. However you can accomplish what you want to do via a chrome tab launch to a well known page which the extension can inject content scripts into, and notify via chrome cross tab messaging after sign in.


Q:

Load Facebook into an iframe

I can't load facebook into an iframe, in a web page like the following one:
<html>
<head>
<!-- some stuffs here -->
</head>
<body>
<!-- some stuffs here -->
<iframe src="http://www.google.com" frameborder="0">
</iframe>
</body>
</html>

I've tested it with other websites and it seems to load without problems for instance for wired.com, but not for facebook.com...
Can anyone explain me why?
I'm using Google Chrome and Safari, if needed.
It seems to be as if Google blocks iframe loading of its page.

A:

If you use Firebug or Google Chrome's developer console, you can see the following error
Refused to display document because display forbidden by X-Frame-Options.

X-Frame-Options

DENY
  The page cannot be displayed in a frame, regardless of the site attempting to do so.
SAMEORIGIN
  The page can only be displayed in a frame on the same origin as the page itself.

Here is another related stackoverflow question
Overcoming “Display forbidden by X-Frame-Options”

A:

Google and Facebook are using a X-Frame-Options in the HTTP response header to avoid the content being loaded in a iFrame.

The X-Frame-Options HTTP response header can be used to indicate
  whether or not a browser should be allowed to render a page in a
   or  . Sites can use this to avoid clickjacking
  attacks, by ensuring that their content is not embedded into other
  sites.

Source: https://developer.mozilla.org/en/The_X-FRAME-OPTIONS_response_header
I don't think it is possible for you to override this setting.


Q:

PHP/SQL Database querying good practice and security

So I'm a slightly seasoned php developer and have been 'doin the damn thing' since 2007; however, I am still relatively n00bish when it comes to securing my applications. In the way that I don't really know everything I know I could and should.
I have picked up Securing PHP Web Applications and am reading my way through it testing things out along the way. I have some questions for the general SO group that relate to database querying (mainly under mysql):
When creating apps that put data to a database is mysql_real_escape_string and general checking (is_numeric etc) on input data enough? What about other types of attacks different from sql injection.
Could someone explain stored procedures and prepared statements with a bit more info than  - you make them and make calls to them. I would like to know how they work, what validation goes on behind the scenes.
I work in a php4 bound environment and php5 is not an option for the time being. Has anyone else been in this position before, what did you do to secure your applications while all the cool kids are using that sweet new mysqli interface?
What are some general good practices people have found to be advantageous, emphasis on creating an infrastructure capable of withstanding upgrades and possible migrations (like moving php4 to php5).
Note: have had a search around couldn't find anything similar to this that hit the php-mysql security.

A:

Javier's answer which has the owasp link is a good start.
There are a few more things you can do more:

Regarding SQL injection attacks, you can write a function that will remove common SQL statements from the input like " DROP " or "DELETE * WHERE", like this:
*$sqlarray = array( " DROP ","or 1=1","union select","SELECT * FROM","select host","create table","FROM users","users WHERE");*
Then write the function that will check your input against this array. Make sure any of the stuff inside the $sqlarray won't be common input from your users. (Don't forget to use strtolower on this, thanks lou).
I'm not sure if memcache works with PHP 4 but you can put in place some spam protection with memcache by only allowing a certain remote IP access to the process.php page X amount of times in Y time period.
Privileges is important. If you only need insert privileges (say, order processing), then you should log into the database on the order process page with a user that only has insert and maybe select privileges. This means that even if a SQL injection got through, they could only perform INSERT / SELECT queries and not delete or restructuring.
Put important php processing files in a directory such as /include. Then disallow all IPs access to that /include directory.
Put a salted MD5 with the user's agent + remoteip + your salt in the user's session, and make it verify on every page load that the correct MD5 is in their cookie.
Disallow certain headers (http://www.owasp.org/index.php/Testing_for_HTTP_Methods_and_XST) . Disallow PUT(If you dont need file uploads)/TRACE/CONNECT/DELETE headers.

A:

My recommendations:

ditch mysqli in favor of PDO (with mysql driver)
use PDO paremeterized prepared statements

You can then do something like:
$pdo_obj = new PDO( 'mysql:server=localhost; dbname=mydatabase',
                    $dbusername, $dbpassword );

$sql = 'SELECT column FROM table WHERE condition=:condition';
$params = array( ':condition' => 1 );

$statement = $pdo_obj->prepare( $sql,
    array( PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY ) );
$statement->execute( $params );
$result = $statement->fetchAll( PDO::FETCH_ASSOC );

PROs:

No more manual escaping since PDO does it all for you!
It's relatively easy to switch database backends all of a sudden.

CONs:

i cannot think of any.

A:

I don't usually work with PHP so I can't provide advice specifically targeted to your requirements, but I suggest that you take a look at the OWASP page, particularly the top 10 vulnerabilities report: http://www.owasp.org/index.php/Top_10_2007
In that page, for each vulnerability you get a list of the things you can do to avoid the problem in different platforms (.Net, Java, PHP, etc.)
Regarding the prepared statements, they work by letting the database engine know how many parameters and of what types to expect during a particular query, using this information the engine can understand what characters are part of the actual parameter and not something that should be parsed as SQL like an ' (apostrophe) as part of the data instead of a ' as a string delimiter. Sorry I can not provide more info targeted at PHP, but hope this helps.


Q:

jQuery textfield validation against json / array

i'm looking for a solution to validate the input of a textfield against an array which is provided by a json-file.
For example: To check within a registration form, if the desired username already exists.
Can anybody help out with a working example, plugin, script, or tutorial?
The 'usernames.json' looks like this...
{"usernames":["carl","jack","jill"]}

...and is read out with...
$.getJSON("usernames.json", function(names) {
var invalidName = names;

I would go on with...
jQuery.validator.addMethod

...but from here on, i'm stuck.
If anybody may help out with a working example, i'd be very glad!
////////////////////////////////////////////////////
EDIT: Thanks to Utkanos and Pavel Staseljun, i could figure out the following solution, which is only roughly tested!
Please also find Utkanos' example down below, because this one includes "keyup"-handling instead of "submit" and does not include a "required"-check.
"#errorresponse" is the div, where an error-message may be displayed.
$.ajax({
  url: "http://yoururlto.json?callback=?",
  dataType:"jsonp",
  jsonpCallback: '?',
  async: false,
  success: function(json) {
        $('#user').keyup(function(evt) {
        var jsonarray = json.usernames;
        var userinput = $('#user').val().toLowerCase()
        var check = $.inArray(userinput, jsonarray);
        if (check !== -1) {
            $("#errorresponse").text('Thanks to Utkanos and Pavel Staseljun!');
            }
        })
      }
});

A:

HTML
<form id='signup'>
    <label>Choose a username</label>
    <input type='text' id='user' />
    <input type='submit' value='submit' />
</form>

JS / jQuery
$.getJSON("usernames.json", function(json) {
    $('#signup').on('submit', function(evt) {
        var user = $('#user').val(), error;
        if (!user)
            error = 'no username entered';
        else if (json.usernames.indexOf(user) != -1)
            error = 'username already taken';
        if (error) { evt.preventDefault(); alert(error); }
    });
});


Q:

How to optimize this function for returning posts in a feed. Django

Hello I made a function that will return posts based on when they were created and ranked by the number of votes they have.  This is for a feed.  I'm not sure that if this is an efficient way to do this and it's important that I get it right because this could potentially be sifting through thousands of posts.  I have simplified it some here and briefly explained each step.  My current concerns and a post of the whole function (without annotations) are after.
The start hours argument is for how many hours ago to get posts.  For example, if startHours=6, than only posts created after six hours ago will be returned.
def rank(request, startHours):

First I order all of the posts by votes
    unorderedPosts=Post.objects.order_by('-votes')

Then posts are excluded by categories the user has specified
    if request.user.is_authenticated():
        preferences=request.user.categorypreference_set.filter(on=False)
        for preference in preferences:
                unorderedPosts=unorderedPosts.exclude(category_name=preference.category_name)

Then I make endHours, which is always 4 hours ahead of startHours argument
    endHours=startHours+4         #4 hour time window

Now I slice the unorderedPosts and get only the ones created in the time window startHours to endHours from now.  For example, if startHours=4, than only posts created after 4 hours ago but before 8 hours ago will be returned.
    posts=unorderedPosts.filter(created__gte=(timezone.now()-datetime.timedelta(hours=endHours)))

    posts=posts.exclude(created__gte=(timezone.now()-datetime.timedelta(hours=startHours)))

Now I make a loop that will move the time window back until at least one post is found that has a creation date that fits the time window.  I make the check variable to prevent an infinite loop (the loop will quit if no posts are found within 200 hours).
    count=posts.count()
    check=endHours
    while count<1 and endHours<(check+200):
        endHours+=4
        startHours+=4
        posts=unorderedPosts.filter(created__gte=(timezone.now()-datetime.timedelta(hours=endHours)))
        posts=posts.exclude(created__gte=(timezone.now()-datetime.timedelta(hours=startHours)))
        count=posts.count()
        if count>=1: return posts, endHours

    return posts

My biggest concern is making a queryset of ALL the posts in the beginning.  This function is meant to return posts in small time windows, will it be unnecessarily slowed down by ranking all of the posts in the database?  I know that django/python querysets are quite efficient but won't ranking a set that contains thousands of objects be cumbersome for the purpose of this function?
If this is a problem, how could I make it more efficient while keeping everything accessible?
Here is a post of the whole thing.
def rank(request, startHours):

    unorderedPosts=Post.objects.order_by('-upVote')

    if request.user.is_authenticated():
        preferences=request.user.categorypreference_set.filter(on=False)
        for preference in preferences: #filter by category preference
                unorderedPosts=unorderedPosts.exclude(category_name=preference.category_name)

    endHours=startHours+4     #4 hour time window

    posts=unorderedPosts.filter(created__gte=(timezone.now()-datetime.timedelta(hours=endHours)))

    posts=posts.exclude(created__gte=(timezone.now()-datetime.timedelta(hours=startHours)))

    count=posts.count()
    check=endHours

    while count<1 and endHours<(check+200):
        endHours+=4
        startHours+=4
        posts=unorderedPosts.filter(created__gte=(timezone.now()-datetime.timedelta(hours=endHours)))
        posts=posts.exclude(created__gte=(timezone.now()-datetime.timedelta(hours=startHours)))
        count=posts.count()
        if count>=1: return posts

   return posts

A:

Your main concern is not something you need to worry about.  Check the docs on When querysets are evaluated - you can define and add clauses to a queryset indefinitely and it won't actually be run against the database until you call something that actually requires hitting the database.
What will require multiple queries is iterating through time until you hit a window that has posts.  You'll have better performance if you check the latest created time in one call, use that to work out your window, then limit the posts based on that and then sort by number of votes.
Something like:
unorderedPosts = Post.objects.all()
if request.user.is_authenticated():
    preferences=request.user.categorypreference_set.filter(on=False)
    for preference in preferences: #filter by category preference
        unorderedPosts=unorderedPosts.exclude(category_name=preference.category_name)
latest_post_datetime = unorderedPosts.aggregate(Max('created'))['created__max']

original_start_time = datetime.datetime.now() - datetime.timedelta(hours=startHours)
latest_post_day_start_time = datetime.datetime.combine(latest_post_datetime.date(), original_start_time.time())
# a timedelta guaranteed to be less than 24 hours
time_shift = latest_post_day_start_time - latest_post_datetime
timewindow = datetime.timedelta(hours=4)
if time_shift.days >= 0:
    extra_windows_needed = time_shift.seconds / timewindow.seconds
else:
    # negative timedeltas store negative days, then positive seconds; negate
    extra_windows_needed = -(abs(time_shift).seconds) / timewindow.seconds
start_time = latest_post_day_start_time - (timewindow * (extra_windows_needed + 1))
posts = unorderedPosts.filter(created__gte=start_time).order_by('-upVote')
return posts

The math here is only right as long as your number of hours in your window (4) divides evenly into the day - otherwise calculating the correct offset gets trickier.  Basically, you need to take time offset mod time window length, and I'm exploiting the fact that if you end up in the same calendar day I know the days mod four hours part works out.
Also, it doesn't include an end time because your original logic doesn't enforce one for the initial startHours period.  It'll only move the start time back out of that if there are none within it, so you don't need to worry about stuff that's too recent showing up.
This version makes at most three DB queries - one to get the category preferences for a logged in user, one to get latest_post_datetime and one to get posts, with confidence of having at least one matching post.
You might also consider profiling to see if your DB back end does better with a subquery to exclude unwanted categories:
if request.user.is_authenticated():
    unorderedPosts = unorderedPosts.exclude(category_name__in=request.user.categorypreference_set.filter(on=False).values_list('category_name')

As the __in lookup docs note, performance here varies with different database back ends.


Q:

Ionic input and select side by side

I have one input and one select that i want to show side by side.
I attempted several way with no avail.
The current code is as follows
<form name="signup">
<ion-list>

<input placeholder="Identificación" name="identificacion" type="text" ng-click="registro.msg = null" ng-model="registro.identificacion" required>

Tipo de Identificación

<select ng-model="registro.tipo_id">
<option ng-repeat="tipo in defaultTipo" value="{{tipo.id}}" ng-selected="{{tipo.selected}}">{{tipo.tipo}}</option>
</select>

</ion-list>
</form>

This outputs the following:

I need to put the input on the left and the select on the right in the same row.
Any ideas?

A:

You can simply use the ionic grid system, but putting them side by side wont leave you a lot a room on a phone. You can read more about it here: http://ionicframework.com/docs/components/#grid-explicit
<form name="signup">
<ion-list>
**
**
**
**

<input placeholder="Identificación" name="identificacion" type="text" ng-click="registro.msg = null" ng-model="registro.identificacion" required>

**
**

Tipo de Identificación

<select ng-model="registro.tipo_id">
<option ng-repeat="tipo in defaultTipo" value="{{tipo.id}}" ng-selected="{{tipo.selected}}">{{tipo.tipo}}</option>
</select>

</ion-list>
</form>

A:

You can try this ::
<ion-grid>
  <ion-row>
   <ion-col width-50>
   <ion-item>
    <ion-label color="primary">Inline Label</ion-label>
    <ion-input placeholder="Text Input"></ion-input>
  </ion-item>
 </ion-col>
 <ion-col width-50>
    <ion-item>
       <ion-label>Minute 2</ion-label>
       <ion-select [(ngModel)]="inr">
       <ion-option value="h1">5</ion-option>
       <ion-option value="h2">6</ion-option>
       <ion-option value="h3" >7</ion-option>
       </ion-select>
    </ion-item>
    </ion-col>
  </ion-row>
  </ion-grid>


Q:

Convert date to ordinal python?

I want to convert
2010-03-01 to 733832
I just found this toordinal code
d=datetime.date(year=2010, month=3, day=1)
d.toordinal()

from this
But i want something more like
d=datetime.date('2010-03-01')
d.toordinal()

Thanks in advance

A:

You'll need to use strptime on the date string, specifying the format, then you can call the toordinal method of the date object:
>>> from datetime import datetime as dt
>>> d = dt.strptime('2010-03-01', '%Y-%m-%d').date()
>>> d
datetime.date(2010, 3, 1)
>>> d.toordinal()
733832

The call to the date method in this case is redundant, and is only kept for making the object consistent as a date object instead of a datetime object.
If you're looking to handle more date string formats, Python's strftime directives is one good reference you want to check out.

A:

like this:
datetime.strptime("2016-01-01", "%Y-%m-%d").toordinal()

A:

You need to firstly convert the time string to datetime object using strptime(). Then call .toordinal() on the datetime object
>>> from datetime import datetime
>>> date = datetime.strptime('2010-03-01', '%Y-%M-%d')
>>> date.toordinal()
733773

It is even better to create a function to achieve this as:
def convert_date_to_ordinal(date):
    return datetime.strptime(date, '%Y-%M-%d').toordinal()

convert_date_to_ordinal('2010-03-01')
#returns: 733773


Q:

Re: JWTs, PURCHASE_CANCELED

Having trouble with the PURCHASE_CANCELED error in Wallet for Digital.
A. I can successfully round-trip JWTs between
https://sandbox.google.com/checkout/customer/gadget/inapp/demo.html
and
https://developers.google.com/commerce/wallet/digital/docs/jwtdecoder
...of course I can, they're both Google tools.
B. I can successfully pass from PyJWT to the decoder, seems no info changes.
C. I can successfully pass from the demo to PyJWT, seems no info changes.
D. The request in the .buy() failure callback is correct.
This is extremely frustrating, to have no feedback from Google Wallet when it does PURCHASE_CANCELED.

I cannot make identical JWTs between PyJWT and the demo encoder. Even with exactly similar data in exactly the same order, the result varies at the end of the long string. Does this matter?
Is there any way of independently generating the signature (encoded) to verify against?
Does the order of keys in the object to encode matter?

Edit:

In the Order History, Wallet says "Google has sent the customer an order confirmation email." No emails arrive to my test buyer.
Also in the Order History, Wallet says "The customer's credit card was authorized for $3.00, and passed all risk checks". Looks promising.
I remember reading that, in the Sandbox, no banking or tax info is necessary. However, Google Books held me up for months on "selling" a $0 (free) book in Google Play due to lack of banking/tax information; without it, the book never made it through the approval process, no other explanation given. Does the Sandbox need even fake/placeholder information to allow .buy() transactions to proceed?

A:

Flow is now working, postbacks are appearing at the server.
Estimated delay was 5-6 hours between sandbox setup and start of postback activity.
No changes made within sandbox tax/banking info.


Q:

Display rows of a 2d array in reverse order

I'm working on an app that is a "poor man's matrix" ie. 1 and 0 fall down the screen.
So far I have managed to get the 2d array to display one row on 1st user input, 2 rows on 2nd user input, 3 rows on 3rd user input etc.
The problem is, that the 1st row always stays at the top and I can't get the "drop-down" effect. It always appends an additional row of 1 and 0 bellow the previous row/row on user input.
Example - how it works so far:
my 2d array:
1 0 1 0 1 1 1 (1st row)
0 1 0 1 0 1 0 (2nd row)
0 0 1 0 1 0 1 (3rd row)
1 0 0 1 0 1 0 (4th row)

1st user input (Console.ReadKey();):
1 0 1 0 1 1 1 (1st row)

2cnd user input (Console.ReadKey();):
1 0 1 0 1 1 1 (1st row)
0 1 0 1 0 1 0 (2nd row)

3rd user input:
1 0 1 0 1 1 1 (1st row)
0 1 0 1 0 1 0 (2nd row)
0 0 1 0 1 0 1 (3rd row)

etc.
What I would like to achive is something similar but in "reverse" order.
Example - what I would like to achive:
1st user input:
1 0 1 0 1 1 1 (1st row)

2cnd user input:
0 1 0 1 0 1 0 (2nd row)
1 0 1 0 1 1 1 (1st row)

3rd user input:
0 0 1 0 1 0 1 (3rd row)
0 1 0 1 0 1 0 (2nd row)
1 0 1 0 1 1 1 (1st row)

So, to summerise, I would like to modify my existing code, so that the 1st row is always added last. Or possible start reading from the end of the array - last row. I have tried this, but I constantly get outOfRange error...
Any help would be welcome.
The code that just adds additional rows below an existing one:
public static int row = 0;
static void PrintRelevantLines()
{
    Console.Clear();
    if (rowl <= pnms.GetLength(0) - 1)
    {
        for (int i = 0; i <= row; i++)
        {
            for (int j = 0; j <= pnms.GetLength(1) - 1; j++)
            {
                Console.Write(pnms[i, j]);
            }
            Console.WriteLine();
        }
    }
    row += 1;
}

Edit: The anwser I requested was
for (int i = row; i >= 0; i--;)

which was provided by: Pranav Hosangadi
But I accepted the anwser from Caius Jard, as he went over and beyond what I asked for.
Thank you.

A:

Here you go; this is a matrix effect:
            int width = 60; //draw 60 columns
            int height = 20; //draw 20 rows

            var chars = "1234567890-=qwertyuiop[]asdfghjkl;'#zxcvbnm,./!\"£$%^&*()_+QWERTYUIOP{}ASDFGHJKL:@~ZXCVBNM<>?".ToCharArray(); //create an array of chars to randomly choose and pump onto screen

            var r = new Random(); //make only one Random. Never make a Random in a loop

            while (true) //forever
            {
                int randCol = r.Next(0, width); //pick which column we will draw now

                for (int i = 0; i < height; i++) {              //for every row from top to bottom
                    Console.SetCursorPosition(randCol, i);      //put the cursor there
                    Console.Write(chars[r.Next(chars.Length)]); //pump a random char
                    Thread.Sleep(200);                          //it's a bit fast otherwise
                }
            }

I haven't out and out given the solution for your exercise, because it looks like a homework (and I don't do homework), but I hope you can step through this and look at how it's working, and make the adaptations that you need to your program to get the result you're after
Perhaps, for example, you can keep your lines in a 2D buffer, and you can decide on a column randomly (like I did), and you can render it down the screen row by row, by reading down the column (or up), writing to the screen, the same column as you selected from the buffer, then select another column
Perhaps you can periodically insert lines into the buffer (scrolling new data through it).
Perhaps also, yoou can write the char first in white, then later overwrite it in grey just before you write the new char in white (the effect is hard to see when the screen has filled up)
Then you can write multiple chars at different offsets at the same time..
..then you can give it to the peeps at codegolf.se.com and they'll write you a version in like, 15 chars of 05AB1E or something


Q:

Custom text view adapter not working on list view

I'm trying to use a custom text view for the items in my list but when deploying my app it doesn't appear.
fragment class
public class FragmentMainList extends android.support.v4.app.Fragment {

    ListView list_main;

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
        View v = inflater.inflate(R.layout.fragment_main_list, container, false);

        String[] listContent = {
            getActivity().getResources().getString(R.string.item_0),
            getActivity().getResources().getString(R.string.item_1),
            getActivity().getResources().getString(R.string.item_2)
        };

        list_main = (ListView)v.findViewById(R.id.list_main);
        ArrayAdapter adapter = new ArrayAdapter(getActivity(),R.layout.list_item,listContent);
        list_main.setAdapter(adapter);

        return v;
    }
}

list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/list_item"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:padding="12dp"
        android:textAppearance="?android:attr/textAppearanceLarge" />

</LinearLayout>

I know the line of below has something to do with it, but I don't know what to change it to:

ArrayAdapter adapter = new ArrayAdapter(getActivity(),R.layout.list_item,listContent);
              list_main.setAdapter(adapter);

A:

You need to add the id of your TextView as an argument to the ArrayAdapter constructor call, such as new ArrayAdapter(getActivity(), R.layout.list_item, R.id.list_item, listContent).


Q:

Why is my NSTableView data source illegal?

For some reason, I'm getting the following error:
* Illegal NSTableView data source ().  Must implement numberOfRowsInTableView: and tableView:objectValueForTableColumn:row:
Here's my AppDelegate.h
#import <Cocoa/Cocoa.h>

@interface AppDelegate : NSObject <NSApplicationDelegate, NSUserNotificationCenterDelegate, NSTableViewDataSource, NSTableViewDelegate> {

    NSMutableArray *userNotifications;
}

@property NSMutableArray *userNotifications;

@end

My AppDelegate.m
#import "AppDelegate.h"

@implementation AppDelegate
@synthesize userNotifications;

- (void)applicationDidFinishLaunching:(NSNotification *)notification
{

    NSUserNotification *userNotification = notification.userInfo[NSApplicationLaunchUserNotificationKey];

    userNotifications = [NSMutableArray new];

    if(userNotification) {
        [self userActivatedNotification:userNotification];
    } else {
        for(int i=1; i <= 10; i++) {

            NSString *title = [NSString stringWithFormat: @"Title %d", i];
            NSString *message = [NSString stringWithFormat: @"Message %d", i];

            NSArray *notificationObj = [[NSArray alloc] initWithObjects:title, message, nil];
//          NSLog(@"Array: %@", notificationObj);
            [userNotifications addObject:notificationObj];
//          NSLog(@"Notifications: %@", userNotifications);
            [self deliverNotificationWithTitle:title message:message];
        }
    }

}

- (void)deliverNotificationWithTitle:(NSString *)title
                            message:(NSString *)message
{

    NSUserNotificationCenter *center = [NSUserNotificationCenter defaultUserNotificationCenter];
    NSUserNotification *userNotification = nil;

    userNotification = [NSUserNotification new];
    userNotification.title = title;
    userNotification.informativeText = message;

    center.delegate = self;
    [center scheduleNotification:userNotification];

}

- (void)userActivatedNotification:(NSUserNotification *)userNotification
{
//  [[NSUserNotificationCenter defaultUserNotificationCenter] removeDeliveredNotification:userNotification];

    printf("* User activated notification:");
//  NSLog(@"Title: %@", userNotification.title);just do it in
//  NSLog(@"Message: %@", userNotification.informativeText);
    [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString:@"https://www.google.com/"]];
}

- (BOOL)userNotificationCenter:(NSUserNotificationCenter *)center
     shouldPresentNotification:(NSUserNotification *)userNotitification
{
    printf("* Notification presented.");
    return YES;
}

- (NSInteger) numberOfRowsInTableView:(NSTableView *)tableView
{
    return [userNotifications count];
}
- (id) tableView:(NSTableView *)tableView objectValueForTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)row
{
    return [userNotifications objectAtIndex:row];
}

@end

A:

I had to set my App Delegate as the data source for the Table view. Once I did that, the errors disappeared.


Q:

My  overlap with nav-justified

I have a nav-justified list for my login page because you can connect with a login / password or guest mode.
The problem is that if I click Login, Guest is still displayed and if I like reclique Guest.
Code :

<!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">
 <link rel="stylesheet" href="{{ app.request.basepath }}/css/main.css">
    <link rel="stylesheet" href="{{ app.request.basepath }}/css/templatemo_main.css">
    <link rel="icon" type="image/icon" href="{{ app.request.basepath }}/favicon.ico"/>
 <link rel="stylesheet" href="{{ app.request.basepath }}/css/bootstrap.min.css">
    <title>Nautilus - {% block title %}Authentification{% endblock %}</title>

{{ block('title') }}

  {% if error %}

    Erreur lors de l'authentification ! {{ error }}

  {% endif %}

Invité

Connexion

       <form class="form-signin form-horizontal" role="form" action="{{ path('login_check') }}" method="post">

          <input type="text" name="_username" value="Invite" class="form-control" required>

          <input type="password" name="_password" class="form-control">

          <button type="submit" class="btn btn-default btn-primary"> Connexion</button>

       </form>

      <form class="form-signin form-horizontal" role="form" action="{{ path('login_check') }}" method="post">

         <input type="text" name="_username" placeholder="Entrez votre login" class="form-control" required>

         <input type="password" name="_password" class="form-control" required placeholder="Entrez votre mot de passe">

         <button type="submit" class="btn btn-default btn-primary"> Connexion</button>

      </form>

Image :
Error

A:

The problem is in your mark-up.
In the div with class tab-content you have place all the tab-pane divs. The one with #connexion was outside.
Here is the correct markup.

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet"/>

<!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">
     <link rel="stylesheet" href="{{ app.request.basepath }}/css/main.css">
     <link rel="stylesheet" href="{{ app.request.basepath }}/css/templatemo_main.css">
     <link rel="icon" type="image/icon" href="{{ app.request.basepath }}/favicon.ico"/>
     <link rel="stylesheet" href="{{ app.request.basepath }}/css/bootstrap.min.css">

Invité

Connexion

           <form class="form-signin form-horizontal" role="form" action="{{ path('login_check') }}" method="post">

              <input type="text" name="_username" value="Invite" class="form-control" required>

              <input type="password" name="_password" class="form-control">

              <button type="submit" class="btn btn-default btn-primary"> Connexion</button>

           </form>

           <form class="form-signin form-horizontal" role="form" action="{{ path('login_check') }}" method="post">

              <input type="text" name="_username" placeholder="Entrez votre login" class="form-control" required>

              <input type="password" name="_password" class="form-control" required placeholder="Entrez votre mot de passe">

              <button type="submit" class="btn btn-default btn-primary"> Connexion</button>

           </form>


Q:

How to pop local and global marks with a common keybinding in Emacs

Is there any way to combine local and global marks together? what I am trying to do is just to have a common keybinding to pop-global-mark and set-mark-command. Something like; "try to pop the local mark, if there are no remaining ones, then try pop the global mark".
This is needed to move back around the code, and not thinking if i should press C-u C-SPC or C-x C-SPC, depending if the jump between functions was inside or outside the same file.

A:

First of all, you cannot really use set-mark-command in code because it checks this-command and last-command so it will not work as intended.
However, examining its code, I came up with (untested!):
(defun pop-local-or-global-mark ()
  "Pop to local mark if it exists or to the global mark if it does not."
  (interactive)
  (if (mark t)
      (pop-to-mark-command)
      (pop-global-mark)))


Q:

how to split string ""180101051436_Radmin_VPN_1.0.3448" into exactly two strings in python

how to split "180101051436_Radmin_VPN_1.0.3448" into two strings in python .I want output as "180101051436_" one string and "Radmin_VPN_1.0.3448" second string

A:

You can split after the first underscore:
s = "180101051436_Radmin_VPN_1.0.3448"

index = s.find("_") + 1  # get the position just after the first underscore (13)

s1 = s[:index]  # get everything in the string *before* index
s2 = s[index:]  # get everything in the string *after* index


Q:

Target a specific table using CSS3 selector

Is it possible to use the nth-child selector to target a specific table within it's parent element?
I'm trying to target the 2nd table in a div but it doesn't seem to be working:
#div table:nth-child(2) {
    color: blue
}

Table 1

Table 2

A:

Your issue could be with the invalid html. You need to wrap the text within td.

Table 1

Table 2

Also make sure you do not have id duplicated.
Here's a working CodePen demo
One more thing to be noted is that this will work only if your table is 2nd child of div, if you want to target 2nd table inside its parent you would need to use nth-of-type(2)


Q:

How to select actual year in Oracle Date?

I need to select the employees that registered in the company this year; the field is a date type(field name :datemp) so i used :
SELECT employee_name
FROM employees
WHERE datemp BETWEEN to_date(01-JAN-2015) AND to_date (31-DEC-2015)

is there another method i can say that the year of a field that has a date type is in the actual year?

A:

You can pull  it from sysdate
SELECT employee_name
FROM employees
WHERE EXTRACT(year FROM datemp) = EXTRACT(year FROM sysdate)


Q:

Code runs much faster in C than in NumPy

I wrote physics simulation code in python using numpy and than rewrote it to C++. in C++ it takes only 0.5 seconds while in python around 40s. Can someone please help my find what I did horribly wrong?
import numpy as np

def myFunc(i):
    uH = np.copy(u)
    for j in range(1, xmax-1):
        u[i][j] = a*uH[i][j-1]+(1-2*a)*uH[i][j]+a*uH[i][j+1]
    u[i][0] = u[i][0]/b
    for x in range(1, xmax):
        u[i][x] = (u[i][x]+a*u[i][x-1])/(b+a*c[x-1])
    for x in range(xmax-2,-1,-1):
        u[i][x]=u[i][x]-c[x]*u[i][x+1]
xmax = 101
tmax = 2000
#All other variables are defined here but I removed that for visibility
uH = np.zeros((xmax,xmax))
u = np.zeros((xmax,xmax))
c = np.full(xmax,-a)
uH[50][50] = 10000
for t in range(1, tmax):
    if t % 2 == 0:
        for i in range(0,xmax):
            myFunc(i)
    else:
        for i in range(0, xmax):
            myFunc(i)

In case someones wants to run it here is whole code: http://pastebin.com/20ZSpBqQ
EDIT: all variables are defined in the whole code which can be found on pastebin. Sorry for confusion, I thought removing all the clutter will make the code easier to understand

A:

So when I ran your numpy python code it took four minutes to run, once I removed the numpy code and replaced it with standard python code it only took one minute! (I have a not so fast computer)
Here's that code:
#import numpy as np

def impl(i,row):
    if row:
        uH = u[:][:] # this copys the array 'u'
        for j in range(1, xmax-1):
            u[i][j] = a*uH[i][j-1]+(1-2*a)*uH[i][j]+a*uH[i][j+1]
        u[i][0] = u[i][0]/b
        for x in range(1, xmax):
            u[i][x] = (u[i][x]+a*u[i][x-1])/(b+a*c[x-1])
        for x in range(xmax-2,-1,-1):
            u[i][x]=u[i][x]-c[x]*u[i][x+1]
    else:
        uH = u[:][:] # this copys the array 'u'
        for j in range(1, xmax-1):
            u[j][i]= a*uH[j-1][i]+(1-2*a)*uH[j][i]+a*uH[j+1][i]
        u[0][i] = u[0][i]/b
        for y in range(1, xmax):
            u[y][i] = (u[y][i]+a*u[y-1][i])/(b+a*c[y-1])
        for y in range(xmax-2,-1,-1):
            u[y][i]=u[y][i]-c[y]*u[y+1][i]

#Init
xmax = 101
tmax = 2000
D = 0.5
l = 1
tSec = 0.1
uH = [[0.0]*xmax]*xmax #np.zeros((xmax,xmax))
u = [[0.0]*xmax]*xmax #np.zeros((xmax,xmax))
dx = l / xmax
dt = tSec / tmax
a = (D*dt)/(dx*dx);
b=1+2*a
print("dx=="+str(dx))
print("dt=="+str(dt))
print(" a=="+str(a))
#koeficient c v trojdiagonalnej matici
c = [-a]*xmax #np.full(xmax,-a)
c[0]=c[0]/b
for i in range(1, xmax):
    c[i]=c[i]/(b+a*c[i-1])
uH[50][50] = 10000
u = uH
for t in range(1, tmax):
    if t % 2 == 0:
        for i in range(0,xmax):
            impl(i,False)
    else:
        for i in range(0, xmax):
            impl(i,True)

I believe that this could be much faster if you were to have used numpy the correct way rather than as a substitute for arrays, however, not using numpy arrays cut the time to 1/4th of the original.


Q:

Solve trigonometric integral $\int_{-\pi/2}^{\pi/2} \frac{\sin^{2014}x}{\sin^{2014}x+\cos^{2014}x} dx $

Please help me to solve the following integral:
$$\int_{-\pi/2}^{\pi/2} \frac{\sin^{2014}x}{\sin^{2014}x+\cos^{2014}x} dx$$
I have tried a lot, but no results. I only transformed this integral to the following also not easy integral:
$$\int \frac{1}{(1+t^2)(1+t^{2014})} dt.$$

A:

Consider the integral
\begin{align}
I = \int_{-\pi/2}^{\pi/2} \frac{\sin^{2a}x}{\sin^{2a}x + \cos^{2a}x} \, dx.
\end{align}
This may also be seen as
\begin{align}
I &= \int_{0}^{\pi/2} \frac{\sin^{2a}x}{\sin^{2a}x + \cos^{2a}x} \, dx + \int_{-\pi/2}^{0} \frac{\sin^{2a}x}{\sin^{2a}x + \cos^{2a}x} \, dx \\
&= \int_{0}^{\pi/2} \frac{\sin^{2a}x}{\sin^{2a}x + \cos^{2a}x} \, dx - \int_{\pi/2}^{0} \frac{\sin^{2a}x}{\sin^{2a}x + \cos^{2a}x} \, dx \\
&= 2 \, \int_{0}^{\pi/2} \frac{\sin^{2a}x}{\sin^{2a}x + \cos^{2a}x} \, dx
\end{align}
where $x \to -x$ was made in the second integral. Now make the substitution $x = t-\pi/2$ to obtain
\begin{align}
I = 2 \, \int_{-\pi/2}^{0} \frac{\cos^{2a}t}{\sin^{2a}t + \cos^{2a}t} \, dt.
\end{align}
Now let $t \to -x$ to obtain
\begin{align}
I = 2 \, \int_{0}^{\pi/2} \frac{\cos^{2a}x}{\sin^{2a}x + \cos^{2a}x} \, dx.
\end{align}
Adding the two integral expressions leads to
\begin{align}
2 I &= 2 \, \int_{0}^{\pi/2} \frac{\sin^{2a}x + \cos^{2a}x}{\sin^{2a}x + \cos^{2a}x} \, dx = 2 \, \int_{0}^{\pi/2} dx = \pi.
\end{align}
It can now be stated that
\begin{align}
\int_{-\pi/2}^{\pi/2} \frac{\sin^{2a}x}{\sin^{2a}x + \cos^{2a}x} \, dx = \frac{\pi}{2}.
\end{align}

A:

Notice the following properties of limits, $$\color{blue}{\int_{-a}^{a}f(x)dx =2\int_{0}^{a}f(x)dx\quad \text{if} \quad f(-x)=f(x)}$$
$$\color{blue}{\int_{0}^{a}f(x)dx =\int_{0}^{a}f(a-x)dx}$$
Now, let $$I=\int_{-\pi/2}^{\pi/2}\frac{\sin^{2014}x}{\sin^{2014}x+\cos^{2014}x}dx$$  $$\implies I=2\int_{0}^{\pi/2}\frac{\sin^{2014}x}{\sin^{2014}x+\cos^{2014}x}dx\tag 1$$
Using secong property, we get $$I=2\int_{0}^{\pi/2}\frac{\sin^{2014}\left(\frac{\pi}{2}-x\right)}{\sin^{2014}\left(\frac{\pi}{2}-x\right)+\cos^{2014}\left(\frac{\pi}{2}-x\right)}dx$$
$$\implies I=2\int_{0}^{\pi/2}\frac{\cos^{2014}x}{\sin^{2014}x+\cos^{2014}x}dx\tag 2$$
Now, adding eq(1) & (2), we get
$$2I=2\int_{0}^{\pi/2}\left(\frac{\sin^{2014}x}{\sin^{2014}x+\cos^{2014}x}+\frac{\cos^{2014}x}{\sin^{2014}x+\cos^{2014}x}\right)dx$$  $$\implies I=\int_{0}^{\pi/2}\left(\frac{\sin^{2014}x+\cos^{2014}x}{\sin^{2014}x+\cos^{2014}x}\right)dx$$ $$=\int_{0}^{\pi/2}1. dx=[x]_{0}^{\pi/2}=\left[\frac{\pi}{2}-0\right]=\color{blue}{\frac{\pi}{2}}$$

A:

Another point of view, just to point out what's going on with the integral:
Consider the integral written in the form:
$$I(2k) = \int^{\pi/2}_{-\pi/2} \frac{1}{1+\cot^{2k}{x}} \, \mathrm{d} x, $$ and look at what happens with the integrand as $k$ goes to $\infty$ (in your case, $k = 512$):

where I have ranged $k$ from $2$ to $20$. Can you infer an asymptotic behavior of $I(2k)$ as $k \to \infty$?
Cheers!

Edit: I was fascinated by the fact pointed out by @enzotib. In fact, this may suggest that $\partial I/\partial k = 0$. Let's compute the derivative of the integrand w.r.t. $k$:
$$ \frac{\partial}{\partial k} \frac{1}{1+\cot^{2k}{x}} = -\frac{2 \cot ^{2 k}(x) \log (\cot (x))}{\left(\cot ^{2 k}(x)+1\right)^2} =:f.$$ We observe that $f$ is only defined for $x > 0$ and, as a matter of fact, it's an odd function with respect the line $x = \pi/4$ for all $k$. Therefore, $F= \int^{\pi/2}_{-\pi/2} f \, \mathrm{d} x= 0$ for every $k$, meaning that $I$ does not depend on $k$. Since $F = \partial I / \partial k$, on integrating $F$ with respect to $k$, we can see that $I = c$, for some constant $c$. To determine the value of $c$, we plug any value of $k$ in $I$ to have that $I = I(0) = \int^{\pi/2}_{-\pi/2} \mathrm{d}x /2  = \pi/2$.


Q:

Is it advisable to have many clickable hyperlinks in an academic CV?

I have recently been updating my academic CV. I realise that some items are not as internationally recognised as to that every reader will be aware of their importance without googling them. Hence, I am thinking about inserting hyperlinks to those items lest the reader wish to learn more.
Now, many items on my CV are clickable, and a reader particularly interested in one item may now just click on it to see a webpage with more details to pop up.
However, I rarely see a CV with many hyperlinks behind those words/phrases. Is this a taboo, or I am OK to do so?

A:

I agree: most academic CVs do not have a festival of hyperlinks.  I don't see a problem with it, unless -- as @Taladris says -- the large amount of hyperlinking creates clutter in the document.  For something like a CV, where the spacing on the page is highly adjustable, I would think that you could probably have even a highly hyperlinked CV and take a little care to make sure that it does not look too busy to the eye.
I can tell you though why I don't feel the need to hyperlink my CV (and I imagine the reason holds more generally).  It's simple: I also have a webpage, and anything which appears on my CV which could get linked to also appears on my webpage.  Further, the translation between the two is straightforward: I have a section of my CV listing papers, and I also have an immediately visible link to a subpage containing papers from my main webpage (which, as you can see, is no frills to say the least, but it seems to get the job done).
Although I am certainly no expert on the visual display of information, webpage design (you'll know that immediately if you clicked on the above link) or anything like that, it is my opinion that a webpage is a more natural medium to have clickable content than a CV.
I think every young academic should have a professional webpage.  If they do have one, I'm not sure that a heavily hyperlinked CV is necessary, although again I see no harm in it.

A:

General advise would be, yes, include links but do not rely on them for key information. You do not necessarily know if the recipients read the electronic version or a printout. If it is a printout, it is very unlikely that people will key in URLs to look up information, unless they are interested. In for, example a job application, your application may be one of a large number and there may not be time to spend on looking up information that should have been included directly in the first place. Remember it is you responsibility to yourself to provide everything the reader of the CV may want, not the other way around.
So although, there is no problem with including links, think twice about what information you link to and what you actually put in your CV.

A:

As long as it does not reduce readability, I don't see any reason for not including hyperlinks.
Readability is of course about format. As a personal preference, I would not like to read a document where all words are in blue and underlined, or equation numbers in a red square. So you have to find a way to make the links discreet (but still easily noticeable by the reader).
Readability is also, and mainly, about the content. Be sure your content is still clear when your CV is printed (or in case links are broken). Also, try to keep links meaningful. In particular, keep all your links high-quality: if links to your publications or to the diploma system of your home country will help for your evaluation, you would ruin all your effect if these links are "drowned" in a sea of meaningless links.
Did you consider about tool-tips instead of some links? It will still provide some information, but with the drawback of having to load a new page.


Q:

How to validate if user is part of group in Azure AD?

I have written a Python application hosted on Open Shift.
After user login into application his privileges are decided based on his  group membership in Azure Active Directory.
How can I validate if  user is part of a group in Azure Active Directory through my application ?

A:

You can call the following Microsoft Graph APIs from your application depending on your scenario -

Check member groups
This one will be helpful if you already know the groups that you want to check/validate membership in.
 POST https://graph.microsoft.com/v1.0/users/{id | userPrincipalName}/checkMemberGroups

In request body, you can provide groupdIds, i.e. a collection that contains the object IDs of the groups in which to check membership. Up to 20 groups may be specified.
 {
  "groupIds": [
       "fee2c45b-915a-4a64b130f4eb9e75525e",
       "4fe90ae065a-478b9400e0a0e1cbd540"
   ]
 }

user: getMemberGroups
This one will be helpful if you don't already know the group and want to get all the groups that this user belongs to.
 POST https://graph.microsoft.com/v1.0/users/{id | userPrincipalName}/getMemberGroups

You can also enable group claims to come in as part of the access token for your application by editing your application's manifest (this can be done directly in Azure Portal) and setting "groupMembershipClaims" property to "All" or "SecurityGroup" as needed.
There is a catch with groupMemembershipClaims though, that token doesn't always come with all the groups that user is member of. In case a user is member of too many groups (AFAIK it's 6 or more), you only get back an overage indicator claim like hasGroups telling you that user is part of many groups and you should call graph api to get the list of all groups. That's the reason I've highlighted the relevant Microsoft Graph API.
Here is a sample application that does authorization based on group claims. It's using .NET 4.5 MVC, C# but concepts are same -
Authorization in a web app using Azure AD groups & group claims
Here is another SO Post, where a similar requirement is discussed. It also mentions considering Application Roles to make authorization decisions, as that can be more appropriate in some cases.


Q:

I am searching for a C++ code implementing the complex polygamma function

I googled about some code on the complex polygamma function especially C++ code, but can't find anything. Does anyone know where to find such code?
The complex digamma function does exist but not the complex polygamma function.

A:

Looking at what the python scipy library does for its special functions, the polygamma is found by returning the digamma if the zeroth derivative is requested, otherwise return $(-1)^{n+1}\Gamma(n+1)\zeta(n+1,z)$ where $\Gamma$ is the gamma function and $\zeta$ the two argument Riemann zeta function. Assuming that this identity holds for the complex numbers, it may explain why you can't find any explicit code.
In fact to add a reference, this is also the method used in the gnu implementation of libstdc++, see here

A:

I implemented a complex polygamma function in the Julia standard library (https://github.com/JuliaLang/julia/pull/7125).   It is possible to call this from C++ by linking to the libjulia library.


Q:

How do I stop apex code being run at the same time?

I'm not sure if anyone is able to answer this question (I've been to Salesforce Support already who weren't any help on this issue) but I thought I'd ask it anyway and see if anyone has any ideas how to solve.
Basically, we have various visualforce pages that will run one off code that creates lots of child records for a certain parent record. These records will run their own triggers and so can take quite a while to complete.
My issue is if a user goes to the visualforce page to run the code while it is already being run by another user, at the end of both transactions there will be two sets of child records that have been created.  Is there a way to detect when a user is already running code so that I can throw errors if someone is already processing?
I've already tried adding 'for update' keyword onto my SOQL statements but what this does is to pause the second transaction until the first is completed (so the second transaction will eventually execute, which I don't want)
((My thoughts would be to try something along the lines of partial processing - so I would update a record to flag that a transaction is in progress, commit that to the database then run the actual logic afterwards? Either through javascript or @future methods.))

A:

The way that I've handled this in the past is to use a custom setting exactly as you have described.  When the user presses the button on the visualforce page to start the processing, the first thing that happens is the custom setting is checked to ensure processing isn't ongoing and then updated to indicate the processing has started. I then proceed in a couple of different ways depending on the requirements:

A flag is then set in the controller to get the page to send the start processing request (via an actionfunction and some javascript that is only rendered if the flag is set).
The processing is kicked off asynchronously via batch apex or an @future method

If other users are already on the other visualforce pages and press the button to start the processing, the custom setting check fails and they get an error/warning that processing is already happening.
For users that navigate to the visualforce pages anew, I incorporate the custom setting check into the rendering code and disable the button to start processing if it is in progress.  I also have an indicator on the page that shows the processing status at the top right - you can be a bit more clever with this and tie it to an actionpoller that periodically updates the status and shows progress.
As the final part of the processing, the custom setting is cleared.


Q:

Cannot use Python's pip on Windows 8. "specified executable is not a valid application for this os platform"

I seem to be receiving a unique error in Python 2.7.6 on Windows 8 64bit.  I was able to install Python perfectly, then was able to install pip using this guide.  But when I got to step 3 and I tried to install virtualenv using pip it gave me this error:
Program 'pip.exe' failed to run: The specified executable is not a valid application for this OS platform.At line:1
char:1
+ pip.exe install virtualenv
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~.
At line:1 char:1
+ pip.exe install virtualenv
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ResourceUnavailable: (:) [], ApplicationFailedException
    + FullyQualifiedErrorId : NativeCommandFailed

Picture:
Also when trying to just run the executable it does this:
I've tried other installation methods such as the pip packaged executable, but it always ends up that whenever it/I get to the stage of actually putting it to use this happens.
Thanks guys, hope you can help!

A:

When installed properly, pip should include C:\Python27\Scripts\pip-script.py, among a few other scripts. I'm guessing there was some sort of issue when you installed pip the first time, and these scripts weren't placed properly.
As a workaround, try downloading pip from Christoph Gohlke's Python Externsion Packages for Windows repository, which is my go-to resource for installing third-party modules on Windows. The installer should automatically detect your Python installation and install the programs and scripts appropriately.


Q:

Run multiple queries each selecting each respective Nth row?

`Related to "Selecting every nth row from SQL Server 2008 query result where table does not have row id column", I understand that doing the following would select every 4th row.
SELECT ID, Whatever FROM MyTable WHERE ID % 4 = 0
But what I want to do is run 4 separate queries that select the 4th row starting at 1, 2, 3 and 4 respectively.  Would it look like this?
SELECT ID, Whatever FROM MyTable WHERE ID % 4 = 0
SELECT ID, Whatever FROM MyTable WHERE ID % 4 = 1
SELECT ID, Whatever FROM MyTable WHERE ID % 4 = 2
SELECT ID, Whatever FROM MyTable WHERE ID % 4 = 3
or maybe
SELECT ID, Whatever FROM MyTable WHERE ID + 1 % 4 = 0
SELECT ID, Whatever FROM MyTable WHERE ID + 2 % 4 = 0
SELECT ID, Whatever FROM MyTable WHERE ID + 3 % 4 = 0
SELECT ID, Whatever FROM MyTable WHERE ID + 4 % 4 = 0
???

A:

I figured it out
Given 20 rows and 4 iterations:
Rows 1,5,9,13,17:   SELECT ID, Whatever FROM MyTable WHERE ID % 4 = 1
Rows 2,6,10,14,18: SELECT ID, Whatever FROM MyTable WHERE ID % 4 = 2
Rows 3,7,11,15,19: SELECT ID, Whatever FROM MyTable WHERE ID % 4 = 3
Rows 4,8,12,16,20: SELECT ID, Whatever FROM MyTable WHERE ID % 4 = 0


Q:

Setting different view controller for one tab

I have 5 tab in my tab bar controller. Users can use my application as anonymus user. One of my tabs is Login page. if user logged in my application, that tab should be Home page. but I don't know how set different view controller for one tab based on if condition

A:

One of the possible solutions is to use container view controller.
So, your view controller will have 2 embedded view controllers, and in code you can choose between them based on your logic.
There you can find some relevant examples and topics:
https://developer.apple.com/library/content/featuredarticles/ViewControllerPGforiPhoneOS/ImplementingaContainerViewController.html
iOS Switching an embedded view in storyboard
Embed UIViewController Programatically?


Q:

Distinct SQL that will return true if in a table

I'm drawing a blank on the best way write this sql,
For simplicity sake I'm Only interested in one column.
Table A Column = [Supplier].
Table B Column = [AuthorizedSuppliers]
Table A contains many rows with the same value in the [Supplier].
Table A
------------------------------
ID |Supplier      | Company  |
---|--------------|----------|
1  | Warehouse 1  | Company 1|
2  | Warehouse 1  | Company 2|
3  | Warehouse 1  | Company 3|
4  | Warehouse 2  | Company 4|
5  | Warehouse 2  | Company 5|
6  | Warehouse 3  | Company 6|
7  | Warehouse 3  | Company 7|
8  | Warehouse 3  | Company 8|

Table B contains a single Supplier from Table A [Supplier] row.
Table B
------------------------------
ID |AuthorizedSupplier       |
---|-------------------------|
1  | Warehouse 1             |
2  | Warehouse 2             |

I need to return the DISTINCT values of [Supplier] and [AuthorizedSupplier] with a additional column let's call it [Authorized] that is marked as true for those values that were in Table B
So the result set of the above sample should look like this
Result Set
------------------------------
Supplier    |Authorized      |
------------|----------------|
Warehouse 1 | True           |
Warehouse 2 | True           |
Warehouse 3 | False          |

A:

Use Distinct and  Left Outer Join:
SELECT DISTINCT Supplier, Authorized = CASE WHEN B.AuthorizedSupplier IS NULL
                                       THEN 'True' ELSE 'False' END
FROM TableA A
LEFT OUTER JOIN TableB B
  ON A.Supplier = B.AuthorizedSupplier

SQL-Fiddle Demo


Q:

transaction value does not match signed transaction params in ethereumJS-TX

I sign this transaction with Ethereumjs-tx:
{
    nonce: 8,
    gasPrice: 20,
    gasLimit: 25000,
    to: '0x45cc01d4b9ad49b81527d5b6629da8664bb525d3',
    value: 1000000,
    data: '0x00',
    chainId: 3
}

however, the value on etherscan shows 0.013845257383850032 Ether
https://ropsten.etherscan.io/tx/0xa891e47b6fad75750a40d6ea2698fe409e4650c59acbc910eaa5cabe1169a4e0
Where doe the 0.0038xxxx extra ether come from?

A:

Larger ints don't work well with ethereumJS-tx. If you have a large int, use
ethereumjs-util.intToBuffer()
or
new BN(value) to convert it to BN which seems to work as well.


Q:

Entry of a list item in a file

Good afternoon, I have a multiple list of IP and MAC, list of arbitrary length
A = [['10.0.0.1','00:4C:3S:**:**:**', 0], ['10.0.0.2', '00:5C:4S:**:**:**', 0], [....], [....]]

I want to check if this MAC is in the oui file:
E043DB   (base 16)   Shenzhen
2405f5   (base 16)   Integrated
3CD92B   (base 16) Hewlett Packard
...

If the MAC from the list is in the file, write the name of the manufacturer as 3 list items. I'm trying to do so and it turns out to check only the first element, the remaining ones are not checked, how can I do this please tell me?
f = open('oui.txt', 'r')
for values in A:
    for line in f.readlines():
        if values[1][0:8].replace(':','') in line:
            values[2]=(line.split('(base 16)')[1].strip())
f.close()
print (A)

And get an answer:
A = [['10.0.0.1','00:4C:3S:**:**:**', 'Firm Name'], ['10.0.0.2', '00:5C:4S:**:**:**', 0], [....], [....]]

A:

The Problem
Consider the "shape" of your code:
f = open('a file')
for values in [ 'some list' ]:
    for line in f.readlines():

Your two loops are doing this:
Start with first value in list
Read all lines remaining in file object f
Move to next value in list
Read all lines remaining in file object f

Except that the first time you told it to "read all lines remaining" it would do so.
So, unless you have some way to put more lines into f (which can happen with async files like stdin!) you are going to get one "good" pass through the file, and then every subsequent pass the file object will point to the end of the file, so you'll get nothing.
A Solution
When you are dealing with a file, you want to only process it one time. File I/O is expensive compared to other operations. So you can choose to either (a) read the entire file into memory, and do whatever you want since it's not a file any more; or (b) scan through it only one time.
If you choose to scan through it only once, the easy solution is just to invert the two for loops. Instead of doing this:
for item in list:
    for line in file:

Do this instead:
for line in file:
    for item in list:

And presto! You are now only reading the file one time.
Other Considerations
If I look at your code, and your examples, it seems like you are trying for an exact match on a particular key. You trim down the MAC addresses in your list to check them against the manufacturer ids.
This suggests to me that you might well have many, many more list values (source MAC addresses) than you have manufacturers. So perhaps you should consider reading the contents of the tile into memory, rather than processing it one line at a time.
Once you have the file in memory, consider building a proper dictionary. You have a key (MAC prefix) and a value (manufacturer). So build something like:
for line in f:
    mac = line.split('(base 16)')[0].strip()
    mfg = line.split('(base 16)')[1].strip()
    mac_to_mfg[mac] = mfg

Then you can make one pass through the source addresses and use the dict's O(1) lookup to your advantage:
for src in A:
    prefix = src[1][:8].replace(':', '')
    if prefix in mac_to_mfg:
        # etc...


Q:

Are these two agreements all right?

Wiktionary.com has two examples for ‘as well as’: conjunction and preposition.
Are the two sentences below grammatically correct?

(preposition) He as well as you is right.
  (conjunction) He as well as you are right.

A:

The correct sentence is the following:

He, as well as you, is right.

The subject of the sentence is he for which you use is as verb, not are. "As well as you" is a parenthetical which doesn't change the subject of the sentence.
To use are, you should say something similar to the following:

He and you are right.

You are both right.

A:

The moon, as well as the stars, was shining down on them. is grammatically correct.
The commas are probably considered optional by some writers and grammarians, but they're helpful for indicating that as well as is a preposition here, so I'd say that they're necessary. M-W online shows this: ": in addition to : besides (the coach, as well as the team, is ready)".  Merriam-Webster's Dictionary of English Usage recommends using the commas when the first subject is singular.
When as well as is used as a conjunction, it joins two elements without using commas, just as it would were the sentence The moon and the stars were shining down on them. M-W online shows this: ": and in addition : and (brave as well as loyal)".
Many native speakers make what are called "proximity errors". Many usage experts disagree on what "subject-verb agreement" means in sentences that have complex subjects with a singular and a plural element.

He as well as you are right is an example of a proximity error: "Under the 'proximity rule', the verb is governed by the element nearest to it."

See Merriam-Webster's Dictionary of English Usage pages 140-141, as well as, for a thorough discussion of the problem.
There is no definitive answer to your question.


Q:

How to line up each word in a list so that entries start at the same point horizontally?

Here's an example I've changed slightly from a previous SO question:
http://jsfiddle.net/tPjQR/72/

ol {
    font-family: Georgia, serif;
}
ol span {
    font-family: Arial, sans-serif;
    font-size: 17px
}

Entry one

Entry two

Entrye three

Entry five

Entry six

Entry Long Long Long Long Long Long Long Long Long Long Long Long Long Long Long Long Long

I would like to line up the columns so that, no matter how much text is in one column, the first characters of each column will be lined up.
E.g.
not
Entry one
Entry two
Entrye three
Entry five
Entry six

rather
Entry  one
Entry  two
Entrye three
Entry  five
Entry  six

Is there a way to do this with list items, or do I need to use a table?

A:

Use the below code to get that design...

li span {
    display:inline-block;
    width: 25%;
}

Entry one

Entry two

Entrye three

Entry five

Entry six

A:

An alternative method...

ol {
  list-style-type: none;
  padding: 0;
}

ol li:before {
  content: "Entry";
  display: inline-block;
  margin-right: 10px;
}

one

two

three

five

six

A:

You can change your css
li span {
    display:inline-block;
    width:15%;

}

li  p {text-align: left; display:inline-block; margin : 0px 45px;}

inline-block value of the display property makes this even easier
CSS margin properties are used to generate space around elements.
learn more about that CSS Margins

li span {
    display:inline-block;  width:15%;

}
li  p {text-align: left; display:inline-block; margin : 0px 75px;}

Entry

  one

Entry

  two

Entryre

    three

Entry

    fiv

Entry

    six