text:
Q: how do I change the frequency while producing a bar plot This is an addition to the original question i had asked here
Unable to change the tick frequency on my chart
The answer works absolutely fine, but when my index starts from say 2100 (instead of 0) in my original Q,the graph looks incorrect.
How do I fix it?
import numpy as np
import pandas as pd

df = pd.DataFrame(np.random.randint(1,10,(90,1)),columns=['Values'])
df.index = np.arange(2100,2190,1)
df.plot(kind='bar', xticks=np.arange(2100,2190,5))

A: With bar plots, the xticks are the range index. So you want:
df = pd.DataFrame(np.random.randint(1,10,(90,1)),columns=['Values'])
df.index = np.arange(2100,2190,1)

ax = df.plot(kind='bar')
ax.set_xticks(np.arange(0,len(df),5))
ax.set_xticklabels(df.index[::5]);

Output:


text:
Q: Yii Application works fine on localhost, but throws "not found" error on GoDaddy.com My Yii site works perfectly fine, when run on my laptop (localhost). But, when copied to GoDaddy.com and run from there, I'm getting following error message:

Not Found
The requested URL /website/Search_Best_Boat_Deals was not found on
  this server.
Additionally, a 404 Not Found error was encountered while trying to
  use an ErrorDocument to handle the request. Apache Server at
  website.com Port 80

My main.php configuration file has the following configuration for URL management
'urlManager'=>array(
        'urlFormat'=>'path',
        'showScriptName'=>false,
        'caseSensitive'=>false,
        'rules'=>array(

            '<controller:\w+>/<id:\d+>'=>'<controller>/view',
            '<controller:\w+>/<action:\w+>/<id:\d+>'=>'<controller>/<action>',
            '<controller:\w+>/<action:\w+>'=>'<controller>/<action>',

            'Search_Best_Boat_Deals'=>'site/vessels',

            '<slug:[a-zA-Z0-9-%]+>/'=>'site/Detailview',

            'message/inboxview/<messageId:[0-9]+>/'=>'message/inboxview',
            'message/view/<messageId:[0-9]+>/'=>'message/view',

            'message/sentview/<messageId:[0-9]+>/'=>'message/sentview',

            'message/compose/<id:[0-9]+>/<VesselId:[0-9]+>'=>'message/compose',
            'Gallery/ajaxUpload/gallery_id/<gallery_id:[0-9]+>'=>'Gallery/ajaxUpload',

            'site/activate/key/<key:[0-9]+>/mail/<mail:[0-9]+>'=>'site/activate',

            ),
        ),

My .htaccess file is as follows:
RewriteEngine on

    RewriteBase /
    RewriteCond %{REQUEST_FILENAME} !-f

    RewriteCond %{REQUEST_FILENAME} !-d

    # otherwise forward it to index.php
    RewriteRule ^([a-zA-Z0-9\-]+)$ index.php?page=$1 [L,NC]

What can be wrong?

