text:
Q: Dynamically populating table names from dropdownlist and displaying in Gridview I am creating a web page that contains one Dropdownlist and Gridview.
Query is Dropdownlist will contains SQL Server database table list. When I select a table name from dropdownlist the Gridview needs to show entire table data and able to perform edit, update, delete, cancel action.
When I click edit Gridview need to show update and cancel buttons and it update should update dropdownlist table and also delete.
My code looks this:
Html page:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="DataGridView_Sample._Default" %>

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

    <title>Untitled Page</title>

    <form id="form1" runat="server">

            Data Grid View Sample

    <asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="true"
    onselectedindexchanged="DropDownList1_SelectedIndexChanged">
         <asp:ListItem Text="-- Select --" Value=""></asp:ListItem>
        <asp:ListItem Text="Emp" Value="Emp"></asp:ListItem>
        <asp:ListItem Text="Dept" Value="Dept"></asp:ListItem>
    </asp:DropDownList>

    Grid View:

    <asp:GridView ID="GridView1" runat="server" Height="181px"
        onrowediting="GridView1_RowEditing" onrowupdating="GridView1_RowUpdating"
        Width="518px">
        <Columns>
            <asp:CommandField ButtonType="Button" ShowEditButton="True" />
        </Columns>
        <EmptyDataTemplate>

        </EmptyDataTemplate>
    </asp:GridView>
    </form>

.aspx page code:
namespace DataGridView_Sample
{
    public partial class _Default : System.Web.UI.Page
    {
        SqlConnection con = new SqlConnection("Data Source=SHINY-PC\\SQLEXPRESS;Initial Catalog=NRK;Integrated Security=True");
        SqlCommand cmd = new SqlCommand();
        SqlDataAdapter da = new SqlDataAdapter();
        DataTable dt = new DataTable();
        DataSet ds = new DataSet();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                con.Open();
                cmd = new SqlCommand("Select name from sys.tables order by name", con);
                da = new SqlDataAdapter(cmd);
                da.Fill(ds);
                DropDownList1.DataSource = ds;
                DropDownList1.DataTextField = "name";
                DropDownList1.DataValueField = "name";
                DropDownList1.DataBind();
                DropDownList1.Items.Insert(0, new ListItem("--Select--", "--Select--"));
            }
        }

        protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (DropDownList1.SelectedIndex != 0)
            {
                cmd = new SqlCommand("select * from " + DropDownList1.SelectedItem.Value, con);
                con.Open();
                da = new SqlDataAdapter(cmd);
                da.Fill(dt);
                GridView1.DataSource = dt;
                GridView1.DataBind();
                con.Close();
            }
        }

        protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
        {
            cmd = new SqlCommand("select * from " + DropDownList1.SelectedItem.Value, con);
            con.Open();
            da = new SqlDataAdapter(cmd);
            da.Fill(dt);
            GridView1.EditIndex = Convert.ToInt16(e.NewEditIndex);
            GridView1.DataSource = dt;
            GridView1.DataBind();
            con.Close();
        }

        protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
        }

        protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
        }
    }
}

Please any one can help.
Thanks in advance.

A: Given the above, I'd create a database table with two fields: tablename and columnname. There will be 4 rows with tablename = emp and each row will have a columnname = one of the columns from the emp table. Similarly, there will be 6 rows where tablename = dept and each row will have a columnname = one of the columns from the dept table. Then, in your GridView1_RowUpdating event, you can pull the names of the columns from the database based on the table that's been chosen in the DropDownList and update accordingly using whatever stored procedure you have in place for that table. In GridView1_RowCancelingEdit, you just need to do
GridView1.EditIndex = -1;

and rebind your data (you'll need a method for that) you're done.


text:
Q: Checking long cover of sensor I've got some probmel with checking long time cover of my sensor (which is used to turn off the screen while phone is near ear). I want to detect short and long cover of this sensor (for example by my finger). It's my code, I can detect cover but I can't check if it was long or short (I think that sth wrong is in my thread but i don't know what)
public class NextActivity extends Activity implements SensorEventListener {

    private static final String TAG = "DISTANCE";
    private SensorManager mSensorManager;
    private Sensor mProximity;
    public TextView tv;
    public TextView tv2;
    public int check=0;
    float distance=0;
    public float eventTime;
    public MyThread thread;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_next);

        mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        mProximity = mSensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);

        tv = (TextView)findViewById(R.id.textView1);
        tv2= (TextView)findViewById(R.id.textView2);
        thread = new MyThread();
        thread.start();
    }

  public final void onSensorChanged(SensorEvent event) {
    distance = event.values[0];
        tv.setText(""+thread.isAlive());
  }

  @Override
  protected void onResume() {
    // Register a listener for the sensor.
    super.onResume();
    mSensorManager.registerListener(this, mProximity, SensorManager.SENSOR_DELAY_NORMAL);
  }

  @Override
  protected void onPause() {
    // Be sure to unregister the sensor when the activity pauses.
    super.onPause();
    mSensorManager.unregisterListener(this);
  }

    public class MyThread extends Thread {

        @Override
        public void run() {
            while(true){
            if(distance<1)
            {
                long time = System.currentTimeMillis();
                while(System.currentTimeMillis()<time+300);
                if(distance<1)
                {
                    tv.setText("DOUBLE -> NEXT");
                    distance=5;
                } else tv.setText("ONCE -> BACK");
            }else tv.setText("NONE CLICKED");
            }}
    }

}

A: Right now the Thread spins constantly which is going to be bad for the battery and perhaps performance of everything else.
           long time = System.currentTimeMillis();
           while(System.currentTimeMillis()<time+300);

should be replaced with:
           try {
               Thread.sleep(300);
           } catch(InterruptedException ie) {}

