text:
Q: Loading page relative to local folder I am trying to show a web page relative to the local folder in a UWP app. This means, I have the page itself as string, but assets (images, scripts) are located in the apps local folder.
I tried to use the NavigateToString method that as I understood should serve this task, in combination with the Source-property of a WebView control.
var baseUri = new Uri("ms-appdata:///local/");
WebView.Source = baseUri;
var page = ...;
WebView.NavigateToString(page);

However, this gives me the following error message when assigning the Source-property of the web view:
Exception thrown: 'System.ArgumentException' in App.exe
Additional information: Value does not fall within the expected range.

So apparently, using the local app folder for assets is not supported?
The app targets minimum Windows 10 Build 10586.
Does anybody know whether there is a useful workaround for this?
Edit: I tried to make a minimum example. In the following, I created a small test app that does nothing but loading a static html file from the local storage. As far as I can tell, this code exactly resembles the XamlWebView example but does raise an ArgumentException.
MainPage.xaml
<Page
    x:Class="App1.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:App1"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">

    <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
        <WebView Name="WebView" />
    </Grid>
</Page>

MainPage.xaml.cs
using System;
using System.IO;
using Windows.Storage;
using Windows.UI.Xaml.Controls;

// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409

namespace App1
{
    ///
    /// An empty page that can be used on its own or navigated to within a Frame.
    ///
    public sealed partial class MainPage : Page
    {
        public MainPage()
        {
            this.InitializeComponent();

            Initialize();
        }

        private async void Initialize()
        {
            var file = await ApplicationData.Current.LocalFolder.CreateFileAsync("index.html", CreationCollisionOption.ReplaceExisting);
            using (var sw = new StreamWriter(await file.OpenStreamForWriteAsync()))
            {
                sw.WriteLine("");
                sw.WriteLine("");
                sw.WriteLine("This is some text");
                sw.WriteLine("");
                sw.WriteLine("");
            }

            WebView.Navigate(new Uri("ms-appdata:///local/index.html"));
        }
    }
}

I do not even know where the difference to the sample is, can't find any.

A: WebView.Source property is ued to gets or sets the Uniform Resource Identifier (URI) source of the HTML content to display in the WebView control.
We usually set the Source property in XAML. The XAML parser automatically converts the string to a Uri. The Source property can be set in code, but rather than doing so, we typically use one of the Navigate methods such as Navigate, NavigateToString and NavigateWithHttpRequestMessage method to load content in code.
And the URI you've used in your code is not a valid URI for WebView control, so you got a Value does not fall within the expected range. error. To load content from app's local storage, we need to place the content in a subfolder under the local folder. Ref Remarks in WebView class:

To load uncompressed and unencrypted content from your app's LocalFolder or TemporaryFolder data stores, use the Navigate method with a Uri that uses the ms-appdata scheme. The WebView support for this scheme requires you to place your content in a subfolder under the local or temporary folder. This enables navigation to URIs such as ms-appdata:///local/folder/file.html and ms-appdata:///temp/folder/file.html . (To load compressed or encrypted files, see NavigateToLocalStreamUri.)
Each of these first-level subfolders is isolated from the content in other first-level subfolders. For example, you can navigate to ms-appdata:///temp/folder1/file.html, but you can't have a link in this file to ms-appdata:///temp/folder2/file.html. However, you can still link to HTML content in the app package using the ms-appx-web scheme, and to web content using the http and https URI schemes.

So when you use WebView.Navigate(new Uri("ms-appdata:///local/index.html"));, you still get the error as ms-appdata:///local/index.html is also not a valid URI for WebView.
Besides, although NavigateToString supports content with references to external files such as CSS, scripts, images, and fonts. But it only supports content in the app package using the ms-appx-web scheme, and web content using the http and https URI schemes. It can't work with assets located in the apps local folder. To achieve what you want you need to put these assets into a subfolder under the local folder and then also store the html string to a file under the same subfolder. In the html, you can use relative URI to reference these assets like what in my previous answer.


text:
Q: C header files and dynamic linking error I have created a dynamically linked library. The only problem I have is that my main program does not recognize my header file. The header file is in a separate folder from my main program. I have tried #include "myheader.h" as well as #include "/folder/dir/myheader.h"
Here is what my .h consist of
    extern int afunction(int,int);
    extern int afunction(int,int);

So far this code works
    gcc -fPIC -c filename1.c
    gcc -fPIC -c filename2.c

    gcc -shared -o libMylib.so filename1.o filename2.o

I then copy the lib to /usr/local/lib, and then
    gcc main.c -L. -lMylib -o exeName -ldl

and I get
    " myheader.h : no such file or directory.

Here is my directory structure:
directory1 ----------------folder1(main program.c)
directory1 ----------------folder2(myheader.h, along with functions for the pgm)
A push in the right direction would help, as I have written all my code and I am just at the last phase.

A: You need gcc ... -I<some directory to myheader.h>. That will enable the compiler to find the header file.

A: You can put your lib header files in the same folder with your current program.
or like @Ed Heal said.. adding -I<path> for include header folder.

redpajama_set_name: RedPajamaStackExchange


text:
Q: MySQL updates all rows when the column name is only specified in the where clause It's been a while I didn't work on mysql and I was suprised to see that the following statement is valid:
UPDATE table_A
SET col_a = value
WHERE id;

It looks like MySQL updates all rows in the table. I have a good MSSQL background and I am trying to understand why this valid in MySql?
Also, I ran a query  with a similar  where clause on a varchar column:
SELECT distinct description
FROM table_A
where NOT description;

I tought it will return only null or empty values. Instead, it returns lots of rows with non-null values.
Any ideas why?
Thanks,

A: WHERE x will match any rows for which x evaluates to a truthy value. Since BOOLEAN is actually a number type TINYINT(1), this works by converting to a number and then comparing to zero - any nonzero number is truthy. (NULL is falsy.)
If you write WHERE id = 123, then only for the row where id is 123, the expression id = 123 will evaluate to TRUE (which is the same as 1) and it will match, otherwise it will evaluate to FALSE (0).
But if you write WHERE id, the requirement is that id evaluates to a truthy value. If id is a number, only IDs 0 and NULL will be falsy.
However, in case of description, you have a string. And the string is first converted to a number. The reason you got many results there is that any string that starts with a number (that is nonzero) is matching, such as 01234hello (which converts to 1234, which is nonzero). Check what CONVERT(description, SIGNED) gives - if it is nonzero, then it matches.
This is why, when building AND or OR queries in code, you can avoid handling the case of zero conditions specially by starting with TRUE or 1 (in the AND case) or FALSE or 0 (in the OR case), since WHERE TRUE/WHERE 1 is valid (matches everything), as is WHERE FALSE/WHERE 0 (matches nothing). So you build a query by starting with WHERE 1 and adding to it: WHERE 1, WHERE 1 AND id = 123, WHERE 1 AND id = 123 AND type = 'xy', etc.


text:
Q: Visual output of Matplotlib bar chart - Python I am working on getting some graphs generated for 4 columns, with the COLUMN_NM being the main index.
The issue I am facing is the column names are showing along the bottom.  This is problematic for 2 reasons, first being there could be dozens of these columns so the graph would look messy and could stretch too far to the right. Second being they are getting cut off (though I am sure that can be fixed)
I would prefer to have the column names listed vertically in the box where 'MAX_COL_LENGTH' current resides, and have the bars different colors per column instead.
Any ideas how I would adjust this or suggestions to make this better?
for col in ['DISTINCT_COUNT', 'MAX_COL_LENGTH', 'MIN_COL_LENGTH', 'NULL_COUNT']:
    grid[['COLUMN_NM', col]].set_index('COLUMN_NM').plot.bar(title=col)
    plt.show()

A: In this case you can plot points one by one and setup the label name for each point:
gs = gridspec.GridSpec(1,1)
fig = plt.figure(figsize=(5, 5))
ax = fig.add_subplot(gs[:, :])
data = [1,2,3,4,5]
label = ['l1','l2','l3','l4','l5']
for n,(p,l) in enumerate(zip(data,label)):
    ax.bar(n,p,label=l)
ax.set_xticklabels([])
ax.legend()

This is the output for the code above:


text:
Q: React-Native - availableHeight is indefinite so heightMeasureMode must be YGMesureModeUndefined I got this Error

Here is my code
<ImageBackground source={BG} style={{ flex: 1 }}>
    <ScrollView horizontal style={{ flex: 1, height: '100%' }}>
        <View style={{ paddingTop: '10%' }}>
            <Text style={[styles.bold, styles.textCenter, { fontSize: 18, color: c.yellow }]}>Data</Text>
            <View style={[styles.row, styles.justifyBetween, { width: '100%', paddingHorizontal: '5%', borderTopWidth: 1, borderBottomWidth: 1, borderColor: c.yellow }]}>
                <Text style={[styles.textWhite, { width: '10%' }]}>Sr.</Text>
                <Text style={[styles.textWhite, { width: '20%' }]}>User ID</Text>
                <Text style={[styles.textWhite, { width: '20%' }]}>Name</Text>
                <Text style={[styles.textWhite, { width: '25%' }]}>Phone</Text>
                <Text style={[styles.textWhite, styles.textCenter, { width: '20%' }]}>Active</Text>
                <Text style={[styles.textWhite, { width: '25%' }]}>Time/Date</Text>
            </View>
        </View>
        {loading ?
            <ActivityIndicator color={c.yellow} size='large' style={{ marginTop: '20%' }} /> :
            data.length > 0 ?
                <FlatList
                    data={data}
                    keyExtractor={(item, index) => index.id}
                    renderItem={dataList}
                    style={{ width: '100%', paddingHorizontal: '1%', marginTop: '5%' }} />
                : <Text style={[styles.textWhite, styles.textCenter, styles.bold, { fontSize: 20, marginTop: '20%' }]}>No Data Found!</Text>
        }
    </ScrollView>
</ImageBackground>

My RN version is 0.70.6
I'm using Ubuntu 22.04 LTS
I'm running this app on physical devices not on emulator
NodeJS version 16.18.1
JDK Info - openjdk 11.0.17 2022-10-18
Android Studio Dolphin 2021.3.1
Here are my dependecies
   "@react-native-async-storage/async-storage": "^1.17.11",
   "@react-native-community/blur": "^4.3.0",
   "@react-native-community/clipboard": "^1.5.1",
   "@react-native-masked-view/masked-view": "^0.2.8",
   "@react-native-picker/picker": "^2.4.8",
   "@react-navigation/native": "^6.0.13",
   "@react-navigation/stack": "^6.3.4",
   "@reduxjs/toolkit": "^1.9.0",
   "axios": "0.27",
   "react": "18.1.0",
   "react-native": "0.70.6",
   "react-native-elements": "^3.4.2",
   "react-native-gesture-handler": "^2.8.0",
   "react-native-image-crop-picker": "^0.38.1",
   "react-native-paper": "^4.12.5",
   "react-native-qrcode-svg": "^6.1.2",
   "react-native-reanimated": "^2.13.0",
   "react-native-safe-area-context": "^4.4.1",
   "react-native-screens": "^3.18.2",
   "react-native-splash-screen": "^3.3.0",
   "react-native-svg": "^13.6.0",
   "react-native-vector-icons": "^9.2.0",
   "react-redux": "^8.0.5"