A: Guy! I appreciate all your help. The following in the .htaccess worked for me
 Options +FollowSymLinks
 IndexIgnore */*

 <IfModule mod_rewrite.c>
 RewriteEngine on

 RewriteCond %{REQUEST_FILENAME} !-f
 RewriteCond %{REQUEST_FILENAME} !-d

 RewriteRule ^.*$ /index.php [L]
 </IfModule>

A: change order of rules.
It seems when accessing /website/Search_Best_Boat_Deals it resolved to Search_Best_Boat_DealsController and actionIndex.
try this
'urlManager'=>array(
    'urlFormat'=>'path',
    'showScriptName'=>false,
    'caseSensitive'=>false,
    'rules'=>array(
        'Search_Best_Boat_Deals'=>'site/vessels',
        '<controller:\w+>/<id:\d+>'=>'<controller>/view',
        '<controller:\w+>/<action:\w+>/<id:\d+>'=>'<controller>/<action>',
        '<controller:\w+>/<action:\w+>'=>'<controller>/<action>',
        '<slug:[a-zA-Z0-9-%]+>/'=>'site/Detailview',
        'message/inboxview/<messageId:[0-9]+>/'=>'message/inboxview',
        'message/view/<messageId:[0-9]+>/'=>'message/view',
        'message/sentview/<messageId:[0-9]+>/'=>'message/sentview',
        'message/compose/<id:[0-9]+>/<VesselId:[0-9]+>'=>'message/compose',
        'Gallery/ajaxUpload/gallery_id/<gallery_id:[0-9]+>'=>'Gallery/ajaxUpload',
        'site/activate/key/<key:[0-9]+>/mail/<mail:[0-9]+>'=>'site/activate',
        ),
    ),

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I have a subscription email format a hyperlink in the comment field? email delivery in ssrs 2005 won't format a hyperlink I enter in unless it generates it.  How do I get a hyperlink in the email text (the comment field in ssrs) instead of it being written out as plain text?

A: Email Delivery in SSRS 2005 would have the Hyperlink if we "Include Link" which will automatically provides us the HyperLink. Correct me if I wrongly understood your question.


text:
Q: Get an Institute List based on my course selection I would like to show list of institutes based on my Course item click. Example If i click on java button i want to show list of institutes that offers Java. If i click on android then institutes of android. How can I achieve that.? Please help. Thanks in advance

A: Approach 1: Can create a tablayout[List of coursed] with a single (activity+fragment)/activity. Fragment will have a recycler view which will show the list of institutes. Based on the tabselection you can refresh the adapter of recycler view given that you already have the data or you are fetching the data on the selection of desired tab where tabs are the list of courses. You can also further extend this to show some details of institute upon click of an item in Recycler view.
Approach 2: Create a Recycler view/List View within a recycler view if list of institutes/course is lets say not much but around 10 or else Recycler view inside of recycler view. Outer one will show the list of courses. Upon click of each course another Recycler view expands below per course and shows list of courses.
Your data object could be:
{
"data": {
    "java": [
        "Insitute1",
        "Insitute2",
        "Insitute3"
    ],
    "android": [
        "Insitute4",
        "Insitute5",
        "Insitute6"
    ]
}

}


text:
Q: I keep getting a DeprecationWarning error with selenium I know it's just a warning and it's not going to change anything but I don't want it there, I've tried out of stupidity to try and catch the exception but still nothing working. :(
error: C:\Users\raze8\PycharmProjects\Selenium\main.py:5: DeprecationWarning: executable_path has been deprecated, please pass in a Service object
driver = webdriver.Chrome("C:/Selenium/chromedriver_win32/chromedriver.exe")
C:\Users\raze8\PycharmProjects\Selenium\main.py:8: DeprecationWarning: find_element_by_* commands are deprecated. Please use find_element() instead
element = driver.find_element_by_id('downloadButton')
C:\Users\raze8\PycharmProjects\Selenium\main.py:10: DeprecationWarning: find_element_by_* commands are deprecated. Please use find_element() instead
progress_element = driver.find_element_by_class_name('progress-label')
from selenium import webdriver

driver = webdriver.Chrome("C:/Selenium/chromedriver_win32/chromedriver.exe")
driver.get("https://jqueryui.com/resources/demos/progressbar/download.html")

driver.implicitly_wait(5)
element = driver.find_element_by_id('downloadButton')
element.click()

progress_element = driver.find_element_by_class_name('progress-label')
print(f"{progress_element.text}")


text:
Q: What resolution will be able to show visible changes on a parcel of farm land? What resolution will be adequate (5m, 2.5m, etc) to show visible changes on a parcel of farm land? Each plot is typically the size of two football pitches.
Details to detect:
a) has the farm land been cleared of bush/ over growth
b) have rows of planting ridges appeared
c) have rows of planting ridges shown signs of change: size, colour, etc
Background
1) we need to track farming activity for given parcels of farm land
2) we have boundary coordinates for each of the farm land above
3) we need to see evidence of farming activity on each allocated parcel of land
4) Our project is in the Sub-Saharan region
My Approach:
1) Collate database of farm-plots boundaries
2) upload set of plot boundaries to a satellite image provider on a weekly (or daily) schedule
3) download latest images from the satellite image provider, then run an image compare algorithm to circle very distinct areas of change (if any)
Is there a simpler approach to achieve the same outlined above?

A: As PolyGeo mentioned in his comment, your question is too broad. There are plenty of satellite images with high spatial resolution including QuickBird, Ikonos, WorldView-1 and WorldView-2 (spatial resolution of 0.46 m), and you can check sample image of WorldView-2, WorldView-3 now provide data at 0.31 m resolution. Answering this question will not be easy, as all the above data has excellent resolution, but it depends on the objective of your research, budget, and temporal resolution (frequency of the sensor to visit the same area again). It is difficult to recommend which is the best because it depends on you. You can check this link which has plenty of sample images of different sensors and sensor information. Then you can decide which is best suitable for you.


text:
Q: Set size and center alert box in twitter bootstrap I'm trying to center and set the size to 80% of an alert box, however it's not working with the class text-center.

  Hey!  It's just an alert...

A:

                Holy guacamole! Best check yo self, you're not looking too good.

The class text-center functions as expected.  Wrapping the .alert within the Bootstrap Grid also provides you the ability to restrict the total width of the notification.
Double-check that you don't have additional CSS that might be overriding your code.  This was tested in Bootply: http://www.bootply.com/MFv1HMC0G7

A: Use center-block instead of text-center with alert if you want to center align the whole alert.

  Hey!  It's just an alert...

If you want to center align the text inside of alert use as:

             Hey!  It's just an alert...

A: To align the alert to the center without adding extra containers, I customized the Bootstrap alert class to look as follows.
.alert {
  left: 0;
  margin: auto; // Centers alert component
  position: absolute; // So that it will display relative to the entire page
  right: 0;
  text-align: center; // Centers 'Alert Test' text
  top: 1em;
  width: 80%;
  z-index: 1; // Displays over app and bootstrap Navbar
}

If you don't want to directly override the base alert class from Bootstrap you can rename the class to whatever you like and reference that class instead.
For this I used React to display my components and included them like this:
Alerts.jsx

  Alert Test
  <button className="close" type="button" data-dismiss="alert">
    ×
  </button>

App.jsx
<>
  <Alerts />
  <Navigation />
  <Switch>
    <Route exact path="/" component={HomePage} />
    <Route path="/login" component={LoginPage} />
  </Switch>
</>

The Alerts.jsx component is imported into the App.jsx component and the result looks something like this.


text:
Q: Laravel 5.7 - VUE Component - Property or method "continent_selected" is not defined on the instance but referenced during render I'm getting this error in a Vue component I'm developing in Laravel 5.7.
Can you tell me what am I missing?
It's just the Input Binding of continent_selected  and country_selected that doesn't work, the rest of the code is fine.

Property or method "continent_selected" is not defined
  on the instance but referenced during render. Make sure > that this property is reactive, either in the data
  option, or for class-based components, by initializing
  the property.

This is my code:
<template>

            <select name="continent_id" v-model="continent_selected" id="continent_id" class="selectpicker" data-live-search="false" title="Pick a continent">
                <option v-if="continents.length>0" v-for="continent in continents" v-bind:value="continent.id">
                    {{ continent.name }}
                </option>
            </select>

            <select name="country_id" v-model="country_selected" id="country_id" class="selectpicker" data-live-search="true" title="Pick a country">
                <option  v-for="(country, index) in countries" v-bind:value="country.id" >
                    {{ country.name }}
                </option>
            </select>

        Continent Selected: {{ continent_selected }}
        Country Selected: {{ country_selected }}

</template>

A: In your data() you have continents_selected instead of continent_selected. Remove the S after continent and it should work.
Your Vue was trying to use a variable that didn't exist (because of the s), which is why this error occured.


text:
Q: kotlin overload resolution ambiguity when generic type is bound to Any Consider this code:
fun main() {
    class A<T> {
        fun m(t: T): Unit {
            print("T")
        }
        fun m(t: List<T>): Unit {
            print("List<T>")
        }
    }

    val a: A<Any> = A()
    val l: List<Any> = listOf()
    a.m(l)
}

The a.m(l) call seems to be ambiguous with the following error:

Overload resolution ambiguity: public final fun m(t: Any): Unit defined in main.A public final fun m(t: List<Any>): Unit defined in main.A

My intuition tells me that the m(t: List<T>) overload should be more specific, but my intuition was already wrong once in the past, when I had a similar case in Java.
I can call the "wrong" overload like this:
a.m(l as Any)

But how can I explicitly call the desired m(t: List<T>) overload? Casting a.m(l as List<Any>) doesn't work.

A: An auxiliary function can help:
fun <T> A<T>.mList(l: List<T>) {
    this.m(l);
}
a.mList(l)

Still curious about an alternative that doesn't involve any indirection like this


text:
Q: How do you create a share link for a document in Sharepoint through Microsoft Graph API I'm trying to create an anonymous link (it's OK if it times out after N number of days) from a file which is in SharePoint Online.
The documentation below seems to work for /me/ folders which are OneDrive for Business basically.
Is there no way of creating a share / anonymous link from a file stored in SharePoint?

A: I'm way too late to help you, but as I just wasted 2.5 hours to get this done, here's the trick :
POST https://graph.microsoft.com/v1.0/sites/{tenantName}.sharepoint.com,{siteCollectionId},{webId}/lists/{listId}/items/{itemId}/driveitem/createLink

With body :
{"type":"view","scope":"anonymous"}

{sitecollectionId} : Can be obtained via {siteCollectionUrl}/_api/site/id
{webId} : Can be obtained via {webUrl}/_api/web/id
{listId} : Can be obtained in URL from the list settings page
{itemId} : Can be obtained by displaying the "ID" field in the current view

*

*How to get the DriveItem from a ListItem : https://learn.microsoft.com/en-us/graph/api/resources/listitem?view=graph-rest-1.0

*How to build a share link for a DriveItem : https://learn.microsoft.com/en-us/graph/api/driveitem-createlink?view=graph-rest-1.0&tabs=csharp


text:
Q: Maven Clean Fails on Linux Vagrant Shared Drive Using vagrant, I git clone'd my java app to c:/shared. In my Vagrantfile, I specified that my host's c:/shared will be mapped to /home/vagrant/myapp on my Virtual Machine.
When I run mvn clean compile from within the VM, I ran into this error:
core/myapp/target/classes/com/myapp/...
        at org.apache.maven.plugin.clean.CleanMojo.execute(CleanMojo.java:215)
        at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:133)
        at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:208)
        ... 19 more
Caused by: java.io.IOException: Failed to delete core/myapp/target/classes/com/myapp/...
        at org.apache.maven.plugin.clean.Cleaner.delete(Cleaner.java:249)
        at org.apache.maven.plugin.clean.Cleaner.delete(Cleaner.java:191)
        at org.apache.maven.plugin.clean.Cleaner.delete(Cleaner.java:158)

However, the Maven build succeeds on my Windows (host) machine.
Running ls gives an odd output as the privileges show up as question marks(?):
[vagrant-centos65 parent]$ ls -lrot target/...
ls: cannot access ...
?????????? ? ? ?            ? $Class$$doMethod$1$1$$anonfun$apply$2.class

I'm running as user kevin, where as /home/vagrant/myapp is owned by vagrant. However, most, if not all, of myapp's directories have wide open (766 or 777) rights.
In the past, I've successfully compiled on the guest VM in a directory shared between host and guest.
I'm using:
vagrant - 1.3.5
Maven - 3.2.1
VirtualBox - 4.3.8

Also, I observed that this particular folder (C:) is not being indexed per this post.
EDIT I'm seeing the same error even when hosting the file with smb.
Why would the build succeed on the host, but not the guest?

A: Had a similar problem, but mainly because I was dumb and had Eclipse running on the host with a project in the shared area abd 'build automatically' selected.
So every time maven deleted a target file, eclipse would recreate it...

A: During compilation, Maven compiled Scala source files into CLASS files.
The length of one .class file was 161. The path's length to this file was ~100.

161 + ~90 = ~261 # exceeds the 255 path length on Windows

In order to fix this problem, @monkjack informed me how to limited the length of a generated CLASS file to 75 characters - https://stackoverflow.com/a/23138361/409976.


text:
Q: GoogleMap V2 Failed to load map.Error contacting Google servers I am using  a Google Api 19.I am getting the Stacktrace error at runtime while running the Google map V2. Failed to load map. Error contacting Google servers. This is probably an authentication issue (but could be due to network errors).
StackTrace:
 E/Random(2450)          : > 17.384058210414967, 78.48609545247936
 E/Random(2450)          : > 17.385480575802443, 78.48634970995319
 E/Random(2450)          : > 17.384707320313552, 78.48718165182942
 E/Random(2450)          : > 17.384469518257607, 78.48737972822704
 E/Random(2450)          : > 17.386012910991372, 78.48664538492055
 E/Random(2450)          : > 17.384268963692328, 78.48682608163563
 E/Random(2450)          : > 17.385942881352822, 78.48616019819285
 E/Random(2450)          : > 17.384971626221553, 78.48736770924768
 E/Random(2450)          : > 17.384794739104553, 78.48631955135781
 E/Random(2450)          : > 17.38564903886939, 78.48614895429334
 D/gralloc_goldfish(2450): Emulator without GPU emulation detected.
 I/Choreographer(2450)   : Skipped 621 frames!  The application may be doing too much work on its main thread.
 E/Google Maps Android API(2450): Failed to load map. Error contacting Google servers. This is probably an authentication issue (but could be due to network errors).

Manifest:
<?xml version="1.0" encoding="utf-8"?>

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="info.androidhive.googlemapsv2"
    android:versionCode="1"
    android:versionName="1.0" >

    <permission
        android:name="info.androidhive.googlemapsv2.permission.MAPS_RECEIVE"
        android:protectionLevel="signature" />

    <uses-permission android:name="info.androidhive.googlemapsv2.permission.MAPS_RECEIVE" />

    <uses-sdk
        android:minSdkVersion="12"
        android:targetSdkVersion="19" />

    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

    <!-- Required to show current location -->
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

    <!-- Required OpenGL ES 2.0. for Maps V2 -->
    <uses-feature
        android:glEsVersion="0x00020000"
        android:required="true" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name">

        <meta-data
     android:name="com.google.android.gms.version"
     android:value="@integer/google_play_services_version" />

        <activity
            android:name="info.androidhive.googlemapsv2.MainActivity"
            android:label="@string/app_name"
            android:theme="@style/AppBaseTheme">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

        <!-- Goolge API Key -->
        <meta-data
            android:name="com.google.android.maps.v2.API_KEY"
            android:value="AIzaSyB2p7rsFLCuYmjA8SnRsIZfjWugwgh4wtU" />

    </application>

</manifest>

MainActivity.java:
package com.map.googlemap;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

public class MainActivity extends Activity {

    // Google Map
    private GoogleMap googleMap;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        try {
            // Loading map
            initilizeMap();

            // Changing map type
            googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);

            // Showing / hiding your current location
            googleMap.setMyLocationEnabled(true);

            // Enable / Disable zooming controls
            googleMap.getUiSettings().setZoomControlsEnabled(false);

            // Enable / Disable my location button
            googleMap.getUiSettings().setMyLocationButtonEnabled(true);

            // Enable / Disable Compass icon
            googleMap.getUiSettings().setCompassEnabled(true);

            // Enable / Disable Rotate gesture
            googleMap.getUiSettings().setRotateGesturesEnabled(true);

            // Enable / Disable zooming functionality
            googleMap.getUiSettings().setZoomGesturesEnabled(true);

            double latitude = 12.987100;
            double longitude = 80.251692;

            // lets place some 10 random markers
            for (int i = 0; i <1; i++) {
                // random latitude and logitude
                double[] randomLocation = createRandLocation(latitude,
                        longitude);

                // Adding a marker
                MarkerOptions marker = new MarkerOptions().position(
                        new LatLng(randomLocation[0], randomLocation[1]))
                        .title("Hello Maps " + i);

                Log.e("Random", "> " + randomLocation[0] + ", "
                        + randomLocation[1]);

                // changing marker color
                if (i == 0)
                    marker.icon(BitmapDescriptorFactory
                            .defaultMarker(BitmapDescriptorFactory.HUE_ROSE));
                if (i == 1)
                    marker.icon(BitmapDescriptorFactory
                            .defaultMarker(BitmapDescriptorFactory.HUE_ORANGE));

                googleMap.addMarker(marker);

                // Move the camera to last position with a zoom level
                if (i == 0) {
                    CameraPosition cameraPosition = new CameraPosition.Builder()
                            .target(new LatLng(randomLocation[0],
                                    randomLocation[1])).zoom(15).build();

                    googleMap.animateCamera(CameraUpdateFactory
                            .newCameraPosition(cameraPosition));
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    protected void onResume() {
        super.onResume();
        initilizeMap();
    }

    /**
     * function to load map If map is not created it will create it for you
     * */
    private void initilizeMap() {
        if (googleMap == null) {
            googleMap = ((MapFragment) getFragmentManager().findFragmentById(
                    R.id.map)).getMap();

            // check if map is created successfully or not
            if (googleMap == null) {
                Toast.makeText(getApplicationContext(),
                        "Sorry! unable to create maps", Toast.LENGTH_SHORT)
                        .show();
            }
        }
    }

    private double[] createRandLocation(double latitude, double longitude) {

        return new double[] { latitude + ((Math.random() - 0.5) / 500),
                longitude + ((Math.random() - 0.5) / 500),
                150 + ((Math.random() - 0.5) * 10) };
    }
}