The second problem is that the TextViews are not being updated in the UI thread. So a Hnadler will have to be set up to receive messges to set the text, or Runnables defined to use with runOnUiThread.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to add regex rules in .ctags file for matching javascript es6 method? I am using this line for matching methods of javascript file:
--regex-javascript=/^[ \t]*([A-Za-z0-9_$]+)\(.*\)[ \t]*{/\1/M,Method,Methods/
But this rule will also match if(), switch() and for(), I changed the rule to
--regex-javascript=/^[ \t]*(?!(?:if|for|switch))([A-Za-z0-9_$]+)\(.*\)[ \t]*{/\1/M,Method,Methods/
But it is not working now, it cannot match any method.
How can I modify the regex then?
The code of rules for matching "methods" in the .ctags file is:
--regex-javascript=/^[ \t]*this\.([A-Za-z0-9_$]+)[ \t]*=.*{$/\1/M,Method,Methods/
--regex-javascript=/^[ \t]*([A-Za-z0-9_$]+)[ \t]*[:=][ \t]*[\(]*function[ \t]*\(/\1/M,Method,Methods/
--regex-javascript=/^[ \t]*static[ \t]+([A-Za-z0-9_$]+)[ \t]*\(/\1/M,Method,Methods/
--regex-javascript=/^[ \t]*(?!(?:if|for|switch))([A-Za-z0-9_$]+)\(.*\)[ \t]*{/\1/M,Method,Methods/
--regex-javascript=/^[ \t]*([A-Za-z0-9_$]+)\(.*\)[ \t]*{/\1/M,Method,Methods/

A: If you are using Universal Ctags, you can choose an alternative approach.
Universal Ctags provides {exclusive} flag. With the flag, you can reject a line matched to a pattern. This feature may help you.
$ cat -n /tmp/input.js
     1  f0 (A) {}
     2  for(something) {}
     3  f1(a) {}
     4  if(1) {}
     5  f2(b) {}
     6  switch(1) {}
     7  f3(c) {}
$ cat -n /tmp/foo.ctags
     1  --regex-javascript=/^[ \t]*this\.([A-Za-z0-9_$]+)[ \t]*=.*\{$/\1/Q,Method,Methods/
     2  --regex-javascript=/^[ \t]*([A-Za-z0-9_$]+)[ \t]*[:=][ \t]*[\(]*function[ \t]*\(/\1/Q,Method,Methods/
     3  --regex-javascript=/^[ \t]*static[ \t]+([A-Za-z0-9_$]+)[ \t]*\(/\1/Q,Method,Methods/
     4  --regex-javascript=/^[ \t]*(if|for|switch)\(.*\)[ \t]*\{//{exclusive}
     5  --regex-javascript=/^[ \t]*([A-Za-z0-9_$]+)\(.*\)[ \t]*\{/\1/Q,Method,Methods/
$ ~/bin/ctags -o - --kinds-javascript=M --options=/tmp/foo.ctags /tmp/input.js
f1  /tmp/input.js   /^f1(a) {}$/;"  Q
f2  /tmp/input.js   /^f2(b) {}$/;"  Q
f3  /tmp/input.js   /^f3(c) {}$/;"  Q


text:
Q: Can GMail html body be formatted with Materialize, Bootstrap etc. in GAS? It's possible to style the html beforehand when sending email with an html body from Google Apps Script with the GMailApp.sendEmail method. But when trying to style using Materialize it fails for me and the mail shows up in basic unformatted html. I am aware the html templating is finicky but can styling frameworks at all be applied? If so, does anyone know how to debug what is causing it to fail?
Sample GA script (code.gs):
function spamMe() {
  let recipient = 'mymail@gmail.com';
  let subject = 'Your daily serving of spam. For FREE!';
  let html = HtmlService
    .createTemplateFromFile('emailbody')
    .evaluate()
    .getContent();
  GmailApp.sendEmail(recipient, subject, '', { htmlBody: html });
}

Sample html body template (emailbody.html):
<!DOCTYPE html>

    <base target="_top">

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">

Hey worldo!

            I am a very simple card. I am good at containing small bits of information.
            I am convenient because I require little markup to use effectively. I am similar to what is called a panel in other frameworks.

A: In theory it could work, as long as you inlined the code (style="..." rather than <link>). That's a really big "could" though, since most systems like Bootstrap, Materialise are built for the web, which functions quite differently than email.
So, most (all?) systems rely on
s, and Outlook desktops don't play well with
s, this is not going to work well for you.
Digging a little deeper, with two and three columns, you would set them up differently too so they stack even without media queries.
Also, a great many components are coded differently, and don't use, for example, flexbox which Bootstrap depends upon. See https://www.caniemail.com/ for detail that way.
However, there is a system called MJML (https://mjml.io/) that is close to what you may want. But it's compiled, rather than class-driven.


text:
Q: Send date to the server using Ksoap2 I'm trying to send request to the server, and one of the argument there should to have type date. How to set type date? Because right now my request has type string.
Request which I'm sending to the server:
    <v:Envelope xmlns:i="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:d="http://www.w3.org/2001/XMLSchema"
    xmlns:c="http://schemas.xmlsoap.org/soap/encoding/"
    xmlns:v="http://schemas.xmlsoap.org/soap/envelope/">
            <v:Header /><v:Body><n0:getOutlets id="o0" c:root="1" xmlns:n0="http://www.kltro.com">
            <userId i:type="d:string">a24f0c23-5f36-11e4-b332-984be174a0cc</userId>
            <date i:type="d:string">2016-08-25</date>
</n0:getOutlets>
</v:Body>
</v:Envelope>

Activity for the sending request:
public class MainActivity extends AppCompatActivity {

    private static final String NAMESPACE = "http://www.kltro.com";
    private static final String METHODNAME = "getOutlets";
    private static final String WSDL = "http://mapx.kashkan.org:5445/tro/ws/kltro";
    private static final String SOAP_ACTION = NAMESPACE + "#kltro:" + METHODNAME;
    private static String TAG = "soap";

    public static String callWebservice() {
        String responseDump = "";
        String requestDump="";

        try {
            SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);

            SoapObject request = new SoapObject(NAMESPACE, METHODNAME);
            request.addProperty("userId", "a24f0c23-5f36-11e4-b332-984be174a0cc");
            request.addProperty("date", "2016-08-25");

            envelope.bodyOut = request;
            HttpTransportSE transport = new HttpTransportSE(WSDL);
            transport.debug = true;
            try {
                transport.call(SOAP_ACTION, envelope);
                requestDump = transport.requestDump;
                responseDump = transport.responseDump;

                Log.e(TAG, requestDump +"requestDump");
                Log.e(TAG, responseDump+"responseDump");
            } catch (IOException e) {
                e.printStackTrace();

                Log.e(TAG, requestDump +"requestDump");
                Log.e(TAG, responseDump+"responseDump");
            }

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

            Log.e(TAG, requestDump+"responseDump");
            Log.e(TAG, responseDump+"responseDump");
        }

        Log.e("requestDump", requestDump);
        Log.e(TAG, responseDump+"responseDump");
        return responseDump;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
        callWebservice();
    }
}

A: Sending a date through ksoap2-android library is a bit more complicated. ksoap2-android library does not know to serialize(or marshal) the type date. So you need to give a custom Marshal class.
But luckily ksoap2-android library already has a MarshalDate class. See its source here.
All you need to do is register this class to your SoapSerializationEnvelope.
Check out the code below,
private static final String NAMESPACE = "http://www.kltro.com";
private static final String METHODNAME = "getOutlets";
private static final String WSDL = "http://mapx.kashkan.org:5445/tro/ws/kltro";
private static final String SOAP_ACTION = NAMESPACE + "#kltro:" + METHODNAME;
private static String TAG = "soap_tester";

public static String callWebservice() {
    String responseDump = "";
    try {
        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);

        // Register the Date Marshal class
        new MarshalDate().register(envelope);

        SoapObject request = new SoapObject(NAMESPACE, METHODNAME);
        request.addProperty("userId", "a24f0c23-5f36-11e4-b332-984be174a0cc");

        // Your date
        String dateStr = "2016-08-25";

        // Parse the date into an object of type java.util.Date
        SimpleDateFormat sdfIn = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH);

        // You might want to play around with the timezones
        Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("ru"), Locale.ENGLISH);
        calendar.setTime(sdfIn.parse(dateStr));

        // Clear the hour, minute and second
        calendar.set(Calendar.HOUR, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        Date date = calendar.getTime();;

        // Create a property with the date object and type as java.util.Date.class
        PropertyInfo dateProperty = new PropertyInfo();
        dateProperty.setValue(date);
        dateProperty.setName("date");
        dateProperty.setType(Date.class);

        // Add it to the request
        request.addProperty(dateProperty);

        envelope.bodyOut = request;
        HttpTransportSE transport = new HttpTransportSE(WSDL);
        transport.debug = true;
        try {
            transport.call(SOAP_ACTION, envelope);
            String requestDump = transport.requestDump;
            responseDump = transport.responseDump;
            Log.e(TAG, requestDump);
            Log.e(TAG, responseDump);
        } catch (IOException e) {
            e.printStackTrace();
        }

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

This is the requestDump,
<?xml version="1.0" encoding="UTF-8"?>
<v:Envelope xmlns:v="http://schemas.xmlsoap.org/soap/envelope/" xmlns:c="http://schemas.xmlsoap.org/soap/encoding/" xmlns:d="http://www.w3.org/2001/XMLSchema" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
   <v:Header />
   <v:Body>
      <n0:getOutlets xmlns:n0="http://www.kltro.com" id="o0" c:root="1">
         <userId i:type="d:string">a24f0c23-5f36-11e4-b332-984be174a0cc</userId>
         <date i:type="d:dateTime">2016-08-24T00:00:00.000Z</date>
      </n0:getOutlets>
   </v:Body>
</v:Envelope>

Good luck :)


text:
Q: Entity propetytype as object in Symfony2 I'm looking information, how use entity propety type as object.
I have entity Products and Categories. In Products Entity propety category is type object. How pass object Categories to that propety? Any ideas how that use? Any Example ?

A: I would say: don't use the object type. Instead use Doctrine's association mappping.
I would advice to use the one-to-many bidirectional or the many-to-many bidirectional if you want to be able to have one product in multiple categories too.
Follow these steps:

*

*Place the examples in your own entity and change the annotations from @... to @ORM\...

*generate the getters and setters with the commandline:
app/console doctrine:generate:entities AppBundle

*update your database schema:
app/console doctrine:schema:update --force
Now check your created getter and setter functions. You might find something like getProducts() removeProduct() and addProduct().


text:
Q: Using external nodejs modules in Node-Webkit I'm trying to use the nodejs 'edge' module from within my node-webkit application. e.g.
var edge = require('../node_modules/edge')
   var helloWorld = edge.func('async (input) => { return ".NET Welcomes " + input.ToString(); }');
      helloWorld('JavaScript', function (error, result) {
         if (error) throw error;
         console.log(result);
});

However, whenever I call it I get the following error:-
Uncaught Error: %1 is not a valid Win32 application.
C:\data\node_modules\edge\lib\native\win32\ia32\0.10.0\edge.node

If I run the same code outside of node-webkit using nodejs it works OK -
This also works OK from within NW:
 var dns = require('../node_modules/native-dns')
    var question = dns.Question({
        name: 'www.google.com',
        type: 'A'
    });

    var req = dns.Request({
        question: question,
        server: { address: '8.8.8.8', port: 53, type: 'udp' },
        timeout: 1000
    });

    req.on('timeout', function () {
        console.log('Timeout in making request');
    });

    req.on('message', function (err, answer) {
        answer.answer.forEach(function (a) {
            console.log(a.address);
        });
    });

    req.on('end', function () {
        console.log('Finished processing request');
    });

    req.send();

Any guidance would be appreciated!


text:
Q: How to run an external program on a second screen? How do I run an external application out of my python application AND display the external program on a second screen? Unfortunately, my main GUI and the external GUI do not fit on one single screen.
So far I used the subprocess module and Popen constructor but I feel like desired functionality is not provided.
I considered to incorporate the STARTUPINFO ( https://docs.python.org/2/library/subprocess.html#windows-popen-helpers ) helper in subprocess but I did not find options seeming to fit my problem.
The external application is written in C++ and C#, if that is of any interest.
Thanks everybody!
Edit: I use Windows 7 and a dual monitor setup (to be exact laptop + monitor).
Second Edit: I found a possible answer on my own:
from win32api import GetSystemMetrics
import win32gui
import win32con

window = win32gui.GetForegroundWindow() # retrieves the freshly opened window
win32gui.MoveWindow(window, GetSystemMetrics(0), 0, 0, 0, True) # translates it about the main monitor width
win32gui.ShowWindow(window, win32con.SW_MAXIMIZE) # maximizes the window

I did not answer myself, since this is not exactly what I asked for. For my needs the solution is sufficient, though I'd be happy for further suggestions.

A: I don't know a good way in Windows to force the OS to place windows in a certain way. There are external tools which may help: https://superuser.com/questions/250334/utility-to-lock-window-position-size-of-windows-in-windows-7
The next question is how to move the window to the second monitor. That depends on how you set up your desktop. The usual mode is "spanning desktop" where you get a virtual desktop and each monitor displays parts of it. The means one monitor will have a top/left edge at '0, 0' and the other at `1920, 0'. To place a window on the second one, you simply need to set the top left corner of the window to '1920, 0'.
On systems with X11, most programs support the option -geometry which makes this very simple but on Windows, your application needs special support for this or you need external tools (see the link above).


text:
Q: DVWP does not honor CalendarDate in SharePoint:SPDataSource SelectCommand I've been able to use the below code to get a DVWP to return appointments for the current month, including recurrences.
However, no matter what I try, I cannot get it to honor the CurrentDate option in QueryOptions.
The DVWP
    <WebPartPages:DataFormWebPart runat="server" Description="" PartOrder="2" HelpLink="" AllowRemove="True" IsVisible="True" AllowHide="True" UseSQLDataSourcePaging="True" ExportControlledProperties="True" IsIncludedFilter="" DataSourceID="" Title="calendar" ViewFlag="8" NoDefaultStyle="TRUE" AllowConnect="True" FrameState="Normal" PageSize="10" PartImageLarge="" AsyncRefresh="False" ExportMode="All" Dir="Default" DetailLink="" ShowWithSampleData="False" ListId="..." ListName="{...}" FrameType="None" PartImageSmall="" IsIncluded="True" SuppressWebPartChrome="False" AllowEdit="True" EnableOriginalValue="False" ChromeType="None" AutoRefresh="False" AutoRefreshInterval="60" AllowMinimize="True" ViewContentTypeId="" InitialAsyncDataFetch="False" MissingAssembly="Cannot import this Web Part." HelpMode="Modeless" ID="..." ConnectionID="00000000-0000-0000-0000-000000000000" AllowZoneChange="True" ManualRefresh="False" __MarkupType="vsattributemarkup" __WebPartId="{...}" __AllowXSLTEditing="true" WebPart="true" Height="" Width="">
    <ParameterBindings>
        <ParameterBinding Name="ListID" Location="None" DefaultValue="{...}"/>
    </ParameterBindings>
    <DataFields>@ID,ID;@ContentType,Content Type;@Title,Title;@Modified,Modified;@Created,Created;@Author,Created By;@Editor,Modified By;@_UIVersionString,Version;@Attachments,Attachments;@File_x0020_Type,File Type;@FileLeafRef,Name (for use in forms);@FileDirRef,Path;@FSObjType,Item Type;@_HasCopyDestinations,Has Copy Destinations;@_CopySource,Copy Source;@ContentTypeId,Content Type ID;@_ModerationStatus,Approval Status;@_UIVersion,UI Version;@Created_x0020_Date,Created;@FileRef,URL Path;@ItemChildCount,Item Child Count;@FolderChildCount,Folder Child Count;@Location,Location;@EventDate,Start Time;@EndDate,End Time;@Description,Description;@fAllDayEvent,All Day Event;@fRecurrence,Recurrence;@WorkspaceLink,Workspace;@ParticipantsPicker,Attendees;@Category,Category;@Facilities,Resources;@FreeBusy,Free/Busy;@Overbook,Check Double Booking;</DataFields>
    <Xsl>...</Xsl>
    <DataSources>
        <SharePoint:SPDataSource runat="server" DataSourceMode="List" SelectCommand="...below..." UseInternalName="True" UseServerDataFormat="True" RecurrenceRowset="True" ID="dataformwebpart1">
            <SelectParameters>
                <WebPartPages:DataFormParameter ParameterKey="ListID" PropertyName="ParameterValues" DefaultValue="{...}" Name="ListID"></WebPartPages:DataFormParameter>
            </SelectParameters>
        </SharePoint:SPDataSource>
    </DataSources>
</WebPartPages:DataFormWebPart>

The SelectCommand:
<View>
    <Query>
        <Where>
            <DateRangesOverlap>
                <FieldRef Name="EventDate" />
                <FieldRef Name="EndDate" />
                <FieldRef Name="RecurrenceID" />
                <Value Type="DateTime">
                    <Month />
                </Value>
            </DateRangesOverlap>
        </Where>
        <OrderBy>
            <FieldRef Name="EventDate" />
        </OrderBy>
    </Query>
    <ViewFields>
        <FieldRef Name="Title" />
        <FieldRef Name="EventDate" />
        <FieldRef Name="EndDate" />
        <FieldRef Name="Location" />
        <FieldRef Name="Description" />
        <FieldRef Name="fRecurrence" />
        <FieldRef Name="RecurrenceData" />
        <FieldRef Name="fAllDayEvent" />
    </ViewFields>
    <QueryOptions>
        <CalendarDate>2016-01-01T12:00:00Z</CalendarDate>
        <RecurrencePatternXMLVersion>v3</RecurrencePatternXMLVersion>
        <ExpandRecurrence>TRUE</ExpandRecurrence>
    </QueryOptions>
</View>

A: I learned that this cannot be done using a DVWP.


text:
Q: Creating multiple files in code::blocks in C++ under 1 project I intend to create lots of small programs each with a main() function and run them separately under 1 project, in code::blocks in C++.
But code::blocks creates the first file "main.cpp" which contains the main() function.
Then, when I create another file with main() function, in the same project, it shows multiple definition of "main" error.
Unlike in BlueJ, where I used Java, I was able to create multiple files, each with a main() function, in the same project.
I searched a lot, but couldn't find relevant answers.
This is the link to a similar question asked.
click here
I followed the most appropriate answer to that question, but that couldn't solve my purpose.
Please help.


text:
Q: How to decode ascii from stream for analysis I am trying to run text from twitter api through sentiment analysis from textblob library, When I run my code, the code prints one or two sentiment values and then errors out, to the following error:
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2 in position 31: ordinal not in range(128)

I do not understand why this is an issue for the code to handle if it is only analyzing text. I have tried to code the script to UTF-8. Here is the code:
from tweepy.streaming import StreamListener
from tweepy import OAuthHandler
from tweepy import Stream
import json
import sys
import csv
from textblob import TextBlob

# Variables that contains the user credentials to access Twitter API
access_token = ""
access_token_secret = ""
consumer_key = ""
consumer_secret = ""

# This is a basic listener that just prints received tweets to stdout.
class StdOutListener(StreamListener):
    def on_data(self, data):
        json_load = json.loads(data)
        texts = json_load['text']
        coded = texts.encode('utf-8')
        s = str(coded)
        content = s.decode('utf-8')
        #print(s[2:-1])
        wiki = TextBlob(s[2:-1])

        r = wiki.sentiment.polarity

        print r

        return True

    def on_error(self, status):
        print(status)

auth = OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
stream = Stream(auth, StdOutListener())

# This line filter Twitter Streams to capture data by the keywords: 'python', 'javascript', 'ruby'
stream.filter(track=['dollar', 'euro' ], languages=['en'])

Can someone please help me with this situtation?
Thank you in advance.

A: You're mixing too many things together. As the error says, you're trying to decode a byte type.
json.loads will result in data as string, from that you'll need to encode it.
texts = json_load['text'] # string
coded = texts.encode('utf-8') # byte
print(coded[2:-1])

So, in your script, when you tried to decode coded you got an error about decoding byte data.


text:
Q: Alternatives to paste( ) to concatenate formatted text expressions on a graph? I'm using pretty10exp() from the sfsmisc package to make the scientific notation look better. For example:
library(sfsmisc)
a <- 0.000392884

The output of pretty10exp() looks like this:
> pretty10exp(a, digits.fuzz=3) #round to display a certain number of digits
expression(3.93 %*% 10^-4)

I can use this to display the pretty version of a on a graph's title or axes as described in this post:
Force R to write scientific notations as n.nn x 10^-n with superscript
However, things get ugly again when I try to combine it with paste() to write a sequence of character strings like this:
# some data
x <- seq(1, 100000, len = 10)
y <- seq(1e-5, 1e-4, len = 10)

# default plot
plot(x, y)
legend("topleft", bty="n",legend=paste("p =", pretty10exp(a, digits.fuzz=3)))

Which gives me the following graph, so I suppose paste() is not able to handle formatted expressions of the kind that can be found in the output of pretty10exp():

Is there an alternative to paste() that I could use to combine the expressions "p =" and the scientific notation of pretty10exp()?

A: One solution is just to copy what pretty10exp() does, which for a single numeric, a, and the options you set/defaults, is essentially:
a <- 0.00039288
digits.fuzz <- 3
eT <- floor(log10(abs(a)) + 10^-digits.fuzz)
mT <- signif(a/10^eT, digits.fuzz)
SS <- substitute(p == A %*% 10^E, list(A = mT, E = eT))
plot(1:10)
legend("topleft", bty = "n", legend = SS)

The equivalent using bquote() would be
SS <- bquote(p == .(mT) %*% 10^.(eT))

A: Definitely not a precise answer, but I just play around with things for a while.  bquote is nice once you get a feel for it.
> call("rep", 10, 7)
## rep(10, 7)

> bquote(.(call("rep", 10, 7)) * q^5)
## rep(10, 7) * q^5

> sprintf("paste('%smm'^'%s')", 5, 5)
## [1] "paste('5mm'^'5')"

And my personal favorite, which will of course return TRUE...
just as soon as I someone writes is.awesome.
> bquote( f <- function(x) { is.awesome(R) })
## f <- function(x) {
##     is.awesome(R)
## }


text:
Q: How to access Windows PC folder on my Android Tablets without internet connection I am trying to access a Windows PC folder on my Android Tablets (let's say 10 Tablets). I have a video folder in my PC and I want to give access to my App to access that folder and play video. Things I have tried are:

*

*Using JCIFS library and samba server but the drawback is it requires internet connection.

*Using WAMP Server and local host this solution was perfect until I tested it on multiple devices. It takes a lot of time to buffer big video files and sometimes fails to access videos.
Is there any other method to do that?
Is there any other method to connect my Android tablets to Windows PC and access the video files from a folder?

A: Filemanager with SMB-support
I use the Filemanager from CheetahMobile to access shares.
https://play.google.com/store/apps/developer?id=Cheetah+Mobile
However depending on your Windows version this can be very annoying to configure.
FTP-Server
The quickest and most stable variant could be to set up a FTP-server
https://filezilla-project.org/download.php?type=server
(Where you have many good working android clients)


text:
Q: Best Encryption Algorithm for long passwords Recently I implemented AES/Rijndael-256 into a component to store passwords. Recently I tried to store a longer password of character length 36 and when decrypting this password from the database the implementation fails due to and invalid padding error. This issue doesn't occur with shorter passwords.
The current implementation:
   public static string Encrypt(string plainText, string passPhrase)
    {
        // Salt and IV is randomly generated each time, but is preprended to encrypted cipher text
        // so that the same Salt and IV values can be used when decrypting.
        var saltStringBytes = Generate256BitsOfRandomEntropy();
        var ivStringBytes = Generate256BitsOfRandomEntropy();
        var plainTextBytes = Encoding.UTF8.GetBytes(plainText);
        using (var password = new Rfc2898DeriveBytes(passPhrase, saltStringBytes, DerivationIterations))
        {
            var keyBytes = password.GetBytes(Keysize / 8);
            using (var symmetricKey = new RijndaelManaged())
            {
                symmetricKey.BlockSize = 256;
                symmetricKey.Mode = CipherMode.CBC;
                symmetricKey.Padding = PaddingMode.PKCS7;
                using (var encryptor = symmetricKey.CreateEncryptor(keyBytes, ivStringBytes))
                {
                    using (var memoryStream = new MemoryStream())
                    {
                        using (var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
                        {
                            cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
                            cryptoStream.FlushFinalBlock();
                            // Create the final bytes as a concatenation of the random salt bytes, the random iv bytes and the cipher bytes.
                            var cipherTextBytes = saltStringBytes;
                            cipherTextBytes = cipherTextBytes.Concat(ivStringBytes).ToArray();
                            cipherTextBytes = cipherTextBytes.Concat(memoryStream.ToArray()).ToArray();
                            memoryStream.Close();
                            cryptoStream.Close();
                            return Convert.ToBase64String(cipherTextBytes);
                        }
                    }
                }
            }
        }
    }

I'm no cryptographer but I assume this is due to the limitations of the AES/Rijndael max key size of 256 bits.
Are there some other recommended encryption methods which would support longer passwords?


text:
Q: Is this a error of GitLab Documentation? I use the GitLab CE docker image and want to expose GitLab on different ports from host.
I read some instructions from the offical documentation:

To expose Web interface on 8929 and SSH service on 2289 use a following docker run command:

sudo docker run --detach \
    --hostname gitlab.example.com \
    --publish 8929:80 --publish 2289:22 \
    ...
    gitlab/gitlab-ce:latest

The second, you need to configure gitlab.rb:

#Set external_url:
external_url "http://gitlab.example.com:8929/"
...
# Set gitlab_shell_ssh_port:
gitlab_rails['gitlab_shell_ssh_port'] = 2289

but after start the container I found that in the container gitlab can be accessed from http://localhost:8929 but not http://localhost:80.
Maybe the document makes a mistake, but the mistake is so stupid, I am not sure.
I think the second step is not needed, is it?

A: Everything is working as it should? Maybe you need to rephrase your question to state what you actually want it to do, but this is how it works:
The Docker container exposes port 80. Now, specifying --publish 8929:80 on the command line tells it to make the port 80 available on port 8929 on the host. That's why http://localhost:8929 correctly shows the Gitlab installation.
That also means that setting the port in the external url is indeed neccessary, otherwise Gitlab will not be able to correctly build URLs that link to the installation.
If you just want to use the exposed ports verbatim, without remapping, just use the -P flag for docker run.
For further information see the Docker documentation


text:
Q: String Evaluation not working I have the following array in a shell script:
#! usr/bin/bash

schemaPrefix=("aos")
tables_aos=("A" "B" "C")
colnames_aos=("id" "id" "id")

for j in "${!schemaPrefix[@]}"; do

aschema=${schemaPrefix[j]}
schema=$aschema
eval tables=tables_$aschema
echo ${tables[@]}
done

This code should display:
A B C

However, it displays:
tables_aos

What am I doing wrong?  Thanks.

A: In bash version > 4.3, you can declare the tables variable as a nameref:
#! /usr/bin/bash

schemaPrefix=("aos")
tables_aos=("A" "B" "C")

declare -n tables

for j in "${!schemaPrefix[@]}"; do
  aschema=${schemaPrefix[j]}
  tables=tables_$aschema
  echo "${tables[@]}"
done

The loop could be written more simply without indirection as
for aschema in "${schemaPrefix[@]}"; do
  tables=tables_$aschema
  echo "${tables[@]}"
done


text:
Q: spring data reactive: where is located entity annotation? I'm running in a issue. @Entity annotation is not found.
Here my pom related dependencies:
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-dependencies</artifactId>
                <version>2.7.0</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-r2dbc</artifactId>
    </dependency>

I was trying to set @javax.persistence.Entity to my Person class.
But compiler is not able to look up it.
Which dependency am I forgoting?

A: add JPA
   <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>


text:
Q: g++ -O2 flag giving segmentation fault The program below is a bst tree which works fine under unoptimized settings but produces a SIGSEGV under special circumstances. Since my debugging skills doesn't extend towards assembly, I can use some input to what is causing this error.  Below is the full code so it can be reproduced. There is nothing fancy, a node struct is there to hold node data, a simple insert operation and a method to confirm the height of the tree.
#include <iostream>
#include <cstdlib>

using namespace std;

typedef struct avl_tree_node //node data
{
  int data;
  int balance{0};
  avl_tree_node *left{NULL};
  avl_tree_node *right{NULL};
  avl_tree_node *parent{NULL};

}node;

class avl
{
private:
  node *root;
  int get_height(node *head) //calculates the height
  {
    if (head == NULL)
      return -1;

    int l_height = get_height(head->left);
    int r_height = get_height(head->right);

    if (l_height > r_height)
      return l_height+1;

    return r_height+1;
  }

  void unbalanced_insert(node *head, int item); //method definition for a simple insert

public:
  avl(int data)
  {
    root->data = data;
    root->parent = NULL;
    root->left = NULL;
    root->right = NULL;
  }

  int height() //gives the height
  {
    return get_height(root);
  }

  void unbalanced_insert(int item) //wrapper
  {
    unbalanced_insert(root, item);
  }

};

void avl::unbalanced_insert(node *head, int item) //inserts node to the tree
{
  //cout << "stepped" << endl;
  if (item > head->data)
    {
      if (head->right == NULL)
    {
      head->right = (node*)malloc(sizeof(node));
      head->right->data = item;
      head->right->parent = head;
      head->right->left = NULL;
      head->right->right = NULL;
      head->balance = 1;
      return;
    }
      unbalanced_insert(head->right, item);
      head->balance++;
      return;
    }

  else
    {
      if (head->left == NULL)
    {
      head->left = (node*)malloc(sizeof(node));
      head->left->data = item;
      head->left->parent= head;
      head->left->left = NULL;
      head->left->right = NULL;
      head->balance = -1;
      return;
    }
      unbalanced_insert(head->left, item);
      head->balance--;
      return;
    }
}

int main()
{
  avl a(0);

  for (int i = 1; i < 5; i++) //works until i < 4
    {
      a.unbalanced_insert(i);
    }
  cout << a.height() << endl;

  return 0;
}

Under normal circumstances, I'd be happy that this works with unoptimized flags, but I have to build this with specific flags. One of such is the -O2 flag. The segmentation fault occurs between the avl a(0) object construction and the for loop inside main. The error also seems to be dependent on the boolean check of the for loop. This works fine if i < 4 and executed with: g++ avl.cpp -g -O2 -o program && ./program

A: One obvious problem, and it occurs on the very first function call in main, i.e. avl a(0):
root->data = data;
The root is uninitialized, thus the behavior is undefined.

A: I guess when instantiate the object of avl here.
 avl a(0);

constructor of class as shown below is called.
avl(int data)
  {
    root->data = data;
    root->parent = NULL;
    root->left = NULL;
    root->right = NULL;
  }

But here I see root pointer is not allocated any memory


text:
Q: volatile keyword in Web API class VolatileClass{
volatile bool _loop = true;
    static void Main()
    {
        VolatileClass vObj = new VolatileClass();
        Thread tObj = new Thread(SomeThread);
        tObj.Start(vObj);
        Thread.Sleep(2000);
        vObj._loop = false;
        Console.WriteLine("_loop value set to false");
    }

    static void SomeThread(object o)
    {
        VolatileClass vObj = (VolatileClass)o;
        Console.WriteLine("Loop started....");
        while (vObj._loop)
        {

        }
        System.IO.File.AppendAllText(@"MyPath\Thread.txt", vObj._loop.ToString());
        Console.WriteLine("Loop end....");
    }}

output:

*

*With volatile keyword : Text file created and exe execution ends.

*Without Volatile keyword: Text file not created and exe does not ends.

After compiling in release mode the volatile keyword makes sure the c# compiler will not optimize or re-arrange the code during compilation. So, after executing the exe there will be no infinite loop and text file was created. If I remove the volatile keyword, then the infinite loop occurs and the text file was not created. The above code was done in console application.
But if I do the same in Web API and build the code in release mode and run the application with debug="false". After running the action method the text file was created with or without volatile keyword. So my question is does the volatile keyword works in Web Application?? or Is there something I am missing??
Below is my Web API code
public class NotificationController{

    public void VolatileTest()
    {
        VolatileClass vObj = new VolatileClass();
        Thread tObj = new Thread(VolatileClass.SomeThread);
        tObj.Start(vObj);
        Thread.Sleep(5000);
        vObj._loop = false;
    }}
public class VolatileClass{
   public bool _loop = true;

    public static void SomeThread(object o)
    {
        VolatileClass vObj = (VolatileClass)o;
        while (vObj._loop)
        {

        }
        System.IO.File.AppendAllText(@"MyPath\Thread.txt", ((VolatileClass)o)._loop.ToString());
    }
}


text:
Q: How to show QRC scan results on Input text Am trying out barcode scanning/reader in phonegap. I have managed to read the QR codes but now am stack on how I can show results on the input text.
Js for Scanning

The variable qrc is being alerted properly, but trouble is on how to show this on my input text.
Body content

    Scan

    <form id="Insert"  method="POST">
    <input type="text"  name="qrc"  id="qrc" value=""/>

    <input type="submit"  value="Post" id="submit">
   </form>

When QRC is scanned results, I want the text input populated with the results.

A: We can assign a value to text fields, like this  $('#qrc').val(qrc);
if you are not using jquery then  document.getElementById("qcr").value = qcr;

A:


text:
Q: Here p is pointer to two dimensional array and when i tried to see its size i got the below answers ,but my question is a pointer is of 4 bytes right? enter code here
#include<iostream>
using namespace std;
int main()
{
    int (*p)[4];
    p =new int[3][4];
    cout<<endl<<sizeof(p)<<endl<<sizeof(*p);
}

Output:
8
16
//every pointer stores adress so it should be of int size i.e 4 in 32 bit and 8 in 64 bit
// *p means its arrays 1st element which is of type int right ,so it should be of 4 or 8 bytes


text:
Q: SF story "The old man says dig" I can't remember much of this, I read it pre 1992 in the UK. It was either a novella length or a slim book.
What I recall..
Protagonist arrived on a planet, he may have been an envoy or a troubleshooter, I think his role was to get the population to transplant to another world - maybe to demolish the existing one but I'm unsure about that.
The planet has been home, for several generations, to hardy pioneers despite extensive volcanic activity and earthquakes.
Their motto, repeated on posters/banners everywhere, is "The old man says dig". (The old man is their name for the planetary leader)
The protagonist learns they spend most of the time basically 'stitching their world together' - I think that phrase was used in the story. They are forever digging out for continent wide concrete reinforcements to the world's crust.
He is stymied when they refuse to transfer to a paradise-like planet that has been chosen for them by the Galactic Council, flat out refusals everywhere. He spends a lot of time trawling inns and taverns to get an understanding of why, then he realises the reason is they're accustomed to this daily battle.
He contacts the Council and then pitches a new proposal to the population, he tells them of another world where life is an even tougher struggle and mocks their prowess on their volcano planet as scratches only compared to the new rough planet.
Stiff necked pride asserts itself and as one they volunteer to take on this harder challenge. Their old man will now say dig harder

A: This is The Case of the Perjured Planet by John Baxter and Ron Smith.
For the record, The Old Man doesn't say 'dig', he says 'BUILD'

Signs of the old Napoleon became obvious almost immediately. On
a wall he found the tattered fading remains of a poster, dating from the
bad old days. It was largely obliterated by later signs but Quist recognised the familiar pattern. There was the face of Marcus Obolensky,
ravaged, fissured like old marble, a stern unsmiling mask. The message was simple, in plain black type: The Old Man Says BUILD.
Quist looked at the poster and began to understand better what
had made Napoleon 6 a habitable planet. The Old Man Says BUILD. It
was good press relations, worked out perhaps by a man without training, but good press relations all the same. The figurehead, paternal,
demanding, stern but compassionate. If you failed, you had to face the
anger of those cold grey eyes. If you succeeded, you might feel that
rough hand laid on your shoulder, perhaps even a word of commendation, from the man who, almost single-handedly, had built this
world. If the old man said 'Build', you built.

There are mentions of planet-wide constructions of concrete and steel intended to hold continental plates together

The fissure was interesting, but other things about it were more
interesting still. Now that the initial shock was over, he noticed that the
crack was more than just the memento of a giant earthquake. About
fifty feet down the side of the opposite cliff, he saw a buttress jutting
from the rock. It leaped out over the abyss, presumably connecting up
with his side of the crack. Moving closer to the edge, he saw another
buttress, and then more, a string of them regularly spaced all along the
cliff. Quist recognised their use, though he had to look to find a name.
They were sutures, stitches of iron and concrete strong enough to hold
a world together.


text:
Q: Populating a container with one entry per Firebase entry I'm using Firebase to store users info and I'm wanting to populate divs with each users info so it can be either accepted or deleted (but not deleted from Firebase).
So I wanted it to be structured something like this:
----------------------
Name
Email
Date
----------------------
Name
Email
Date
----------------------
and so on....

What I'm currently getting back is something like this:

What is the proper way to generate a div dependent upon how much data is in Firebase and format the content as specificed?
HTML:

Some entry here

    <button id="0" class="remove">Remove</button>

Another entry here
    <button id="1" class="remove">Remove</button>

Javascript:
var ref = firebase.database().ref('requests');
ref.on('value', function(snapshot) {
  snapshot.forEach(function(child) {
    var datas = child.val();
    var email = child.val().Email;
    var name = child.val().Name;
    var date = child.val().Scheduled_Date;
    date = date.replace('.', '/');
    $('#name').append(name);
    $('#email').append(email);
    $('#date').append(date);
  });
});

A: For each child, you are appending the values to the same HTML elements (i.e. all the names are appended to the h4 element with id "name", all the emails to the one with id "email" and so on).
So it is normal they are displayed on a line (one row).
You have to create a new placeholder for each child (and it's set of values). You can do that with e.g. a table, like:
var tableRef = document.getElementById('myTable').getElementsByTagName('tbody')[0];

var ref = firebase.database().ref('requests');
ref.on('value', function(snapshot) {
  snapshot.forEach(function(child) {
    var datas = child.val();
    var email = child.val().Email;
    var name = child.val().Name;
    var date = child.val().Scheduled_Date;
    date = date.replace('.', '/');

    // Insert a row in the table at the last row
    var newRow = tableRef.insertRow(tableRef.rows.length);
    // Insert a cell in the row at index 0
    var newCell = newRow.insertCell(0);
    // Append a text node to the cell with name value
    var newText = document.createTextNode(name);  // <-- name value from the child
    newCell.appendChild(newText);

    var newRow = tableRef.insertRow(tableRef.rows.length);
    var newCell  = newRow.insertCell(0);
    var newText  = document.createTextNode(email);  // <-- email value from the child
    newCell.appendChild(newText);

    var newRow   = tableRef.insertRow(tableRef.rows.length);
    var newCell  = newRow.insertCell(0);
    var newText  = document.createTextNode(date);  // <-- date value from the child
    newCell.appendChild(newText);

  });
});

Inspired by How to insert row in HTML table body in Javascript?. See the fiddle in this SO post.
Or you can do it with divs, here is a possible code:.
HTML

JavaScript
var element;
var ref = firebase.database().ref('requests');
ref.on('value', function(snapshot) {
  snapshot.forEach(function(child) {
    var datas = child.val();
    var email = child.val().Email;
    var name = child.val().Name;
    var date = child.val().Scheduled_Date;
    date = date.replace('.', '/');

    element = document.createElement("div");
    element.appendChild(document.createTextNode(name));
    document.getElementById('parentDiv').appendChild(element);

    element = document.createElement("div");
    element.appendChild(document.createTextNode(email));
    document.getElementById('parentDiv').appendChild(element);

    element = document.createElement("div");
    element.appendChild(document.createTextNode(date));
    document.getElementById('parentDiv').appendChild(element);
    //You could add a specific css class to this div to generate the bottom border

  });
});

To be complete, note that you could also use some MVVM javascript frameworks like vue.js, knockout.js as well as angular, react... in order to easily reflect in your HTML DOM the results of queries to your backend (and vice-versa).


text:
Q: How to validate a JTextField of email ID with a regex in swing code? I have tried a lot for this validation but I'm not getting where to put the following code
String expression="^[\\w\\-]([\\.\\w])+[\\w]+@([\\w\\-]+\\.)+[A-Z]{2,4}$";.

Please help me in this.

A: I hope this will help. When you Click on Submit button on SWING UI, in actionListener write the validation code.
   Emailvalidator emailValidator = new Emailvalidator();
   if(!emailValidator.validate(emailField.getText().trim())) {
        System.out.print("Invalid Email ID");
        /*
           Action that you want to take. For ex. make email id field red
           or give message box saying invalid email id.
        */
   }

This is the seperate class EmailValidator
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class EmailValidator {

    private Pattern pattern;
    private Matcher matcher;

    private static final String EMAIL_PATTERN =
        "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
        + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";

    public EmailValidator() {
        pattern = Pattern.compile(EMAIL_PATTERN);
    }

    /**
     * Validate hex with regular expression
     *
     * @param hex
     *            hex for validation
     * @return true valid hex, false invalid hex
     */
    public boolean validate(final String hex) {

        matcher = pattern.matcher(hex);
        return matcher.matches();

    }
}

On a side note, this will enable you that the entered email id is in the correct format. If you want to validate the id, send an email containing a confirmation no and ask the user to enter that number on your UI and then proceed.

A: The format of an e-mail address can get pretty complex.  In fact, its complexity is almost legendary.
The InternetAddress class in JavaMail is a much more reliable way to parse an e-mail address than a regular expression.


text:
Q: How to create right API URLs for getting data I'm creating a simple API which works with geographical data.
Some URLs look very simple like:
GET /towns/{id}

or
GET /towns

Now I want to get a town by alias, should I use this kind of URL?
GET /towns/alias/{alias}

What if I also want to get a list of towns located near certain town?
GET /towns/closest/{id}/radius/{radius}

I understand that my URLs can be any I want. What is a canonical way to do it?

A:
I understand that my URLs can be any I want. What is a canonical way to do it?

There isn't really a "canonical way" to design URLs, any more than there is a canonical way to name variables -- there are only local spelling conventions.
RFC 3986 distinguishes between hierarchical and non-hierarchical data:

The path component contains data, usually organized in hierarchical form, that, along with data in the non-hierarchical query component (Section 3.4), serves to identify a resource within the scope of the URI's scheme and naming authority (if any)

The effect of using hierarchical data is that you can take advantage of dot-segments to compute one URI from another.
For example
/town/alias/{alias}
/alias/{alias}

Both of these spellings are "fine", but /town/alias gives us the option of using dot segments to specify an identifier under /town
/town/alias/abc + ../123
  => /town/alias/../123
  => /town/123

That can be handy when it allows you to re-use a representation for multiple resources in your hierarchy.

A: Yes it can possible through the URL routing.You can send any number of parameter through url.
Can you please confirm the technology you used?


text:
Q: Accessing values within a hash The server is receiving the following JSON object.  The action also logs the nature of the object
Update: {"update_id":589695627,"message":{"message_id":190,"from":{"id":3241,first_name":"Bob","username":"Bobby B","language_code":"en"},"date":1592897101,"text":"/activate NjElMV8yMTkuMTkuNDU="}}
Rails.logger.info update.is_a? Hash
json = update.to_json
Rails.logger.info json.is_a? String

The logger returns true to both is_a queries.
The resulting json string is identical to the received statement save the Update  prefix.
How can one extract say message.from.username immediately from the hash (as it seems as overload to run a json handling loop as well)?

A: You can try using Hash#dig:
update = {"update_id":589695627,"message":{"message_id":190,"from":{"id":3241,"first_name":"Bob","username":"Bobby B","language_code":"en"},"date":1592897101,"text":"/activate NjElMV8yMTkuMTkuNDU="}}
update.dig(:message, :from, :username) # "Bobby B"


text:
Q: SQL determine schedule availability I have a tbl_availability that determines when a resource is available. The table structure is:
id - running id
startdate - when this availability starts
enddate - when this availability ends
dayofweek - weekday of availability
fromtime - start time
totime - end time

There can be multiple records for the same dayofweek, for example one record for Sundays 1000-1200 and another record for Sundays 1300-1400.
I am trying to figure out how to get two things:

*

*Check when entering a new record that there is no conflict (overlap)
with an existing record

*Given a startdate and enddate, find all of
the available periods that apply.

A: To determine if there's a conflict this query will return any overlapping time ranges:
SELECT * FROM tbl_availability
WHERE (startDate > @CheckEnd AND startDate <= @CheckStart)
OR (endDate < @CheckStart AND endDate >= @CheckEnd)
OR (startDate >= @CheckStart AND endDate <= @CheckEnd)

The first part of the where clause checks for anything that overlaps the start time.   The second part check for anything that overlaps the end time.  The third part check for anything within the range.
To check for available time ranges for a specified duration use this:
SELECT * FROM
(SELECT endDate AS PeriodStart, (SELECT TOP 1 startDate
  FROM tbl_availability as sub
  WHERE sub.startDate > tbl_availability.endDate
  ORDER by sub.startDate) AS PeriodEnd
FROM tbl_availability) AS OpenPeriods
WHERE DateDiff(MINUTE, PeriodStart, PeriodEnd) >= DateDiff(MINUTE, @RangeStart, @RangeEnd)

I haven't tested these queries, so there may have to be some tweaking going on here.


text:
Q: Inline two elements using flexbox I want to inline two elements next to each other using flexbox. I want this to work exactly like display: inline works but for flexbox. How would you do this? What am I missing? :)
Demo: https://jsfiddle.net/24duh8wr/

A: If you want the text in the second item to wrap around the text it the first item, flexbox is not the way to achieve this. You have two options (remove display: flex from the container in both cases):
1) Just make them inline:
.item {
  display: inline;
}

2) Float the first item left:
.item:first-child {
  float: left;
}

A: It's not possible to do it with flexbox, if I understand your expectation http://take.ms/sLdMr . Flexbox is tool to build layout.

A: Please try display: inline-flex;

A: As explained in the commentary. Use flex-direction.

.flexbox {display: inline;}
.flexbox2{
display:flex;
flex-direction:row;
}

Date:

Quisque rutrum. Vivamus laoreet. Aenean viverra rhoncus pede. Curabitur turpis. Morbi ac felis.In ut quam vitae odio lacinia tincidunt. Aenean ut eros et nisl sagittis vestibulum. Sed hendrerit. Nunc egestas, augue at pellentesque laoreet, felis eros vehicula leo, at malesuada velit leo quis pede. Praesent nonummy mi in odio.

Date:

Quisque rutrum. Vivamus laoreet. Aenean viverra rhoncus pede. Curabitur turpis. Morbi ac felis.In ut quam vitae odio lacinia tincidunt. Aenean ut eros et nisl sagittis vestibulum. Sed hendrerit. Nunc egestas, augue at pellentesque laoreet, felis eros vehicula leo, at malesuada velit leo quis pede. Praesent nonummy mi in odio.


text:
Q: Create a default kernel header file (C) I'm having difficulties understanding how GCC searches for headers contained in <> (eg. <stdio.h>). I have made a system call header file and I want to make it global. How do I proceed?
I have tried including my header file within usr/include and then compiling the new kernel (it didn't include my file though).
I have tried running gcc -Iheaders mysyscalls.h in the command line. No errors appears but GCC still complains that it can not find my header file.
Any help is greatly appreciated.


text:
Q: How to add text to a chart by excel macro? Using the following codes to add text to a chart by excel macro?
When compiled to a module, it shows "object doesn't support this property or method", any suggestion or revised codes really appreciated. Thanks
Set myDocument = Ch.Chart

  myDocument.Shapes.AddTextbox(msoTextOrientationHorizontal, 382, 266, 122, 20).Select

    Selection.ShapeRange.TextFrame.Characters.Text = ThisWorkbook.ActiveSheet.Cells(6, 8)

   With Selection.ShapeRange.TextFrame.Characters

    .Font.Name = "Tahoma"

    .Font.Size = 10

    .Font.Bold = msoTrue

   End With

A: There's no need to select the chart before adding your textbox, etc.  Your code can be re-written as follows...
Dim theChartObj As ChartObject
Set theChartObj = Worksheets("Sheet1").ChartObjects("Chart 1") 'change the sheet and chart names accordingly

Dim theChart As Chart
Set theChart = theChartObj.Chart

Dim theTextBox As Shape
Set theTextBox = theChart.Shapes.AddTextbox(msoTextOrientationHorizontal, 382, 266, 122, 20)

With theTextBox.TextFrame.Characters
    .Text = ThisWorkbook.ActiveSheet.Cells(6, 8).Value
    With .Font
        .Name = "Tahoma"
        .Size = 10
        .Bold = msoTrue
    End With
End With


text:
Q: How to show "®" read from text file in assets directory? Does anybody know the best way to show the "®" symbol when read from a text file in the assets directory? I've tried replacing the "®" symbol with &® or ® or \u00AE, but none of these work.
Is the only solution to define it as html?
Here's the code I'm using to read the text file from assets:
    mTextViewTermsConditions = (TextView) findViewById(R.id.textView_terms_conditions);

    StringBuffer stringBufferEula = new StringBuffer();

    try
    {
        InputStream inputStream = getAssets().open("eula");

        BufferedReader f = new BufferedReader(new InputStreamReader(inputStream));

        String line = f.readLine();

        while (line != null)
        {
            Logger.d(line);

            stringBufferEula.append(line);

            line = f.readLine();
        }

    }
    catch (IOException e)
    {
        Logger.e(e.toString());
        e.printStackTrace();
    }

    mTextViewTermsConditions.setText(stringBufferEula);

A: This is an encoding problem. Make sure that your asset file is stored with UTF-8 encoding.

A: Answer thanks to Ted Hopp above:
Make sure that the text file is encoded UTF-8.


text:
Q: Error at running Simulink FMU in ROS: "Creation of dllfmu failed" I'm trying to run a Simulink FMU in ROS for a co-simulation in Gazebo. I've been able to simulate and validate the FMU in Python but, when I try to load it in ROS, I'm obtaining an error.
I'm trying the The problem was that ROS wasn't able to find the binaries for Linux (fmu_traject.so file inside binaries/linux64) since the FMU was exported in Windows 10 and I was trying to load it in Ubuntu 18.04. The solution has simply been to export the FMU from MATLAB-Simulink installed in the Ubuntu machine.next commands from this guide.
In terminal 1:
source /opt/ros/dashing/setup.bash
cd ~/FMI/Trajectory # The path where the FMU is
ros2 run fmi_adapter fmi_adapter_node __params:=my_params.yaml

Just in case, the file "my_parmas.yaml" just contains the path to the FMU:
fmi_adapter_node:
  ros__parameters:
    fmu_path: '/home/ubuntu1804/FMI/Trajectory/fmu_traject.fmu'

In terminal 2:
source /opt/ros/dashing/setup.bash
ros2 lifecycle set /fmi_adapter_node configure
ros2 lifecycle set /fmi_adapter_node activate

Just after running ros2 lifecycle  set /fmi_adapter_node configure, the following is printed in terminal 2:
Transitioning failed

And the next error appears in terminal 1:
[ERROR][FMI2XML] Start attribute is required for this causality, variability and initial combination
[FATAL][FMILIB] Could not change to the DLL directory /tmp/fmi_adapter_DrX8pj/binaries/linux64/
[FATAL][FMILIB] The FMU contains no binary for this platform.
[ERROR] []: Caught exception in callback for transition 10
[ERROR] []: Original error: Creation of dllfmu failed!
[WARN] []: Error occurred while doing error handling.

In addition, I've also tested to create a launch file and run it in the following way.
source /opt/ros/dashing/setup.bash
cd ~/FMI/Trajectory # The path where the FMU is
ros2 launch SimulinkFMU_launcher.launch.py

I'm attaching below the launch file "SimulinkFMU_launcher.launch.py", which is entirely based on the mentioned guide.
import ament_index_python.packages

import launch
import launch.actions
import launch.launch_description_sources
import launch.substitutions

def generate_launch_description():
    # fmu_path = (ament_index_python.packages.get_package_share_directory('fmi_adapter_examples') +
    #             '/share/DampedPendulum.fmu')
    fmu_path = 'FMI/Trajectory/fmu_traject.fmu'

    fmi_adapter_description = launch.actions.IncludeLaunchDescription(
        launch.launch_description_sources.PythonLaunchDescriptionSource(
            ament_index_python.packages.get_package_share_directory(
                'fmi_adapter') + '/launch/fmi_adapter_node.launch.py'),
        launch_arguments={'fmu_path': fmu_path}.items())

    description = launch.LaunchDescription()
    description.add_action(fmi_adapter_description)

    return description

This is the log I obtain with the launch file:
[INFO] [launch]: All log files can be found below /home/ubuntu1804/.ros/log/2022-04-27-09-24-45-820715-ubuntu-13445
[INFO] [launch]: Default logging verbosity is set to INFO
[INFO] [fmi_adapter_node-1]: process started with pid [13462]
[fmi_adapter_node-1] [ERROR] []: Caught exception in callback for transition 10
[fmi_adapter_node-1] [ERROR] []: Original error: Given FMU file 'FMI/Trajectory/fmu_traject.fmu' not found or cannot be read!
[fmi_adapter_node-1] [WARN] []: Error occurred while doing error handling.
[ERROR] [launch_ros.actions.lifecycle_node]: Failed to make transition 'TRANSITION_CONFIGURE' for LifecycleNode '/fmi_adapter_node'

A: The problem was that ROS wasn't able to find the binaries for Linux (fmu_traject.so file inside binaries/linux64) since the FMU was exported in Windows 10 and I was trying to load it in Ubuntu 18.04. The solution has simply been to export the FMU from MATLAB-Simulink installed in the Ubuntu machine.


text:
Q: Getting MaxRequestDurationExceeded error when try to read the table range When trying to get the range of the table using Graph API /items/{workbookId}/workbook/tables/{tableName}/range?$select=address, we are getting an error immediately with the following details
{
    "error": {
        "code": "MaxRequestDurationExceeded",
        "message": "We're sorry. We couldn't finish what you asked us to do because it was taking too long.",
        "innerError": {
            "code": "gatewayTimeoutUncategorized",
            "message": "The service wasn't able to complete the request within the time limit.",
            "innerError": {
                "code": "MaxRequestDurationExceeded",
                "message": "We're sorry. We couldn't finish what you asked us to do because it was taking too long."
            },
            "date": "2023-01-06T14:45:21",
            "request-id": "4b6b5b18-e879-451a-b480-107a29240f19",
            "client-request-id": "4b6b5b18-e879-451a-b480-107a29240f19"
        }
    }
}

We have verified that data in the Excel is within the limits provided in this link
We have product that writes data to Excel on schedule. As part of that solution, we read the range of the table and clear it before writing. When we make a request to get range, it should return the proper range instead of error


text:
Q: How to get the number of epochs the best model was trained using Keras Tuner? I used Keras Tuner's RandomSearch class to search for the best model, and I used an EarlyStopping callback when I called fit() (see the code below).
Now I would like to know for how many epochs the best model was actually trained. The goal is to retrain the best model on the full training set (including the validation set) for that number of epochs. Since there won't be a validation set anymore, I cannot use it for early stopping.
tuner = kt.RandomSearch(
    build_model,
    objective="val_accuracy",
    max_trials=5,
    overwrite=True,
    directory="test_search",
    project_name="test_project"
)
tuner.search(
    X_train, y_train, epochs=100,
    validation_data=(X_valid, y_valid),
    callbacks=[tf.keras.callbacks.EarlyStopping(patience=10)]
)
best_trials = random_search_tuner.oracle.get_best_trials(num_trials=3)


text:
Q: Divide generic.xaml to several files I got generic.xaml file in Windows Phone project, and it is getting too big. How to divide generic.xaml to several files?
I know about <ResourceDictionary.MergedDictionaries> but, I can not make it work. Project compiles, but then I got runtime exception when Page is trying to parse xaml resource.
I tryed:
<ResourceDictionary.MergedDictionaries>
    <ResourceDictionary Source="WatermarkedPinBox.xaml"/>
</ResourceDictionary.MergedDictionaries>

Help me please, I do not like big resource files. It is hard to keep their structure in good state.

A: You can use MergedDictionaries to split your Generic.xaml file. Take a look on this example:
<ResourceDictionary
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:mscorlib="clr-namespace:System;assembly=mscorlib">

    <ResourceDictionary.MergedDictionaries>
        <ResourceDictionary Source="/YourProjectName;component/Themes/YourSecondResourceFileName.xaml" />
        <ResourceDictionary Source="/YourProjectName;component/Themes/YourThirdResourceFileName.xaml" />
    </ResourceDictionary.MergedDictionaries>

</ResourceDictionary>

Build Action for YourSecondResourceFileName.xaml and YourThirdResourceFileName.xaml must set to Page.


text:
Q: how to use lookups Lookup table:-
FROM_METER  TO_METER    COST
1             5         0.004
6             10        0.006
11            20        0.012

Needed output:-  (here for 15 and 7 for example cost output will come as from lookup master)
METER  COST
15     0.012
7      0.006
etc....

A: A lookup table is normally used t provide code or reference values for regular data.  Assuming your business table is the one you called MASTER you would join its records to your lookup like this:
select m.meter
       , l.cost
from master m
      join lookup l
            on ( m.meter between l.meter_from and l.meter_to)

Your data model ppears to have a problem: it doesn't guarantee that every METER in the MASTER table will find a matching record in the lookup table.  This is why a more common approach is to use types or categories (say 'cheap', 'reasonable', 'expensive').
Obviously, without knowing your business rukes it is hard for me to say whether you model is correct, but you probably should consider what to do if the MASTER table doesn't have a matching row.  Perhaps the relation is enforced in the application but in my experience that approach is hard to make it bulletproof.

A: select ? Meter, cost from Lookup
where ? > = FROM_METER
and  ? < = TO_METER

replace the ? with your parameter.


text:
Q: How to use a module for "global" variables with multiprocessing? I am using the common pattern where a module has a number of module-level variables and is imported by other modules, eg module a, b, c... etc import module 'globalv' which has, for examples, module-level variable foo with value 'bar'. So far so good, works as expected in a single-process environment, and one can import the module and/or it's variables. I like this pattern, it makes the code clean and easily readable, and IDEs such as eclipse auto-complete the variable names.
However, in a multiprocessing environment this doesn't work as described in the python documentation because each process has a separate interpreter with distinct address spaces.
Now, I am wondering if perhaps there is commonly accepted way to make this pattern work with multiprocessing ? Perhaps with Manager, Value, or Array ?
My thoughts are to make globalv.foo a Value or Manager instance and pass it to the child processes as and argument; I only use simple, pickleable objects, e.g integers, and strings for my "global" variables. The first thing to do when the child process runs is then to replace foo in the child process with the foo passed by the parent process, which is a Value or Manager instance. It should then be the same as the original foo in the parent process and updating foo in the parent or child process should be shared. However, this seems clumsy, any ideas how to do this better be welcome.

A: You could make use of the shared memory functionality of multiprocessing:
https://docs.python.org/3.9/library/multiprocessing.shared_memory.html


text:
Q: Scheduled Jobs and Custom Clock Processes with Clockwork I am trying to understand how to execute custom code with clockwork. This is the example lib/clock.rb file that Heroku uses in its devcenter document.
require File.expand_path('../../config/boot',        __FILE__)
require File.expand_path('../../config/environment', __FILE__)
require 'clockwork'

include Clockwork

every(4.minutes, 'Queueing interval job') { Delayed::Job.enqueue IntervalJob.new }
every(1.day, 'Queueing scheduled job', :at => '14:17') { Delayed::Job.enqueue ScheduledJob.new }

What is IntervalJob and ScheduledJob? Where are these files supposed to be located? I want to run my own custom job that has access to my database records.
EDIT
This is my /lib/clock.rb
require 'clockwork'
require './config/boot'
require './config/environment'

module Clockwork

  handler do |job|
    puts "Running #{job}"
  end

  every(2.minutes, 'Filtering Streams') { Delayed::Job.enqueue FilterJob.new}
end

This is my /lib/filter_job.rb
  class FilterJob
    def perform
      @streams = Stream.all

      @streams.each do |stream|
      # manipulating stream properties
      end
    end
   end

I get the error:
uninitialized constant Clockwork::FilterJob (NameError)
/app/lib/clock.rb:11:in `block in <module:Clockwork>'

A: You need to do the following:
Firstly install the clockwork gem.
In your lib folder create a clock.rb
require 'clockwork'
require './config/boot'
require './config/environment'

module Clockwork

  handler do |job|
    puts "Running #{job}"
  end

  every(1.day, 'Creating Cycle', :at => '22:00') { Delayed::Job.enqueue CyclePlannerJob.new}
end

In the example your provided IntervalJob and ScheduledJob, are delayed jobs. Clockwork triggers them on the time specified. I am calling the CyclePlannerJob, this is what my file looks like.
lib/cycle_planner_job.rb
class CyclePlannerJob
  def perform
    CyclePlanner.all.each do |planner|
      if Time.now.in_time_zone("Eastern Time (US & Canada)").to_date.send("#{planner.start_day.downcase}?")
        planner.create_cycle
      end
    end
  end
end

In my example everyday at 10pm, I am running the CyclePlanner job, which runs the delayed job I have setup. Similar to the Heroku example.
Bare in mind to use this you need to setup the clock work and delayed jobs on your Heroku app in the dashboard.
Also your Procfile should look like this.
worker:  bundle exec rake jobs:work
clock: bundle exec clockwork lib/clock.rb

Let me know if you have any questions, I can go into more detail if needed.

A: Looks like name space issue. Move your filter_job.rb to models directory and try.


text:
Q: Convert csv to tsv taking a lot of CPU A simple csv (from stdin) to tsv(stdout) with Python is taking 100% CPU for large files (GB..)
From top:
PID USER      PR  NI    VIRT    RES    SHR S  %CPU %MEM     TIME+ COMMAND
2430 nir      20   0  121288   8440   4656 R  99.0  0.1   0:59.56 python3

Python code:
#!/usr/bin/env python3
#

import csv, sys

delimiter_char=','
quote_char='"'
if sys.argv[1:]:
        delimiter_char=sys.argv[1]
if sys.argv[2:]:
        quote_char=sys.argv[2]

csv.writer(sys.stdout, dialect='excel-tab').writerows(
                csv.reader(sys.stdin,delimiter=delimiter_char, quotechar=quote_char))

The way I'm calling this script is from bash:
split -C 64M -d -a 4 --filter 'gzip > $FILE.gz' < (cat file.txt |  csv2tsv.py) split/file_

Any advice out to tune it?

A: Something along the lines of
mywriter = csv.writer(sys.stdout, dialect="excel-tab")
line = sys.stdin.readline()
while line != "":
    mywriter.writerow(line)
    line = sys.stdin.readline()


text:
Q: Google Cloud Storage Document Thumbnail Image? We are needing to grab a thumbnail image of our documents on Google Could Storage for use in our Drupal module. Previously https://docs.google.com/viewer?url=DOC_STORAGE_URL&a=bi&pagenumber=1 worked for us, but the google viewer seems to no longer support the a=bi parameter.
Does anyone have any information about the viewer no longer generating a thumbnail, or know if there is a way to grab a thumbnail image of the document stored on Google Could Storage using its API like you can with the Drive API? We are currently using the google-api-php-client.
https://developers.google.com/drive/v2/reference/files

A: As @rein said, GCS doesn't generate thumbnails for any object. But there is an alternative: the Images API. Although is not available for PHP, if you can write in Python [1] or JAVA [2] this library contains the functionality you are looking for.
Check the function get_serving_url here [3]. It will generate an url that accepts parameters. Specifically, the parameter =sXX will generates thumbnails of XX pixels (on the longest dimension).
[1] https://cloud.google.com/appengine/docs/python/images/
[2] https://cloud.google.com/appengine/docs/java/images/
[3] https://cloud.google.com/appengine/docs/python/images/functions

A: Google Cloud Storage does not generate thumbnails for any objects. You would need to generate these thumbnails, upload them to Google Cloud Storage, and then reference them yourself.


text:
Q: Play audio file stored in google drive (remote URL) - Swift I'm using AVPlayer to play audios which are stored in google drive. Problem is that as public link of files stored in google drive don't have extension mentioned, that's why AVPlayer doesn't play audio because cannot get its extension from URL. Following is code i'm using.
let url = URL(string: "https://drive.google.com/file/d/1n6GeWY11Txvou5K-Tl7Ju39fQsWQTDvR/view?usp=sharing")

        let playerItem:AVPlayerItem = AVPlayerItem(url: url!)

        player = AVPlayer(playerItem: playerItem)

        player!.play()

For example, in case of following url
https://drive.google.com/file/d/1n6GeWY11Txvou5K-Tl7Ju39fQsWQTDvR/view?usp=sharing
AVPlayer isn't playing it and showing it's duration to 0.
But when i play audio file like following
https://www2.cs.uic.edu/~i101/SoundFiles/BabyElephantWalk60.wav
it plays without any problem because of file extension available.
So, could someone please comment how to play audio when extension not available in remote URLs.
Thanks

A: Just got to modify the URL, Use this:
https://drive.google.com/uc?export=open&id=1n6GeWY11Txvou5K-Tl7Ju39fQsWQTDvR

Here's what I did,
Sharing an audio file looks like this:
https://drive.google.com/file/d/XXXXXXXXXXXXXXXXXX/view?usp=sharing

XXXXXXXXXXXXXXXXXX is the file ID. You can access the direct file by getting rid of everything after the ID and replacing file/d/ with uc?export=open&id=
Keep in mind, if Google decide to change the way their file sharing works then this solution may break.


text:
Q: Simulate the "exit do" statement fused in vba in tcl This question is related to Breaking parent loop in tcl , but I am not able to implement the answer to my current code.
I have a proc written in VBA for Excel which uses "Exit do":
Do While i < numofentries
    Debug.Print "------------------"
    Debug.Print "j = " & j
    Debug.Print "length | Element i"
    path_beg = i
    path_end = i
    Length = 0
    length_l = 0
    length_u = 0
    blnAngle = True
    Do While Length < minlength
        If (angles(i) < limitangle Or path_beg = i) Then
            Length = Length + ElemEdgeLengths(i)
            Debug.Print Length & " | " & i
            path_end = i
            i = i + 1
            If i = numofentries Then Exit Do
        Else
            Debug.Print "Angle change..."
            If path_end = path_beg Then
                path(j - 1) = path_end
                blnAngle = False
                Debug.Print "1 Elm only: included to predecessor path:"
                Debug.Print "path_end of path j = " & j - 1 & " changed to " & path_end
            Else
                path(j) = path_end
                j = j + 1
                blnAngle = False
                Debug.Print path_end - path_beg + 1 & " Elms: own path with length " & Length
            End If
            Exit Do
        End If
    Loop
    If blnAngle = True Then
        length_l = Abs(Length - ElemEdgeLengths(path_end - 1) - minlength)
        length_u = Abs(Length - minlength)
        If length_l <= length_u Then
            i = path_end
            path(j) = path_end - 1
            j = j + 1
            Debug.Print "last Elm set to " & path_end - 1
        Else
            path(j) = path_end
            j = j + 1
            Debug.Print "last Elm is " & path_end
        End If
    End If
Loop

I have "translated" the sub to tcl like this, but I am not able to simulate the behaviour of ExitDo correctly. How can I recode the VBA Sub in Tcl correctly ? :

proc magictrap {code body} {
    if {$code <= 4} {error "bad magic code"}; # Lower values reserved for Tcl
    if {[catch {uplevel 1 $body} msg opt] == $code} return
    return -options $opt $msg
}
proc magicthrow code {return -code $code "doesn't matter what this is"}

proc pathfinder {ElemEdgeLengths minlength LimitAngle angles} {
set j 0
set i 0
set numofentries [llength $ElemEdgeLengths]

    while { $i < $numofentries }  {

        set path_beg $i
        set path_end $i
        set length 0
        set length_l 0
        set length_u 0
        set blnAngle 1

        while { ( $length < $minlength )  } {

            if { ( [lindex $angles $i] < $LimitAngle ) || ( $path_beg == $i ) } {
                set length [ expr { $length + [lindex $ElemEdgeLengths $i] } ]
                set path_end $i
                incr i
                if { $i == $numofentries } { magicthrow 5 }
            } else {
                if { $path_end == $path_beg } {
                    set k [expr { $j - 1 }]
                    set path($k) $path_end
                    set blnAngle 0
                } else {
                    set path($j) $path_end
                    incr j
                    set blnAngle 0
                }
                set length inf
            }
        }

        if { $blnAngle == 1  } {
            set length_l [ expr { abs( $length - [lindex $ElemEdgeLengths [expr {$path_end - 1} ] ] - $minlength   ) } ]
            set length_u [ expr { abs( $length - $minlength ) } ]
        }

        if { $length_l <= $length_u } {
            set i $path_end
            set path($j) [expr {$path_end - 1}]
            incr j
        } else {
            set path($j) $path_end
            incr j
        }

    }

    return  $path

}

A: The VB Exit Do corresponds very closely to break in Tcl (and many other languages besides).

A: "break" exits the innermost loop.
you could set a boolean variable at the "exit do" location:
    set blnBreak 1
    break

just outside the loop you will have to test it:
    if { $blnBreak == 1  } {
        break
    }


text:
Q: Ambiguity during explicit initialization of arrays in C #include<stdio.h>
int main()
{
  char a[4] = {'7','4','5'};
  for(int i=0; a[i] != '\0'; i++)
     printf("%c\n", a[i]);
}

Since the compiler automatically null terminates the array, the mentioned code works as expected.
But when i change line 4 to char a[] = {'7', '4', '5'}; the code still works but prints off a few extra characters beyond the end of string.
My question is why doesn't the compiler terminate the array with a null in the second case.

A: The compiler does not automatically null-terminates the array. All it does is filling in the portion that you have not initialized explicitly with zeros. In your case it's only one element that's left uninitialized, but it may be an arbitrary number of elements:
char a[14] = {'7', '4', '5'}; // Compiler provides 11 zeros

or no elements at all if you specify N initializers for an array of N elements:
char a[3] = {'7', '4', '5'}; // Compiler provides no zeros

When you let the compiler deduce the size of the array from initializers, there are no elements left to be zero-initialized, because the array has exactly three elements - '7','4', and '5'. There's no space for '\0', because it's equivalent to the situation above, when the compiler does not provide any additional zeros.
That is why if you want null termination you need to do it yourself, like this
char a[] = {'7', '4', '5', '\0'};

or let the compiler do it for you by initializing with a string literal, like this:
char a[] = "745";

Note: The compiler will provide null terminator for char arrays initialized with string literals only when there is sufficient space for the terminator in the array. For example, char a[3] = "745" would not be terminated, because there is no space for '\0'.

A: You declared the first array as a 4-element array of char, and only explicitly initialized the first three elements.  As a result, the compiler implicitly initialized the fourth element to 0 (the compiler isn't treating the array as a string, though; it's just a rule that if there aren't as many initializers as there are elements in the array, the remaining elements are initialized to 0 or NULL depending on the type of the array).
You declared the second array as a 3-element array of char and explicitly initialized all of the elements (the array size is taken from the number of initializers).  There's no room for a null terminator, and the compiler doesn't extend the array to insert one.


text:
Q: Accessing users groups through attributes / foreign keys in Django I'm trying to access my users groups in Django, but keep getting
auth.Group.None

as the result.
When in the django shell I'll first create a group, then a user and add the user to the group. After this, I try to print the users groups, like so:
from django.contrib.auth.models import User, Group

Artists = Group.objects.create(name="Artists")
Artists.save()
Rihanna = User.objects.create_user(username="Rihanna", password="newpassword")
Rihanna.save()
Artists.user_set.add(Rihanna)
# Save both of them again just to double check
Rihanna.save()
Artists.save()

# Now try to access Rihanna's groups through her attributes:
print Rihanna.groups, Rihanna.groups.name

and the results are
>>> auth.Group.None None

What I'd like to happen is for it to print the groups name.
I know I can query the members of a group by the filter and get commands, but I'd like to access the groups straight through a users attributes/foreign keys. Any idea what I'm doing wrong?

A: You added user to group in group object, but your user object does not have update state for this.
Try access groups like this:
print Rihanna.groups.all()

or add group in user model:
Rihanna.groups.add(Artists)


text:
Q: javascript validation of control array I am doing an application in which end user can create 'n' number of textbox on runtime. If any user will demand 'n' number of textboxex then i have used control array e.g.
Enter the data: <input type="text" name="txtData[]" id="txtData1" />

Enter the data: <input type="text" name="txtData[]" id="txtData2" />

In whole application name based validation is used (http://www.javascript-coder.com/html-form/javascript-form-validation.phtml). I am unable to validate above functionality using this validation.
Is any way to validate control array?

A: Just a thought, does it validate when you add the correct index to you names?
Enter the data: <input type="text" name="txtData[1]" id="txtData1" />

Enter the data: <input type="text" name="txtData[2]" id="txtData2" />

And you should maybe start the numbering from 0 if want to loop more easily trough your form data after submit. So:
Enter the data: <input type="text" name="txtData[0]" id="txtData0" />

Enter the data: <input type="text" name="txtData[1]" id="txtData1" />


text:
Q: Demographic of users on different Stack Exchange sites I'm interested in the demographic of users on non-CS-related SE sites (think Travel, Cooking, etc.).
Specifically, I'm interested in knowing how many of them are programmers.
I imagine a not-so-terrible way to measure that is to see how many of them are on SO.
Have these ever been investigated anywhere? How can I find them out?

Update:
Just like I suspected, on almost all SE sites, most people seem to be programmers.
Perhaps it's just me, but this seems like an astonishingly biased demographic for sites like Cooking, English, Travel, etc., which have nothing to do with programming.
@Admins/Mods/Powers-that-be:  Have you considered whether this is desirable?

A: If you're for the simplest case only interested interested in the number of users on a site that also have an Stack Overflow account, the following multi-database query gives you those numbers:
  -- start create url from dbname
IF OBJECT_ID ( '#siteurl', 'P' ) IS NOT NULL
    DROP PROCEDURE #siteurl;
GO
create procedure #siteurl
   @dbname nvarchar(250),
   @res nvarchar(250) OUT
   as
   begin
      -- we have three sites that have borked DNS entries
      set @dbname = (case @dbname
      when 'StackExchange.Audio' then 'StackExchange.Avp'
      when 'StackExchange.Audio.Meta' then 'StackExchange.Avp.Meta'
      when 'StackExchange.Mathoverflow.Meta' then 'net.Mathoverflow.meta'
      else @dbname
      end)
      -- and one of those doesn't want to end with .com
      if @dbname <> 'net.Mathoverflow.meta'
         set @dbname = 'com.' + @dbname
      exec #recursesiteurl @dbname,  @res OUTPUT
   end
GO
-- create url from dbname
IF OBJECT_ID ( '#recursesiteurl', 'P' ) IS NOT NULL
    DROP PROCEDURE #recursesiteurl;
GO
create procedure #recursesiteurl
   @dbname nvarchar(250),
   @res nvarchar(250) OUT
   as
   begin
      declare @pos integer
      declare @rec nvarchar(250)

      set @res = @dbname
      set @pos = CHARINDEX('.', @dbname)
      if (@pos > 0 )
      begin
         set @rec = substring(@dbname, @pos+1, len(@dbname))
         exec #recursesiteurl @rec,  @rec output
         set @res = @rec
                  + '.'
                  + substring(@dbname, 0, @pos)
      end
   end;
GO

-- all databases
declare  db_c cursor for select [name]
                         from sys.databases
                         where database_id > 5 -- skip master, temp, model, msdb, Data.SE
                         and ([name] not like '%.meta' or [Name] = 'Meta.StackExchange')
                         and [Name] <> 'Stackoverflow'

declare @db_c_name sysname   -- holds name of db after fetch
declare @sql nvarchar(max) -- holds build up sql string

-- result table
create table #all_users ( site nvarchar(250)
                            , total bigint
                            , totso bigint);

open db_c
fetch next from db_c into @db_c_name
while(@@FETCH_STATUS = 0)
begin
    set @sql = N'use '+ QUOTENAME(@db_c_name) +';
               declare @url nvarchar(250)
               exec #siteurl ''' + @db_c_name  + ''', @url output
               insert into #all_users
               select @url
               , count(*)
               , sum(case when s.id is not null
                          then 1
                          else 0
                     end)
               from users u
               left outer join Stackoverflow.dbo.users s
                            on s.accountid = u.accountid;'
    exec (@sql)
   fetch next from db_c into @db_c_name
end;
close db_c;
deallocate db_c;

select replace(
       replace(
       replace(site,
         '.StackExchange.com',''),
         '.com',''),
         '.net','') as [site]
     , total as [All Users]
     , totso as [Users also on SO]
     , cast(totso as float) / total * 100 as [%]
from #all_users
order by cast(totso as float) / total * 100 desc

drop table #all_users

drop procedure #recursesiteurl
drop procedure #siteurl

When run today the first rows look like this:

If you consider users to be participating on a site only after they reached 200 reputation this fork might be interesting, thanks to Marshmellow.


text:
Q: launchd does run but script is not executed? I have looked for answers here but could not find them.
So my issue is the following:
I have created a launchd like this: com.schedule.arp.plist
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
    <string>com.schedule.arp.plist</string>
<key>ProgramArguments</key>
<array>
    <string>/Library/Scripts/arp.sh</string>
</array>
    <key>StartInterval</key>
    <integer>300</integer>
</dict>
</plist>

I can see the it runs every 5 minutes like it should. here is the console:
Apr 21 09:46:39 eps-amsterdam com.apple.xpc.launchd[1] (com.schedule.arp.plist[2946]): Service exited with abnormal code: 1
Apr 21 09:51:39 eps-amsterdam com.apple.xpc.launchd[1] (com.schedule.arp.plist[3274]): Service exited with abnormal code: 1
Apr 21 09:56:39 eps-amsterdam com.apple.xpc.launchd[1] (com.schedule.arp.plist[3554]): Service exited with abnormal code: 1
Apr 21 10:01:39 eps-amsterdam com.apple.xpc.launchd[1] (com.schedule.arp.plist[4156]): Service exited with abnormal code: 1
The actual script is here:/Library/Scripts/arp.sh
it contains the following:
#!/bin/sh
sudo php56 /opt/local/apache2/htdocs/epsamsterdam/arpreach_full/a.php cli/auto

But this last part is not executed?
Manual hitting this command in terminal runs fine.
So where do I go wrong?
I'm running at El Capitan 10.11.4


text:
Q: WinForms binding I have some controls bound to a BindingSource control.
I want to do a calculation when the value changes  in one control and set the result on another control.
Do I update the textbox the property is bound to or do I update the underlying entity which would update the control anyway (I hope)?
When I change combobox A (OnPropertyChange) textbox B is updated with the new calculated result. This works fine, but I have noticed that when I leave combobox A it reverts back to its original value. What is going on here!
Private Sub ComboBoxEditCostCode_EditValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ComboBoxEditCostCode.EditValueChanged
    Select Case ComboBoxEditCostCode.EditValue
        Case "7"
            CType(TransactionEntityBindingSource.Current, TblTransactionsEntity).Qbdescription = "7-is here"

        Case "2"
            CType(TransactionEntityBindingSource.Current, TblTransactionsEntity).Qbdescription = "2-is here"

        Case Else
            CType(TransactionEntityBindingSource.Current, TblTransactionsEntity).Qbdescription = "7-is here"
    End Select
End Sub

A: if we bind a control to a source, then if the source changes, we can make the its value automatically reflected in the control. About the problem you are facing, it would be better if you show the code snippet.

A: Tell more about your changing, how second text box is bound?
You have to change your initial data instead of changing textbox b value.
Also when textbox A loses it focus raises EndEdit event and I think binding mechanism refreshes value in textbox B.
You can control on which action editing is done when you setting your binding to textboxes.

A: as a rule of thumb, if you are using a binding source you always CRUD the data through it.  Don't forget to call BindingSource.EndEdit when you are done, hope this helps


text:
Q: Vertical list of items with gap size as percentage of item size I have a vertical list of items of equal but implicit size. I want a gap between the items to be a percentage relative to this implicit size.
The main problem is that vertical margins are relative to widths, not heights, so they can't be used for this. (Otherwise, one could have a child in the item add the gap as a margin.)
The gap property of flex boxes and grids is in relation to the entire container.
I think this is likely impossible but I wanted to check with the community to verify.

A: I'm not sure it can be done with pure css, but here is a simple version with javascript, I just looped through a lists children and dynamically set the margin in this case as 10% of its height.

var list = document.getElementById('list');
var children = list.children;
for (var i = 0; i < children.length; i++) {
   children[i].style.marginTop = (parseInt(children[i].clientHeight) * .1).toString() + "px";
}
*{
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.container {
 background-color: gray;
 padding: 10px;
}

.list{
 background-color: lightgray;
 display: flex;
 flex-direction: column;
 list-style: none;
}

.list-item{
  background-color: lightblue;
}

#li1{
  height: 25px;
}
#li2{
  height: 50px;
}
#li3{
  height: 75px;
}

Item 1

Item 2

Item 3