I've searched for Error but I got nothing. The answers says this error was exited in RN v0.56.
I want to use Vertical Flatlist inside Horizontal ScrollView


text:
Q: Calculate average from multiple rows
To produce a useful Line Graph, out of a set of "time increments", I converted said increments to seconds and rounded the values.
The image showcases this with a table of column-A: time increments, column-B: =ROUND(A2/1000000; 0) filled down, and column-D: points (for example).

Column-B, if rounded, has lots of non-unique values, which may be averaged to a single row (I prefer averaging over distracting).
What I tried:
Due to little experience in Excel, I tried copying column-B by value to a new column (to avoid errors when removing rows), then filter by unique values, and copy the sets to a new sheet, to then proceed creating a graph with less values for improved readability.

Having filtered by Unique records only from Data > Filter, Advanced, I selected column-D and generated a Line Graph, without having to edit the horizontal-axis, due to the time increments being in sequence.
However, this method is definitely slow and not viable when having to do this often. Any suggestion is very much appreciated!

A:
off to the side in a column you are not using list your seconds.  Lets say the first cell is F1.  Seed your list with the following formula:
=MIN(B:B)

It will pull your lowest second.  Once you have the start of your list, use the following formula in F2 and copy down until it is producing cells with "" in them.
=IF(OR(F1=MAX(B:B),F1=""),"",F1+1)
It checks to see when you have reached the maximum value in the previous cell and places a "" in it.  It will also do that if there previous cell is equal to "".  Otherwise it increases the value of the previous cell by 1.
In G1 get the average value for in column C for all seconds matching what is in F1.  Use the following formula for G1 and copy down to the bottom of your list in column G.
=AVERAGEIF(B:B,F1,C:C)

NOTE my system uses , as a separateor instead of ;. you will need adjust the formulas to match your system.


text:
Q: How to trigger AWS Lambda function error to test Cloudwatch Alarm Have a lambda function in production, however I need to verify that upon an execution error, the configured cloudwatch alarm will successfully go to Alarm state.  One option is to update the code and simply break it temporarily, but this isn't feasible.
Looking for an API call that can force an AWS Lambda to error without having to modify the actual code.

A:
Looking for an API call that can force an AWS Lambda to error without having to modify the actual code.

This is no such call. But some lambda errors (specially runtime errors) can be "forced" without changing a source code. For example, but removing lambda permissions or changing function execution timeout.
You can also manually set your CW alarm into alarm state using set-alarm-state API call.

A: As mentioned in other answers, there is no such API. There are however two ways I could imagine doing this:

*

*Invoking your Lambda with faulty input data using either the AWS Console or AWS CLI (see example below).

*Manipulating the configuration of the Lambda in such a way, that it causes an error. For example setting the memory too low, using a timeout that too short or removing required permissions.

Depending on your code, there might be a way by invoking your Lambda with faulty input data (see 1. above). Imagine a Go Lambda for a party planning service like the following:
func handleRequest(event MyEvent) error {
    if event.NumberOfGuests < 2 {
        return errors.New("there should be at least 2 guests")
    }
    return nil
}

func main() {
    lambda.Start(handleRequest)
}

You could now invoke your Lambda with a payload like this:
{
  "NumberOfGuests": 1
}

This would force the Lambda above to return an error.
Obviously, this highly depends on the code of your Lambda, but if you have code paths like this, all you need to do is to invoke the Lambda with input data that would run this code paths.


text:
Q: What good resources are available for an experienced ASP.NET developer to learn Windows Forms/WPF programming? I am a ten-year veteran of ASP.NET and C# development and I'm moving into a position where I will be doing much more Windows Forms and WPF development. I have minimal experience with these technologies.
Can you recommend any good books or resources that will help me ramp up on these technologies quickly? I'd like to find resources that skip over basic .NET programming topics and get right to the heart of good application architecture, design and implementation.

A: There are many resources on windowsclient.net.  This is the official, Microsoft run Windows Forms and WPF site.
That being said, I'd recommend only trying to get a very basic idea of Windows Forms, and instead, focus on learning WPF.  This will help for Silverlight development, as well.  WPF is the newer technology, and really is a better path going forward for future proofing yourself.  By learning it first, you won't have to unlearn many bad habits you'll pick up with Windows Forms development.

A: Take a look at MEF and Prism if you are looking for good WPF application design. As for books - I'd recommend Apress' Pro WPF in C# 2008 (Don't know when it will be updated for 4.0, but relative few new things to learn here (mostly a few new controls and improvements in existing controls/syntax).

A: I really liked this video by Jason Dolinger on the MVVM pattern for WPF.  It is a really great into what you can do with WPF, how data binding works, and helps get you thinking in the right direction.
http://blog.lab49.com/archives/2650


text:
Q: App engine call to Google API python client return 403 with @oauth_required It should be a trivial job but i cannot get it out.
I need to call the Google Calendar API from Gae; thus I set all up as per Google docs and examples:
I've an /auth.py:
CLIENT_SECRETS = os.path.join(os.path.dirname(__file__), 'client_secrets.json')
SCOPES = [
    'https://www.googleapis.com/auth/calendar',
]
decorator = appengine.OAuth2DecoratorFromClientSecrets(
    filename=CLIENT_SECRETS,
    scope=SCOPES,
    cache=memcache,
    prompt='consent',
)

called by main.py functions:
class Landing(webapp2.RequestHandler):
    @auth.decorator.oauth_aware
    def get(self):
        if auth.decorator.has_credentials():
            self.redirect('/in')
        else:
            self.response.out.write('''
            etc. {}'''.format(auth.decorator.authorize_url()))

class Main(webapp2.RequestHandler):
    @auth.decorator.oauth_required
    def get(self):
        links = { ... }
        render(self, 'base.html', template_values=links)

class Calendar(webapp2.RequestHandler):
    @auth.decorator.oauth_required
    def get(self):
        service = build('calendar', 'v3', http=auth.decorator.http())
        api_request = service.events().list(calendarId='primary')
        api_response = api_request.execute()
        self.response.headers['Content-Type'] = 'application/json; charset=utf-8'
        self.response.out.write(json.dumps(api_response, indent=4))

class PutEvent(webapp2.RequestHandler):
    @auth.decorator.oauth_required
    def post(self):
        # ...
        # http = httplib2.Http(memcache)
        service = build('calendar', 'v3') #, http=http)

        api_response = []
        for i in json.loads(self.request.get('events')):
            # ...
            event = { ... } # Google Calendar event
            api_request = service.events().insert(calendarId='primary', body=scadenza)
            api_response.append(api_request.execute(http=auth.decorator.http()))

        self.response.headers['Content-Type'] = 'application/json; charset=utf-8'
        self.response.out.write(json.dumps(api_response, indent=4))

As you can see this is a fairly simple post requested by an Ajax jQuery call ($.post('{{ putEvent_url }}', jsonData, function( data ){ console.log(data); })...
I'm in the development server, using test@example user, and the app is authorized to access my personal account's Google Calendar.
Strange thing to me is that any call to Calendar() works as expected, but call to PutEvent() end in ERROR 500.
Looking to the end of the traceback in console:
  File "/home/pierpaolo/Devnos/whiterabbit/include/oauth2client/contrib/appengine.py", line 644, in check_oauth
    resp = method(request_handler, *args, **kwargs)
  File "/home/pierpaolo/Devnos/whiterabbit/main.py", line 211, in post
    api_response.append(api_request.execute(http=auth.decorator.http()))
  File "/home/pierpaolo/Devnos/whiterabbit/include/oauth2client/_helpers.py", line 133, in positional_wrapper
    return wrapped(*args, **kwargs)
  File "/home/pierpaolo/Devnos/whiterabbit/include/googleapiclient/http.py", line 838, in execute
    raise HttpError(resp, content, uri=self.uri)
HttpError: <HttpError 403 when requesting https://www.googleapis.com/calendar/v3/calendars/primary/events?alt=json returned "Forbidden">
INFO     2017-01-04 15:13:32,385 module.py:788] default: "POST /api/put/scadenze HTTP/1.1" 500 -

I cannot understand the
HttpError: https://www.googleapis.com/calendar/v3/calendars/primary/events?alt=json returned "Forbidden">
it looks to me I already granted the app access to my account and that Google App Engine decorators have been correctly put in place to make the OAuth2.0 thing as per https://developers.google.com/api-client-library/python/guide/google_app_engine...
EDIT:
I was wondering if my trouble can be related to the way i call Google Calendar API:
     HTML/JS            GAE/Py
+------------------+
|                  |
| <form>           |
|   ...data        |
| <\JS/Ajax        |
|   $.post(...data |  -->  GAE/main.py
|                  |         @auth.decorator.oauth_required
|                  |         def post(self, data):
+------------------+           event = elaborate(data)
                               service = build('calendar', 'v3')
                               api_request = service.events()
                                             .insert(calendarId='primary',
                                                     body=event)
                               api_response = api_request
                                              .execute(auth.decorator
                                                           .http())
                               self.response(api_response)

EDIT 3:
I looked a bit into oauth2client.contrib.appengine and I added some logger.debug here and there: I think the problem could be in execute(http=decorator.http()) call, but it is the same in my other handlers! Neither positional nor keyword nor put authrized Http in service build changes the misbehaviour...
Nor can I see what problem may pose _helpers.py", line 133, in positional_wrapper...
Dear all, some hint on how to research further?
Actually, I can insert Acl and/or insert a secondary calendar in the same RequestHandler that throws Forbidden exception with events().insert()...!

A: I haven't got enough reputation to comment so I'll just leave it as an answer:
Firstly, double check that you've got calandar api enabled at https://console.cloud.google.com/apis/dashboard?project=yourproject
Secondly. I've used the contacts API and discovered that once you've granted access once you cannot be granted access again unless you first revoke the initial allowance. I encountered this when a user connected my app to Google Contacts, then disconnected, then tried to reconnect - the second reconnect would fail. To check / revoke, head to https://security.google.com/settings/security/permissions

A: Apparently, the problem is to try to insert an all-day event with endTimeUnspecified: True...
I opened an issue on google-api-python-client GitHub tracker: https://github.com/google/google-api-python-client/issues/334.
Maybe someone will look into it or post a more precise answer.
Thank you all.


text:
Q: Downloading a zip file using download manager I want to download a zip file using download manager.Using this code it shows downloading file in notification and later shows download failed. I gave permissions such as read and write external directory.My code is as follows:
              if(DownloadTask.readAndWriteExternalStorage(context)){
                    downloadManager=
               (DownloadManager)getSystemService(Context.DOWNLOAD_SERVICE);
                    Uri  uri=Uri.parse("url of zip");
                    DownloadManager.Request request=  new
                                         DownloadManager.Request(uri);

    request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE|
                              DownloadManager.Request.NETWORK_WIFI);
                    request.setVisibleInDownloadsUi(true);
                    request.setTitle("Example");
                    request.setDescription("Downloading a very large zip");

                    request.setAllowedOverRoaming(true);
                    request.setMimeType("df.zip");
                    request.allowScanningByMediaScanner();

  request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,
              "df.zip");
                     request.setNotificationVisibility(DownloadManager.
           Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
                    Long reference=downloadManager.enqueue(request);
                }