Output:

I doesn't know how to solve these stackTrace Error.Anybody can help me with these.Thank You.

A: I solved these problem by doing the following steps:

*

*In Emulator:
You have to use the latest API Google APIs(Google Inc.)-API Level
19.
Do the rest of the things placed in the screenshot itself.

*API Key:
Create New API Key and Check carefully about Google Map API key and SHA Key.

*Google Play Services:
You have to download the latest Google Play Services
   com.android.vending-4.8.20.apk.In that site if google play
   services wasn't working means you can find a lot of sites in
   internet named com.android.vending 4.8.20.apk.
you can run the Google play Services by using the Command Prompt
   adb install com.android.vending 4.8.20.apk.
Note: You have to download the latest Google play services because year by year latest version will be updated in internet.

*output:

A: For me the issue was in that I have used network_security_config setting in Manifest under the application tag.
I am still not sure how to handle it correctly but after I just removed that setting (occasionally it wasn`t needed for my project) Maps become to work.


text:
Q: mysql select from 3 different tables I am trying to select from three different tables and order by the date columns:
table_1:
date_1, col_1a, col_1b, col_1c, col_1d, col_1e

table_2:
date_2, col_2a, col_2b, col_2c

table_3:
date_3, col_3a, col_3b, col_3c, col_3d

I am trying to achieve something like:
select * from table_1, table_2, table_3 order by (date) desc

I want the output to be ordered by the most recent date. Is this possible?
Many thanks,
Neil.

A: Your query does a cross join of the 3 tables which produces the cartesian product of the 3 tables which is not what you want (I think).
I suspect you want UNION or UNION ALL:
select 'table_1' fromtable, date_1 date, col_1a cola, col_1b colb, col_1c colc, col_1d cold, col_1e cole from table_1
union all
select 'table_2', date_2, col_2a, col_2b, col_2c, null, null from table_2
union all
select 'table_3', date_3, col_3a, col_3b, col_3c, col_3d, null from table_3
order by date

For this code to work the corresponding columns in all 3 tables must have the same data type.

A: If the tables share a common column, that is, table_1.date = table_2.date, you can do a join
SELECT * FROM table_1
    LEFT JOIN (t2 CROSS JOIN t3)
                 ON (table_2.date = table_1.date AND table_3.date = table_1.date)

If the three tables are completely distinct from each other, then no, you cannot display them in one SELECT.


text:
Q: Three monitors, 3D support, HDMI w/sound I'm setting up a new general purpose PC, and trying to figure out what I need in the way of graphics card and/or motherboard. (I don't have any restrictions on what CPU/GPU/manufacturer/etc - that will follow from this).
Two monitors are regular computer monitors (DVI, at least 1680x1050 - note I don't have these yet), and one is a 1080p TV (HDMI, 1920x1080).
I'd like to be able to play some games (but I do so little that I am probably satisfied with 1-2 year old games, so new lower-end hardware), with that ability on both the TV and one of the LCD monitors. Although I do have a separate PVR system for regular media playback, it would be nice to have 1080p video playback on this one as well (and eventually BluRay, when I get around to that).
It may be nice to have 3 separate displays, but I'd be happy with 2 and having the TV and a monitor show the same thing (I'd be sure to get 1920x1080 LCD monitors if I go this way). Note, if it's 3 separate displays, I need the ability to pick which one does 3D full screen gaming.
I'd also like to be able to output sound over HDMI; and ideally it is the same audio as gets output from the motherboard audio (which should have analog, and coax or optical outputs). The audio will go into both computer speakers/headphones (via analog/spdif), and a Pioneer receiver (via HDMI, or coax if there's no way to do HDMI audio).
What I'm confused about is if this needs to be all on one video card, or split between one card and on-board video on a motherboard, or two cards. Do the monitors go in one, and the TV on another card/motherboard, or does the secondary LCD go on the other card/motherboard?

A: Really tough to beat the Radeon 5xxx series for this.


text:
Q: Do you need an Google account to use Google BigQuery? Background: Is it possible to have user without an google account to use google bigquery web UI to query your data?
I know you can set quota based on google group and add people that does not have a google account in there. I am thinking since this is possible, there might be a way to let user use BigQuery without an google account.
Trying to use the quota function with Google BigQuery web UI. I am not sure if they are able to access Google BigQuery web UI without an Google Account even.

A: Unfortunately no. Our web UI requires sign in with a Google account.


text:
Q: How to upload file using Selenium WebDriver? (not work send_keys) I tried file upload using Selenium WebDriver (Python), but I can't upload it.
I want to upload the file to this website.
https://iotcube.net/process/type/wf1
But, when I tried sending a file using 'send_keys', it not worked.
I run that code in Python:
driver.find_element_by_id('my-awesome-dropzone').send_keys('FilePath')

How can I send file to that website? Help me.

A: if its a window based file handling then selenium alone wont workout. You have to either use AutoIT or ROBOT.
Can have a look at this


text:
Q: Convert int type to HEX equivalent in Java? I have crc16 calculation method:
private static final int POLYNOMIAL = 0x0589;
private static final int PRESET_VALUE = 0xFFFF;
private static byte[] data = new byte[512];

public static int crc16(byte[] data){
        int current_crc_value = PRESET_VALUE;
        for (int i = 0; i < data.length; i++){
            current_crc_value ^= data[i] & 0xFF;
            for (int j = 0; j < 8; j++ ) {
                if ((current_crc_value & 1) != 0) {
                    current_crc_value = (current_crc_value >>> 1) ^ POLYNOMIAL;
                }
                else{
                    current_crc_value = current_crc_value >>> 1;
                }
            }
            if ((i+1)%64==0) {
                System.out.println("\nValue: \t"+(~current_crc_value & 0xFFFF));
            }
        }

        current_crc_value = ~current_crc_value;

        return current_crc_value & 0xFFFF;
    }

After passing data[] array in the crc16 method, It prints the crc value (calculated) System.out.println("\nValue: \t"+(~current_crc_value & 0xFFFF));as:
Value:  64301

Value:  63577

Value:  65052

Value:  63906

Value:  65223

Value:  65369

Value:  63801

Value:  64005

But actually i want it in HEX format as 0x.... Also i can see that the Value is actually 5 digit but this need to be 16 bit crc value,  also i can see that all of them has same MSB i.e 6. Should i omit that value?
I think this is kind of silly question but help would be appreciated.

A: Usually when you need to output variables in a specific format, you can use String.format() for that purpose:
System.out.println(String.format("\nValue: \t0x%x", ~current_crc_value & 0xFFFF));

*

*%x is the hexadecimal format.

*0x is just a plain string here

A: You can simply try using Integer.toHexString(int)
Something like
int val = 12345;
String hex = Integer.toHexString(val);

and to get them back try this:
int i = (int) Long.parseLong(hex, 16);


text:
Q: MVVM catch textbox paste event I have tried to transform this this (from old application) to MVVM pattern but I don't see how I will do it.
textBoxLoader.AddHandler(CommandManager.ExecutedEvent, new RoutedEventHandler(PasteFunction), true);

    private void PasteFunction(object sender, RoutedEventArgs e)
        {
            if ((e as ExecutedRoutedEventArgs).Command == ApplicationCommands.Paste)
            {
                // verify that the textbox handled the paste command

                textBoxLoader.IsEnabled = false;
                List<string[]> MachineList = new List<string[]>();
                List<string> list = new List<string>(Regex.Split(textBoxLoader.Text, Environment.NewLine));
}}

How can I reproduce this and call  command from WPF TextBox Paste event?
I can successfully bind Enter Key event, but how do I bind Paste event?
Below is a code snippet on how I am binding a Icommand in new MVVM (Enter Key listener)
<UserControl.InputBindings>
        <KeyBinding Key="Enter" Command="{Binding ClickCommand}" CommandParameter="{Binding Text, ElementName=textBoxLoader}"/>
    </UserControl.InputBindings>

A: In view :
<TextBox Text="{Binding Text, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Width="120" Height="200"/>

In view model :
class MainWindowViewModel : BindableBase
{
    private string text;

    public string Text
    {
        get { return text; }
        set { SetProperty(ref text, value); }
    }
}

In this way, when you paste the text or press Ctrl+V the Text value is updated and PropertyChanged event is raised. Thus you can identify the pasted text into textbox.
If you want to identify Ctrl+V for some special reason, try this :
void AssociatedObject_PreviewKeyDown(object sender, KeyEventArgs e)
{
    if (Keyboard.Modifiers == ModifierKeys.Control && e.Key == Key.V)
    {
          // Your action
    }
}

A: In MVVM the textbox is bound to a property on the VM. Why not simply subscribe to the VM's notify property change (could be done on the VM itself actually) and look for a change reported on that bound property.
Once a change notification is sent, do the logic needed.
Example
This working example, wouldn't be used in the real world because the work would be done in the setter of Name, demonstrates how to subscribe to the notify event. When Name is changed the VM catches the change from the event and FullName is computed and the property changed is raised for FullName from the subscription.
public class ExampleVM : INotifyPropertyChanged
{
    private string _Name;

    public string Name
    {
        get { return _Name; }
        set { _Name = value; OnPropertyChanged(); }
    }

    public string FullName { get; set; }

    public ExampleVM()
    {
        this.PropertyChanged += (s, a) =>
        {
            if (a.PropertyName == "Name")
            {
                FullName = $"Mr. {Name}";
                OnPropertyChanged("FullName");
            }
        };
    }

    public event PropertyChangedEventHandler PropertyChanged;

    void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

C# 6 coding is used, but can be rewritten in any other version of C#.


text:
Q: Calculate month or quarter of a given date for ISOWEEK calendar In Excel there is a ISOWEEK() function that returns the WEEK of a given date (according to the ISOWEEK system). I wonder how to create similar functions for the MONTH and for the QUARTER (i.e. given a certain data, what is its ISO month or its ISO quarter)? Thanks.
I have tried myself to build the functions but by looking at historical data I cant see a regular pattern, for instance depending on the year, some months have 4 or 5 weeks, but this change seems not following a regular pattern. Also the duration of the quarter for the ISOWEEK system is not so clear to me, shall I assume that the quarter is always 13  full weeks in the case of years with 52 weeks, and with 13+13+13+14 weeks when the year has 53 weeks?.
There are some functions to calculate the quarter as described here: https://www.extendoffice.com/documents/excel/2475-excel-convert-date-to-fiscal-year-or-quarter-or-month.html, for instance
Quarter for a given date:
=CHOOSE(MONTH(A6),3,3,3,4,4,4,1,1,1,2,2,2)

Fiscal month for a given date:
=CHOOSE(MONTH(A6),7,8,9,10,11,12,1,2,3,4,5,6)

However, seems that they don't completely match the ISOWEEK system (for more info about ISOWEEK: https://en.wikipedia.org/wiki/ISO_week_date ).
ISOMONTH should return the given month of a date, for instance ISOMONTH (15/01/2019) should return 1. In a similar way, ISOQUARTER (15/01/2019) should return 1.


text:
Q: List binding I have been reading hundreds of posts on ASP.NET blogs and questions on StackOverflow but I can't find a solution to this (apparently) simple problem. Here is a simplified version:
Question Class
public class Question
{
    public int QuestionId { get; set; }
    public string QuestionBody { get; set; }
    public List<string> Answers { get; set; }
}

I have a simple form for the creation of a Question object. I know there isn't an automatic EditorFor for collections, so I have tried with:
In my form:

     @Html.TextBox("Answers")
     @Html.TextBox("Answers")
     @Html.TextBox("Answers")

In my controller:
public ActionResult Create(Question question, List<string> Answers)
 ...

The answers are correctly passed but they are not being binded to my model!
Question #1: Does exist a way to automatically tie this List of strings to the List of strings contained in my Question model?
Then I tried to "force" this List to be the List in my model, doing:
   question.Answers = Answers;
   db.Questions.Add(question);
   db.SaveChanges();

But my collection is always being passed as empty. I think this is due to the ASP.NET MVC model binding and validation.
So, Question #2: Does exist a way to "modify" my question object just before it is saved to the database with db.SaveChanges() ?
Thank you.

A: you will need to create an editor template for your list see here:
Editor Templates for List<string>
or you can simply put

     @Html.TextArea("Answers")

then the returning info will arrive as string and you can then split that string by line and make a list of it using Linq extensions:
public ActionResult Create(Question question, string answers)
{
    var answerList = answers.Split('\n').ToList();
     question.Answers = answerList;
     db.Questions.Add(question);
    db.SaveChanges();
}


text:
Q: Not able to find the href tag from string collection here is my code....
   $(lines[i]).find('[href]').each(function () {
        checkLinkFooter = true;
        footerLinks += $(this).attr('href') + '~';
        });                   And my string is : If you prefer not to receive, reply to   the sender or        contact us at tmcustomerresponse@agi.com. Getting console error " Syntax error, unrecognized expression:"

A: You need to wrap your string with another dom object to use .find().
Now you have a string starting with a word, so jQuery will consider it as a selector, but since it contains invalid characters, it might throw an error saying something like Uncaught Error: Syntax error, unrecognized expression: hi .
$('
', {
    html: lines[i]
}).find('[href]').each(function () {
    checkLinkFooter = true;
    footerLinks += $(this).attr('href') + '~';
});

Demo: Fiddle


text:
Q: onmouseover transition with map area with multiple images So I have a pie-nav, divided into 6 sections, when I hover over every section using the map tool, it highlights it and change the color of the other sections, I did this the easy way using 6 images, so when I use onmouseover the whole image changes and gives the impression of the selector effect. However, I just want to add simple transition. I can use css transitions for 2 images, but here I'm using 6 images and specific area shape.
<img src="assets/img/default.png" usemap="#Map" id="main-img">
<map name="Map">
  <area shape="poly" onmouseover="document.getElementById('main-img').src = 'assets/img/image1.png';" onmouseout="document.getElementById('main-img').src = 'assets/img/default.png';" coords="40,126,115,42,215,4,255,4,260,102,187,130,127,177" href="#">
  <area shape="poly" onmouseover="document.getElementById('main-img').src = 'assets/img/image2.png';" onmouseout="document.getElementById('main-img').src = 'assets/img/default.png';" coords="32,384,121,337,103,267,123,186,31,135,2,233,5,314" href="#">
  <area shape="poly" onmouseover="document.getElementById('main-img').src = 'assets/img/image3.png';" onmouseout="document.getElementById('main-img').src = 'assets/img/default.png';" coords="32,384,121,337,103,267,123,186,31,135,2,233,5,314" href="#">
  <area shape="poly" onmouseover="document.getElementById('main-img').src = 'assets/img/image4.png';" onmouseout="document.getElementById('main-img').src = 'assets/img/default.png';" coords="32,384,121,337,103,267,123,186,31,135,2,233,5,314" href="#">
  <area shape="poly" onmouseover="document.getElementById('main-img').src = 'assets/img/image5.png';" onmouseout="document.getElementById('main-img').src = 'assets/img/default.png';" coords="32,384,121,337,103,267,123,186,31,135,2,233,5,314" href="#">
  <area shape="poly" onmouseover="document.getElementById('main-img').src = 'assets/img/image6.png';" onmouseout="document.getElementById('main-img').src = 'assets/img/default.png';" coords="32,384,121,337,103,267,123,186,31,135,2,233,5,314" href="#">
</map>

https://jsfiddle.net/kkjjqfkg/

A: Yo, you could create a css file and import it.
img{
  transition: 1s;
}


text:
Q: How can one configure OpenLayers to allow unlimited zooming We are experimenting with using OpenLayers within a PHP application that displays data from PostgreSQL/PostGIS and GeoServer.
The initial use of OpenLayers is terrific except for one problem:
A lot of our data has very small extent eg < 0.1m.
When we zoom in to look at the features they disappear.
We have read the documentation, looked for examples, tried setting zoom values > 19 but to no avail.
There are NO scale thresholds in the SLD so this is not the issue.
Can anyone suggest how to get around this? Is there a NO-LEVELs mode for OpenLayers as we are not interested in mimicking Google Maps etc.


text:
Q: SERVICE_NOT_AVAILABLE GCM I had everything working, but suddenly, when I call
*UPDATE 1 : This is happening on an LG L5, but working normally on Samsung Galaxy s3
regid = gcm.register(Constants.SENDER_ID);

I get an exception of : SERVICE_NOT_AVAILABLE
I did what Google tells to do and set a button to retry whenever such an exception occurs, however I still get the above exception
I checked the following :

*

*Time and date are correct.

*The device has a sim.

*Google play services is installed.
As I said, it was working, but suddenly stopped.
Could this be from google's end as their servers might be overloaded ?

A: SERVICE_NOT_AVAILABLE might mean that your device can't read the response or there was a 500/503 from the server. You said you have a re-try button but Google suggests to have an exponential back-off and then your application should itself try following that exponential back-off time.
Also check if you have "com.google.android.c2dm.intent.REGISTRATION" added to the GCMBroadcastReceiver in your manifest and you are handling that. Check out : GCM SERVICE_NOT_AVAILABLE on Android 2.2 for detailed solution, if you haven't already. Comment if that works.

A: Apparently this is a bug from Google's side, which is unsolved until today.
See here.
Reverting back to the old API solved the issue.


text:
Q: Unable to dispay rows in proper order while reading csv file in PHP I am unable to display row and Columns in proper order when opening in browser.
Expected output : hello,hello1,hello3,hello4,ff,hh,ii,jj
Actual output:hello,ff,hello1,hh,hello3,ii,hello4,jj
I need to iterate the Column1 and then column 2.Below is my CSV file and PHP code.
Name    position
hello   ff
hello1  hh
hello3  ii
hello4  jj

<?php
     $file = fopen('joinUs.csv', "r");
    while ($row = fgetcsv($file, 1000, ',')) {
        $colCount = count($row);

             for ($x=0; $x<$colCount; $x++) {
        echo "
";
            echo "
$row[$x]|
";
        echo "
";
    }

    }

    fclose($file);

 ?>

Please let me know how i can iterate first column in PHP.I am new to PHP.

A: As I understand you want to go through column 1 then column 2.  If we can assume you have a comma separated file then something like this should work:
<?php
$file = fopen('joinUs.csv', "r");

# skip the first line with the titles.
fgets($file);

$first = array();
$second = array();

while ($row = fgetcsv($file, 1000, ','))
{
    # first column
    $first[] = trim($row[0]);

    # second column
    $second[] = trim($row[1]);
}

fclose($file);

echo "
";
foreach( array_merge($first,$second) as $item )
{
    echo "
".$item."|
";
}

echo "
";

?>

The output is then:

hello|

hello1|

hello3|

hello4|

position|

ff|

hh|

ii|

jj|

That is assuming you want to have the order as hello,hello1,hello3,hello4,ff,hh,ii,jj.
There might be a more efficient method but this should get you going.


text:
Q: I have a function that has int a and int b all I have to do is find the max value I keep getting the following error (warning: control may reach end of non void function [-Wreturn-type])
This is what I have right now.
int min(int a, int b) {
    if (b > a) {
        return a;
    }
    if (a > b) {
        return b;
    }
}

A: If b == a then there is no explicit return value. Your compiler is warning you of that.
This is why you should always use a final } else { block.
Although adding
if (a == b){
    return a; // either would do
}

would be an immediate fix, such a change could cause you problems in the future, if you ever write a version of min that takes double types, and one of the inputs is NaN. No compiler I know of currently warns you of that.
Really though, you should ditch this function entirely and use the one from a respected library. For a whole host of technical reasons, the canonical way of writing min is to use
return (b < a) ? b : a;

A: in
int min(int a, int b) {
    if (b > a){
        return a;
    }
    if (a > b){
        return b;
    }
}

you missed the case where a==b
can be just
int min(int a, int b) {
  return (a < b) ? a : b;
}


text:
Q: ADF Copy activity delimited to parquet data type mapping with extra column I'm trying to use a copy activity in ADF to copy data from a csv to a parquet.  I can get column name mappings to work and I can mostly get the data types to map successfully however I am adding a dynamic column called LoadDate that is created from an expression in ADF and I can't seem to get it to map correctly.  Looking at the parquet file that is output for the column "date" which is in the delimited file we get the type of INT96 which Azure Databricks correctly reads as a date.  However for the LoadDate column which is generated using an expression we get the type BYTE_ARRAY.
I just can't seem to get it to output the extra column in the correct format.  Any help would be appreciated.
Below is the mapping section of my JSON.
"mappings": [
                            {
                                "source": {
                                    "name": "Date",
                                    "type": "DateTime",
                                    "physicalType": "String"
                                },
                                "sink": {
                                    "name": "Date",
                                    "type": "DateTime",
                                    "physicalType": "INT_96"
                                }
                            },
                            {
                                "source": {
                                    "name": "Item",
                                    "type": "String",
                                    "physicalType": "String"
                                },
                                "sink": {
                                    "name": "Item",
                                    "type": "String",
                                    "physicalType": "UTF8"
                                }
                            },
                            {
                                "source": {
                                    "name": "Opt",
                                    "type": "INT32",
                                    "physicalType": "String"
                                },
                                "sink": {
                                    "name": "Opt",
                                    "type": "Int32",
                                    "physicalType": "INT_32"
                                }
                            },
                            {
                                "source": {
                                    "name": "Branch",
                                    "type": "INT32",
                                    "physicalType": "String"
                                },
                                "sink": {
                                    "name": "Branch",
                                    "type": "Int32",
                                    "physicalType": "INT_32"
                                }
                            },
                            {
                                "source": {
                                    "name": "QTY",
                                    "type": "INT32",
                                    "physicalType": "String"
                                },
                                "sink": {
                                    "name": "QTY",
                                    "type": "Int32",
                                    "physicalType": "INT_32"
                                }
                            },
                            {
                                "source": {
                                    "name": "LoadDate",
                                    "type": "DateTime",
                                    "physicalType": "String"
                                },
                                "sink": {
                                    "name": "LoadDate",
                                    "type": "DateTime",
                                    "physicalType": "INT_96"
                                }
                            }
                        ]


text:
Q: Getting data of more than 2 joined tables in Laravel and Eloquent Here are my tables.
╔════════════╤═╤══════════╤═╤═══════╗
║ Insurances │ │ Devices  │ │ Brands║
╠════════════╪═╪══════════╪═╪═══════╣
║ id         │ │ id       │ │ id    ║
╟────────────┼─┼──────────┼─┼───────╢
║ IMEI       │ │ type     │ │ name  ║
╟────────────┼─┼──────────┼─┼───────╢
║ device_id  │ │ name     │ │       ║
╟────────────┼─┼──────────┼─┼───────╢
║ user_id    │ │ brand_id │ │       ║
╚════════════╧═╧══════════╧═╧═══════╝

now I wanna show the results data in a table like
╔══════╤════════════╤═════════════╤══════════════╤═════════╗
║ IMEI │ brand_name │ device_name │ device_price │ user_id ║
╚══════╧════════════╧═════════════╧══════════════╧═════════╝

Imagine if it is AJAX and I have to join the tables before sending the data to the view. I have defined the relationships in models. but with the with() method I only can call 2 of em the same time and yet I dunno how to call them in the view.
Are there anyways to not use plain DB::class and just use eloquent?

A: Have you tryed so:
SELECT IMEI, B.name AS Brand_Name, D.name AS Device_Name, D.price, user_id
FROM Insurances I
INNER JOIN Devices D ON I.device_id = D.id
INNER JOIN Brands B on D.brand_id = B.id

A: You should be able to do something like this in your controller to get that result in your view.
$insurance = Insurance::with('device.brand')->find($id);

return json_encode([
  'imei' => $insurance->IMEI,
  'brand_name' => $insurance->device~>brand->name,
  'device_name' => $insurance->device->name,
  'device_price' => $insurance->device->price
  'user_id' => $insurance->user_id

]);


text:
Q: How to add and edit Title column for HTML files How can I add a column in Windows Explorer which either will display the title tag from an html document or which I will be able to edit?
For some reason any column that I tried adding including the title column gave me a empty column and couldn't be edited.

A: In Windows Explorer, you can only edit the filename (+ extension). You can't edit any other column. These columns represent different metadata in the file headers and the explorer is not capable of doing what you want. If you tell us what kind of information you want to store, we might be able to suggest an alternative program which can provide the functionality you are looking for.

A: The columns are meant to allow you to sort by a particular file property.  Whether that be the name of the file, the file's size, or the date modified (or many others).  You can't actually edit the names of those columns however as you're basically asking to create a new property for a file which doesn't really make any sense.  For instance, creating a column named walrus and then expecting windows explorer to associate walrus with every file in your windows explorer view is silly.  A file's size makes sense.  A file's walrus, does not.


text:
Q: GCDAsyncSocket - Read stream never completes I am playing with GCDAsyncSocket (MRC / iOS5.1) for a while, especially with "large" files (5 - 10 mb). Unfortunately sometimes the read stream is never completed (e.g. it gets stuck) just a few bytes at the end of the stream; the didReadPartialDataOfLength: stops giving me information and the didReadData is not fired at all.
Here's some of my code (for both writing / reading examples the connection between the host and client have been established)
WRITING
#define kHeadTag 0
#define kDataTag 1

typedef struct {
    NSUInteger size;
} head_t;

-(void)sendData:(NSData *)__data  {
    _sendData = [__data retain];

    head_t header;
    header.size = __data.length;
    [_socket writeData:[NSData dataWithBytes:&header
                                   length:sizeof(header)]
       withTimeout:-1
       tag:kHeadTag];
}

-(void)socket:(GCDAsyncSocket *)sock
       didWriteDataWithTag:(long)tag {
    if (tag == kHeadTag) {
        [sock writeData:_sendData withTimeout:-1 tag:kDataTag];
        [_sendData release];
        _sendData = nil;
    }
}

READING
-(void)socket:(GCDAsyncSocket *)sock
       didReadData:(NSData *)data
       withTag:(long)tag {
    switch (tag) {
            // ------------------------------------- HEAD
        case kHeadTag:{
            head_t head;
            [data getBytes:&head length:sizeof(head)];
            _readHead = head;
            NSLog(@"Received header (total size = %i bytes)", head.size);
            [sock readDataToLength:head.size
                withTimeout:-1
                tag:kDataTag];
        }
            break;

            // ------------------------------------- BODY
        case kDataTag: {
             NSLog(@"Data received with %i bytes", data.length);
             [sock readDataToLength:sizeof(head_t) withTimeout:-1 tag:kHeadTag];
        }
            break;
    }
};

-(void)socket:(GCDAsyncSocket *)sock
       didReadPartialDataOfLength:(NSUInteger)partialLength
       tag:(long)tag {
    if (tag == kDataTag) {
        NSLog(@"Data read with %i bytes", partialLength);
    }
};

I hope this is enough code to see what I'm doing wrong or maybe this is a bad practice for writing/reading large chunks of data.

A: I added
[self.partnerSocket writeData:[GCDAsyncSocket CRLFData] withTimeout:-1 tag:0];
at the end of sendData: method, and it works fine for me. You just have to append separator chars at the end of the data.
I can transfer around 48MB of file from one iDevice to other iDevice


text:
Q: pgfgantt: How to adjust \gantttitle width same as chart width? Consider the following Minimum Working Example (MWE):
\documentclass{standalone}
\usepackage{tikz}
\usepackage{pgfgantt}

\begin{document}
    \begin{ganttchart}[time slot format=isodate]{2019-01-01}{2019-02-15}
        \gantttitle{TITLE}{30} \\
        \gantttitlecalendar{year, month=name}\\
    \end{ganttchart}
\end{document}

Screenshot of the result:

The question:
How can I automatically adjust the width of the \gantttitle to the same width as the chart itself? Messing around with absolute (incremental) values like 30 does not seem to make a big sense - I guess there is some better solution available?

A: You can define a command that returns the range, and use it.
\documentclass{standalone}
\usepackage{pgfgantt}
\makeatletter
\def\ganttrange{\the\numexpr1+\the\gtt@endjulian-\the\gtt@startjulian\relax}
\makeatother
\begin{document}
    \begin{ganttchart}[time slot format=isodate]{2019-01-01}{2019-02-15}
        \gantttitle{TITLE}{\ganttrange} \\
        \gantttitlecalendar{year, month=name}\\
    \end{ganttchart}
\end{document}


text:
Q: how to send data from baseAdapter to Fragment and go to it in android? I tried this code to go to another fragment from the baseAdapter, but it didn't work for me. I got a lot of errors and I fixed them but now I am getting a new error which is --
The method replace(int, Fragment) in the type FragmentTransaction is not applicable for the arguments (int, Log)
I don't know how to fix this. I have searched a lot but could find no answer.
I'm using a listView inside a fragment and I want to go to another fragment when the item in this list is clicked and I want to pass data to the fragment as well.
 LogFrag fragment2 = new LogFrag();
 FragmentManager fragmentManager = getFragmentManager();
 FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
 fragmentTransaction.replace(R.id.fragment1, fragment2);
 fragmentTransaction.commit();

A: here is the a sample code for that!
class TrackAdapter extends SimpleAdapter {
    Context context;

    public TrackAdapter(Context context, List<? extends Map<String, ?>> data, int resource, String[] from, int[] to) {
        super(context, data, resource, from, to);
        this.context = context;
    }

@Override
public View getView(final int position, View convertView, final ViewGroup parent) {
    final TrackAdapter proxy = this;
    final View trackView = super.getView(position, convertView, parent);

    final TextView name = (TextView) trackView.findViewById(R.id.name);
    name.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent(context ,FRAGMENT_ACTIVITY.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent);

        }
    });

The most important part in the "FLAG_ACTIVITY_NEW_TASK" flag! It must be added for starting fragments!


text:
Q: jQuery BBQ, How to detect a repeat click, which doesn't trigger a hashchange I'm using the jQuery plugin hashchange: http://benalman.com/projects/jquery-hashchange-plugin/
$(function(){
    $(window).hashchange( function(){
      // location.hash
    })
    $(window).hashchange(); // Trigger the event (useful on page load).
});

This works great the problem is if you click on a link more than once:
im a link

the hashchange doesn't refire which I want so that when the user clicks on a link more than once I can refresh the data. Is that possible?
Any ideas on how I can detect a repeat click?
Thanks

A: Check the hash before you apply it, and/or use a flag.


text:
Q: Why does LuaLaTeX not accept this date format in the PDF file? Here's a complete MWE to modify a PDF file and include it in lualatex, which fails:
wget https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf -O dummy.pdf
grep -a Date dummy.pdf
sed -E "s-/CreationDate\(D:.*\)-/CreationDate(D:19700101000000)-" -i dummy.pdf
grep -a Date dummy.pdf
echo "\documentclass{article}\usepackage{graphicx}\begin{document}\includegraphics{dummy.pdf}\end{document}" | lualatex

The document in question is very simple:
\documentclass{article}
\usepackage{graphicx}
\begin{document}
    \includegraphics{dummy.pdf}
\end{document}

The error is:
! error:  (file dummy.pdf) (pdf inclusion): reading image failed

It seems that lualatex does not like the truncated PDF date - this variant works fine:
wget https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf -O dummy.pdf
grep -a Date dummy.pdf
sed -E "s-/CreationDate\(D:.*\)-/CreationDate(D:19700101000000+01'00')-" -i dummy.pdf
grep -a Date dummy.pdf
echo "\documentclass{article}\usepackage{graphicx}\begin{document}\includegraphics{dummy.pdf}\end{document}" | lualatex

But I believe that lualatex is too picky here, as the date of the modified PDF file is valid. Compare https://www.oreilly.com/library/view/pdf-explained/9781449321581/ch04.html

All parts of the date after the year are optional. For example, (D:1999) is perfectly valid.


text:
Q: Nothing happens when I right-click the taskbar I don't get the context menu for the taskbar (or any kind of reaction at all) when I right-click an empty portion of the taskbar.

A: Create a text file with the following contents:
Windows Registry Editor Version 5.00

[HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer]
"NoTrayContextMenu"=-

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\Explorer]
"NoTrayContextMenu"=-

Then rename it to whatever.reg
Then double click on it. You may have to reboot for the changes to take effect.

A: Open the command prompt as administrator. Then run the
sfc /scannow

command. Wait for the execution of the command, and then restart your PC.


text:
Q: How to compute SQL query complexity I have a table with only 3 columns: id, name and timestamp ,
and it is required to extract for each id (and therefore for each name) the most recent timestamp.
For example having this table:

id
name
timestamp

1
foo
2022-02-02

1
foo
2022-03-02

2
bar
2022-01-01

2
bar
2022-04-01

It is expected to get as result:
1,foo,2022-03-02
2,bar,2022-04-01

One implementation could be:
select id, name, timestamp
from
(select
    *,
    row_NUMBER() over(partition by id order by timestamp desc ) ranking
from sample) a
where a.ranking=1

Another possible solution would be this:
select *
from
(select id,max(timestamp) max_timestamp
from sample
group by id) foo,
sample s
where foo.id=a.id
and a.timestamp=foo.max_timestamp

but I think is less efficient.
How can I formally compute the space complexity of the first solution and compare it with the second one?

A: You can easily use group by and max functions to get the last timestamp for each id.
select id
      ,name
      ,max(timestamp)
from t
group by id, name

id
name
max

1
foo
2022-03-02 00:00:00

2
bar
2022-04-01 00:00:00

Fiddle

A: If we want to take last timestamp from each id, and name must be from this last record, then:
select
  distinct on (id) id,
  name,
  timestamp
from sample
order by id,timestamp desc

Complexity can be checked by using EXPLAIN keyword before query.
EXPLAIN show estimates, EXPLAIN ANALYZE additionally run query and shows real time consumed by query.
Efficiency depends on table definition and indexes.


text:
Q: C# 4 optional parameter Is C# 4 optional parameter implementation the same as VB.NET, the optional parameter is compiled on the call site(can cause versioning problems)?

A: Yes.

A: According to SamNg, C#'s default arguments are is compiled at the call site, similar to default parameters in C++.
Yes, it would cause versioning problems.  However, optional parameters should be used where it makes sense.  In many cases, this means passing null or default-constructed class to a method or constructor.


text:
Q: mat-hint svgicon not showing any text I have following code in angular it showing only svg icon and not showing text. I am trying to get output something like   [1]:
https://i.stack.imgur.com/jJmQh.png
There is any other component than mat-hint which gives me same output as per image?
<mat-hint
    *ngIf="hashOptions.placeholder=='Account Name'"
  >
  <mat-icon svgIcon="Application_Information">Note: All accounts created for organizational purposes</mat-icon>
  </mat-hint>


text:
Q: In c# I want to show panel in form1 when i click a button in form 2 1.In c# I want to show panel in form1 when i click a button in form 2. i create a method showpanel(){ panel1.show();} in form1 in this form1 i call showpanel() it is works fine. when i call with form2 it is not work.
In Form2:
private void panel1_MouseDoubleClick(object sender, MouseEventArgs e)
{
    Form1 f1 = new Form1();
    f1.showpanel();
}

In Form1:
public void showpanel()
{
    panel1.Visible = true;
}

2.i also make panel public and call directly from form2 also
In Form2:
private void panel1_MouseDoubleClick(object sender, MouseEventArgs e)
{
     Form1 f1 = new Form1();
     f1.panel1.Show();
     f1.panel1.Visible = true;
 }

but it also not work.

A: From form2 Before showing the form1 you need to make panel1 visible.
private void panel1_MouseDoubleClick(object sender, MouseEventArgs e)
    {
         Form1 f1 = new Form1();
         f1.panel1.Visible = true;
         f1.panel1.Show();
     }


text:
Q: GAE slowness with external MySQL DB I have a Java GAE hobby project utilizing a MySQL DB. I have been using Google's own CloudSQL, but am exploring switching to a cheaper, external MySQL host (Hostinger) for cost reasons.
When I am running the application locally, though still against the new remote MySQL host, the application runs quickly and responsively, just as it did with Google's CloudSQL (both locally and deployed). However whenever I deploy it to the GAE servers, it runs incredibly slow, and from looking at the logs its clear the time is in the DB requests (just reads/selects - no writes at this time).
Is there something inherently slow about GAE applications connecting to external/non-CloudSQL DBs? Anything that can be tweaked to improve performance?

A: As far as I know there is nothing inherently slow when connecting to external services.
What can be generating this long time for connections from GAE to Hostinger is the distance between both datacenters. You can try deploying the GAE in a region closer to the hostinger datacenter and the time shall get reduced.
As a work around for this you can deploy the database in cloudSQL in a micro instance in one of the regions that apply for always free tier this way you can get the short time of response and it will still be cheap.


text:
Q: How to get meta data information about the task metadata in AWS I want to get the meta data information from the task which runs the docker container in AWS. As per the AWS Documentation, I can hit http://169.254.170.2/v2/metadata end point from a container to fetch the info but I am getting bad request exception. Please guide me. Below is my attempt.
 try
{
    string endpointUrl = "http://169.254.170.2/v2/metadata";

    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(endpointUrl);
    request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;

    using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
    using (Stream stream = response.GetResponseStream())
    using (StreamReader reader = new StreamReader(stream))
    {
        var metadata = reader.ReadToEnd();
        Console.WriteLine(metadata);
    }
}
catch (Exception ex)
{
    Console.WriteLine(ex?.Message);
    Console.WriteLine(ex?.InnerException?.Message);
}

The remote server returned an error: (400) Bad Request.


text:
Q: MySQL - One SQL request instead two (both request include diffrent COUNT(*) Once again i need yours help ;). I have a lot data and mysql request are slower and slower so the need request that i need i want group in one comand.
My example DB structure:
|product|opinion (pos/neg)|reason|
__________________________________
|milk   | pos             | good |
|milk   | pos             |fresh |
|chocolate| neg           | old  |
|milk   | neg             | from cow|

So i need information about all diffrent product (GROUP BY) count of it, and count of pos opinion for each product. I want output like that:
|product|count|pos count|
_________________________
|milk   |  3  | 2       |
|chocolate| 1 |  0      |

I hope that my explain was good enought ;)
Or go to work:  I write two commands
SELECT COUNT(*) as pos count FROM table WHERE product = "milk" AND opinion = "pos" GROUP BY `opinion`

And Second one
SELECT product, COUNT(*) FROM table GROUP BY `product`

I don't know how to join this two request, maybe that is impossible? In my real use code i have additional category collumn and i use WHERE in second command too

A: select product,
       count(*) as total_count
       sum(
         case when opinion='pos' then 1
         else 0 end
       ) as pos_count
from the_table
group by product;

A: SELECT  product,
        COUNT(*) TotalCount,
        SUM(opinion = 'pos') POSCount
FROM    tableName
GROUP   BY product

SUM(opinion = 'pos') is MySQL specific syntax that counts the total of result based from the result of boolean arithmethic. If you want it to be more RDBMS friends, use CASE
SUM(CASE WHEN opinion = 'pos' THEN 1 ELSE 0 END)

*

*SQLFiddle Demo


text:
Q: Get Form data from html on page refresh(php) I ran into a little problem with my college project again :(
<input type="text" name="timrem" value="" />

This is a hidden field that I want the data from.
if(isset($_REQUEST['timrem']))
{
    $tim=$_REQUEST['timrem'];
}

This is the code used to get the value from timrem.
The variable timrem is used to initialize a countdown sequence on the page(implemented using javascript)
<span id="countdown-1" style="float:right"><?php echo $tim;?>

The value of the hidden field is dynamically changed via java script counter implemented.
sremtime=(parseInt(minRemain*60)) + (parseInt(secsRemain));
document.frmTest.timrem.value=sremtime;

this works fine when the page is submitted, ie, the time doesn't restart from the next page. But when the page is refreshed, the timer is restarted to the value of the $tim when the timer first started.
Is it possible to somehow get the value of the hidden input on page refresh?
And also, please comment on the approach taken to preserve the time elapsed to the next page. This is a project on online examination.

A: A good idea might be storing a timestamp either in your PHP page or in a database (for multiple users), and use it to generate $tim. Passing data on refresh doesn't seem possible as there is no request triggered.

A: How about you store a "target time" (what ever time remaining is counting down to) in your url. you could even store it in epoch time:
myurl.com/stuff.html?target_time=1359553896

that way when the page is refreshed you still have it with you and you can calculate time remaining from that. if you don't want it in your url, you could probably hide it on the page somewhere with a display:none style.
how about something like this:
http://jsfiddle.net/QpZcV/1/

A: If you need your variable to persist across refreshes, you cannot rely on information passed back from client to server. The only information you can rely on is the information passed with the very first request, and that obviously doesn't include your time. The best solution I can think of is to store your timestamp in a session variable on the server:
session_start();
if(empty($_SESSION['timrem'])) $_SESSION['timrem'] = time(); // set this if it is the first time this page is loaded
$tim = time() - $_SESSION['timrem']; // $tim is now the number of seconds since the page was first loaded in this session

You do not need to pass the time back and forth between client and server to keep track of it, although your javascript will probably need it.


text:
Q: Zipping a Mac app bundle with Python I'm writing a Python (2.7) script to build and distribute my Mac (10.7) app. I want to zip it up for distribution, but the following code results in an empty zipped app (0 bytes):
from zipfile import ZipFile

with ZipFile(zip_file_dist_path, 'w') as dist_zip:
    dist_zip.write(archived_app, os.path.basename(archived_app))

Is it treating it as a file, when I need to treat it as a directory? If I zip it up by walking the app bundle's directory tree and writing each file to the zip, will it unzip with all the proper file system metadata (i.e. will I get back out a proper app)?

A: I switched from ZipFile to shutil.make_archive, since it takes care of the directory recursing, and I don't need any finer-grained control:
import shutil

zip_file_path = shutil.make_archive(zip_file_build_path, 'zip', root_dir = dist_dir);

A: ZipFile only zip one file to an archive once.
You can find how to adding folders to a zip file here:
Adding folders to a zip file using python


text:
Q: Extract String From Files In Directory And Assign It To Dataframe in Python I have 3 Excel files in a folder called:

*

*FY18_Msft Cloud_test.xlsm

*FY19_Msft Cloud_test.xlsm

*FY20_Msft Cloud_test.xlsm

They all have a sheet called "Digital" and I want to merge the data from the three files into a new data frame which I've done with the code below. However, then I also want to add two new columns: one called "Channel" that will read "Digital" for all files and another one called "Fiscal" that will read "FY18" for the data taken from the first file, FY19 from the second file and FY20 from the third file.
I have the for loop below and while I manage to get the get the data merge and the Channel okay I can't figure out a way to add the correct fiscal against each data entry. I extract the name of the fiscal from the file name by taking the string before the first underscore.
digital_df = pd.DataFrame()
os.chdir(plans_folder)

            for infile in glob.glob(plans_folder + "*Msft Cloud*.xlsm"):
                for fiscal in glob.glob("*Msft Cloud*.xlsm"):
                    data_digital = pd.read_excel(infile, sheetname="Digital", skiprows=9)
                    data_digital.insert(0, "Channel", "Digital")
                    digital_df = digital_df.append(data_digital, ignore_index=True)
                    fiscal = fiscal.split('_', 1)[0]
                    digital_df['Fiscal'] = fiscal

digital_df

Any ideas?

A: You can use os.path.basename() to get your information more easily - from a full filepath, this reports the name of the file (usually!).
So you could do the following (assuming you've already imported os). Note you can simplify your loops - you previously did both infile and fiscal which were effectively returning the same list of files, meaning you;d get each of the four files four times! Also, it's much easier to add the fiscal year before merging the DataFrames:
for infile in glob.glob(plans_folder + "*Msft Cloud*.xlsm"):
    data_digital = pd.read_excel(infile, sheetname="Digital", skiprows=9)
    data_digital["Channel"] = "Digital"
    f_year = os.path.basename(infile).split('_')[0]
    data_digital["Fiscal"] = f_year
    digital_df = digital_df.append(data_digital, ignore_index=True)

As an aside, if you're using os.path.basename() in this way, you don't need to change into the directory (with os.chdir)
To write this dataframe to a csv, you can use the to_csv() method of a DataFrame:
digital_df.to_csv(os.path.join(plans_folder, 'Summary.csv'), index=False)

This should overwrite any existing file, and using os.path.join ensures we end up in the same folder as the files.


text:
Q: How to Sort WPF MultiBinding DataGridTextColumn based on the MultiBinding? I want to Sort the DataGridTextColumn based on the Multibinding Values - The Text Column is bind with both Date and Time, so the sorting operation should be done based on DateTime.
The XMAL Source Code is
<DataGridTextColumn Header="Visit Date" CanUserSort="True" >
    <DataGridTextColumn.SortMemberPath>
        <MultiBinding StringFormat="{}{0} {1}">
            <Binding Path="VisitDate"/>
            <Binding Path="VisitTime" />
        </MultiBinding>
    </DataGridTextColumn.SortMemberPath>
    <DataGridTextColumn.Binding>
        <MultiBinding StringFormat="{}{0} {1}">
            <Binding Path="VisitDate"/>
            <Binding Path="VisitTime" />
        </MultiBinding>
    </DataGridTextColumn.Binding>
</DataGridTextColumn>

The View and View Model C# Source Code is
public class Employee
{
    public string empName { get; set; }
    public string VisitDate { get; set; }
    public string VisitTime { get; set; }
}

public class EmployeeInfo
{
    public ObservableCollection<Employee> EmployeeList { get; set; }

    public EmployeeInfo()
    {
        EmployeeList = new ObservableCollection<Employee>();
        EmployeeList.Add(new Employee { empName = "John", VisitDate = "11/28/2015", VisitTime = "05:12 PM" });
        EmployeeList.Add(new Employee { empName = "Potter", VisitDate = "10/28/2015", VisitTime = "04:33 PM" });
        EmployeeList.Add(new Employee { empName = "James", VisitDate = "11/27/2015", VisitTime = "09:12 AM" });
    }
}


text:
Q: Banach space with non-complemented subspace I see examples on Stack Exchange and elsewhere of Banach spaces with non-complemented subspaces (examples: 1, 2 [Remark 8], 3 [a remarkable example of a Banach space with no complemented closed subspaces]). My question is thus:
We know that every vector space (and therefore every Banach space) has a vector space basis. Therefore, for a Banach space $X$ and a subspace $E$, we can write a basis $\mathcal{B}_E$ for $E$ and extend it to a basis $\mathcal{B}$ for $X$. Consider $F$ to be the subspace spanned by $\mathcal{B}\setminus \mathcal{B}_E$. Why is $F$ not necessarily a complementary subspace to $E$? It seems that for $v\in X$, we should have that $v$ is uniquely represented by an element of $E$ plus an element of $F$, since it is uniquely represented by a finite linear combination of elements in $\mathcal{B}$ (and we can therefore segregate those elements into elements of $\mathcal{B}_E$ and $\mathcal{B}\setminus \mathcal{B}_E$). Also, it seems that $E\cap F = \{0\}$, since the basis vectors for $E$ and $F$ are linearly independent from each other. Could somebody please help by pointing out where I might have made a faulty assumption?

A: Let me summarise some known facts related to your question.

*

*If $X$ is isomorphic to a Hilbert space then every closed subspace of $X$ is complemented.

*By a very deep result of Lindenstrauss and Tzafriri, a Banach space whose every closed subspace is complemented is necessarily isomorphic to a Hilbert space. Thus, spaces not isomorphic to Hilbert spaces always contain uncomplemented subspaces.

*Complementability is related to the possibility of extension of operators. If $Y$ is a closed subspace of $X$ then $Y$ is complemented if and only if the inclusion map extends to a bounded operator $X\to Y$.

*If $X$ is $\ell_\infty(\Gamma)$, $L_\infty(\mu)$, or more generally an injective space then whenever we have a bounded operator from a subspace $Y$ of some Banach space $Z$ to $X$, this operator can be extended to a bounded operator $Z\to X$. The same is true for $X=c_0$ as long as the space $Z$ is separable.

A: The point is that once in infinite-dimensions, a subspace can be somewhat wrapped up by its surrounding space to prevent unique representation of vectors by components in and out of the subspace. I think the best example to understand this phenomenon is in the non-locally-convex Ribe space which is a quasi-Banach topology on $R+L$ where $L$ is the space little-$L_1$ of absolutely summable sequences. It is constructed so that $R+\{0\}$ is equal to dual annihilated subspace and is contained in every closed infinite-dimensional closed subspace. Thus, it is a one-dimensional subspace that is not complemented. In Banach spaces, one-dimensional spaces are always complemented.
This is presented in a cleaned up manner in https://www.cambridge.org/core/books/an-fspace-sampler/917AAA51A5370CD786D32448FE828810 but
A later article by N.J. Kalton shows this space has no strictly weaker Hausdorff topology, i.e. is an F-space with no basic sequences. This can be found as article 150. at the cite: https://kaltonmemorial.missouri.edu/publications.html


text:
Q: Android ImageView causing whitespace at the bottom My code below is causing a whitespace at the bottom of the image. I wanted the image to cover the entire screen, but somehow it isn't.
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MainActivity">

<RelativeLayout android:layout_width="match_parent"
                android:layout_height="match_parent">

    <ImageView
        android:src="@drawable/ohm"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scaleType="centerCrop"
        android:adjustViewBounds="true"/>

    <ImageView
        android:id="@+id/logo"
        android:src="@drawable/test2"
        android:layout_width="70dp"
        android:layout_height="70dp"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="20dp"/>

    <ImageView
        android:id="@+id/night"
        android:src="@drawable/night"
        android:layout_width="340dp"
        android:layout_height="250dp"
        android:layout_below="@id/logo"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="10dp"/>

    <EditText
        android:id="@+id/username"
        android:layout_width="340dp"
        android:layout_height="50dp"
        android:layout_centerHorizontal="true"
        android:layout_below="@id/night"
        android:layout_marginTop="20dp"
        android:alpha="0.2"
        android:background="@drawable/rounded_edittext_states"
        android:textColor="#D69E29"
        android:textStyle="bold"
        android:paddingLeft="15dp"
        android:hint="USERNAME"
        android:textColorHint="#D69E29"/>

    <EditText
        android:id="@+id/password"
        android:layout_width="340dp"
        android:layout_height="50dp"
        android:layout_centerHorizontal="true"
        android:layout_below="@id/username"
        android:layout_marginTop="10dp"
        android:alpha="0.2"
        android:background="@drawable/rounded_edittext_states"
        android:textColor="#D69E29"
        android:textStyle="bold"
        android:paddingLeft="15dp"
        android:hint="PASSWORD"
        android:textColorHint="#D69E29"/>

</RelativeLayout>
</ScrollView>

I've tried changing to different scaleType but it is still the same. Then, if I change the adjustViewBounds to false, the image will become double in height.
Below images are the 2 issues I am facing.
http://i.imgur.com/BOM5Cfe.png
http://i.imgur.com/Fe5WMoQ.png

A: I have met this problem before, my solution is to use the image which have the same width:height ratio with the screen.

A: I found a solution for this issue. I create a Layout and put the ScrollView inside it, then create another Layout inside the ScrollView. I'm not sure if this is a good or bad practice, but it seems to be a solution for now. Will need some experts to view the solution.
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<ScrollView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/ohm">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    </RelativeLayout>

</ScrollView>
</LinearLayout>


text:
Q: OK to have two designated initializers? I have the following in a subclass of UIViewController;
- (id) initWithFullScreen
{
    self = [super initWithNibName:nil bundle:nil];

    if (self)
    {
        _fullScreen = YES;
    }

    return self;
}
- (id) init
{
    self = [super initWithNibName:nil bundle:nil];

    if (self)
    {
        _fullScreen = NO;
    }

    return self;
}

- (id) initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    return [self init];
}

As you can see they aren't all chained together like recommended as there are two initializers that call the super classes designated initializer. Is this OK to do?

A: Why not do it this way instead:
- (id)initWithFullScreen:(BOOL)useFullScreen
{
  self = [super initWithNibName:nil bundle:nil];
  if(self) {
    _fullScreen = useFullScreen;
  }
  return self;
}

- (id)init
{
  return [self initWithFullScreen:NO];
}

- (id)initWithNibNameBlahBlahBlah...
{
  return [self init];
}

A: Yes, it's OK.
A designated initializer isn't part of the Objective-C language, it's just a convention. In general, if you route everything through one init method, your don't have to worry about duplicating code across all the other convenience init methods that you might want to offer.
It also lets you know which init method you should call on the superclass when you want to create a subclass. (Your third init method, initWithNibName... violates this rule, actually. Instead of calling the superclass's designated initializer, you're just calling init.)
In your case, declaring an initializer with the method signature initWithFullScreen:(BOOL)fullScreen and designating it the designated initializer is probably the way to go. And within that you make sure you call the superclass's designated initializer, which you are.
You could then create convenience initializers: initWithFullScreen and initWithoutFullScreen if you wanted to; they would both just call your designated initializer. For example:
- (id)initWithoutFullScreen
{
    return [self initWithFullScreen:NO];
}

So, it's OK to break the convention. You may have your reasons. But it's generally easier to keep your code organized if you stick to it.
Amendment
For extra credit, consider the NSCoding protocol, which requires classes to have an initWithCoder: method. One might say it violates the rule, since classes which adopt NSCoding and whose superclasses also adopt NSCoding must be prepared to have two paths to initialization: an initWithCoder: method which calls [super initWithCoder:coder] and the regular designated initializer.

A: Think of them as methods rather than initializers. So yes you can have as many methods as you want.
Also try to utilize nibNameOrNil and nibBundleOrNil in initWithFullScreen and init unless you really don't need them.
Also for simplicity you can have a method like this
- (id) initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil fullScreen:(BOOL)useFullScreen
{
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])
      {
         _fullScreen = useFullScreen;
      }
    return self;
}


text:
Q: Linq query for grouping I have to generate say Customers Report.
there is condition for grouping records like
grouped and/or filtered by CustomerFirstName\CustomerCity
       or CustomerLastName\CustomerCity

What would this Linq query look like?

A: Simple image representation of group by might help you

Full aricle : SQL to LINQ ( Visual Representation )


text:
Q: C# Finding a socket ID? Recently I have started working on a program that will monitor the packets of one of my open-source programs in an attempt to learn more about programming and networking. Also, I want to add additional functionality to the program without editing the source, like an external control panel.
(I used WPE Pro to filter packets in case you'r wondering, WireShark is too much hassle for such a simple task.) One thing bothers me though, the Socket ID.
I know what it is, and I've asked a question about it before, but I cant figure out how to use it/assign one/intercept one.
Without the right socket ID, my program wont be able to do anything, so my question is if it's possible to find out what Socket ID a socket is using, once you capture the packet?
If not, are there any other ways of doing? -or possible other languages like Visual Basic?
Thank you for your time.

A: If, by socket ID, you mean the return value of a successful call to socket() function, I don't think there's a way.
The closest thing you can obtain is the process ID because, as you may already know, each IP packet has a destination that's described by the tuple (IP address, port) and inside a system only one socket can be successfully bound to that tuple. Utilities like TCPView are able to map an IP tuple to a process, so a way does exist if that information is enough for you.
If that's not the case, I'm not aware of any method to retrieve the socket ID you need if the target application is not collaborative.

A: This library: SharpPcap promises doing capturing, injecting, analyzing and building packets using any .NET language such as C# and VB.NET (more info).
It is the library used by Wireshark and it is for sure that it can capture and analyze.

A: socket() returns a file descriptor if this is what you are referring to as a socket ID then the ways to get this without the process's collaboration on windows are limited. FWIW on linux open FDs are enumerated in the proc filesystem.
That being said, the only thing you would be able to do with the fd is send additional information from the socket. You could also read from the fd, but any data read in this way would not be sent to the application that owns the socket. Without some coordination, that would probably not be what you desire as you would just get bits and pieces of data.
If just want to be able to listen in on the traffic in your program, then something like packet filtering should be sufficient so I assume you actually want to be able to be like a man in the middle for it.
If this is the case, then the best thing to do would actually be to set your application up as a proxy for your other service.
By this I mean, write a program that opens a listening port and accepts connections when a connection is initiated, it should immediately open its own connection to a pre-configured IP:port combination and begin forwarding traffic. Once this is written it's a simple matter to inspect the traffic before forwarding and possibly modify it.
If your program is a server, run it on a non-standard port, configure this application to open the server's normal port and then forward connections to the non-standard port you set up on localhost.
If your program is a client, simply point the interceptor application at the server and choose a random listen port on your box. Then configure the client to connect to this listen port as though it were the server.
This should work for pretty much anything. The only caveat is if the traffic is encrypted you will (obviously) not be able to inspect/modify it. This is effectively the same as placing your application behind a NAT.


text:
Q: How to add a name to a function? This is probably a really simple question but I am sort of confused how jQuery or JavaScript work in this way.
If I have a function for instance like this
$(function() {
    $('section').on('click', 'div', function(e) {
    var number = Math.floor(Math.random()*videos.length);
    $(this).find('source').each(function(index){
          videoSrc = videos[number][index].src;
          $(this).attr('src', videoSrc);
          $('video').load();
          $('video').play();
        });
    });
});

How would I write it so that I could reference it to run in html?

I see functions written like window.onload=function() or thisFunction = function() etc..
and it sort of has me confused as to how a function is declared when compared to something like HTML where it is literally just div id="name" or class="name" etc..
I guess my main question is how would I get the above code to run onload in html instead of on click? Where do I title a function so that I can use it for later?
Any help on clarifying this would be greatly appreciated! Cheers!
A lot of the answers i've received have ended up making more more confused and I am actually not sure what to do now.. I know I must be over thinking this but I still can't figure out how to get the site to randomize both on click and on page load.
Here is the code I have currently.
HTML

        <title>Randomizer</title>

            <video loop autoplay>
              <source src="" type="">
              <source src="" type="">
              Your browser does not support the video element.
            </video>

JavaScript
var videos = [
    [{type:'mp4', 'src':'/videos/1.webm'}, {type:'webm', 'src':'/videos/1.mp4'}],
    [{type:'mp4', 'src':'/videos/2.webm'}, {type:'webm', 'src':'/videos/2.mp4'}],
    [{type:'mp4', 'src':'/videos/3.webm'}, {type:'webm', 'src':'/videos/3.mp4'}],
    [{type:'mp4', 'src':'/videos/4.webm'}, {type:'webm', 'src':'/videos/4.mp4'}],
    [{type:'mp4', 'src':'/videos/5.webm'}, {type:'webm', 'src':'/videos/5.mp4'}],

];

$(function() {
    $('section').on('click', 'div', function(e) {
    var number = Math.floor(Math.random()*videos.length);
    $(this).find('source').each(function(index){
          videoSrc = videos[number][index].src;
          $(this).attr('src', videoSrc);
          $('video').load();
          $('video').play();
        });
    });
});

$(document).ready(function() {
    var number = Math.floor(Math.random()*videos.length);
     $(this).find('source').each(function(index){
          videoSrc = videos[number][index].src;
          $(this).attr('src', videoSrc);
          $('video').load();
          $('video').play();
        });
 }
);

I was able to finally understand how it works with the above code.
Thanks for the help everyone!

A: You don't need a function with a name for what you want to achieve (function names are mostly useful for making stacktraces in debuggers more useful than a list of a dozen (anonymous function)). You need to have a function in a variable.

There are four ways to create a function in JavaScript.
Function declaration
This will create a variable foo in the current scope and assign a named function to it.
function foo () {

}

Function declarations are hoisted so it doesn't matter where, in the applicable scope, you put them. It is considered good coding practise to define them before you use them though.
Anonymous function expression
This will create a function without a name and use it in an expression. In this example it is assigned to the variable something.
something = function () {

};

Named function expression
This is the same as an anonymous function expression except that it has a name, creates a variable of that name in the scope of itself and is horribly broken in older versions of Internet Explorer.
something = function foo () {

};

Function constructor
Do not use function constructors. They are eval by another name. You can read about them on MDN if you're interested.

You are currently using an anonymous function expression and passing it as a function argument (instead of assigning it to a variable as the example above does).
Just define the function separately (using any of the above techniques) and then pass the variable instead.
function foo(e) {
    var number = Math.floor(Math.random()*videos.length);
    // etc
}

$('section').on('click', 'div', foo);

Watch out for scope. Declaring a function inside another function will create a local variable that you can't call globally using an intrinsic event attribute.
That said, we're approaching two decades since 1997 so you shouldn't be using intrinsic event attributes anyway.
$(document).on('load', foo);

A: Surely
function myname() {
    $('section').on('click', 'div', function(e) {
    var number = Math.floor(Math.random()*videos.length);
    $(this).find('source').each(function(index){
          videoSrc = videos[number][index].src;
          $(this).attr('src', videoSrc);
          $('video').load();
          $('video').play();
        });
    });
};

is required
Then
myname();

A: What you have in your code is an anonymous function. These are useful for one-time calls or for use as callback functions. For what you are trying to accomplish, you want to assign the FUNCTION REFERENCE to a variable. A function reference can be INVOKED at a later time by using parentheses, e.g. var_name()
var x = function(){
  // your code
}

onclick="x()"

A: It would look like this:
$(function() {
    function myFunction() {
        $('section').on('click', 'div', function(e) {
            ...
        });
    }

    $('body').on('load', function() {
        myFunction();
    });
});

Placing the onload listener in the script like this is preferable for several reasons, such as separation of concerns, cleaner markup, etc.
That said, your original code does the same job without the body onload property. You don't actually need either method.

A: To name the function you can write
function function_name(){
    $('section').on('click', 'div', function(e) {
    var number = Math.floor(Math.random()*videos.length);
    $(this).find('source').each(function(index){
          videoSrc = videos[number][index].src;
          $(this).attr('src', videoSrc);
          $('video').load();
          $('video').play();
        });
    });
};

Then you call it as function_name();
To make it run when the html is ready you write
$( document ).ready(
    function_name();
});


text:
Q: How to profile all web requests to Azure Cloud Service with Application Insights Profiler? I have a question about Application Insights Profiler.
I installed it on the Cloud Service and it works when I add the inline code from the docs:
https://github.com/CawaMS/EnableProfilerForCompute/blob/master/How%20to%20enable%20Application%20Insights%20Profiler%20on%20Azure%20Compute%20resources.md#enable-the-profiler-on-cloud-services-applications
using (var operation = client.StartOperation<RequestTelemetry>("[unique_name_for_your_operation]"))
{
    ProcessQueueMessage(msg);
}

But how can I trace all the requests with a profiler for a web role? I can't find any info for several days. The official docs say that for web roles it track all requests automatically:
https://learn.microsoft.com/en-us/azure/application-insights/app-insights-profiler-cloudservice#enable-profiler-for-your-azure-cloud-service

*Track requests with Application Insights:

  For ASP.Net web roles, Application Insights can track the requests
  automatically.
For Worker Roles, add code to track requests.

And also the troubleshooting docs describe the App Service problems, not Cloud Service:
https://learn.microsoft.com/en-us/azure/application-insights/app-insights-profiler-troubleshooting?toc=/azure/azure-monitor/toc.json