A: I solved the issue with this:
DownloadManager downloadManager;

private int count = 0;
    private long Zip_DownloadId,imid;
     Uri uri =

 Uri.parse("http://website//"+rowItems.get(i).get("Attachments"));
              if ( uri.toString().endsWith(".jpg")) {
                    imid=DownloadData(uri, view);
                  Check_Image_Status(imid);
              } else if (uri.toString().endsWith(".png")) {
                  imid=DownloadData(uri, view);
                  Check_Image_Status(imid);
              } else if (uri.toString().endsWith(".jpeg")) {
                  imid=DownloadData(uri, view);
                  Check_Image_Status(imid);

              } else if (uri.toString().endsWith(".zip")) {
                   Zip_DownloadId = DownloadData(uri, view);
                  Check_Zip_Status(Zip_DownloadId);
              }
                Toast.makeText(getApplicationContext(),uri.toString(),Toast.LENGTH_LONG).show();

            }

        });

        downloadReceiver = new BroadcastReceiver() {

            @Override
            public void onReceive(Context context, Intent intent) {

                //check if the broadcast message is for our Enqueued download
                long referenceId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);

                if (referenceId == imid) {

                    Toast toast = Toast.makeText(SupportTicketViewActivity.this,
                            "Image Download Complete", Toast.LENGTH_LONG);
                    toast.setGravity(Gravity.TOP, 25, 400);
                    toast.show();

                } else if (referenceId == Zip_DownloadId) {
                    Toast toast = Toast.makeText(SupportTicketViewActivity.this,
                            "Zip Download Complete", Toast.LENGTH_LONG);
                    toast.setGravity(Gravity.TOP, 25, 400);
                    toast.show();
                }

            }
        };
        return view;
    }

    private void Check_Zip_Status(long Zip_DownloadId) {

        DownloadManager.Query ZipDownloadQuery = new DownloadManager.Query();
        //set the query filter to our previously Enqueued download
        ZipDownloadQuery.setFilterById(Zip_DownloadId);

        //Query the download manager about downloads that have been requested.
        Cursor cursor = downloadManager.query(ZipDownloadQuery);
        if (cursor.moveToFirst()) {
            DownloadStatus(cursor, Zip_DownloadId);
        }}

    private void Check_Image_Status(long imid) {
        DownloadManager.Query ImageDownloadQuery = new DownloadManager.Query();
        //set the query filter to our previously Enqueued download
        ImageDownloadQuery.setFilterById(imid);

        //Query the download manager about downloads that have been requested.
        Cursor cursor = downloadManager.query(ImageDownloadQuery);
        if(cursor.moveToFirst()){
            DownloadStatus(cursor, imid);
        }
    }

    private void DownloadStatus(Cursor cursor, long DownloadId) {
        int columnIndex = cursor.getColumnIndex(DownloadManager.COLUMN_STATUS);
        int status = cursor.getInt(columnIndex);
        //column for reason code if the download failed or paused
        int columnReason = cursor.getColumnIndex(DownloadManager.COLUMN_REASON);
        int reason = cursor.getInt(columnReason);
        //get the download filename
        int filenameIndex = cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_FILENAME);
        String filename = cursor.getString(filenameIndex);

        String statusText = "";
        String reasonText = "";

        switch(status){
            case DownloadManager.STATUS_FAILED:
                statusText = "STATUS_FAILED";
                switch(reason){
                    case DownloadManager.ERROR_CANNOT_RESUME:
                        reasonText = "ERROR_CANNOT_RESUME";
                        break;
                    case DownloadManager.ERROR_DEVICE_NOT_FOUND:
                        reasonText = "ERROR_DEVICE_NOT_FOUND";
                        break;
                    case DownloadManager.ERROR_FILE_ALREADY_EXISTS:
                        reasonText = "ERROR_FILE_ALREADY_EXISTS";
                        break;
                    case DownloadManager.ERROR_FILE_ERROR:
                        reasonText = "ERROR_FILE_ERROR";
                        break;
                    case DownloadManager.ERROR_HTTP_DATA_ERROR:
                        reasonText = "ERROR_HTTP_DATA_ERROR";
                        break;
                    case DownloadManager.ERROR_INSUFFICIENT_SPACE:
                        reasonText = "ERROR_INSUFFICIENT_SPACE";
                        break;
                    case DownloadManager.ERROR_TOO_MANY_REDIRECTS:
                        reasonText = "ERROR_TOO_MANY_REDIRECTS";
                        break;
                    case DownloadManager.ERROR_UNHANDLED_HTTP_CODE:
                        reasonText = "ERROR_UNHANDLED_HTTP_CODE";
                        break;
                    case DownloadManager.ERROR_UNKNOWN:
                        reasonText = "ERROR_UNKNOWN";
                        break;
                }
                break;
            case DownloadManager.STATUS_PAUSED:
                statusText = "STATUS_PAUSED";
                switch(reason){
                    case DownloadManager.PAUSED_QUEUED_FOR_WIFI:
                        reasonText = "PAUSED_QUEUED_FOR_WIFI";
                        break;
                    case DownloadManager.PAUSED_UNKNOWN:
                        reasonText = "PAUSED_UNKNOWN";
                        break;
                    case DownloadManager.PAUSED_WAITING_FOR_NETWORK:
                        reasonText = "PAUSED_WAITING_FOR_NETWORK";
                        break;
                    case DownloadManager.PAUSED_WAITING_TO_RETRY:
                        reasonText = "PAUSED_WAITING_TO_RETRY";
                        break;
                }
                break;
            case DownloadManager.STATUS_PENDING:
                statusText = "STATUS_PENDING";
                break;
            case DownloadManager.STATUS_RUNNING:
                statusText = "STATUS_RUNNING";
                break;
            case DownloadManager.STATUS_SUCCESSFUL:
                statusText = "STATUS_SUCCESSFUL";
                reasonText = "Filename:\n" + filename;
                break;
        }

        if (DownloadId == Zip_DownloadId) {

            Toast toast = Toast.makeText(SupportTicketViewActivity.this,
                    "Zip Download Status:" + "\n" + statusText + "\n" +
                            reasonText,
                    Toast.LENGTH_LONG);
            toast.setGravity(Gravity.TOP, 25, 400);
            toast.show();

        } else {

            Toast toast = Toast.makeText(SupportTicketViewActivity.this,
                    "Image Download Status:" + "\n" + statusText + "\n" +
                            reasonText,
                    Toast.LENGTH_LONG);
            toast.setGravity(Gravity.TOP, 25, 400);
            toast.show();

            // Make a delay of 3 seconds so that next toast (Music Status) will not merge with this one.
            final Handler handler = new Handler();
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                }
            }, 3000);

        }

    }

}

    private long DownloadData(Uri uri, View view) {
        long downloadReference;

        downloadManager = (DownloadManager)getSystemService(DOWNLOAD_SERVICE);
        DownloadManager.Request request = new DownloadManager.Request(uri);

        //Setting title of request
        request.setTitle("Data Download");

        //Setting description of request
        request.setDescription("Android Data download using DownloadManager.");

        //Set the local destination for the downloaded file to a path within the application's external files directory

         if(uri.toString().endsWith(".jpg")) {
             request.setDestinationInExternalFilesDir(SupportTicketViewActivity.this, Environment.DIRECTORY_DOWNLOADS, "AndroidTutorialPoint.jpg");
         }else if (uri.toString().endsWith(".zip")){
             request.setDestinationInExternalFilesDir(SupportTicketViewActivity.this, Environment.DIRECTORY_DOWNLOADS, "AndroidTutorialPoint.zip");
         }else if(uri.toString().endsWith(".png")) {
             request.setDestinationInExternalFilesDir(SupportTicketViewActivity.this, Environment.DIRECTORY_DOWNLOADS, "AndroidTutorialPoint.png");
         } else  if(uri.toString().endsWith(".jpeg")) {
             request.setDestinationInExternalFilesDir(SupportTicketViewActivity.this, Environment.DIRECTORY_DOWNLOADS, "AndroidTutorialPoint.jpeg");
         }  //Enqueue download and save the referenceId
        downloadReference = downloadManager.enqueue(request);

        return downloadReference;
    }


text:
Q: Fix the first row of a HTML table I want to make the first row of a HTML table always visible when the user scrolls down the page.
I tried to style it as "position: fixed", but the problem is that when I do that, the cells of the first row start to have different widths compared to the cells of the other rows.
My table is styled as "table-layout: fixed, width: 100%".
Do you know why please?

A: in your css
tr{ position:absolute; }


text:
Q: PySide2 how to use Qtimer like time.sleep I have a simple GUI App, it's a timer with LCD display I have problem with delaying one function that's responsible for counting down the time it's should count down every second, but it's count the minute in one second, it for loop function here the demo of the project
from PySide2 import QtWidgets , QtCore
import sys
from clock_gui import Ui_clock # this is the GUI components

class clockApp(QtWidgets.QMainWindow, Ui_clock):
    def __init__(self):
        super(clockApp,self).__init__()
        self.setupUi(self) # it set up the UI from Ui_clock
        self.min = self.spinBox_min.value()
        self.sec = self.spinBox_sec.value()
        self.button.clicked.connect(self._buttonFunction) # the button
        self.show() # render the GUI

    def _buttonFunction(self): # the function that counts down after the button clicked
        self.total = (self.min *60) + self.sec # take minutes and seconds to one variable
        if self.total >=1:
           for i in range(self.total):
               self.total -= 1
               # here the problem I want the delay to start here
               # I can use time.sleep but I want to use Qtimer I try it in different ways, but didn't work there is no error but the Qtimer didn't delay anything

app = QtWidgets.QApplication(sys.argv)
window  = clockApp()
app.exec_()

I try setInterval and I try singleShot but nothing works, maybe I use them wrong?

A: Using a QTimer is the right approach, but you need to use the timeout signal instead of a for-loop (which will block GUI updates until it ends). It might also help to use a QTime object to count down the seconds, as this will make it easier to format the dsiplay for the LCD widget.
Below is a simple demo that shows one way to implement this. Hopefully you can see how to adapt this code to suit your own requirements:

from PySide2 import QtCore, QtWidgets

class Window(QtWidgets.QWidget):
    def __init__(self):
        super().__init__()
        self.timer = QtCore.QTimer(self)
        self.timer.setInterval(1000)
        self.timer.timeout.connect(self.handleTimeout)
        self.buttonStart = QtWidgets.QPushButton('Start')
        self.buttonStart.clicked.connect(self.handleStart)
        self.buttonStop = QtWidgets.QPushButton('Stop')
        self.buttonStop.clicked.connect(self.timer.stop)
        self.min = QtWidgets.QSpinBox()
        self.min.setRange(0, 10)
        self.sec = QtWidgets.QSpinBox()
        self.sec.setRange(0, 59)
        self.lcd = QtWidgets.QLCDNumber()
        layout = QtWidgets.QGridLayout(self)
        layout.addWidget(self.lcd, 0, 0, 1, 2)
        layout.addWidget(self.min, 1, 0)
        layout.addWidget(self.sec, 1, 1)
        layout.addWidget(self.buttonStart, 2, 0)
        layout.addWidget(self.buttonStop, 2, 1)
        self.time = QtCore.QTime(0, 0)
        self.handleTimeout()

    def handleStart(self):
        if not self.timer.isActive():
            self.time.setHMS(0, self.min.value(), self.sec.value())
            self.handleTimeout()
            self.timer.start()

    def handleTimeout(self):
        self.lcd.display(self.time.toString('m:ss'))
        if self.time.minute() or self.time.second():
            self.time = self.time.addSecs(-1)
        else:
            self.timer.stop()

if __name__ == '__main__':

    app = QtWidgets.QApplication(['Test'])
    window = Window()
    window.setGeometry(600, 100, 300, 200)
    window.show()
    app.exec_()


text:
Q: Issue with char array, contains garbage I'm trying to run one of examples delivered by Raspberry for Raspberry Pi Pico. It is an example to read data from GPS module via I2C.
Raw data from GPS should be stored in a variable char numcommand[max_read], but instead of data from GPS, there is some garbage.
Here is the full code:
/**
 * Copyright (c) 2020 Raspberry Pi (Trading) Ltd.
 *
 * SPDX-License-Identifier: BSD-3-Clause
 */

#include <stdio.h>
#include <string.h>
#include "pico/stdlib.h"
#include "pico/binary_info.h"
#include "hardware/i2c.h"
#include "string.h"

/* Example code to talk to a PA1010D Mini GPS module.
   This example reads the Recommended Minimum Specific GNSS Sentence, which includes basic location and time data, each second, formats and displays it.
   Connections on Raspberry Pi Pico board, other boards may vary.
   GPIO PICO_DEFAULT_I2C_SDA_PIN (On Pico this is 4 (physical pin 6)) -> SDA on PA1010D board
   GPIO PICO_DEFAULT_I2C_SCK_PIN (On Pico this is 5 (physical pin 7)) -> SCL on PA1010D board
   3.3v (physical pin 36) -> VCC on PA1010D board
   GND (physical pin 38)  -> GND on PA1010D board
*/

const int addr = 0x10;
const int max_read = 250;

#ifdef i2c_default

void pa1010d_write_command(const char command[], int com_length) {
    // Convert character array to bytes for writing
    uint8_t int_command[com_length];

    for (int i = 0; i < com_length; ++i) {
        int_command[i] = command[i];
        i2c_write_blocking(i2c_default, addr, &int_command[i], 1, true);
    }
}

void pa1010d_parse_string(char output[], char protocol[]) {
    // Finds location of protocol message in output
    char *com_index = strstr(output, protocol);
    int p = com_index - output;

    // Splits components of output sentence into array
    int no_of_fields = 14;
    int max_len = 15;

    int n = 0;
    int m = 0;

    char gps_data[no_of_fields][max_len];
    memset(gps_data, 0, sizeof(gps_data));

    bool complete = false;
    while (output[p] != '$' && n < max_len && complete == false) {
        if (output[p] == ',' || output[p] == '*') {
            n += 1;
            m = 0;
        } else {
            gps_data[n][m] = output[p];
            // Checks if sentence is complete
            if (m < no_of_fields) {
                m++;
            } else {
                complete = true;
            }
        }
        p++;
    }

    // Displays GNRMC data
    // Similarly, additional if statements can be used to add more protocols
    if (strcmp(protocol, "GNRMC") == 0) {
        printf("Protcol:%s\n", gps_data[0]);
        printf("UTC Time: %s\n", gps_data[1]);
        printf("Status: %s\n", gps_data[2][0] == 'V' ? "Data invalid. GPS fix not found." : "Data Valid");
        printf("Latitude: %s\n", gps_data[3]);
        printf("N/S indicator: %s\n", gps_data[4]);
        printf("Longitude: %s\n", gps_data[5]);
        printf("E/W indicator: %s\n", gps_data[6]);
        printf("Speed over ground: %s\n", gps_data[7]);
        printf("Course over ground: %s\n", gps_data[8]);
        printf("Date: %c%c/%c%c/%c%c\n", gps_data[9][0], gps_data[9][1], gps_data[9][2], gps_data[9][3], gps_data[9][4],
               gps_data[9][5]);
        printf("Magnetic Variation: %s\n", gps_data[10]);
        printf("E/W degree indicator: %s\n", gps_data[11]);
        printf("Mode: %s\n", gps_data[12]);
        printf("Checksum: %c%c\n", gps_data[13][0], gps_data[13][1]);
    }
}

void pa1010d_read_raw(char numcommand[]) {
    uint8_t buffer[max_read];

    int i = 0;
    bool complete = false;

    i2c_read_blocking(i2c_default, addr, buffer, max_read, false);

    // Convert bytes to characters
    while (i < max_read && complete == false) {
        numcommand[i] = buffer[i];
        printf("raw data [ %d ]: %s \n", i, numcommand[i]);
        // Stop converting at end of message
        if (buffer[i] == 10 && buffer[i + 1] == 10) {
            complete = true;
        }
        i++;
    }
}

#endif

int main() {
    stdio_init_all();
#if !defined(i2c_default) || !defined(PICO_DEFAULT_I2C_SDA_PIN) || !defined(PICO_DEFAULT_I2C_SCL_PIN)
#warning i2c/mpu6050_i2c example requires a board with I2C pins
    puts("Default I2C pins were not defined");
#else

    char numcommand[max_read];

    // Decide which protocols you would like to retrieve data from
    char init_command[] = "$PMTK314,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0*29\r\n";

    // This example will use I2C0 on the default SDA and SCL pins (4, 5 on a Pico)
    i2c_init(i2c_default, 400 * 1000);
    gpio_set_function(PICO_DEFAULT_I2C_SDA_PIN, GPIO_FUNC_I2C);
    gpio_set_function(PICO_DEFAULT_I2C_SCL_PIN, GPIO_FUNC_I2C);
    gpio_pull_up(PICO_DEFAULT_I2C_SDA_PIN);
    gpio_pull_up(PICO_DEFAULT_I2C_SCL_PIN);

    // Make the I2C pins available to picotool
    bi_decl(bi_2pins_with_func(PICO_DEFAULT_I2C_SDA_PIN, PICO_DEFAULT_I2C_SCL_PIN, GPIO_FUNC_I2C));

    printf("Hello, PA1010D! Reading raw data from module...\n");

    pa1010d_write_command(init_command, sizeof(init_command));

    while (1) {
        // Clear array
        memset(numcommand, 0, max_read);
        // Read and re-format
        pa1010d_read_raw(numcommand);
        pa1010d_parse_string(numcommand, "GNRMC");

        // Wait for data to refresh
        sleep_ms(1000);

        // Clear terminal
        printf("\e[1;1H\e[2J");
    }
#endif
    return 0;
}

And here is part of the output:
raw data [ 0 ]: 0 Raspberry Pi Trading Ltd
raw data [ 1 ]: rry Pi Trading Ltd
raw data [ 2 ]:
raw data [ 3 ]: Mu..z
raw data [ 4 ]:
raw data [ 5 ]:
raw data [ 6 ]:
raw data [ 7 ]:
raw data [ 8 ]:
raw data [ 9 ]:
raw data [ 10 ]:
raw data [ 11 ]:
raw data [ 12 ]:
raw data [ 13 ]:
raw data [ 14 ]:
raw data [ 15 ]:
raw data [ 16 ]: C.`A`pGÅT-ï..
raw data [ 17 ]: .`A`pGÅT-ï..
raw data [ 18 ]:
raw data [ 19 ]: Mu..z
raw data [ 20 ]:
raw data [ 21 ]:
raw data [ 22 ]:
raw data [ 23 ]:
raw data [ 24 ]: ) 2020 Raspberry Pi Trading Ltd
raw data [ 25 ]: ˝.L3'.T3_.MS›&S4—&MCA&C4)&UBµ%DTÖ.DEã.WV7.IF°$EXı#RE}#RP≈#FCa#CX1#ECE

Any suggestions what's wrong?

A: You do not check the result of the I2C read. Probably it did not read anything.
You need to know how many bytes were read or if an error has occurred:
int bytesRead = i2c_read_blocking(i2c_default, addr, buffer, max_read, false);
if(bytesRead == PICO_ERROR_GENERIC) { /* handle error */ }
else
{
   /* do your stuff */
}

This is definitely wrong
if (buffer[i] == 10 && buffer[i + 1] == 10) {


text:
Q: Guarantees when starting a Boost thread I'am using Boost and Visual Studio 2013 which don't supports the C++ 11 memory model.
Are there any memory guarantees when starting a Boost thread? I look for a guarantee like in the Java Language Specification 17.4.5:

A call to start() on a thread happens-before any actions in the started thread.

In my case I want to create a (not thread safe) TCP client and than start a receiver thread:
struct Connection {
    boost::shared_ptr<TcpClient> client;
};

auto client = boost::shared_ptr<TcpClient>{new TcpClient};
client->setTimeouts(60 * 1000, 60 * 1000);
client->connect(host, port);

auto connection = boost::shared_ptr<Connection>{new Connection};
connection->client = client;

auto receiverThread = boost::shared_ptr<thread>{new thread([&connection]() {
  // can I access the client safely?
  while (connection->client->isConnected()) {
    // do receiving stuff
  }
})};

Are the changes to client, i. e. timeouts, host and port, visible in the started thread?

A: Yes. The thread didn't exist before-hand so it cannot have "stale" values (e.g. in registers). All writes prior to CreateThread are visible to the new thread.
The underlying OS functions act as implied memory barriers (CreateThread e.g.).
See also, e.g.: C++ - Should data passed to a thread be volatile?

Side note: Consider capturing the connection shared pointer by value. That's the whole point of shared pointers, to share ownership.


text:
Q: Airflow + Okta integration problem OAuth2.0 I'm trying to authenticate to Airflow using Okta (our Idp) and OAuth2.0/OpenID. For this I used this as reference:

*

*https://tech.scribd.com/blog/2021/integrating-airflow-and-okta.html

*https://flask-appbuilder.readthedocs.io/en/latest/security.html
The problem is that after finishing all the configuration when I tried to log in using Okta I get the message "Invalid login. Please try again."

The only logs I see coming from Flask i suppose are like:
172.17.0.1 - - [06/Aug/2021:14:05:01 +0000] "GET /static/pin_32.png HTTP/1.1" 304 0 "http://localhost:8080/login/?next=http%3A%2F%2Flocalhost%3A8080%2Fhome" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.131 Safari/537.36"

172.17.0.1 - - [06/Aug/2021:14:05:26 +0000] "GET /login/okta?next=http://localhost:8080/home HTTP/1.1" 302 985 "http://localhost:8080/login/?next=http%3A%2F%2Flocalhost%3A8080%2Fhome" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.131 Safari/537.36"

172.17.0.1 - - [06/Aug/2021:14:05:41 +0000] "GET /oauth-authorized/okta?code=V3YfnQL9IQOIwJLWt1KdALrtRRYM1xtZBDxNP9exlp4&state=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJuZXh0IjpbImh0dHA6Ly9sb2NhbGhvc3Q6ODA4MC9ob21lIl19.GbawEXaz1lpX1nOYuGyHHSstM9b-X36sghlhBoLuot0 HTTP/1.1" 302 221 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.131 Safari/537.36"

172.17.0.1 - - [06/Aug/2021:14:05:41 +0000] "GET /login/ HTTP/1.1" 200 17174 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.131 Safari/537.36"

I see nothing wrong there..
Configuration steps:
1. Configuring Okta:

Also the "Authorization server is the default one"
2. Complete the webserver_config.py
import os
from flask_appbuilder.security.manager import AUTH_OAUTH

AUTH_TYPE = AUTH_OAUTH
OAUTH_PROVIDERS = [
{'name': 'okta', 'icon': 'fa-circle-o',
'token_key': 'access_token',
'remote_app': {
'client_id': '0oa1ceaw9cxc1rXhi5d7',
'client_secret': 'MY CLIENT SECRET',
'api_base_url': 'https://MY OKTA DOMAIN/oauth2/default/v1/',
'client_kwargs': {
'scope': 'openid profile email groups'
},
'access_token_url': 'https://MY OKTA DOMAIN/oauth2/default/v1/token',
'authorize_url': 'https://MY OKTA DOMAIN/oauth2/default/v1/authorize',
}
}
]

3. Create a Dockerfile:
 FROM apache/airflow
 enter code here`RUN pip install authlib   \
 && pip install flask-appbuilder==3.2.2 \
 && pip install sqlalchemy==1.3.18 \
 COPY ./webserver_config.py /opt/airflow/webserver_config.py

4.Build the image and run the airflow container:
#docker build -t airflowcustom .
#docker run -d -p 8080:8080 --name airflow airflowcustom webserver

I'm stuck here ... did anyone do this or experience a similar problem?
Do you know what logs can I see and where? I don't see anything inside the airflow container.

A: Try adding these to your webserver_config.py
AUTH_USER_REGISTRATION = True
AUTH_USER_REGISTRATION_ROLE = 'User' # Or any role that you want as default


text:
Q: Cut .00 from float variable I wrote this function for cutting two last characters from (float) type variable. I would like that e.g 315.00 becomes 315
function formatFloat($value) {
    $integer = number_format($value, 2);
    return $integer;
}

But i have failed - function returns 315.00 :D What's wrong guys?

A: Use the intval function. Here is the documentation for that.
Write you code like this:
function formatFloat($value) {

    $integer = intval($value);
    return $integer;

}

Or you can directly pass the variable in that:
intval($value);

Then you don't need to make the function.

A: Like I mentioned in the comments, if you just use intval(), you can get the integer part of it, and effectively remove the decimal. This means that you don't need a function formatFloat() at all, unless you intend on doing anything more inside it.
echo intval(315.00); // 315

If you insist on using number_format(), you should see that according to the documentation, the second parameter displays the amount of decimal places. You have set it to two, so you will get two decimal places. Set it to zero, or remove it altogether (as it's default zero).
echo number_format(315.00); // 315
echo number_format(315.00, 0); // 315
echo number_format(315.00, 2); // 315.00

*

*Live demo

*PHP.net on number_format()

*PHP.net on intval()


text:
Q: Procedure to create a table with a variable number of columns I'm trying to make a stored procedure that will create a temporary table A whose columns would be dependent on the number of rows of another table, B. The background for this is that I'm allowing users to create their own 'groups', and information about the groups would be stored in table B. The creation of table A would look at the number of rows in table B, and create a column for each group in table B (using the name of the group in table B as the column name in table A). I am unable to invert the axes (axises?) because the rows would be an entry for each user in my system, which would also be variable.
So in summary: How would I create a procedure to create a temporary table with a variable number of columns?
Thank you.

A: DECLARE @sSQL varchar(max),
  @ColumnName CHAR(128)

DECLARE TableCursor CURSOR FOR
  SELECT ColumnName FROM GroupTable

SET @sSQL = 'CREATE TABLE ##NewTempTable ('

OPEN TableCursor

FETCH NEXT FROM TableCursor INTO @ColumnName

WHILE @@FETCH_STATUS = 0
BEGIN

SET @sSQL = @sSQL + RTRIM(@ColumnName) + ' CHAR(10) ,'

FETCH NEXT FROM TableCursor INTO @ColumnName

END

CLOSE TableCursor

DEALLOCATE TableCursor

SET @sSQL = @sSQL + ')'

EXEC (@sSQL)

SELECT * FROM ##NewTempTable

I hope this helps. In the DECLARE CURSOR, you will need to change the "ColumnName" and "TableName" to your actual column/table that you are querying.

A: You should not do this - instead, make the group name a column in table A as well.


text:
Q: send the value of tooltip to javascript function how can i get the value of tooltip from this object to the javascript function LoadDiv() i created
this is the object:

<asp:Image ID="image1" runat="server" ImageUrl = '<%#"data:image/jpg;base64," + Convert.ToBase64String((byte[])Eval("Data")) %>' onclick = "LoadDiv(this.src, this)" style ="cursor:pointer" ToolTip='<%# Eval("AdsID") %>' />

and this is the javascript function i created

function LoadDiv(url, lnk) {
            var img = new Image();
            var bcgDiv = document.getElementById("divBackground");
            var imgDiv = document.getElementById("divImage");
            var imgLoader = document.getElementById("imgLoader");
            var imgFull = document.getElementById("imgFull");
            var dl = document.getElementById("<%=rpImages.ClientID%>");
            var imgs = dl.getElementsByTagName("img");
}

A: Try:
var myToolTip = document.getElementsByTagName("img")[0].getAttribute("ToolTip");
document.getElementsByTagName("img") will return an array.

A: The first thing to understand here is that the ASP code won't be available in that exact form to the JavaScript. It gets compiled on the server to standard HTML, and the JavaScript will operate on that HTML. The ToolTip attribute may not appear in the HTML as is; at a guess I'd say it probably gets rendered to the title and/or alt attributes. So, taking the code you provided as an example, it would render out the HTML thus:
<img id="Image1" src="data:image/jpg;base64 ..." alt="TOOLTIP VALUE" title="TOOLTIP VALUE" onclick="LoadDiv(this.src, this)" style="cursor:pointer" />

The first thing you should do is check your rendered HTML to see how it ends up--it may or may not match what I have there. Fire the page up in your browser, and then view source or open up the F12 tools. Once you know that, you should be able to pull it off the lnk parameter in your function (to which you've passed this).

*

*If it's the title attribute, you can get it with lnk.title

*If it's the alt attribute, you can get it with lnk.alt

*If it's some other attribute, you can get it using lnk.getAttribute("attribute_name")
It should be noted that MSDN has this to say on the subject:

This property is rendered for all browsers. However, only Microsoft Internet Explorer will display this property as a ToolTip. All other browsers will ignore this property.

This suggests that it renders as a ToolTip attribute, and that it only works in Internet Explorer. If that's the case, I'd recommend using a different approach to render it for better cross-browser support.


text:
Q: Save current user's message list in parse with swift I use parse for my app. I want to let user able to type messages that they want to send via textField and save it to that user's messages column in parse with PFRelation via save button in view controller and the messages will be saved as an array and show it in tableView.
The problem is I don't know how to add text in textfield to an array and save it to parse.
Any help is appreciated and let me know if you need any additional information!
UPDATE:
These are screenshots of my parse's class "User"
This is my current user's friend list inside "Friends" column
I've not yet create Messages column because when run relationForKey code in Xcode it will automatically create for me
UPDATE 2:
This is my code:
@IBAction func addMessage(sender: AnyObject) {
    var newMessage = addMessageText.text
    let message = PFObject(className: "Messages")
    var query = PFQuery(className: "Messages")
    message["messageTextColumn"] = newMessage

    message.saveInBackgroundWithBlock {
        (success: Bool, error: NSError?) -> Void in
        if (success) {

            println("added to Message Class")
            query.whereKey("messageTextColumn", equalTo: newMessage)
            query.getFirstObjectInBackgroundWithBlock{(object:PFObject!, error: NSError!) -> Void in
                if error == nil {
                    let relation = PFUser.currentUser().relationForKey("Messages")
                    var addMessageWithObject = object
                    if addMessageWithObject != nil {
                        relation.addObject(addMessageWithObject)
                        println("Added with getFirstObject")
                    }
                    else{
                        println("Error Added with getFirstObject")
                    }
                }
            }

        } else {
            println("added to Message class Error")
        }
    }
    }

I save new message to the array first and then I save it with saveInBackgroundWithBlock.. and inside I query that message to add it to relation.
The messages that I've added appear on Messages class table but not in that user's relation but it shows log
"added to Message Class" and "Added with getFirstObject"

Which means that my code execute exactly like it should be. Probably about the method?
UPDATE 3 this is the object println
<Messages: 0x7fd4484f75f0, objectId: LFXoSaHfQl, localId: (null)> {
ACL = "<PFACL: 0x7fd4484d2e70>";
messageTextColumn = 9;

}
UPDATE 4
this is my code
@IBAction func addMessage(sender: AnyObject) {
    var newMessage = addMessageText.text
    let message = PFObject(className: "Messages")
    var user = PFUser.currentUser()
    var query = PFQuery(className: "Messages")
    message["messageTextColumn"] = newMessage

        message.saveInBackgroundWithBlock {
            (success: Bool, error: NSError?) -> Void in
            if (success) {

                println("added to Message Class")
                query.getFirstObjectInBackgroundWithBlock{(object:PFObject!, error: NSError!) -> Void in
                    if error == nil {
                        var addMessageWithObject = object
                        if addMessageWithObject != nil {
                            user.saveInBackground()
                            println("Added with getFirstObject")
                        }
                        else{
                            println("Error Added with getFirstObject")
                        }
                    }
                }
            }
    }
}

user column is (undefined) as in screenshot here

and the error log can't add non pointer to relation  is back
how do I fix this? Thanks!

A: Here's what you do:

*

*Manually create your Message table on Parse

*Add a messages column to your user table of type Relation with Target Class as your Message table.

*In your code, in your buttons trigger:
// Get the message text from your textField
let messageText = textField.text

// Create your new Message object
let newMessage = PFObject(className: "Message")
// ... Add your data to your new message object
newMessage["messageTextColumn"] = messageText

newMessage.saveInBackgroundWithBlock {
    (success: Bool, error: NSError?) -> Void in
    if (success) {
        // Add the new message to the user's relation
        let relation = yourUser.relationForKey("messagesColumnName")
        relation.addObject(newMessage)

        // Save the user object
        yourUser.saveInBackground()
    } else {
        // There was a problem, check error.description
    }
}

Here's a link to Parse's Relation reference.
UPDATE:
Missing code to save your user object.
query.getFirstObjectInBackgroundWithBlock{(object:PFObject!, error: NSError!) -> Void in
            if error == nil {
                let relation = PFUser.currentUser().relationForKey("Messages")
                var addMessageWithObject = object
                if addMessageWithObject != nil {
                    relation.addObject(addMessageWithObject)

                    PFUser.currentUser().saveInBackground()

                    println("Added with getFirstObject")
                }
                else{
                    println("Error Added with getFirstObject")
                }
            }
        }

UPDATE 2:
Messages without PFRelation:

*

*Add a column (let's say user) of type Pointer with Target Class as _User to the Messages table to identify each message by their user.

*Saving new messages: Save the new message object like above (just without adding the relation and it'e related code):
@IBAction func addMessage(sender: AnyObject) {
    var newMessage = addMessageText.text

    let message = PFObject(className: "Messages")
    message["messageTextColumn"] = newMessage
    message["user"] = PFUser.currentUser()

    message.saveInBackgroundWithBlock {(success: Bool, error: NSError?) -> Void in
        if (success) {
            println("added to Message Class")
        } else {
            // Error saving message
        }
    }
}

*Querying the messages for a user: You can query using the current user as a constraint so no matter which device a particular switches to, he/she will get only his messages.
var query = PFQuery(className:"Messages")
query.whereKey("user", equalTo:PFUser.currentUser())
query.findObjectsInBackgroundWithBlock {
    ...
}


text:
Q: Parent model have 2 properties one comes null on Add I have created a ParentModel because i want to use two models inside this so that i can use the same in view in MVC.
When i get the data on initial load both properties defined in Parent model populate properly.
However, when I try to add new data I see second property as null.
Here is my code :
public class UserModel
{
    public User User { get; set; }
    public IEnumerable<RolesModel> rolesModel { get; set; }
}

[HttpPost]
[ValidateAntiForgeryToken()]
public ActionResult Add(UserModel userDetails)
{
    try
    {
        if (ModelState.IsValid)
        {
            userDetails.User.FullName = userDetails.User.FirstName + " " + userDetails.User.MiddleName + " " + userDetails.User.LastName;
            userDetails.User.CreatedDate = DateTime.Now;
            _userService.Insert(userDetails.User);
            _unitOfWorkAsync.SaveChanges();
            foreach (RolesModel rolesModel in userDetails.rolesModel)
            {
                // Here userdetails.rolesmodel is null
            }
        }

View :
@model Axp.Gcst.Gps.Web.Areas.Admin.Models.UserModel
@using (Html.BeginForm("Add", "user", FormMethod.Post, new { @class = "form-horizontal" }))
{
    @Html.AntiForgeryToken()
    @Html.Partial("_UserDetails", Model)
    @foreach (var itemRole in Model.rolesModel)
    {
        if (itemRole.Role.RoleGroupId == item.RoleGroupId)
        {
            <div class="col-md-12 col-sm-12 col-xs-12 panel_cell">
                @Html.CheckBoxFor(model => itemRole.isSelected, new { @class = "panel_checkbox" })
                @Html.DisplayFor(model => itemRole.Role.Name)
            </div>
            @Html.HiddenFor(model=>itemRole.Role.RoleId)
        }
    }
}

A: When you post back a List Back to controller you should use a for loop:
@foreach (var itemRole in Model.rolesModel)
{
    if (itemRole.Role.RoleGroupId == item.RoleGroupId)
    {

        @Html.CheckBoxFor(model => itemRole.isSelected, new { @class = "panel_checkbox" })
        @Html.DisplayFor(model => itemRole.Role.Name)
        @Html.HiddenFor(model => itemRole.Role.RoleId)
    }
}

Use a For loop:
@for(int i =0; i< Model.rolesModel.Count; i++){
            @Html.CheckBoxFor(m => m.rolesModel[i].isSelected, new { @class = "panel_checkbox" })
            @Html.DisplayFor(m => m.rolesModel[i].Role.Name)
            @Html.HiddenFor(m => m.rolesModel[i].Role.RoleId)

}

A similar Answer here: https://stackoverflow.com/a/27926181/1910735
The MVC Model Binder Requires the Input fields to be in the format:
list[0].prop1
list[0].prop2
list[0].prop3

list[1].prop1
list[1].prop2
list[1].prop3


text:
Q: How to handle multiple versions of files on a PHP/SQL powered file mirror? This is my first time working with either PHP or SQL.
I'm making a simple website which hosts apps alongside their names, authors, version, descriptions etc. The PHP script fetches this information from a MySQL database I've made. Each app has a unique identifier assigned to it. Multiple versions would re-use the same identifier.
I've got it to display the entries with only one version fine.
However...
When an updated version of an app is released, I want it to list the old version(s) (just the version number linked to the old version's link) in a drop down next to the newest version. I made the database assuming that I'd figure out a way to display it fine, thus when I added an updated version of an app to the database, I left the things that didn't change blank (like name, author, description), gave it the same identifier as the older version and only added the newer version number and the filename of the newer version. See here for an example.
However, I assumed wrong.
I have no clue how to proceed. I have a query:
SELECT * FROM apps WHERE identifier IN ( SELECT identifier FROM apps GROUP BY identifier HAVING count(*) > 1)

However, this only selects all of the entries which have duplicate "identifier"s. I don't know how to run this through a loop, to echo the older entry's description/name but the newer entry's version number/link (while ALSO being able to echo the old version number/link for my dropdown). Oh, and also so it wouldn't assign names/descriptions/etc to apps which DO have a duplicate identifier, but which isn't identical to other apps' identifiers. Sorry, this is hard to explain.
My current loop, which is:
$result=mysqli_query($connection,$query);
$num=mysqli_num_rows($result);
$i=0;while ($i < $num) {while ($row = mysqli_fetch_array($result))  {
            // do stuff (echo)
                    } ;$i++;};

just echoes the entries seperately, one being the old version and one being the new version (with no description, name or author displayed).
How should I proceed?

A: How about something like this:
You select all the data from your table, ordered by identifier and then by version. The query being something like:
--                              ↓ orders data by identifier, thereby 'grouping' together records with the same identifier
SELECT * FROM apps ORDER BY identifier, version DESC
--                                           ↑ orders each 'group' by version number descending - highest / 'newest' first

Then, from this data, you could create an array structure in PHP which would enable you to easily loop through the data. Something like the following:
$result = mysqli_query($connection,$query);
$apps = array(); // Create apps array

while ($row = mysqli_fetch_array($result))  {
    // Assign the Name, Description, Author of the row
    // These will be blank until the last (oldest version) which has these values
    // $app[$row[1]] will create a key for each identifier or use the existing one
    $apps[$row[1]]["name"] = $row[2];
    $apps[$row[1]]["description"] = $row[3];
    $apps[$row[1]]["author"] = $row[4];

    // If there is no current version stored
    if(empty($apps[$row[1]]["current_version"])){
        $apps[$row[1]]["current_version"]["version"] = $row[5];
        $apps[$row[1]]["current_version"]["source"] = $row[6];
        $apps[$row[1]]["current_version"]["filename"] = $row[7];
    } else { // If not, this means this row is an older version
        $v = array(
            "version" => $row[5],
            "source" => $row[6],
            "filename" => $row[7],
        );
        $apps[$row[1]]["older_versions"][] = $v; // Add the array to the older_versions array
    }
}

This then produces the following array structure:
Array
(
    [vitashell] => Array
        (
            [name] => VitaShell
            [description] => VitaShell is an alternative replacement...
            [author] => TheFloW
            [current_version] => Array
                (
                    [version] => 0.86
                    [source] => http://www.example.com/link/version/0_86
                    [filename] => vitashell_0_86.vpk
                )

            [older_versions] => Array
                (
                    [0] => Array
                    (
                        [version] => 0.8
                        [source] => http://www.example.com/link/version/0_8
                        [filename] => vitashell_0_8.vpk
                    )
            )
    )

    [identifier] => Array (...)
)

You could then use a couple of foreach loops to go through the $apps array printing out the data as necessary.

I made a simple example of printing out the data. For display purposes, I added some dummy rows to the dataset:
<?php foreach($apps as $app){ ?>

        Name: <?php echo $app["name"]; ?>

        Description: <?php echo $app["description"]; ?>

        Author: <?php echo $app["author"]; ?>

        Version: <a href="<?php echo $app["current_version"]["source"]; ?>"><?php echo $app["current_version"]["version"]; ?>

        <?php if(!empty($app["older_versions"])){ ?>
        Older Versions:
        <select name="older_versions">
            <?php foreach($app["older_versions"] as $version){ ?>
            <option value="<?php echo $version["source"] ?>"><?php echo $version["version"]; ?></option>
            <?php } ?>
        </select>
        <?php } ?>

<?php } ?>

Which creates:

Note: "TIMSTUFF" only has 1 version, hence no drop-down for older versions


text:
Q: Evaluating a scalar product of a vector and a differential operator vector I created a scalar product of a vector $\in \mathbb{R}^2$ and of a vector consisting of a differential operators
op[t_] = (D[#, {t, 2}] - 3 D[#, t] + 2 #) &;   (1)
delop = {op[t], op[z]}; X = {1, -2};

I would like to apply this scalar product to a function and tried the following (not working solutions)
(X.delop)@Sin[t+z]    (2)
(X.delop) Sin[t+z]

leading to
((D[#1, {t, 2}] - 3 D[#1, t] + 2 #1 & ) - 2 (D[#1, {z, 2}] - 3 D[#1, z] + 2 #1 & ))[Sin[t + z]]
((D[#1, {t, 2}] - 3 D[#1, t] + 2 #1 & ) - 2 (D[#1, {z, 2}] - 3 D[#1, z] + 2 #1 & )) Sin[t + z]

How can I evaluate those expressions or directly obtain an evaluated expression in formula (2)?

A: I would define "delop" as a function and do the scalar product after applying the function:
Clear["Globals`*"]
op[t_] = (D[#, {t, 2}] - 3 D[#, t] + 2 #) &;
delop[t_, z_] = {op[t][#], op[z][#]} &;
X = {1, -2};
X.(delop[t, z]@Sin[t + z])

(* -3 Cos[t + z] + Sin[t + z] - 2 (-3 Cos[t + z] + Sin[t + z]) *)

Note, the brackets are not necessary, due to preferences. I put them in to make the preference clear.


text:
Q: Upload JS file on asset library We have a SharePoint 2013 enviroment were we are unable to upload JS file to a an asset library from client machine, while it work ok if we upload from inside the server.
How can we resolve the issue?
Error From SP Designer

Could not find a web server at www.thedomain.com on port 80. Please check to make sure that the web server name is
  Valid and your proxy settings are set correctly. If you are sure that everything is correct, the web server may be
  Temporarily out of service.

Error from web Browser

Something went wrong

This error is random and it worked also in some rare case. This issue is specially with JS file and HTML with JS. It works ok with text file.

A: After long investigation we found that antivirus of the enterprise PC was creating the issue.We added exception for sharepoint designer exe on the antivirus client which resolves the issue.


text:
Q: Dynamic buttons that filter objects Django @UPDATE @UPDATE
I want to make dynamic multiple buttons that filtering objects, similar to website https://justjoin.it/brands
For now I've done filtering with Django-filter that allows users to filter companies by Type, City and is company open for Students. But this django-filter require page to be refreshed which means it's not dynamic updating. It looks like this
image 1
image 2
and this is functional, works excellent.
Then I've created simple API with django-rest-framework which is accesible on 127.0.0.1:8000/api/companies and looks like this
Image
and also works fine.
The next thing that I've made is adding jQuery and simple script to get data from API, when someone submit form with ID=submit (image below)
image
But now I've stucked because I dont know how to get Data from API and compare this to template. I'm asking for any suggetions because I couldnt find any good example.
My files (updated)
models.py
from django.db import models
from django.db import models
from django.utils import timezone
from django.utils.text import slugify
from django.core.validators import MinValueValidator
from multiselectfield import MultiSelectField
import django_filters

TYPES = (
        ('Startup', 'Startup'),
        ('Software House', 'Software House'),
        ....)
CITIES = (
         ('Warszawa', 'Warszawa'),
         ('Poznan', 'Poznan'),
         ....)
COMPANY_TECHNOLOGIES = (
        ('PHP', 'PHP'),
        ('js', 'JavaScript'),
        ....)
STUDENTS = (
        ('No', 'No'),
        ('Yes', 'Yes')
    )
class Company(models.Model):
    name = models.CharField(max_length=100, blank=False)
    students = models.CharField(max_length=3, choices=STUDENTS)
    type = models.CharField(max_length=15, choices=TYPES)
    workers = models.PositiveIntegerField(validators=[MinValueValidator(1)])
    city = models.CharField(max_length=15,choices=CITIES)
    stack = MultiSelectField(choices=COMPANY_TECHNOLOGIES)
    ....

    def save(self, *args, **kwargs):
        self.slug = slugify(self.name)
        super(Company, self).save(*args, **kwargs)

    def publish(self):
        self.published_date = timezone.now()
        self.save()

    def __str__(self):
        return self.name

views.py
from django.shortcuts import render, get_object_or_404, redirect
from django.utils import timezone
from .models import Company
from .filters import CompanyFilter
from rest_framework import viewsets
from .serializers import CompanySerializer
# Create your views here.

def companies_list(request):
    my_companies = Company.objects.all()

    ## filter by company type
    type = request.GET.get('type')
    if type:
        my_companies = Company.objects.filter(type=type)
    ## filter by company city
    city = Company.objects.all()
    if city:
        my_companies = Company.objects.filter(city=city)
    ## filter by company technologies
    stack = request.GET.get('stack')
    if stack:
        my_companies = Company.objects.filter(city=city)

    my_companies = my_companies.order_by('published_date')
    return render(request, 'company/companies_list.html', {'my_companies': my_companies})

def comp_list(request):
    f = CompanyFilter(request.GET, queryset=Company.objects.all())
    return render(request, 'company/comp_list.html', {'filter': f})

##def brands(request, slug):
  ##  brands = Company.objects.all()
    ##return render(request, 'company/comp_view.html', {'brands': brands})

def brands(request, pk):
    brand = get_object_or_404(Company, pk=pk)
    return render(request, 'company/comp_view.html', {'brand': brand})

comp_list.html
{% extends 'company/base.html' %}
{% block content %}

    <form action="" method="get" id="submit">
        {{ filter.form.as_p }}
        <input type="submit"/>
    </form>
    {% for obj in filter.qs %}
    {{ obj.name }}

Image {% if obj.image != None %}

        {% endif%}

Icon {% if obj.icon != None %}

        {% endif%}

 Type: {{  obj.type }} City: {{ obj.city }} Stack: {{  obj.stack }}

    {% endfor %}
{% endblock %}

serializers.py
from .models import Company
from rest_framework import serializers

    class CompanySerializer(serializers.ModelSerializer):
        class Meta:
            model = Company
            fields = "__all__"

filters.py
import django_filters
from .models import Company, COMPANY_TECHNOLOGIES
from django_filters import ChoiceFilter

    class CompanyFilter(django_filters.FilterSet):

        class Meta:
            model = Company
            fields = ['type', 'city', 'students']

        def __init__(self, *args, **kwargs):
            super(CompanyFilter, self).__init__(*args, **kwargs)
            self.filters['type'].extra.update(
                {'empty_label': 'All'})
            self.filters['city'].extra.update(
                {'empty_label': 'All'})
            self.filters['students'].extra.update(
                {'empty_label': 'All'})

ajax.js
$( "#submit" ).click(function(event) {
event.preventDefault();

    $.ajax({
        url: "http://127.0.0.1:8000/api/companies/",
        method: 'GET',
        success: function(data){
        console.log(data)
        },
        error: function(error_data){
        console.log("error")
        console.log(error_data)
        }
        })});

A: Filtering is usually done via GET parameters.
In this example, if you add ?company_name=acme to the URL, only company names with acme in the name would be shown:
def companies_list(request):
    my_companies = company.objects.filter(
        published_date__lte=timezone.now())

    company_name = request.GET.get('company_name', None)
    if company_name:
        my_companies = my_companies.filter(company_name__icontains=company_name)

    my_companies = my_companies.order_by('published_date')
    return render(request, 'company/index.html', {'my_companies': my_companies})

There's also django-filter to ease this stuff.
As for the SPA, this is beyond the scope of the question, but it should be done with an AJAX request and replacing the DOM element with the response of the view, or returning a JSONResponse and building the element with JavaScript.


text:
Q: SaveMode is not working in Spark SQL I was running Spark SQL example with SaveMode option but getting following error.
val df = sqlContext.read.format("json").load("/user/root/spark/data/people.json")
df.select("name","age").write.format("json").save("Output",SaveMode.ErrorIfExist)

<console>:35: error: overloaded method value save with alternatives:
  ()Unit <and>
  (path: String)Unit
 cannot be applied to (String, org.apache.spark.sql.SaveMode)
              df.select("name", "age").write.format("json").save("Output",SaveMode.ErrorIfExists

I checked documentation , it says SaveMode is deprecated. How do I fix this?
Any suggestion.

A: You can use DataFrameWriter.mode method:
df.write.mode("error").save(...)

or
df.write.mode(SaveMode.ErrorIfExists).save(...)


text:
Q: Inter Site Communication: How to communicate authenticate users registered on Site A to/with Site B? I have a situation where there are 'n' number of users registered on Site A. After the user has utilized the services on Site A, he/she is re-directed to Site B to access the services hosted at Site B. How can the application on Site B ensure/verify that the user is an authenticated user at Site A and not a rogue re-direct request.
There is a possibility of using Federated Identity. However, I am looking at some other solution.
Could someone direct me as to where I should start looking to enable such a service/feature.
The application hosted on Site B is developed in JAVA. Definitely the communication is independent of the technology,however it would be an added advantage to use JAVA cause of the skill set.

A: This topic is generally called single sign on, for which there are many, many solutions and the full topic is really beyond the scope of a single answer here.
It depends on a lot of factors, what technology stacks you need/want to use, etc etc etc.
I've done some work with Oracle SSO.  It's kind of annoying actually and you have to intercept HTTP requests for custom headers to authenticate users, etc.
Some projects worth checking out are JOSSO and CAS.


text:
Q: How to get an txt file output with visible moviclips on stage to SQL database with AS3? I have no idea about SQL but I have this college prj. to be submitted.
Basicallyits a color change game where all movieclips are visible to false. When select a shirt button and click red button that color MC will be visible to true.
Now I want the end product that is the user while clicking the save button, I want all the movieclips that r visible on stage to be generated as a list to be sent to SQL database and also to server.
How could I go about it?
Any suggestions and ideas r welcome and much appreciated..
Many Thanks in advance.

A: What you can do, is create a local database, and store what you need to store in it,
Here is an example about how to create / use SQLite
Some documentation that will help you : SQLConnection, SQLStatement
PS : This is a simple thing that you should have found it if you googled for it ...


text:
Q: Loading two models from Saver in the same Tensorflow session I have two networks: a Model which generates output and an Adversary which grades the output.
Both have been trained separately but now I need to combine their outputs during a single session.
I've attempted to implement the solution proposed in this post: Run multiple pre-trained Tensorflow nets at the same time
My code
with tf.name_scope("model"):
    model = Model(args)
with tf.name_scope("adv"):
    adversary = Adversary(adv_args)

#...

with tf.Session() as sess:
    tf.global_variables_initializer().run()

    # Get the variables specific to the `Model`
    # Also strip out the surperfluous ":0" for some reason not saved in the checkpoint
    model_varlist = {v.name.lstrip("model/")[:-2]: v
                     for v in tf.global_variables() if v.name[:5] == "model"}
    model_saver = tf.train.Saver(var_list=model_varlist)
    model_ckpt = tf.train.get_checkpoint_state(args.save_dir)
    model_saver.restore(sess, model_ckpt.model_checkpoint_path)

    # Get the variables specific to the `Adversary`
    adv_varlist = {v.name.lstrip("avd/")[:-2]: v
                   for v in tf.global_variables() if v.name[:3] == "adv"}
    adv_saver = tf.train.Saver(var_list=adv_varlist)
    adv_ckpt = tf.train.get_checkpoint_state(adv_args.save_dir)
    adv_saver.restore(sess, adv_ckpt.model_checkpoint_path)

The problem
The call to the function model_saver.restore() appears to be doing nothing. In another module I use a saver with tf.train.Saver(tf.global_variables()) and it restores the checkpoint fine.
The model has model.tvars = tf.trainable_variables(). To check what was happening I used sess.run() to extract the tvars before and after restore. Each time the initial randomly assigned variables are being used and the variables from the checkpoint are not being assigned.
Any thoughts on why model_saver.restore() appears to be doing nothing?

A: Solving this problem took a long time so I'm posting my likely imperfect solution in case anyone else needs it.
To diagnose the problem I manually looped through each of the variables and assigned them one by one. Then I noticed that after assigning the variable the name would change. This is described here: TensorFlow checkpoint save and read
Based on the advice in that post I ran each of the models in their own graphs. It also means that I had to run each graph in its own session. This meant handling the session management differently.
First I created two graphs
model_graph = tf.Graph()
with model_graph.as_default():
    model = Model(args)

adv_graph = tf.Graph()
with adv_graph.as_default():
    adversary = Adversary(adv_args)

Then two sessions
adv_sess = tf.Session(graph=adv_graph)
sess = tf.Session(graph=model_graph)

Then I initialised the variables in each session and restored each graph separately
with sess.as_default():
    with model_graph.as_default():
        tf.global_variables_initializer().run()
        model_saver = tf.train.Saver(tf.global_variables())
        model_ckpt = tf.train.get_checkpoint_state(args.save_dir)
        model_saver.restore(sess, model_ckpt.model_checkpoint_path)

with adv_sess.as_default():
    with adv_graph.as_default():
        tf.global_variables_initializer().run()
        adv_saver = tf.train.Saver(tf.global_variables())
        adv_ckpt = tf.train.get_checkpoint_state(adv_args.save_dir)
        adv_saver.restore(adv_sess, adv_ckpt.model_checkpoint_path)

From here whenever each session was needed I would wrap any tf functions in that session with with sess.as_default():. At the end I manually close the sessions
sess.close()
adv_sess.close()

A: The answer marked as correct does not tell us how to load two different models into one session explicitly, here is my answer:

*

*create two different name scopes for the models you want to load.

*initialize two savers which are going to load parameters for variables in the two different networks.

*load from the corresponding checkpoint files.
with tf.Session() as sess:
    with tf.name_scope("net1"):
      net1 = Net1()
    with tf.name_scope("net2"):
      net2 = Net2()

    net1_varlist = {v.op.name.lstrip("net1/"): v
                    for v in tf.get_collection(tf.GraphKeys.VARIABLES, scope="net1/")}
    net1_saver = tf.train.Saver(var_list=net1_varlist)

    net2_varlist = {v.op.name.lstrip("net2/"): v
                    for v in tf.get_collection(tf.GraphKeys.VARIABLES, scope="net2/")}
    net2_saver = tf.train.Saver(var_list=net2_varlist)

    net1_saver.restore(sess, "net1.ckpt")
    net2_saver.restore(sess, "net2.ckpt")

A: Please check this:
adv_varlist = {v.name.lstrip("avd/")[:-2]: v

It should be "adv" , ain't it


text:
Q: How to obtain updated co-ordinates from matrix after applying transform and scale in OpenGL ES? I am applying some transform and scaling on opengl layer in iPhone. All I want to know is is there any api to retrieve rectangle co-ordinates after applying glTranform and glScale?
I found one api glGetFloatV(GL_MODELVIEW_MATRIX, matrix). This api returns array of 16 elements describing matrix information. Can I retrieve updated coordinates from this? Is there any other api which can help?

A: I don't believe this is possible. Even if it was, it may not be the best option for your application as it would mean retrieving data back from the GPU.
The easiest solution would be to perform the same transformations within your program on the CPU, for example by implementing matrix multiplication functions.
If you don't have time to re-invent the wheel, there is a library called GLM which would allow you to do matrix multiplication and it's specifically based on OpenGL - so it shouldn't be too hard for you to use. All you will have to do is create the same transformation matrix that you are using currently, except you'll do it with GLM functions instead of (or in addition to) the OpenGL functions. Then you just multiply your desired rectangle vertices with the GLM matrix to get your transformed points.
Just keep in mind that, with this method, if you are intending to transform a lot of vertices you will run into performance issues (because you will be doing the transformations sequentially on the CPU, rather than in parallel on the GPU). If you're only looking to get the transformed vertices of a few rectangles though, this should be your best bet.

A: On iOS the easiest thing to do is probably use the GLKMathProject function. The function signature looks like this:
GLKVector3 GLKMathProject(GLKVector3 object, GLKMatrix4 model, GLKMatrix4 projection, int *viewport);

To use it, you'll need:

*

*The coordinates you want to transform are in object. You'll transform one coordinate of your rectangle at a time.

*The model view matrix, which you'll get with the glGetFloatv call as you mentioned. You need to turn it into a GLKMatrix4 (see below).

*The projection matrix, which you also get with glGetFloatv, but with the GL_PROJECTION_MATRIX parameter.

*The coordinates of the viewport, which is where in the window you are drawing to. If you have not called glViewport then the viewport is an int array with elements [0, 0, width of window, height of window] in it.

To get the matrix as the GLKMatrix4 you should be able to do something like this:
GLMatrix4 modelviewMat;
glGetFloatv(GL_MODELVIEW_MATRIX, modelviewMat.m);

Hope this helps! The GLM library is also useful, but if you use GLKit you won't have to add any other files to your project, just import the GLKit framework.


text:
Q: How to create Startup and Cleanup script for Visual Studio Test Project? I'm using a Visual Studio Test project, am modifying the test config with deployment files, etc. (through the VS GUI) and now I need to write a Startup script for the test run.
I have no clue what language or file type or mechanism is used for these scripts. Need a tip.

A: Create a unit test in your test project.  In the unit test class, create methods with the [TestInitialize] and [TestCleanup] attributes.  They will be run before/after each test method.
Or, if you want to run before/after all test in that class, create static methods with [ClassInitialize] and [ClassCleanup] attributes.
Lastly, to run before/after all tests in the assembly, create static methods with [AssemblyInitialize] and [AssemblyCleanup] attributes.


text:
Q: How to declare an array of C strings? (needed for a WinAPI function) I want to use HttpOpenRequest to download a file from internet using GET. I don't know how to declare the AcceptType parameter. The MS documentations says that it is an array of strings. So I declare it like this:
CONST
   AcceptType: packed array[0..1] of LPWSTR = (PChar('*/*'), nil);

I have done something wrong? LPWSTR is a pointer to a string, however, the documentation says that I need a string. How do I declare a matrix of strings that are compatible with C++ ?

procedure THTTPGetThread.Execute;
CONST
   AcceptType: packed array[0..1] of LPWSTR = (PChar('*/*'), nil);              // Originally was:   AcceptType:= PWideChar('Accept: ' + FTAcceptTypes);
VAR
   hConnect: hInternet;
   FileName: String;
   Data: Array[0..1024] of Char;
   TempStr: PAnsiChar;
   RequestMethod: PChar;
   InternetFlag: DWord;
begin
     ...
     hRequest:= HttpOpenRequest(hConnect, RequestMethod, PChar(FileName), PChar('HTTP/1.0'), PChar(FTReferer), @AcceptType, InternetFlag, 0);
     ...
end;

I use Delphi XE.
The MS documentation is here: http://msdn.microsoft.com/en-us/library/windows/desktop/aa384233(v=vs.85).aspx
My function is multi-threaded so it won't block the program while it downloads. Single threaded functions won't work for me.

A: You are almost there. You just need to pass a pointer to the first element of the array:
@AcceptType[0]

In fact, as @Serg points out, this is equivalent to your existing code. So it seems that, as you have commented below, the issue you are facing is unrelated to the passing of this parameter.

As an aside, I think I would use PWideChar rather than LPWSTR, but that's not the issue here since they are equivalent.


text:
Q: How are the chinese coding? Do they code in Latin?
Do they have their own programming language?
I'm just curious.

A: Why would they use any other tools like we do? I'm german myself and don't program in german either. But a good question.

A: The Chinese and other cultures I have come into contact with all code in English. I live in Vietnam and they still use English here; even for all the variable names. On occasion you will see Vietnamese comments, but for the code itself.. all English. This makes sense when you realize that the majority of online resources are in English and the fact that sharing code with people of other cultures becomes easier too.

A: In mainland China at least virtually everyone of an age to be getting a job programming already knows Pinyin--a version of their language set into our alphabet.  Also, you have to know it to type anything into the computer as that's how the input editor works.
Thus it seems to me a trivial step to use the standard keywords--why in the world would they make a different version of the language in order to get around this??  The inconvenience of their code not being interchangeable would far exceed the tiny advantage to not having to deal with reserved words not in their script.

A: I maintain the Korean IME (Input Method Editor) for Microsoft Windows and Office. Thus I work with Korean devs on a daily basis, Japanese devs regularly, and Chinese devs occasionally. We all code in C/C++.
I am most familiar with the code for the Korean IME. There are a few places with comments in Korean script (Hangul) where it is absolutely necessary, but even  most comments are in English.
This may be because we are an international company, so we all need to communicate in a common language. Even emails are usually sent in English. However, when I verbally speak with my Korean co-workers, it's almost always in Korean.
Although C/C++ reserved words are also "English" words, they have their own very specific meaning and end up becoming part of a language that isn't even really "English," per se.
edit: Incidentally, I was just listening to the stackoverflow podcast (#29, I think) where a similar question came up. Joel said the scripting language in Excel was localizable (reserved words changed to the local language.)

A: I've got two native Chinese speakers on my team - I'll ask them personally on Tuesday if you don't get a good answer by then, but here's my initial guess.
Code is written in the standard programming languages, although comments (and perhaps variable names) could be written in Chinese. No use re-inventing the wheel (where "the wheel" is C++, Perl, Python, etc.) when you can just learn a few keywords.

A: To answer the exact questions asked:  For the most part, they code in "English" (that is, they code in the exact same version of the programming languages used in the U.S., with English-based keywords and so on).  However, there are some programming languages that cater to Chinese to varying degrees.  As one commenter mentioned, ChinesePython is one.
However, I think there is more to the endeavor of programming than just producing source code.  For the perspective of someone who has lived in Shanghai for years and worked with programmers there during that time, I think this blog article is an extremely good one.
For further references on Stack Overflow, not necessarily about Chinese in particular:
*

*Do there exist any compilers with localized versions of programming languages?

*Truly multi-lingual programming languages?

*Coding in Other (Spoken) Languages

*Do you use another language instead of English? [deleted]

*Should identifiers and comments be always in English or in the native language of the application and developers [deleted]

(The deleted posts are not visible to users with less than 10000 rep.)
Also, on Software Engineering SE (formerly Programmers SE):

*

*Do people in non-English-speaking countries code in English?

A: Most of the commonly used language are English-based, and most of them are so to appeal to an international audience. Some countries do actually have their own personalized/localized programming languages. Here is a list of some of them: Wikipedia: Non-English based programming languages
Looks like there is a version of BASIC called Chinese Basic. I'd be surprised if it's used on the same scale as other widely used languages at the moment :)

A: Most Chinese people just code in the same way as rest of the world, using those common programming languages, at most with some Chinese comment or romanized Chinese variable name.
There are also some programming language being created/translated into Chinese, see https://en.wikipedia.org/wiki/Non-English-based_programming_languages or  https://en.wikipedia.org/wiki/Chinese_programming_languages , but as far as I know nearly all of them aren't used more than those language in http://code.tutsplus.com/articles/10-most-bizarre-programming-languages-ever-created--net-2412 except one: EPL Easy Programming Language, which is a programming language that apparently based off VB and allow user with no English knowledge nor programming knowledge to learn coding quickly and let them easily produce some simple programs. Now it is predominately use by those with little foundation to develop things like game cheat and malware...